diff --git a/.github/workflows/model.yml b/.github/workflows/model.yml index 661f33a..cfd0c35 100644 --- a/.github/workflows/model.yml +++ b/.github/workflows/model.yml @@ -113,7 +113,9 @@ jobs: uv run --project model/benchmark --locked --extra cuda --extra data --python 3.12 python model/ci.py evaluate --directory "$RUN_DIR" - name: Require strict improvement - run: python3 model/ci.py report --directory "$RUN_DIR" $BOOTSTRAP + run: >- + uv run --project model/benchmark --locked --extra cuda --extra data --python 3.12 + python model/ci.py report --directory "$RUN_DIR" $BOOTSTRAP - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 if: always() with: diff --git a/README.md b/README.md index 1f80394..41e7f0c 100644 --- a/README.md +++ b/README.md @@ -43,22 +43,8 @@ https://github.com/user-attachments/assets/3b46a5d7-b39b-40f7-8575-fd3f6f0c1d7a Accepted adapter: [LongLink/pyshell-worker](https://huggingface.co/LongLink/pyshell-worker/tree/4064ca4a5ebab1c97dd166133a74be4231771973). Base model: `Qwen/Qwen3.5-0.8B`. -**Execution success: 15.00% (9/60 tasks).** - -| Category | Passed | Success | -| --- | ---: | ---: | -| Filtered means | 0/5 | 0.00% | -| Grouped revenue | 0/5 | 0.00% | -| Inspect callable | 1/5 | 20.00% | -| Joined totals | 0/5 | 0.00% | -| Left join | 0/5 | 0.00% | -| Linear system | 2/5 | 40.00% | -| Missing input | 2/5 | 40.00% | -| Missing values | 0/5 | 0.00% | -| Monthly totals | 0/5 | 0.00% | -| Recover execution | 0/5 | 0.00% | -| Stateful followup | 2/5 | 40.00% | -| Statistics | 2/5 | 40.00% | +**Task success: 15.00% (9/60 tasks).** +**Valid Python: 99.08% (215/217 responses).** diff --git a/model/benchmark/src/evaluate.py b/model/benchmark/src/evaluate.py index 7092eb4..e8442ea 100644 --- a/model/benchmark/src/evaluate.py +++ b/model/benchmark/src/evaluate.py @@ -1,6 +1,7 @@ import json from pathlib import Path from contextlib import ExitStack, closing +from model.benchmark.src import scoring from model.benchmark.src.trial import trial from model.benchmark.src.settings import Settings from model.benchmark.src.execution import Worker @@ -18,7 +19,6 @@ def run(config: Settings) -> None: generate = HFCompletion(config) config.output.parent.mkdir(parents=True, exist_ok=True) - passed = 0 with config.output.open("x") as file, ExitStack() as stack: workers = [] for _ in range(min(config.batch_size, len(records))): @@ -40,7 +40,6 @@ def run(config: Settings) -> None: row = result.value file.write(json.dumps(row) + "\n") file.flush() - passed += row["status"] == "passed" completed += 1 print(f"{completed}/{len(records)}: {row['id']} {row['status']}", flush=True) record = next(remaining, None) @@ -50,4 +49,5 @@ def run(config: Settings) -> None: prompt = next(task) pending.append((worker, task, prompt)) active = pending - print(f"Passed {passed}/{len(records)} ({passed / len(records):.1%})", flush=True) + rows = [json.loads(line) for line in config.output.read_text().splitlines()] + print(scoring.summary(scoring.score(rows)), flush=True) diff --git a/model/benchmark/src/scoring.py b/model/benchmark/src/scoring.py new file mode 100644 index 0000000..7ac2612 --- /dev/null +++ b/model/benchmark/src/scoring.py @@ -0,0 +1,42 @@ +import ast +from collections.abc import Sequence + + +def score(rows: Sequence[dict]) -> dict: + """Score task outcomes and Python syntax across all generated responses.""" + if not rows or len({row["id"] for row in rows}) != len(rows): + raise ValueError("Evaluation must contain unique, nonempty tasks") + statuses = {"passed", "incorrect", "call_limit", "boundary_error"} + if any(row["status"] not in statuses for row in rows): + raise ValueError("Unknown evaluation status") + generations = 0 + valid_python = 0 + for row in rows: + for step in row.get("steps", []): + source = step["source"] + if not isinstance(source, str): + raise ValueError("Generated source must be text") + generations += 1 + try: + tree = ast.parse(source) + compile(tree, "", "exec") + except (SyntaxError, ValueError): + continue + valid_python += bool(tree.body) + passed = sum(row["status"] == "passed" for row in rows) + return { + "passed": passed, + "total": len(rows), + "generations": generations, + "success_rate": passed / len(rows), + "valid_python": valid_python, + "valid_python_rate": valid_python / generations if generations else None, + } + + +def summary(result: dict) -> str: + """Format both aggregate scores with their distinct denominators.""" + python = "not measured (0 responses)" + if result["valid_python_rate"] is not None: + python = f"{result['valid_python_rate']:.2%} ({result['valid_python']}/{result['generations']} responses)" + return f"Task success: {result['success_rate']:.2%} ({result['passed']}/{result['total']} tasks)\nValid Python: {python}" diff --git a/model/benchmark/src/worker.py b/model/benchmark/src/worker.py index cf3c008..4dce2ae 100644 --- a/model/benchmark/src/worker.py +++ b/model/benchmark/src/worker.py @@ -1,3 +1,4 @@ +import io import os import sys import json @@ -21,6 +22,7 @@ def main() -> None: from api.shell import PythonShell protocol = sys.stdout + incoming = sys.stdin shell = None handler = signal.signal(signal.SIGALRM, deadline) @@ -36,11 +38,15 @@ def publish(result: dict[str, Any]) -> None: if request["action"] not in ("reset", "execute"): raise ValueError("Unsupported worker action") signal.alarm(10) - with contextlib.redirect_stdout(sink), contextlib.redirect_stderr(sink): - if request["action"] == "reset": - shell = PythonShell() - shell.namespace.update(np=np, pd=pd, statistics=statistics, json=json) - result = shell.execute(request["source"]) + with io.StringIO() as stdin, contextlib.redirect_stdout(sink), contextlib.redirect_stderr(sink): + sys.stdin = stdin + try: + if request["action"] == "reset": + shell = PythonShell() + shell.namespace.update(np=np, pd=pd, statistics=statistics, json=json) + result = shell.execute(request["source"]) + finally: + sys.stdin = incoming signal.alarm(0) publish(result) except BaseException as error: diff --git a/model/benchmark/tests/test_evaluate.py b/model/benchmark/tests/test_evaluate.py index c08ed1e..253dc27 100644 --- a/model/benchmark/tests/test_evaluate.py +++ b/model/benchmark/tests/test_evaluate.py @@ -19,7 +19,8 @@ def benchmark(tmp_path, monkeypatch): worker = Mock() monkeypatch.setattr(evaluate, "Worker", worker) rows = [ - {**record, "status": status, "steps": []} for record, status in zip(records, ("passed", "incorrect", "call_limit"), strict=True) + {**record, "status": status, "steps": [{"source": "result = 1"}]} + for record, status in zip(records, ("passed", "incorrect", "call_limit"), strict=True) ] def task(worker, record, calls): @@ -37,7 +38,9 @@ def test_run_evaluates_one_adapter_and_saves_results(benchmark, capsys): assert [json.loads(line) for line in config.output.read_text().splitlines()] == rows model.assert_called_once_with(config) worker.return_value.close.assert_called_once_with() - assert "Passed 1/3 (33.3%)" in capsys.readouterr().out + output = capsys.readouterr().out + assert "Task success: 33.33% (1/3 tasks)" in output + assert "Valid Python: 100.00% (3/3 responses)" in output def test_existing_results_are_not_overwritten(benchmark): diff --git a/model/benchmark/tests/test_scoring.py b/model/benchmark/tests/test_scoring.py new file mode 100644 index 0000000..cda7342 --- /dev/null +++ b/model/benchmark/tests/test_scoring.py @@ -0,0 +1,50 @@ +import pytest +from model.benchmark.src import scoring + + +@pytest.mark.parametrize( + ("source", "valid"), + [ + ("result = sum(values)", True), + ("print(missing_variable)", True), + ("raise AssertionError('must not execute')", True), + ("def answer():\n return 42", True), + ("", False), + (" \n# only a comment\n", False), + ("```python\nresult = 42\n```", False), + ("Here is the Python code:\nresult = 42", False), + ("result = 42\nThe answer is forty two.", False), + ("result =", False), + ("return 42", False), + ("break", False), + ("result = 42\x00", False), + ("<|end_code|>", False), + ], +) +def test_python_validity_checks_unmodified_source_without_executing_it(source, valid): + result = scoring.score([{"id": "task", "status": "incorrect", "steps": [{"source": source}]}]) + assert result["valid_python"] == int(valid) + assert result["valid_python_rate"] == float(valid) + assert result["success_rate"] == 0 + + +def test_syntax_scores_all_responses_and_task_success_scores_tasks(): + rows = [ + {"id": "a", "status": "passed", "steps": [{"source": "result ="}, {"source": "result = 1"}]}, + {"id": "b", "status": "call_limit", "steps": [{"source": "# empty"}, {"source": "print(missing)"}]}, + {"id": "c", "status": "boundary_error", "steps": [{"source": "result = 1"}]}, + ] + result = scoring.score(rows) + assert result == {"passed": 1, "total": 3, "generations": 5, "success_rate": 1 / 3, "valid_python": 3, "valid_python_rate": 0.6} + assert scoring.summary(result) == "Task success: 33.33% (1/3 tasks)\nValid Python: 60.00% (3/5 responses)" + + +def test_older_results_without_generations_are_not_reported_as_zero_percent(): + result = scoring.score([{"id": "a", "status": "passed"}]) + assert result["valid_python_rate"] is None + assert "Valid Python: not measured (0 responses)" in scoring.summary(result) + + +def test_nontext_source_is_rejected(): + with pytest.raises(ValueError, match="must be text"): + scoring.score([{"id": "a", "status": "passed", "steps": [{"source": 42}]}]) diff --git a/model/benchmark/tests/test_worker.py b/model/benchmark/tests/test_worker.py index 761ea40..05432f6 100644 --- a/model/benchmark/tests/test_worker.py +++ b/model/benchmark/tests/test_worker.py @@ -22,12 +22,32 @@ def run_worker(self, requests, protocol=None): worker.main() assert sys.stdout is protocol assert sys.stderr is errors + assert sys.stdin is incoming assert errors.getvalue() == "" lines = protocol.getvalue().splitlines() assert len(lines) == len(requests) return [json.loads(line) for line in lines] + @pytest.mark.parametrize("source", ["exit(1)", "quit(1)", "import sys; sys.stdin.close()", "input()"]) + def test_generated_code_cannot_close_or_consume_protocol_input(self, source): + results = self.run_worker( + [ + {"action": "reset", "source": "value = 42"}, + {"action": "execute", "source": source}, + {"action": "execute", "source": "print(value)"}, + {"action": "reset", "source": "print('new task')"}, + ] + ) + if source in ("exit(1)", "quit(1)"): + assert "SystemExit" in results[1]["exception"] + assert results[1]["done"] is None + elif source == "input()": + assert "EOFError" in results[1]["exception"] + assert results[2]["stdout"] == "42\n" + assert results[2]["exception"] is None + assert results[3]["stdout"] == "new task\n" + @pytest.mark.parametrize("requests", [[], [{"action": "reset", "source": "pass"}]]) def test_previous_signal_handler_is_restored_on_eof(self, requests): def previous_handler(_signal, _frame): diff --git a/model/ci.py b/model/ci.py index b8c862d..e59dfb3 100644 --- a/model/ci.py +++ b/model/ci.py @@ -6,7 +6,6 @@ import shutil import subprocess import sys -from collections import Counter from pathlib import Path @@ -24,23 +23,10 @@ def changes(paths: list[str]) -> bool: def score(path: Path) -> dict: + from model.benchmark.src import scoring + rows = [json.loads(line) for line in path.read_text().splitlines()] - if not rows or len({row["id"] for row in rows}) != len(rows): - raise ValueError("Evaluation must contain unique, nonempty tasks") - statuses = {"passed", "incorrect", "call_limit", "boundary_error"} - if any(row["status"] not in statuses for row in rows): - raise ValueError("Unknown evaluation status") - families = Counter(row["family"] for row in rows) - passed = Counter(row["family"] for row in rows if row["status"] == "passed") - return { - "passed": sum(passed.values()), - "total": len(rows), - "success_rate": sum(passed.values()) / len(rows), - "families": { - family: {"passed": passed[family], "total": total} - for family, total in sorted(families.items()) - }, - } + return scoring.score(rows) def compare(candidate: Path, baseline: Path) -> dict: @@ -94,7 +80,6 @@ def train(directory: Path) -> None: def evaluate(directory: Path, adapter: str, output: str) -> None: - sys.path.insert(0, str(Path.cwd())) from model.benchmark.src import evaluate, settings config = settings.Settings.model_validate( @@ -119,6 +104,8 @@ def evaluate(directory: Path, adapter: str, output: str) -> None: def report(directory: Path, bootstrap: bool) -> None: + from model.benchmark.src import scoring + result = {"candidate": score(directory / "candidate.jsonl"), "improved": True} if not bootstrap: result = compare(directory / "candidate.jsonl", directory / "baseline.jsonl") @@ -135,9 +122,9 @@ def report(directory: Path, bootstrap: bool) -> None: f"{os.environ['GITHUB_REPOSITORY']}/actions/runs/{os.environ['GITHUB_RUN_ID']}" ) (directory / "metrics.json").write_text(json.dumps(result, indent=2) + "\n") - summary = f"Candidate: {result['candidate']['success_rate']:.2%}\n" + summary = f"Candidate:\n{scoring.summary(result['candidate'])}\n" if not bootstrap: - summary += f"Accepted: {result['baseline']['success_rate']:.2%}\n" + summary += f"Accepted:\n{scoring.summary(result['baseline'])}\n" summary += ( "Bootstrap baseline\n" if bootstrap else f"Improved: {result['improved']}\n" ) @@ -205,15 +192,14 @@ def readme(content: str, directory: Path, repo: str, revision: str) -> str: f"Accepted adapter: [{repo}](https://huggingface.co/{repo}/tree/{revision}).", f"Base model: `{adapter['base_model_name_or_path']}`.", "", - f"**Execution success: {score['success_rate']:.2%} ({score['passed']}/{score['total']} tasks).**", - "", - "| Category | Passed | Success |", - "| --- | ---: | ---: |", + f"**Task success: {score['success_rate']:.2%} ({score['passed']}/{score['total']} tasks).**", ] - for family, result in sorted(score["families"].items()): + if score.get("valid_python_rate") is None: + lines.append("**Valid Python: not measured.**") + else: lines.append( - f"| {family.replace('_', ' ').capitalize()} | {result['passed']}/{result['total']} | " - f"{result['passed'] / result['total']:.2%} |" + f"**Valid Python: {score['valid_python_rate']:.2%} " + f"({score['valid_python']}/{score['generations']} responses).**" ) if metrics.get("evaluated_at") or metrics.get("workflow"): lines.append("") @@ -302,7 +288,6 @@ def main() -> None: if args.command == "baseline": baseline(directory, args.repo, args.bootstrap) elif args.command == "train": - sys.path.insert(0, str(Path.cwd())) train(directory) elif args.command == "evaluate": evaluate(directory, args.adapter, args.output) @@ -315,4 +300,5 @@ def main() -> None: if __name__ == "__main__": + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) main() diff --git a/model/tests/test_ci.py b/model/tests/test_ci.py index 6b686f7..14f7d49 100644 --- a/model/tests/test_ci.py +++ b/model/tests/test_ci.py @@ -86,7 +86,8 @@ def test_only_strict_improvement_passes(tmp_path, statuses, improved): comparison = ci.compare(candidate, baseline) assert comparison["improved"] is improved assert comparison["baseline"]["success_rate"] == 0.5 - assert comparison["candidate"]["families"]["arithmetic"]["total"] == 2 + assert comparison["candidate"]["total"] == 2 + assert "families" not in comparison["candidate"] @pytest.mark.parametrize("content", ["", '{"id":"x","family":"f","status":"error"}\n']) @@ -121,7 +122,28 @@ def test_failed_gate_preserves_metrics(tmp_path, status): assert json.loads((tmp_path / "metrics.json").read_text())["improved"] is False -def test_improved_candidate_passes_on_current_benchmark(tmp_path, monkeypatch): +def test_better_python_validity_does_not_bypass_task_success_gate(tmp_path, capsys): + for name, source in (("baseline", "result ="), ("candidate", "result = 1")): + row = { + "id": "task", + "family": "arithmetic", + "status": "incorrect", + "steps": [{"source": source}], + } + (tmp_path / f"{name}.jsonl").write_text(json.dumps(row) + "\n") + (tmp_path / "baseline.json").write_text('{"repo":"example/model","revision":"old"}') + with pytest.raises(SystemExit, match="strictly improve"): + ci.report(tmp_path, False) + metrics = json.loads((tmp_path / "metrics.json").read_text()) + assert metrics["candidate"]["valid_python_rate"] == 1 + assert metrics["baseline"]["valid_python_rate"] == 0 + assert metrics["improved"] is False + output = capsys.readouterr().out + assert "Valid Python: 100.00% (1/1 responses)" in output + assert "Valid Python: 0.00% (0/1 responses)" in output + + +def test_improved_candidate_passes_on_current_benchmark(tmp_path, monkeypatch, capsys): monkeypatch.setenv("GITHUB_REPOSITORY", "example/pyshell") monkeypatch.setenv("GITHUB_RUN_ID", "42") results(tmp_path / "candidate.jsonl", ["passed", "passed"]) @@ -136,6 +158,8 @@ def test_improved_candidate_passes_on_current_benchmark(tmp_path, monkeypatch): datetime.timedelta(0) ) assert metrics["workflow"] == "https://github.com/example/pyshell/actions/runs/42" + assert "Task success: 100.00% (2/2 tasks)" in capsys.readouterr().out + assert metrics["candidate"]["valid_python_rate"] is None def test_both_adapters_use_current_benchmark_and_identical_settings( @@ -279,10 +303,9 @@ def accepted_model(tmp_path): "passed": 1, "total": 3, "success_rate": 1 / 3, - "families": { - "statistics": {"passed": 1, "total": 2}, - "left_join": {"passed": 0, "total": 1}, - }, + "generations": 4, + "valid_python": 3, + "valid_python_rate": 0.75, }, "baseline": {"passed": 0, "total": 3, "success_rate": 0}, "workflow": "https://github.com/example/pyshell/actions/runs/42", @@ -304,8 +327,8 @@ def test_readme_replaces_only_model_statistics_and_is_idempotent(accepted_model) assert "Evaluated commit:" not in updated assert "Development benchmark:" not in updated assert "Budget:" not in updated - assert "| Left join | 0/1 | 0.00% |" in updated - assert "| Statistics | 1/2 | 50.00% |" in updated + assert "Valid Python: 75.00% (3/4 responses)" in updated + assert "Category" not in updated assert "https://huggingface.co/example/model/tree/accepted-revision" in updated assert "2026-11-10T12:00:00+00:00" in updated assert "https://github.com/example/pyshell/actions/runs/42" in updated @@ -314,6 +337,24 @@ def test_readme_replaces_only_model_statistics_and_is_idempotent(accepted_model) ) +def test_readme_does_not_invent_python_validity_for_older_metrics(accepted_model): + path = accepted_model / "metrics.json" + metrics = json.loads(path.read_text()) + for field in ("generations", "valid_python", "valid_python_rate"): + del metrics["candidate"][field] + metrics["candidate"]["families"] = {"old_category": {"passed": 1, "total": 3}} + path.write_text(json.dumps(metrics)) + updated = ci.readme( + "", + accepted_model, + "example/model", + "revision", + ) + assert "Valid Python: not measured." in updated + assert "33.33% (1/3 tasks)" in updated + assert "old_category" not in updated + + @pytest.mark.parametrize( "content", [