"""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()