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
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
#!/usr/bin/env python3
"""One-shot stage executor for the TrajWiki Table 10 reproduction.

Runs the stage named in ./stage.txt on Space startup, pushes its result to the
bundle dataset repo, then serves a status page on $APP_PORT.

Stages:
  idle          no-op
  router-test   verify HF router serves gpt-4o-mini and claude-sonnet-4-6
  data          download official LoCoMo, convert to adapter layout, upload
                category files + integrity report
  setup         clone TrajWiki @ pinned commit, install package, verify CLI
                flags, run mock-provider smoke test, upload logs
"""
from __future__ import annotations

import io
import json
import os
import shutil
import subprocess
import sys
import tarfile
import threading
import time
import traceback
import urllib.request
import zipfile
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path

from huggingface_hub import HfApi

REPO_ID = "Neurips-2026-MLIntern-Repro/trajwiki-table10-repro"
DEST_MIRROR = "Frame17/trajwiki-repro-mirror"   # user-owned: direct write
DEST_PUBLIC = "Neurips-2026-MLIntern-Repro/trajwiki-table10-repro"  # PR best-effort
SPACE_ID = "Neurips-2026-MLIntern-Repro/trajwiki-executor"
MIRROR_ID = "Frame17/trajwiki-executor-private"
SHARED_FILES = ["Dockerfile", "executor_entrypoint.py"]
WORK = Path("/tmp/work")
PINNED_COMMIT = "79b5b51043b3475308130725125eea9f0c442a0b"
TARBALL_URL = (
    "https://codeload.github.com/JingyuSunUOE/TrajWiki/tar.gz/" + PINNED_COMMIT
)
LOCOMO_URL = (
    "https://raw.githubusercontent.com/snap-research/LoCoMo/main/data/locomo10.json"
)
# Model substitution (documented deviation): the paper's exact models are not
# served by HF Inference Providers (router-test enumerated the full catalog:
# no gpt-4o-mini, no claude-*). Structural analogs chosen instead:
#   backbone: openai/gpt-oss-20b  (small OpenAI-weights generator)
#   judge:    GLM-5.3-Flash / DeepSeek-V4.1-Flash (non-OpenAI family, blinded)
BACKBONE_MODEL = "openai/gpt-oss-20b"
JUDGE_MODEL_CANDIDATES = ["zai-org/GLM-5.3-Flash", "deepseek-ai/DeepSeek-V4.1-Flash"]
PAPER_BACKBONE_MODEL = "openai/gpt-4o-mini"
PAPER_JUDGE_MODEL = "anthropic/claude-sonnet-4-6"
CLAIM_FLAGS = [
    "--sample-size", "--variants", "--sampling-profile", "--sample-seed",
    "--max-total-tokens", "--max-output-tokens", "--token-counter",
    "--independent-judge-provider-kind", "--independent-judge-model",
]
STATUS_HTML = Path("/tmp/status.html")


def read_stage() -> str:
    path = Path(__file__).parent / "stage.txt"
    if not path.exists():
        return "idle"
    # Stage name is the FIRST line; remaining lines are human annotations.
    lines = [line.strip() for line in path.read_text(encoding="utf-8").splitlines()]
    lines = [line for line in lines if line and not line.startswith("#")]
    return lines[0] if lines else "idle"


def hf_api() -> HfApi:
    token = os.environ.get("HF_TOKEN")
    if not token:
        raise RuntimeError(
            "HF_TOKEN Space secret is not set. Add it in Space settings "
            "(Settings > Variables and secrets > New secret > HF_TOKEN)."
        )
    return HfApi(token=token)


def push_file(name: str, data: bytes) -> dict:
    """Push to the user-owned mirror repo directly, and best-effort as a PR to
    the public bundle repo (org policy may forbid direct main commits)."""
    ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
    path_in_repo = f"logs/{ts}_{name}"
    api = hf_api()
    outcomes: dict = {}
    for repo_id, create_pr in [(DEST_MIRROR, False), (DEST_PUBLIC, True)]:
        try:
            api.upload_file(
                path_or_fileobj=data, path_in_repo=path_in_repo,
                repo_id=repo_id, repo_type="dataset", create_pr=create_pr,
            )
            outcomes[repo_id] = "ok"
        except Exception as exc:  # noqa: BLE001
            outcomes[repo_id] = f"error: {str(exc)[:250]}"
    return {"path_in_repo": path_in_repo, "destinations": outcomes}


def push_result(stage: str, payload: dict) -> dict:
    payload = dict(payload, stage=stage)
    try:
        payload["result_url"] = push_file(
            stage, json.dumps(payload, indent=2, ensure_ascii=False).encode("utf-8"))
    except Exception as exc:  # noqa: BLE001
        payload["push_error"] = f"{exc}"
    return payload


def run(cmd: list[str], **kw) -> subprocess.CompletedProcess:
    proc = subprocess.run(cmd, capture_output=True, text=True, **kw)
    if proc.returncode != 0:
        tail = (proc.stdout[-1500:] + "\n" + proc.stderr[-2500:])
        raise RuntimeError(f"command failed ({' '.join(map(str, cmd[:4]))}...):\n{tail}")
    return proc


def download(url: str, dest: Path) -> None:
    dest.parent.mkdir(parents=True, exist_ok=True)
    with urllib.request.urlopen(url, timeout=120) as resp, dest.open("wb") as out:
        shutil.copyfileobj(resp, out)


# ---------------------------------------------------------------- stage: data
def stage_data() -> dict:
    download(LOCOMO_URL, WORK / "locomo10.json")
    conv = run([sys.executable, "convert_locomo.py",
                "--source", str(WORK / "locomo10.json"),
                "--out-dir", str(WORK / "locomo")])
    report = json.loads((WORK / "locomo" / "conversion_report.json").read_text())
    report["converter_stdout_tail"] = conv.stdout[-800:]
    uploaded = []
    for name in sorted(p.name for p in (WORK / "locomo").glob("category_*.jsonl")):
        data = (WORK / "locomo" / name).read_bytes()
        uploaded.append(push_file(f"data_{name}", data))
    # multi-hop row count is the one the claim depends on
    multi = report["rows_per_category"].get("category_1_multi_hop.jsonl", {})
    return {"report": report, "uploaded": uploaded,
            "multi_hop_queries": multi.get("queries"),
            "multi_hop_conversations": multi.get("conversations")}


# --------------------------------------------------------------- stage: setup
def stage_setup() -> dict:
    api = hf_api()
    name = "category_1_multi_hop.jsonl"
    data_dir = WORK / "locomo"
    data_dir.mkdir(parents=True, exist_ok=True)
    for repo_id in (DEST_MIRROR, DEST_PUBLIC):
        try:
            files = api.list_repo_files(repo_id=repo_id, repo_type="dataset")
        except Exception:  # noqa: BLE001
            continue
        match = [f for f in files if f.startswith("logs/") and f.endswith(".jsonl")
                 and "category_1_multi_hop" in f and "data_" in f]
        if match:
            local = api.hf_hub_download(repo_id=repo_id, repo_type="dataset",
                                        filename=sorted(match)[-1])
            (data_dir / name).write_bytes(Path(local).read_bytes())
            break
    else:
        raise RuntimeError("data-stage output not found in mirror or bundle repo — run the 'data' stage first")

    repo_dir = WORK / "TrajWiki"
    with urllib.request.urlopen(TARBALL_URL, timeout=120) as resp:
        with tarfile.open(fileobj=io.BytesIO(resp.read()), mode="r:gz") as tar:
            tar.extractall(WORK)
    extracted = list(WORK.glob("TrajWiki-*"))
    if len(extracted) != 1:
        raise RuntimeError(f"expected one extracted dir, found {[p.name for p in extracted]}")
    extracted[0].rename(repo_dir)
    commit_file = (repo_dir / ".git_commit.txt")
    commit_file.write_text(PINNED_COMMIT)

    env = {**os.environ, "PYTHONPATH": str(repo_dir / "src"), "PATH": os.environ["PATH"]}
    # TrajWiki requires Python >= 3.11; the Space runtime is 3.10. Build a 3.11
    # venv with uv (no root needed) and run all pipeline steps from it.
    run([sys.executable, "-m", "pip", "install", "--quiet", "uv"], env=env)
    run([sys.executable, "-m", "uv", "python", "install", "3.11"], env=env)
    run([sys.executable, "-m", "uv", "venv", "--python", "3.11", str(WORK / "venv")],
        env=env)
    py = str(WORK / "venv" / "bin" / "python")
    run([sys.executable, "-m", "uv", "pip", "install", "--python", py,
         "--no-cache-dir", "-e", str(repo_dir)], env=env)
    help_text = run([py, "-m", "trajpatch", "run-answer-ablation", "--help"],
                    env=env).stdout
    push_file("setup_help.txt", help_text.encode("utf-8"))
    ansi = __import__("re").compile(r"\x1b\\[[0-9;]*m")
    help_flat = ansi.sub("", help_text).replace("\n", " ").replace("\\", "")
    missing = [f for f in CLAIM_FLAGS if f not in help_flat]
    if missing:  # rich help may wrap long flags mid-token; verify against source
        cli_src = (repo_dir / "src" / "trajpatch" / "cli.py").read_text(encoding="utf-8")
        still = [f for f in missing if f not in cli_src]
        if still:
            raise RuntimeError(
                f"claim-critical flags missing even in cli.py source at pinned "
                f"commit: {still}")
        missing = []  # present in source; help wrapping was the artifact
    smoke = run([py, "-m", "trajpatch", "benchmark-locomo",
                 "--dataset-path", str(data_dir), "--subset", "multi_hop",
                 "--backbone-provider-kind", "mock", "--judge-provider-kind", "mock",
                 "--embedding-model", "hash-embedding", "--max-samples", "1",
                 "--output-dir", str(WORK / "smoke")], env=env)
    return {
        "pinned_commit": PINNED_COMMIT,
        "claim_flags_verified": CLAIM_FLAGS,
        "smoke_tail": smoke.stdout[-2500:],
    }


# ----------------------------------------------------------- stage: router test
def _router_candidates(listing: dict) -> dict:
    gpt = ["openai/gpt-4o-mini", "gpt-4o-mini"]
    sonnet = ["anthropic/claude-sonnet-4-6", "claude-sonnet-4-6"]
    seen_g, seen_s = set(gpt), set(sonnet)
    for name in listing.get("all", []):
        low = name.lower()
        if "gpt-4o-mini" in low and name not in seen_g:
            gpt.append(name); seen_g.add(name)
        if "sonnet" in low and "claude" in low and name not in seen_s:
            sonnet.append(name); seen_s.add(name)
    return {"gpt": gpt[:6], "sonnet": sonnet[:6]}


def _probe(router, candidates: list[str]) -> dict:
    attempts = {}
    for model in candidates:
        try:
            r = router.chat.completions.create(
                model=model,
                messages=[{"role": "user", "content": "Reply with exactly: OK"}],
                max_tokens=8,
            )
            attempts[model] = {"ok": True, "content": r.choices[0].message.content,
                               "prompt_tokens": r.usage.prompt_tokens,
                               "completion_tokens": r.usage.completion_tokens}
            return {"ok_model": model, "attempts": attempts,
                    "detail": attempts[model]}
        except Exception as exc:  # noqa: BLE001
            attempts[model] = {"ok": False, "error": repr(exc)[:300]}
    return {"ok_model": None, "attempts": attempts}


def _probe_json_schema(router, model: str) -> dict:
    """Does the router honor response_format json_schema for this model?"""
    schema = {"type": "object", "properties": {"answer": {"type": "string"}},
              "required": ["answer"], "additionalProperties": False}
    try:
        r = router.chat.completions.create(
            model=model,
            messages=[{"role": "user", "content": 'Return {"answer": "OK"}'}],
            max_tokens=64,
            response_format={"type": "json_schema",
                             "json_schema": {"name": "probe", "strict": True,
                                             "schema": schema}},
        )
        content = r.choices[0].message.content or ""
        return {"ok": True, "content": content[:120]}
    except Exception as exc:  # noqa: BLE001
        return {"ok": False, "error": repr(exc)[:300]}


def stage_router_test() -> dict:
    from openai import OpenAI

    router = OpenAI(base_url="https://router.huggingface.co/v1",
                    api_key=os.environ["HF_TOKEN"])
    listing: dict = {}
    try:
        names = sorted(m.id for m in router.models.list())
        listing = {
            "total": len(names),
            "all": names,
            "gpt4omini_hits": [n for n in names if "gpt-4o-mini" in n.lower()],
            "claude_sonnet_hits": [n for n in names
                                   if "sonnet" in n.lower() and "claude" in n.lower()],
        }
    except Exception as exc:  # noqa: BLE001
        listing = {"error": repr(exc)[:400]}
    candidates = _router_candidates(listing)
    substitutes = _probe(router, [BACKBONE_MODEL])
    judges = _probe(router, JUDGE_MODEL_CANDIDATES)
    structured = _probe_json_schema(router, BACKBONE_MODEL) \
        if substitutes.get("ok_model") else {"skipped": True}
    return {"paper_models": {"backbone": candidates["gpt"],
                             "judge": candidates["sonnet"]},
            "listing": {k: v for k, v in listing.items() if k != "all"},
            "backbone_substitute": substitutes,
            "judge_substitutes": judges,
            "backbone_json_schema": structured}


def stage_mirror() -> dict:
    """Mirror mode: execute nothing; verify file parity with the org Space.
    Runs on the private Frame17 mirror Space. Reads are public-only (no token
    needed), and local files are compared against the org Space's files.
    """
    api = HfApi()
    parity = {}
    for name in SHARED_FILES + ["stage.txt"]:
        try:
            local = (Path(__file__).parent / name).read_bytes()
        except OSError as exc:
            parity[name] = f"local-missing: {exc}"
            continue
        try:
            remote = Path(api.hf_hub_download(
                repo_id=SPACE_ID, repo_type="space", filename=name)).read_bytes()
            parity[name] = "match" if local == remote else "DIFFER"
        except Exception as exc:  # noqa: BLE001
            parity[name] = f"org-read-error: {exc}"
    try:
        org_stage = Path(api.hf_hub_download(
            repo_id=SPACE_ID, repo_type="space", filename="stage.txt"
        )).read_text(encoding="utf-8").strip()
    except Exception as exc:  # noqa: BLE001
        org_stage = f"org-read-error: {exc}"
    differ = [k for k, v in parity.items() if v != "match"]
    return {"mode": "mirror", "parity": parity, "org_stage": org_stage,
            "note": "mirror executes no stages; set stage.txt to a real stage here "
                    "to make this Space the compute engine (failover)",
            "parity_ok": not differ}


STAGES = {"router-test": stage_router_test, "data": stage_data,
          "setup": stage_setup, "mirror": stage_mirror}


def run_stage(stage: str) -> dict:
    started = datetime.now(timezone.utc).isoformat()
    try:
        payload = STAGES[stage]() if stage in STAGES else {
            "error": f"unknown stage {stage!r}"}
    except Exception as exc:  # noqa: BLE001
        payload = {"error": f"{exc}",
                   "traceback": traceback.format_exc()[-3000:]}
    payload["started_at"] = started
    payload["finished_at"] = datetime.now(timezone.utc).isoformat()
    return push_result(stage, payload)


def write_status(payload: dict) -> None:
    STATUS_HTML.parent.mkdir(parents=True, exist_ok=True)
    STATUS_HTML.write_text(
        "<html><body><h1>TrajWiki executor</h1><pre>"
        + json.dumps(payload, indent=2, ensure_ascii=False)
        + "</pre></body></html>", encoding="utf-8")


def serve() -> None:
    port = int(os.environ.get("APP_PORT") or 7860)

    class Handler(BaseHTTPRequestHandler):
        def do_GET(self) -> None:  # noqa: N802
            body = STATUS_HTML.read_bytes() if STATUS_HTML.exists() else b"starting..."
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

        def log_message(self, *args) -> None:
            pass

    HTTPServer(("0.0.0.0", port), Handler).serve_forever()


def main() -> None:
    stage = read_stage()
    threading.Thread(target=serve, daemon=True).start()
    payload = run_stage(stage)
    write_status(payload)
    print(json.dumps(payload, indent=2, ensure_ascii=False), flush=True)
    while True:
        time.sleep(60)


if __name__ == "__main__":
    main()