File size: 7,098 Bytes
2b9a95b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
"""
Claim 1 — run LLM agents on CausalGame and measure whether they recover the causal
mechanism. Models are served via Hugging Face Inference Providers (provider 'hf' added
to run_agent.py / config/agent.json).

For each (model, scenario, mode, seed) we:
  - (re)start the FastAPI backend bound to that scenario,
  - run run_agent.py, capturing the machine-readable result JSON (survival, victory,
    final design, reflection) written via REPRO_RESULT_JSON,
  - derive a behavioral 'causal recovery' signal (did the final design adopt the
    causally-correct lever for that family?),
  - optionally LLM-judge the written report on a causal-reasoning rubric (CR proxy).

Outputs: outputs/llm_results.jsonl (one row per session) + outputs/llm_summary.csv.
"""
import os, sys, json, time, socket, subprocess, argparse, random
from pathlib import Path

HERE = Path(__file__).resolve().parent
CG_ROOT = Path(os.environ.get("CG_ROOT", HERE.parent / "CausalGame"))
OUT = Path("outputs"); OUT.mkdir(exist_ok=True)

# Behavioral 'causal recovery' rule per family:
#   antenna family     -> sacrifice antenna (antenna_def <= 5) => stealth mechanism found
#   deployment family  -> pick signal-filter/hardened enhancement AND shield => EMI comm mechanism
#   weather_noise      -> high antenna_def (>=25) => protect-antenna mechanism
def causal_recovery(scenario, design, equipment):
    design = design or {}
    equipment = equipment or {}
    a = design.get("antenna_def", design.get("antenna", None))
    if scenario.startswith("antenna_trap"):
        return (a is not None) and (a <= 5)
    if scenario.startswith("deployment_zone_trap"):
        eqvals = " ".join(str(v).lower() for v in equipment.values())
        used_filter = any(k in eqvals for k in ["signal_filter", "hardened", "adaptive", "aggressive", "thermal_shield"])
        shield = design.get("shield_def", 0) or 0
        return used_filter or shield >= 20
    if scenario == "weather_noise":
        return (a is not None) and (a >= 25)
    return None


# run_agent.py connects to the base_url in config/server.json (localhost:8000),
# ignoring env overrides, so we always bind the backend to that fixed port and run
# sessions serially.
PORT = int(os.environ.get("CG_PORT", "8000"))


def kill_port(port):
    subprocess.run(["bash", "-lc", f"pkill -f 'uvicorn api.app:app.*--port {port}' 2>/dev/null; "
                                   f"lsof -ti tcp:{port} | xargs kill -9 2>/dev/null"], check=False)
    time.sleep(1)


def start_backend(scenario, port):
    kill_port(port)
    env = dict(os.environ)
    env["CAUSALGAME_EXPERIMENT"] = scenario
    logf = open(OUT / f".server_{scenario}.log", "w")
    proc = subprocess.Popen(
        [sys.executable, "-m", "uvicorn", "api.app:app", "--port", str(port)],
        cwd=str(CG_ROOT), env=env, stdout=logf, stderr=subprocess.STDOUT,
    )
    import urllib.request
    for _ in range(60):
        try:
            urllib.request.urlopen(f"http://localhost:{port}/api/v2/mission_status", timeout=2).read()
            return proc, logf
        except Exception:
            time.sleep(1)
    proc.terminate()
    raise RuntimeError(f"backend for {scenario} did not start")


def run_session(model, scenario, mode, port, seed, timeout=900):
    # Absolute path: the run_agent.py subprocess runs with cwd=CG_ROOT, so a
    # relative outputs/ path would resolve inside the repo and fail to write.
    res_path = (OUT / f".res_{model}_{scenario}_{mode}_{seed}.json").resolve()
    if res_path.exists():
        res_path.unlink()
    env = dict(os.environ)
    env["REPRO_RESULT_JSON"] = str(res_path)
    env["CAUSALGAME_EXPERIMENT"] = scenario
    env["PYTHONHASHSEED"] = str(seed)
    cmd = [sys.executable, "run_agent.py", "--model", model,
           "--experiment", scenario, "--mode", mode]
    logf = OUT / f".sess_{model}_{scenario}_{mode}_{seed}.log"
    t0 = time.time()
    try:
        with open(logf, "w") as lf:
            subprocess.run(cmd, cwd=str(CG_ROOT), env=env, stdout=lf,
                           stderr=subprocess.STDOUT, timeout=timeout)
    except subprocess.TimeoutExpired:
        pass
    dur = time.time() - t0
    row = {"model": model, "scenario": scenario, "mode": mode, "seed": seed,
           "duration_s": round(dur, 1)}
    if res_path.exists():
        try:
            data = json.load(open(res_path))
            row.update({
                "survival_rate": data.get("survival_rate"),
                "victory": data.get("victory"),
                "final_design": data.get("final_design"),
                "equipment": (data.get("final_evaluation") or {}).get("equipment"),
                "reflection": data.get("reflection"),
                "tokens": data.get("tokens"),
                "success": data.get("success"),
            })
        except Exception as e:
            row["parse_error"] = str(e)
    else:
        row["error"] = "no result json"
    row["causal_recovery"] = causal_recovery(scenario, row.get("final_design"), row.get("equipment"))
    return row


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--models", nargs="+", required=True)
    ap.add_argument("--scenarios", nargs="+", required=True)
    ap.add_argument("--modes", nargs="+", default=["legacy"])
    ap.add_argument("--repeats", type=int, default=1)
    ap.add_argument("--timeout", type=int, default=900)
    ap.add_argument("--out", default=str(OUT / "llm_results.jsonl"))
    args = ap.parse_args()

    results = []
    outp = Path(args.out)
    fout = open(outp, "a")
    for scenario in args.scenarios:
        port = PORT
        proc, logf = start_backend(scenario, port)
        print(f"\n### backend up for {scenario} on :{port}", flush=True)
        try:
            for model in args.models:
                for mode in args.modes:
                    for seed in range(args.repeats):
                        print(f"  -> {model} | {scenario} | {mode} | seed {seed}", flush=True)
                        row = run_session(model, scenario, mode, port, seed, timeout=args.timeout)
                        sr = row.get("survival_rate")
                        print(f"     survival={sr} victory={row.get('victory')} "
                              f"causal_recovery={row.get('causal_recovery')} ({row.get('duration_s')}s)", flush=True)
                        results.append(row)
                        fout.write(json.dumps(row) + "\n"); fout.flush()
        finally:
            proc.terminate()
            try:
                proc.wait(timeout=10)
            except Exception:
                proc.kill()
            logf.close()
    fout.close()

    # summary CSV
    import csv
    cols = ["model", "scenario", "mode", "seed", "survival_rate", "victory",
            "causal_recovery", "duration_s"]
    with open(OUT / "llm_summary.csv", "w", newline="") as f:
        w = csv.writer(f); w.writerow(cols)
        for r in results:
            w.writerow([r.get(c) for c in cols])
    print(f"\nWrote {outp} and outputs/llm_summary.csv ({len(results)} sessions)")


if __name__ == "__main__":
    main()