import asyncio import json from types import SimpleNamespace import pytest from eval_only.evaluate_trajectories import edge_f1, fully_overlapped_cohorts, jaccard, score, summarize, summarize_train from runner.protocol import MAX_TURNS, MODELS, Sample from runner.rollout_engine import JsonlWriter, rollout class Session: overview = {"anomalies": [["SVC_01"]], "graph": {"services": 2}, "evidence_id": "EV_000000000001"} def call(self, name, arguments): if name == "get_initial_symptom_overview": return self.overview if arguments["propagation_path"]: return {"error": "invalid_propagation_path"} return {"status": "accepted", "terminal": True} def model_call(name, arguments): return {"choices": [{"message": {"tool_calls": [{"function": { "name": name, "arguments": json.dumps(arguments), }}]}, "finish_reason": "stop"}], "usage": {"prompt_tokens": 77, "completion_tokens": 23, "total_tokens": 100}} def test_force_after_twenty_rejections(monkeypatch): session = Session() sample = Sample("test", "openrca_v1", "case-" + "a" * 24, 0) sandbox = SimpleNamespace(open_session=lambda *args: session) seen = [] async def fake_completion(client, params): seen.append(params["temperature"]) forced = len(seen) == MAX_TURNS + 1 if forced: assert params["tool_choice"]["function"]["name"] == "submit_diagnosis" schema = params["tools"][0]["function"]["parameters"]["anyOf"][0] assert schema["properties"]["root_entity_id"]["enum"] == ["SVC_01"] assert schema["properties"]["propagation_path"]["maxItems"] == 0 elif len(seen) > 1: assert params["messages"][-2]["content"] == '{"error":"invalid_propagation_path"}' return model_call("submit_diagnosis", { "root_entity_id": "SVC_01", "propagation_path": [] if forced else [["SVC_02", "SVC_01"]], "key_evidence_ids": [], "fault_category": "resource pressure", }), 0 monkeypatch.setattr("runner.rollout_engine.completion", fake_completion) row = asyncio.run(rollout(None, sandbox, MODELS[0], sample, "example")) assert row["termination"] == "accepted" assert row["num_turns"] == MAX_TURNS + 1 assert row["turns"][-1]["forced"] assert row["turns"][-1]["usage"]["total_tokens"] == 100 assert all(value == 0.0 for value in seen) @pytest.mark.parametrize("path,expected_grounded,expected_f1", [ (None, None, None), ([], True, 1.0), ([{"src": "service-a", "dst": "service-b"}], False, 0.0), ]) def test_exact_scoring_and_empty_paths(path, expected_grounded, expected_f1): answer = {"root_cause_entities": ["instance-a", "service-a"], "ground_truth_causal_path": path} decoded = {"root_entity_id": "service-a", "propagation_path": []} result = score({"num_turns": 3, "termination": "accepted"}, answer, {"service-a": "service", "service-b": "service", "instance-a": "instance"}, decoded, True, 0) assert result["root_hit"] and result["layer_hit"] assert result["grounded"] is expected_grounded assert result["path_edge_f1"] == expected_f1 assert summarize([result])["ungrounded_hit_ratio"] == (expected_grounded is not True) def test_path_edges_are_directed_and_jaccard_uses_root_hit_pairs(): left = {("a", "b"), ("a", "c")} right = {("b", "a"), ("a", "c")} assert edge_f1(left, right) == 0.5 assert jaccard(left, right) == pytest.approx(1 / 3) group = [ {"root_hit": True, "predicted": left}, {"root_hit": True, "predicted": right}, *[{"root_hit": False, "predicted": set()} for _ in range(6)], ] summary = summarize_train([group, group[:6]]) assert summary["total_cases_sampled"] == 1 assert summary["pass_at_8_root"] == 1.0 assert summary["cases_with_mixed_outcomes_ratio"] == 1.0 assert summary["mean_intra_case_path_jaccard"] == pytest.approx(1 / 3) def test_resume_truncates_only_incomplete_tail(tmp_path): path = tmp_path / "data.jsonl" sample = Sample("train", "openrca_v1", "case-" + "b" * 24, 0) row = {"schema_version": 1, "mode": sample.mode, "dataset": sample.dataset, "case_id": sample.case_id, "sample_idx": sample.sample_idx, "session_seed": sample.session_seed, "model": MODELS[0], "worklist_sha256": "example"} with JsonlWriter(path) as writer: writer.append(row) with path.open("a") as stream: stream.write('{"partial"') with JsonlWriter(path) as writer: assert writer.existing_keys(MODELS[0], {sample}, "example") == {sample} assert json.loads(path.read_bytes()) == row def test_timing_separates_cohorts_after_the_other_sampler_finished(): def cohort(seconds): return {"mode": "train", "planned": 800, "new_trajectories": 800, "elapsed_s": seconds} first = {"run_wall_s": 310, "cohorts": [cohort(300)]} second = {"run_wall_s": 450, "cohorts": [cohort(210), cohort(230)]} assert fully_overlapped_cohorts([first, second]) == [300, 210]