File size: 8,194 Bytes
bd43184
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
import os
import shutil
import subprocess
import time
from pathlib import Path
from typing import Any


ROOT = Path(__file__).resolve().parents[1]
DEFAULT_EVALS = ROOT / "data" / "codex_tool_calling_eval.jsonl"
WORK_ROOT = ROOT / "tmp" / "codex-eval"


def iter_jsonl(path: Path):
    with path.open() as f:
        for line in f:
            if line.strip():
                yield json.loads(line)


def seed_workspace(case: dict[str, Any], workdir: Path) -> None:
    if workdir.exists():
        shutil.rmtree(workdir)
    workdir.mkdir(parents=True)
    for rel, text in case["files"].items():
        path = workdir / rel
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(text)


def apply_expected_outputs(case: dict[str, Any], workdir: Path) -> None:
    for rel, text in (case.get("verify") or {}).items():
        path = workdir / rel
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(text)
    for rel, needles in (case.get("verify_contains") or {}).items():
        path = workdir / rel
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text("\n".join(needles) + "\n")
    for rel, expected in (case.get("verify_json") or {}).items():
        path = workdir / rel
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(json.dumps(expected, indent=2) + "\n")
    for rel in case.get("verify_missing") or []:
        path = workdir / rel
        if path.exists():
            path.unlink()


def verify_case(case: dict[str, Any], workdir: Path) -> list[str]:
    errors: list[str] = []
    for rel, expected in (case.get("verify") or {}).items():
        path = workdir / rel
        if not path.exists():
            errors.append(f"{rel} is missing")
        elif path.read_text() != expected:
            errors.append(f"{rel} did not match expected content")
    for rel, needles in (case.get("verify_contains") or {}).items():
        path = workdir / rel
        if not path.exists():
            errors.append(f"{rel} is missing")
            continue
        text = path.read_text().lower()
        for needle in needles:
            if needle.lower() not in text:
                errors.append(f"{rel} does not contain {needle!r}")
    for rel, expected in (case.get("verify_json") or {}).items():
        path = workdir / rel
        if not path.exists():
            errors.append(f"{rel} is missing")
            continue
        try:
            actual = json.loads(path.read_text())
        except Exception as exc:
            errors.append(f"{rel} is not valid JSON: {exc}")
            continue
        for key, value in expected.items():
            if actual.get(key) != value:
                errors.append(f"{rel} field {key!r} expected {value!r}, got {actual.get(key)!r}")
    for rel in case.get("verify_missing") or []:
        if (workdir / rel).exists():
            errors.append(f"{rel} still exists")
    command = case.get("verify_command")
    if command:
        proc = subprocess.run(command, cwd=workdir, text=True, capture_output=True, timeout=120)
        if proc.returncode != 0:
            errors.append(f"verify_command failed: {proc.stdout}{proc.stderr}")
    return errors


def parse_events(stdout: str) -> tuple[list[str], list[str]]:
    event_types: list[str] = []
    item_types: list[str] = []
    for line in stdout.splitlines():
        line = line.strip()
        if not line or not line.startswith("{"):
            continue
        try:
            event = json.loads(line)
        except json.JSONDecodeError:
            continue
        if isinstance(event.get("type"), str):
            event_types.append(event["type"])
        item = event.get("item")
        if isinstance(item, dict) and isinstance(item.get("type"), str):
            item_types.append(item["type"])
    return event_types, item_types


def event_errors(case: dict[str, Any], event_types: list[str], item_types: list[str]) -> list[str]:
    observed = set(event_types) | set(item_types)
    expected = set(case.get("expected_events") or [])
    return [f"missing expected event/item type {name}" for name in sorted(expected - observed)]


def self_check_case(case: dict[str, Any]) -> dict[str, Any]:
    workdir = WORK_ROOT / f"self-check-{case['id']}"
    seed_workspace(case, workdir)
    apply_expected_outputs(case, workdir)
    errors = verify_case(case, workdir)
    return {"id": case["id"], "passed": not errors, "verify_errors": errors}


def run_case(case: dict[str, Any], args: argparse.Namespace) -> dict[str, Any]:
    workdir = WORK_ROOT / case["id"]
    seed_workspace(case, workdir)
    last_message = workdir / "last-message.txt"
    command = [
        "codex",
        "-a",
        "never",
        "exec",
        "--json",
        "--ephemeral",
        "--skip-git-repo-check",
        "--color",
        "never",
        "--sandbox",
        args.sandbox,
        "-C",
        str(workdir),
        "-c",
        f"model_provider=\"{args.provider}\"",
        "-m",
        args.model,
        "-o",
        str(last_message),
        case["prompt"],
    ]
    env = os.environ.copy()
    env.setdefault("OMLX_API_KEY", "omlx")

    start = time.time()
    proc = subprocess.run(command, cwd=workdir, text=True, capture_output=True, timeout=args.timeout, env=env)
    event_types, item_types = parse_events(proc.stdout)
    verify_errors = verify_case(case, workdir) if proc.returncode == 0 else ["codex exited nonzero"]
    event_check_errors = event_errors(case, event_types, item_types) if proc.returncode == 0 else []
    return {
        "id": case["id"],
        "returncode": proc.returncode,
        "seconds": round(time.time() - start, 3),
        "passed": proc.returncode == 0 and not verify_errors and not event_check_errors,
        "verify_errors": verify_errors,
        "event_errors": event_check_errors,
        "event_types": sorted(set(event_types)),
        "item_types": sorted(set(item_types)),
        "last_message": last_message.read_text() if last_message.exists() else "",
        "stdout_tail": proc.stdout[-4000:],
        "stderr_tail": proc.stderr[-4000:],
    }


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--evals", type=Path, default=DEFAULT_EVALS)
    parser.add_argument("--model", default="qwen35")
    parser.add_argument("--provider", default="omlx")
    parser.add_argument("--sandbox", default="workspace-write")
    parser.add_argument("--timeout", type=int, default=300)
    parser.add_argument("--limit", type=int)
    parser.add_argument("--self-check", action="store_true", help="Verify eval seed/check logic without invoking Codex.")
    args = parser.parse_args()

    WORK_ROOT.mkdir(parents=True, exist_ok=True)
    cases = list(iter_jsonl(args.evals))
    if args.limit is not None:
        cases = cases[: args.limit]

    results = []
    for case in cases:
        if args.self_check:
            result = self_check_case(case)
        else:
            print(f"running {case['id']}")
            try:
                result = run_case(case, args)
            except subprocess.TimeoutExpired as exc:
                result = {
                    "id": case["id"],
                    "returncode": None,
                    "seconds": args.timeout,
                    "passed": False,
                    "verify_errors": ["codex timed out"],
                    "event_errors": [],
                    "event_types": [],
                    "item_types": [],
                    "last_message": "",
                    "stdout_tail": (exc.stdout or "")[-4000:],
                    "stderr_tail": (exc.stderr or "")[-4000:],
                }
        print(json.dumps(result, indent=2))
        results.append(result)

    out = ROOT / "tmp" / "codex-eval-results.json"
    out.write_text(json.dumps(results, indent=2) + "\n")
    failed = [row for row in results if not row["passed"]]
    print(f"passed {len(results) - len(failed)}/{len(results)}")
    return 1 if failed else 0


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