"""Run C1 (ground-truth validity) and C3 (v2 prompt) on the AUTH-PROBLEM rows, judging both v5 (before) and v6 (after the deterministic auth fixes) so the only variable is the authored NL (calls are byte-identical v5==v6). Auth-problem set = union of (a) auth-primary CAUGHT rows -> caught_reasons_v5.jsonl primary==D_auth_verification (b) rows the deterministic lint FIXED in v6 -> NL differs v5 vs v6 Reports, for this set: * C3 v2 caught rate v5 vs v6 (drop = the auth fixes fooled the judge) * C1 fail/borderline v5 vs v6 (should not regress; calls unchanged) Run: python -u temp/story_remediation/unbundle/run_auth_c1c3.py """ from __future__ import annotations import json, logging, sys from collections import Counter from concurrent.futures import ThreadPoolExecutor from pathlib import Path import yaml for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): logging.getLogger(_n).setLevel(logging.WARNING) HERE = Path(__file__).resolve().parent ROOT = HERE.parents[2] sys.path.insert(0, str(ROOT)) from datasetreview import pipelines as P # noqa: E402 from datasetreview import judge_prompts as J # noqa: E402 from datasetreview.llm_client import make_judge # noqa: E402 OUT = HERE / "out" cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" SAMPLES = 3 WORKERS = max(8, cfg["run"].get("workers", 4)) v5 = {e["example_id"]: e for e in (json.loads(l) for l in open(OUT / "trajectories_all_v5.jsonl", encoding="utf-8") if l.strip())} v6 = {e["example_id"]: e for e in (json.loads(l) for l in open(OUT / "trajectories_all_v6.jsonl", encoding="utf-8") if l.strip())} # (a) auth-primary caught rows auth_caught = {json.loads(l)["item_id"] for l in open(OUT / "caught_reasons_v5.jsonl", encoding="utf-8") if l.strip() and json.loads(l).get("primary") == "D_auth_verification"} # (b) lint-fixed rows (NL differs) fixed = {eid for eid in v5 if json.dumps(v5[eid].get("history")) != json.dumps(v6[eid].get("history")) or v5[eid].get("query") != v6[eid].get("query")} AUTH_IDS = sorted((auth_caught | fixed) & set(v5) & set(v6)) print(f"auth-primary caught: {len(auth_caught)} | lint-fixed: {len(fixed)} " f"| union present in both: {len(AUTH_IDS)}") base = {} for line in open(BASELINE, encoding="utf-8"): if line.strip(): d = json.loads(line); base[d["item_id"]] = d reals = P.real_trajectories() pairer = P.make_pairer(reals) judge = make_judge(cfg["model"]) def c3_pair(fake, real, swap): system, user = J.load_prompt("C3v2") fr = J.render_trajectory(fake, blind_tools=True, include_metadata=False, conversation_only=True) rr = J.render_trajectory(real, blind_tools=True, include_metadata=False, conversation_only=True) a, b, key = (rr, fr, "B") if swap else (fr, rr, "A") user = user.replace("{{CONV_A}}", a).replace("{{CONV_B}}", b) return {"system": system, "user": user, "answer_key": key} def maj(msgs, field): vals = [] for _ in range(SAMPLES): try: vals.append(judge.judge({"system": msgs["system"], "user": msgs["user"]}).get(field)) except Exception: # noqa: BLE001 pass if not vals: return None, 0.0 m = Counter(vals).most_common(1)[0][0] return m, vals.count(m) / len(vals) def one(eid): real = pairer(v5[eid]) swap = (base.get(eid) or base.get(v5[eid].get("metadata", {}).get("orig_eid")) or {} ).get("answer_key") == "B" out = {"item_id": eid, "role": v5[eid].get("metadata", {}).get("unbundle_role")} for tag, ds in (("v5", v5), ("v6", v6)): fake = ds[eid] c3 = c3_pair(fake, real, swap); key = c3["answer_key"] g, ga = maj(c3, "guess") c1 = J.build_c1(fake) vd, vda = maj(c1, "verdict") out[f"{tag}_c3_guess"] = g out[f"{tag}_c3_caught"] = (g == key) out[f"{tag}_c1_verdict"] = vd return out def main(): print(f"judging {len(AUTH_IDS)} auth rows x2 versions x(C1+C3v2) " f"(samples={SAMPLES}, workers={WORKERS})") with ThreadPoolExecutor(max_workers=WORKERS) as ex: rows = list(ex.map(one, AUTH_IDS)) (OUT / "auth_c1c3.jsonl").write_text("\n".join(json.dumps(r) for r in rows) + "\n", encoding="utf-8") n = len(rows) v5c = sum(1 for r in rows if r["v5_c3_caught"]) v6c = sum(1 for r in rows if r["v6_c3_caught"]) flipped = [r for r in rows if r["v5_c3_caught"] and not r["v6_c3_caught"]] regress = [r for r in rows if not r["v5_c3_caught"] and r["v6_c3_caught"]] def c1fail(tag): return sum(1 for r in rows if r[f"{tag}_c1_verdict"] in ("fail", "borderline")) print("\n" + "=" * 74) print(f"AUTH-PROBLEM ROWS: {n}") print(f" C3 (v2 prompt) caught v5: {v5c}/{n} = {v5c/n:.0%} " f"v6: {v6c}/{n} = {v6c/n:.0%}") print(f" -> flipped caught->fooled by the fixes: {len(flipped)}/{max(v5c,1)}" f" = {len(flipped)/max(v5c,1):.0%}") print(f" -> regressions (fooled->caught): {len(regress)}") print(f" C1 fail/borderline v5: {c1fail('v5')}/{n} v6: {c1fail('v6')}/{n} " f"(calls unchanged; expect ~equal)") print("=" * 74) print("\nflipped (auth fix fooled the C3 v2 judge):") for r in flipped[:20]: print(f" {r['item_id']:44s} role={r['role']} v5={r['v5_c3_guess']}->v6={r['v6_c3_guess']}") if regress: print("\nREGRESSIONS to inspect:") for r in regress: print(f" {r['item_id']:44s} role={r['role']}") print(f"\nsaved -> {(OUT/'auth_c1c3.jsonl').relative_to(ROOT)}") if __name__ == "__main__": main()