File size: 3,310 Bytes
94da461
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""SANDBOX C3 error analysis: for each of the 51 humanized injected rows, capture

the judge's REASONING (not just the guess), and line it up against the baseline

reasoning for that SAME host row (from datasetreview/results/new/C3.jsonl). Lets

us read, per example, WHY the host was caught and whether humanization addressed

that specific tell. One judgment per row (fake in A), reasoning captured.



Run from repo root:  python -u temp/injection_sandbox/analyze_c3_reasons.py

"""
from __future__ import annotations

import json
import logging
import sys
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          # noqa: E402
from datasetreview import judge_prompts as J       # noqa: E402
from datasetreview.llm_client import make_judge     # noqa: E402

SAND = Path(__file__).resolve().parent
OUT = SAND / "out"
MERGED = OUT / "_staging_merged_injections.jsonl"
PROV = {p["example_id"]: p for p in 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"))
reals = P.real_trajectories()
pairer = P.make_pairer(reals)
judge = make_judge(cfg["model"])
injected = [json.loads(l) for l in open(MERGED, encoding="utf-8") if l.strip()]

base = {}
for line in open(BASELINE, encoding="utf-8"):
    if line.strip():
        d = json.loads(line)
        base[d.get("item_id")] = {"caught": d.get("caught"),
                                  "reason": ((d.get("result") or {}).get("reasoning") or "")}


def judge_one(fake):
    eid = fake["example_id"]
    real = pairer(fake)
    msgs = J.build_c3(fake, real, swap=False)     # fake is A
    try:
        r = judge.judge({"system": msgs["system"], "user": msgs["user"]})
    except Exception as e:                         # noqa: BLE001
        return {"example_id": eid, "error": str(e)}
    return {"example_id": eid, "host_of": PROV[eid]["host_of"], "node": PROV[eid]["rebalance_node"],
            "confuser": PROV[eid]["confuser"], "guess": r.get("guess"),
            "caught": r.get("guess") == "A", "confidence": r.get("confidence"),
            "reason": r.get("reasoning") or ""}


def main():
    with ThreadPoolExecutor(max_workers=cfg["run"].get("workers", 4)) as ex:
        res = list(ex.map(judge_one, injected))
    res.sort(key=lambda r: r["example_id"])
    for r in res:
        r["host_baseline_caught"] = base.get(r.get("host_of"), {}).get("caught")
        r["host_baseline_reason"] = base.get(r.get("host_of"), {}).get("reason", "")
    (OUT / "c3_reasons.jsonl").write_text("\n".join(json.dumps(r) for r in res) + "\n", encoding="utf-8")
    caught = sum(1 for r in res if r.get("caught"))
    print(f"judged {len(res)} injected rows (orientation A, 1 sample). caught={caught}/{len(res)}")
    print("wrote out/c3_reasons.jsonl")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())