File size: 16,060 Bytes
c5f5de4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 | """Score anonymous trajectories against the read-only vault in a network-isolated process."""
import argparse
from collections import defaultdict
from functools import lru_cache
from itertools import combinations
import json
import os
from pathlib import Path
import socket
from statistics import fmean
from runner.protocol import MAX_TURNS, MODELS, MODES, PORTS, load_plan, row_key, samples, trajectory_path
from sandbox.evaluator import decode_diagnosis
from sandbox.query_tools import SandboxSession, TokenBudget
from sandbox.snapshot import DATASETS, Window, load_snapshot
from .plan_work import load_truth
def average(values, empty=None):
return fmean(values) if values else empty
def truth_edges(value):
if value is None:
return None
if not isinstance(value, list):
raise ValueError("invalid_truth_path")
edges = set()
for edge in value:
if isinstance(edge, dict):
src, dst = edge["src"], edge["dst"]
elif isinstance(edge, list) and len(edge) == 2:
src, dst = edge
else:
raise ValueError("invalid_truth_path_edge")
if type(src) is not str or type(dst) is not str:
raise ValueError("invalid_truth_path_endpoint")
edges.add((src, dst))
return edges
def edge_f1(predicted, expected):
denominator = len(predicted) + len(expected)
return 2 * len(predicted & expected) / denominator if denominator else 1.0
def jaccard(left, right):
union = left | right
return len(left & right) / len(union) if union else 1.0
def direct_query(name, args):
if name in {"query_entity_metrics", "query_entity_events"}:
return {args["entity_id"]}
if name == "query_call_edge_detail":
return {args["caller_id"], args["callee_id"]}
return set()
def is_accepted(result):
return result.get("status") == "accepted" and result.get("terminal") is True
def replay(row, session):
initial = row["initial_observation"]
if initial["turn"] != 0 or initial["name"] != "get_initial_symptom_overview" or initial["arguments"] != {}:
raise ValueError("invalid_initial_observation")
if initial["result"] != session.call(initial["name"], {}):
raise ValueError("initial_observation_replay_mismatch")
if row["num_turns"] != len(row["turns"]) or not 0 <= row["num_turns"] <= MAX_TURNS + 1:
raise ValueError("invalid_turn_count")
queried = set()
decoded = None
rejected = 0
for turn, step in enumerate(row["turns"], 1):
if step["turn"] != turn or step["forced"] is not (turn == MAX_TURNS + 1) or not step["tool_calls"]:
raise ValueError("invalid_turn")
if decoded is not None:
raise ValueError("continued_after_submit")
for call in step["tool_calls"]:
name, args, result = (call[key] for key in ("name", "arguments", "result"))
if decoded is not None:
replayed = {"error": "session_already_submitted"}
elif name is None:
replayed = {"error": "tool_call_required"}
elif args is None:
replayed = {"error": "invalid_arguments"}
elif step["forced"] and name != "submit_diagnosis":
replayed = {"error": "submit_diagnosis_required"}
else:
replayed = session.call(name, args)
if replayed != result:
raise ValueError("tool_result_replay_mismatch")
if name == "submit_diagnosis":
if is_accepted(result):
if row["submission"] != args:
raise ValueError("submission_mismatch")
decoded = decode_diagnosis(session, args)
else:
rejected += 1
elif "error" not in result:
queried.update(direct_query(name, args))
if decoded is None:
if row["submission"] is not None or row["termination"] == "accepted":
raise ValueError("missing_accepted_submission")
if row["termination"] == "turn_limit" and row["num_turns"] != MAX_TURNS + 1:
raise ValueError("missing_forced_submit")
elif row["termination"] != "accepted":
raise ValueError("unexpected_terminal_status")
supported = decoded is not None and row["submission"]["root_entity_id"] in queried
return decoded, supported, rejected
def score(row, answer, layers, decoded, queried, rejected):
targets = set(answer["root_cause_entities"])
target_layers = {layers[target] for target in targets if target in layers}
root = decoded["root_entity_id"] if decoded is not None else None
predicted = {tuple(edge) for edge in decoded["propagation_path"]} if decoded else set()
expected = truth_edges(answer["ground_truth_causal_path"])
hit = root in targets
grounded = None
path_score = None
if expected is not None:
grounded = hit and queried and (not expected or len(predicted & expected) / len(expected) >= 0.5)
path_score = edge_f1(predicted, expected) if decoded is not None else 0.0
return {
"root_hit": hit, "layer_hit": layers.get(root) in target_layers,
"layer_resolved": bool(target_layers), "path_edge_f1": path_score, "grounded": grounded,
"predicted": predicted, "expected_edges": None if expected is None else len(expected),
"known_edges": None if expected is None else sum(src in layers and dst in layers for src, dst in expected),
"turns": row["num_turns"], "invalid": decoded is None, "forced": row["num_turns"] > MAX_TURNS,
"rejected": rejected, "termination": row["termination"],
}
def summarize(metrics):
hits = [item for item in metrics if item["root_hit"]]
path = [item for item in metrics if item["grounded"] is not None]
return {
"root_ac_at_1": average([item["root_hit"] for item in metrics]),
"layer_accuracy": average([item["layer_hit"] for item in metrics]),
"path_edge_f1": average([item["path_edge_f1"] for item in path]),
"grounded_ac_at_1": average([item["grounded"] for item in path]),
"ungrounded_hit_ratio": average([item["grounded"] is not True for item in hits], 0.0),
"avg_turns": average([item["turns"] for item in metrics]),
"invalid_submit_rate": average([item["invalid"] for item in metrics]),
"trajectories": len(metrics),
"path_annotated_trajectories": len(path),
"truth_layer_resolved_trajectories": sum(item["layer_resolved"] for item in metrics),
"truth_path_edges": sum(item["expected_edges"] for item in path),
"truth_path_edges_with_observable_endpoints": sum(item["known_edges"] for item in path),
"forced_submit_trajectories": sum(item["forced"] for item in metrics),
"intermediate_rejected_submits": sum(item["rejected"] for item in metrics),
}
def summarize_train(groups):
complete = [group for group in groups if len(group) == MODES["train"][0]]
hits_by_group = [[item["predicted"] for item in group if item["root_hit"]] for group in complete]
consistency = [average([jaccard(a, b) for a, b in combinations(hits, 2)])
for hits in hits_by_group if len(hits) >= 2]
return {
"total_cases_sampled": len(complete),
"pass_at_8_root": average([bool(hits) for hits in hits_by_group]),
"cases_with_mixed_outcomes_ratio": average(
[0 < len(hits) < MODES["train"][0] for hits in hits_by_group]
),
"mean_intra_case_path_jaccard": average(consistency),
"cases_with_at_least_two_root_hits": len(consistency),
}
def complete_cohort(cohort):
return cohort["mode"] == "train" and cohort["planned"] == cohort["new_trajectories"] == 800
def fully_overlapped_cohorts(runs):
"""For a fresh dual launch, bound cohort end times within the common active interval."""
if len(runs) != len(MODELS):
return []
common_end = min(run["run_wall_s"] for run in runs)
elapsed = []
for run in runs:
cohorts = run["cohorts"]
# Include all coordinator overhead before the first cohort as a conservative upper bound.
end = max(0, run["run_wall_s"] - sum(cohort["elapsed_s"] for cohort in cohorts))
for cohort in cohorts:
end += cohort["elapsed_s"]
if complete_cohort(cohort) and end <= common_end:
elapsed.append(cohort["elapsed_s"])
return elapsed
def assert_isolation():
if not os.statvfs("/data/vault").f_flag & os.ST_RDONLY or Path("/proc/1/root").exists():
raise RuntimeError("evaluator_isolation_required")
for port in PORTS.values():
try:
connection = socket.create_connection(("127.0.0.1", port), timeout=0.1)
except OSError:
continue
connection.close()
raise RuntimeError("evaluation_network_not_isolated")
def evaluate(trajectory_dir, plan_path, smoke=False, allow_incomplete=False):
assert_isolation()
plan, plan_hash = load_plan(plan_path)
answers = {dataset: load_truth("/data/vault", dataset) for dataset in DATASETS}
for dataset, splits in plan.items():
for mode, cases in splits.items():
if any(answers[dataset][case]["split"] != mode for case in cases):
raise ValueError("worklist_truth_split_mismatch")
windows = json.loads(Path("/data/windows.json").read_bytes())["windows"]
budget = TokenBudget("/data/tokenizer.json")
@lru_cache(maxsize=256)
def case_snapshot(dataset, case):
return load_snapshot(Path("/data/snapshots"), dataset, case, Window.from_values(windows[dataset][case]))
expected = {mode: set(samples(plan, mode, smoke)) for mode in MODES}
report = {
"overall_pass": False, "test_split_greedy": {}, "train_split_8rollouts_stats": {},
"train_split_metrics_by_dataset": {}, "acceptance": {},
}
all_metrics = []
complete = True
fatal = False
cohort_times = []
fresh_dual_runs = []
model_cohort_mean = {}
for model in MODELS:
path = trajectory_path(trajectory_dir, model, smoke)
seen = set()
model_groups = defaultdict(list)
mode_metrics = defaultdict(list)
groups = defaultdict(list)
with path.open("rb") as reader:
for line in reader:
if not line.endswith(b"\n"):
raise ValueError("unfinished_jsonl")
row = json.loads(line)
key = row_key(row)
if (row["schema_version"] != 1 or row["model"] != model or key in seen
or key not in expected[key.mode] or row["worklist_sha256"] != plan_hash):
raise ValueError("unexpected_trajectory")
seen.add(key)
snapshot = case_snapshot(key.dataset, key.case_id)
decoded, queried, rejected = replay(row, SandboxSession(snapshot, key.session_seed, budget))
layers = {real_id: node.layer for real_id, node in snapshot.entities.items()}
result = score(row, answers[key.dataset][key.case_id], layers, decoded, queried, rejected)
all_metrics.append(result)
model_groups[(key.mode, key.dataset)].append(result)
mode_metrics[key.mode].append(result)
if key.mode == "train":
groups[key.dataset, key.case_id].append(result)
if len(seen) % 500 == 0:
print(json.dumps({"model": model, "replayed": len(seen)}), flush=True)
if seen != set.union(*expected.values()):
complete = False
if not allow_incomplete:
raise ValueError("missing_required_trajectories")
fatal |= any(item["termination"] not in {"accepted", "turn_limit"}
for rows in mode_metrics.values() for item in rows)
report["test_split_greedy"][model] = {
dataset: summarize(model_groups["test", dataset]) for dataset in DATASETS
}
report["train_split_metrics_by_dataset"][model] = {
dataset: summarize(model_groups["train", dataset]) | summarize_train(
[values for key, values in groups.items() if key[0] == dataset]
) for dataset in DATASETS
}
report["train_split_8rollouts_stats"][model] = summarize_train(list(groups.values())) | {
"trajectories": len(mode_metrics["train"]),
"invalid_submit_rate": average([row["invalid"] for row in mode_metrics["train"]]),
}
timing_path = path.with_name(f"{path.stem}.timing.jsonl")
if timing_path.exists():
fresh_cohorts = {}
timings = [json.loads(line) for line in timing_path.read_text().splitlines()]
for entry in timings:
if entry["worklist_sha256"] != plan_hash or entry["model"] != model:
raise ValueError("timing_inventory_mismatch")
if entry["parallel_models"] == len(MODELS):
for cohort in entry["cohorts"]:
if complete_cohort(cohort):
fresh_cohorts[cohort["cohort"]] = cohort["elapsed_s"]
if len(timings) == 1 and sum(
cohort["new_trajectories"] for cohort in entry["cohorts"]
) == len(seen) == sum(len(keys) for keys in expected.values()):
fresh_dual_runs.append(entry)
cohort_times.extend(fresh_cohorts.values())
model_cohort_mean[model] = average(list(fresh_cohorts.values()))
invalid = sum(item["invalid"] for item in all_metrics)
invalid_rate = invalid / len(all_metrics) if all_metrics else None
cohort_mean = average(cohort_times)
concurrent_times = fully_overlapped_cohorts(fresh_dual_runs)
report["acceptance"] = {
"smoke_run": smoke, "full_inventory_and_replay_pass": complete and not smoke,
"expected_trajectories": len(MODELS) * sum(len(keys) for keys in expected.values()),
"replayed_trajectories": len(all_metrics), "sampler_execution_error": fatal,
"invalid_terminal_trajectories": invalid, "invalid_terminal_ratio": invalid_rate,
"isolated_query_replay_pass": True, "dual_instance_full_800_trajectory_cohorts": len(cohort_times),
"mean_800_trajectory_wall_time_s": cohort_mean,
"mean_800_trajectory_wall_time_s_by_model": model_cohort_mean,
"fully_overlapped_800_trajectory_cohorts": len(concurrent_times),
"mean_fully_overlapped_800_trajectory_wall_time_s": average(concurrent_times),
"worklist_sha256": plan_hash,
}
report["overall_pass"] = (
not smoke and complete and not fatal and invalid_rate is not None and invalid_rate < 0.05
and cohort_mean is not None and cohort_mean < 1200
)
return report
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--trajectory-dir", type=Path, default=Path("/data/trajectories"))
parser.add_argument("--worklist", type=Path, default=Path("/output/worklist.json"))
parser.add_argument("--output", type=Path, default=Path("/output/w1_04_baseline_eval_summary.json"))
parser.add_argument("--smoke", action="store_true")
parser.add_argument("--allow-incomplete", action="store_true")
args = parser.parse_args()
if args.smoke and args.output.name == "w1_04_baseline_eval_summary.json":
parser.error("Choose a separate --output for smoke results")
report = evaluate(args.trajectory_dir, args.worklist, args.smoke, args.allow_incomplete)
text = json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False) + "\n"
temp = args.output.with_suffix(".tmp")
temp.write_text(text)
temp.replace(args.output)
print(json.dumps({"output": args.output.name, "overall_pass": report["overall_pass"],
**report["acceptance"]}), flush=True)
if __name__ == "__main__":
main()
|