| """SANDBOX C3 run: judge the 51 temp merged injections with the SAME procedure
|
| as the baseline run (single orientation, samples=3 majority, workers=4, model
|
| from datasetreview/config.yaml). Compares the injected caught-rate against the
|
| baseline overall rate and the 51 host rows' own baseline caught. Writes results
|
| only into the sandbox (out/c3_injected_results.jsonl); canonical files untouched.
|
|
|
| Run from repo root: python -u temp/injection_sandbox/run_c3.py
|
| """
|
| from __future__ import annotations
|
|
|
| import json
|
| import logging
|
| import random
|
| import 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)
|
|
|
| ROOT = Path(__file__).resolve().parents[2]
|
| sys.path.insert(0, str(ROOT))
|
|
|
| from datasetreview import pipelines as P
|
| from datasetreview import judge_prompts as J
|
| from datasetreview.llm_client import make_judge
|
|
|
| SAND = Path(__file__).resolve().parent
|
| OUT = SAND / "out"
|
| MERGED = OUT / "_staging_merged_injections.jsonl"
|
| PROV = json.load(open(OUT / "_merged_injections.prov.json", encoding="utf-8"))
|
| BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
|
|
| cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| SAMPLES = 3
|
| WORKERS = cfg["run"].get("workers", 4)
|
|
|
| reals = P.real_trajectories()
|
| pairer = P.make_pairer(reals)
|
| judge = make_judge(cfg["model"])
|
| fakes = [json.loads(l) for l in open(MERGED, encoding="utf-8") if l.strip()]
|
|
|
|
|
| def judge_one(fake):
|
| eid = fake["example_id"]
|
| real = pairer(fake)
|
| swap = random.Random(eid).random() < 0.5
|
| msgs = J.build_c3(fake, real, swap=swap)
|
| key = msgs["answer_key"]
|
| guesses, err = [], None
|
| for _ in range(SAMPLES):
|
| try:
|
| r = judge.judge({"system": msgs["system"], "user": msgs["user"]})
|
| guesses.append(r.get("guess"))
|
| except Exception as e:
|
| err = str(e)
|
| if not guesses:
|
| return {"example_id": eid, "error": err, "answer_key": key, "real_id": real.get("example_id")}
|
| majority = Counter(guesses).most_common(1)[0][0]
|
| agree = guesses.count(majority) / len(guesses)
|
| return {"example_id": eid, "answer_key": key, "real_id": real.get("example_id"),
|
| "guess": majority, "agreement": agree, "n_samples": len(guesses),
|
| "sample_guesses": guesses, "caught": majority == key, "error": None}
|
|
|
|
|
| def main():
|
| print(f"judging {len(fakes)} injected rows (samples={SAMPLES}, workers={WORKERS}, "
|
| f"model={cfg['model']['label']})")
|
| with ThreadPoolExecutor(max_workers=WORKERS) as ex:
|
| results = list(ex.map(judge_one, fakes))
|
| results.sort(key=lambda r: r["example_id"])
|
| (OUT / "c3_injected_results.jsonl").write_text(
|
| "\n".join(json.dumps(r) for r in results) + "\n", encoding="utf-8")
|
|
|
| ok = [r for r in results if r.get("error") is None and "caught" in r]
|
| errs = [r for r in results if r.get("error") is not None or "caught" not in r]
|
| caught = sum(1 for r in ok if r["caught"])
|
| n = len(ok)
|
|
|
|
|
| base = {}
|
| for line in open(BASELINE, encoding="utf-8"):
|
| if line.strip():
|
| d = json.loads(line)
|
| base[d.get("item_id")] = d.get("caught")
|
| base_all = [v for v in base.values() if v is not None]
|
| base_rate = sum(base_all) / len(base_all) if base_all else 0.0
|
| host_of = {p["example_id"]: p["host_of"] for p in PROV}
|
| host_caught = [base.get(host_of[r["example_id"]]) for r in ok]
|
| host_caught = [v for v in host_caught if v is not None]
|
| host_rate = sum(host_caught) / len(host_caught) if host_caught else 0.0
|
|
|
| print("\n=== C3 RESULT (injected rows) ===")
|
| print(f" injected caught: {caught}/{n} = {caught/n:.1%}" if n else " no valid results")
|
| print(f" errors: {len(errs)}")
|
| print(f"\n baseline overall (795 rows): {sum(base_all)}/{len(base_all)} = {base_rate:.1%}")
|
| print(f" the 51 hosts' own baseline caught: {sum(host_caught)}/{len(host_caught)} = {host_rate:.1%}")
|
| delta = caught / n - base_rate if n else 0.0
|
| print(f"\n injected vs baseline-overall delta: {delta:+.1%} "
|
| f"(negative = injected fooled the judge MORE than baseline)")
|
| print(f" wrote out/c3_injected_results.jsonl")
|
| return 0
|
|
|
|
|
| if __name__ == "__main__":
|
| raise SystemExit(main())
|
|
|