From 4f29f74f756483ac3d88b1ebc073e858c11456bd Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:18:40 +0100 Subject: [PATCH] Keep runner process failures separate from failed stages Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 12 ++++--- src/loopzero/sandbox.py | 64 ++++++++++++++++++++++++-------------- tests/test_cli.py | 33 ++++++++++++++++++++ tests/test_stage_runner.py | 46 ++++++++++++++------------- 4 files changed, 107 insertions(+), 48 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 49620cba..6171c02a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -493,10 +493,13 @@ ASCII escaping and compact separators (`,` and `:`). Stdout must contain exactly one JSON object echoing worktree, head, base, command, network and env_sha256, plus `exit_code` (integer), `duration_s` (finite nonnegative number), `not_started` (boolean), and `tail` (string). Env values must not be echoed. Diagnostics belong -on stderr. Missing, extra, duplicate, malformed or mismatched fields and runner -process failures fail the stage closed. Runner timeouts report exit code 124 -and the measured elapsed duration. `not_started=true` requires exit_code=0, +on stderr. Missing, extra, duplicate, malformed or mismatched fields fail the +stage closed. A nonzero runner process exit or a supervisor timeout aborts with +retryable infrastructure exit 2 and leaves the prior receipt and PR Validation +intact. A valid frame from a successful runner supplies the stage verdict. +`not_started=true` requires exit_code=0, duration_s=0 and empty tail, and permits only local fallback through bwrap. +Unavailable local fallback uses the same infrastructure exit. The runner may read `worktree` as data to execute the exact clean head, including unpushed local commits, with the supplied environment and network policy under @@ -506,7 +509,8 @@ stage is retried after success or uncertain launch. Only the coordinator writes the authoritative `checks.json` receipt. Writers lock the task state directory while rechecking HEAD and atomically replacing the receipt from a synced sibling temporary file. Successful keyed stages are checkpointed in the same receipt -for reuse. The checkpoint cannot satisfy readiness before final worktree +for reuse. Delegated runs keep the latest checkpoint in memory and publish it +if interrupted. Runner outages leave the prior receipt intact. The checkpoint cannot satisfy readiness before final worktree validation. Runners cannot select stages or mint receipts. Stage admission belongs to the runner: the outer `loopzero check` must not hold a heavy slot when a runner is configured. Without a runner, the diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index 6f725e28..bbd1a945 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -15,6 +15,7 @@ import tempfile import threading import time +from collections import deque from collections.abc import Callable from contextlib import ExitStack, contextmanager from dataclasses import asdict, replace @@ -48,7 +49,7 @@ class SandboxUnavailable(LoopZeroError): - """bubblewrap is missing or cannot create a sandbox on this host.""" + """Check execution infrastructure is unavailable.""" @contextmanager @@ -104,7 +105,8 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO git_dir = _git_dir(config, worktree, "--git-dir") _validate_scratch(config.scratch, worktree, common_dir, git_dir) - with _proc.unwind_on_sigterm(), _private_directories() as stack: + with (_proc.unwind_on_sigterm(), _defer_runner_checkpoint(config, checkpoint) as checkpoint, + _private_directories() as stack): prefix = [] if not config.check_runner: home = _enter_private_directory(stack, "loopzero-home-") @@ -153,20 +155,36 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO f"({result.duration_s:.1f}s)") if result.exit_code != 0: break - final_head = _git(config, worktree, "rev-parse", "HEAD").strip() - final_dirty = bool(_git(config, worktree, "status", "--porcelain").strip()) - if (final_head, final_dirty) != (head, dirty): - results.append(CheckResult("", 1, 0.0, ( - f"HEAD before: {head}; HEAD after: {final_head}; " - f"dirty before: {dirty}; dirty after: {final_dirty}" - ))) - dirty = True - # A runner upgrade during execution makes the resulting receipt unverified. - settings_sha256 = ( - settings_sha256 if not config.check_runner - or settings_sha256 == settings_fingerprint(config, worktree, base=base) else None - ) - return CheckReport(head=head, dirty=dirty, results=tuple(results), settings_sha256=settings_sha256) + final_head = _git(config, worktree, "rev-parse", "HEAD").strip() + final_dirty = bool(_git(config, worktree, "status", "--porcelain").strip()) + if (final_head, final_dirty) != (head, dirty): + results.append(CheckResult("", 1, 0.0, ( + f"HEAD before: {head}; HEAD after: {final_head}; " + f"dirty before: {dirty}; dirty after: {final_dirty}" + ))) + dirty = True + # A runner upgrade during execution makes the resulting receipt unverified. + settings_sha256 = ( + settings_sha256 if not config.check_runner + or settings_sha256 == settings_fingerprint(config, worktree, base=base) else None + ) + return CheckReport(head=head, dirty=dirty, results=tuple(results), settings_sha256=settings_sha256) + + +@contextmanager +def _defer_runner_checkpoint(config: Config, checkpoint: Callable[[CheckReport], None] | None): + if not config.check_runner or checkpoint is None: + yield checkpoint + return + pending: deque[CheckReport] = deque(maxlen=1) + try: + yield pending.append + except SandboxUnavailable: + raise + except BaseException: + if pending: + checkpoint(pending[0]) + raise INCOMPLETE_CHECK_COMMAND = "" @@ -622,9 +640,8 @@ def _dispatch_one( input=json.dumps({**binding, "env": env}), encoding="utf-8") if done.exit_code: stderr = _proc.tail(done.stderr)[-2000:] - detail = f"Stage runner failed: process exit {done.exit_code}" - return CheckResult(command, done.exit_code, done.duration_s, - f"{detail}\n{stderr}".rstrip()) + raise SandboxUnavailable(f"Stage runner failed: process exit {done.exit_code} " + f"({done.duration_s:.2f}s elapsed). Retry the check.\n{stderr}".rstrip()) frame = _stage_frame(done.stdout, binding) if not _stage_unchanged(config, worktree, head): raise ValueError("Worktree changed after stage") @@ -641,8 +658,9 @@ def _dispatch_one( return CheckResult(command, frame["exit_code"], frame["duration_s"], _check_tail(frame["tail"])) except _proc.ProcTimeout as exc: - return CheckResult(command, TIMEOUT_EXIT, - exc.duration_s if exc.duration_s is not None else timeout, - _check_tail(exc.stdout + f"\n[loopzero] timed out after {timeout:g}s")) - except (LoopZeroError, ValueError, TypeError, OverflowError, RecursionError, OSError) as exc: + elapsed = exc.duration_s if exc.duration_s is not None else timeout + raise SandboxUnavailable( + f"Stage runner timed out after {timeout:g}s ({elapsed:.2f}s elapsed). Retry the check.\n" + f"{_check_tail(exc.stderr or exc.stdout)}".rstrip()) from exc + except (_proc.ToolMissing, config_mod.ConfigError, ValueError, TypeError, OverflowError, RecursionError, OSError) as exc: return CheckResult(command, 1, 0.0, _check_tail(f"Stage runner failed: {exc}")) diff --git a/tests/test_cli.py b/tests/test_cli.py index 5c136d5d..e4386fbb 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -703,6 +703,39 @@ def test_check_sandbox_unavailable_exits_two(wt: Path, fake_tool, capsys) -> Non assert not (wt / ".loopzero" / "checks.json").exists() +@pytest.mark.parametrize("prior_receipt", [False, True]) +def test_check_runner_outage_preserves_receipt(wt, gh, monkeypatch, capsys, prior_receipt): + if prior_receipt: + assert run(capsys, "check")[0] == 0 + receipt = wt / ".loopzero/checks.json" + previous = receipt.read_bytes() if prior_receipt else None + calls = list(gh.calls) + context = cli._context + script = """ +import json, sys +frame = json.load(sys.stdin) +if frame["command"] != "echo ok": + sys.exit(75) +del frame["env"] +print(json.dumps(dict(frame, exit_code=0, duration_s=0.0, tail="", not_started=False))) +""" + + def with_runner(*args, **kwargs): + worktree, settings = context(*args, **kwargs) + return worktree, replace(settings, check_runner=(sys.executable, "-c", script), + inputs={"echo ok": ("feature.py",)}) + + monkeypatch.setattr(cli, "_context", with_runner) + + code, out, err = run(capsys, "check") + + assert code == 2 + assert "process exit 75" in err and "Retry" in err + assert "PASS" not in out and "FAIL" not in out + assert (receipt.read_bytes() if receipt.exists() else None) == previous + assert gh.calls == calls + + @pytest.mark.parametrize("bootstrap", [False, True]) def test_config_flag_overrides_root(wt: Path, tmp_path: Path, capsys, bootstrap) -> None: if bootstrap: diff --git a/tests/test_stage_runner.py b/tests/test_stage_runner.py index ddc88774..1847f405 100644 --- a/tests/test_stage_runner.py +++ b/tests/test_stage_runner.py @@ -15,7 +15,6 @@ @pytest.mark.parametrize('base_ref,body,verdict,tails', [ *[(base_ref, 'print(json.dumps(r))', True, ['ok', 'ok']) for base_ref in ('stale', 'missing', 'recorded')], ('stale', 'r["exit_code"]=7;print(json.dumps(r))', False, ['ok']), - ('stale', 'print("x" * 3000 + "worker socket unavailable", file=sys.stderr);sys.exit(42)', False, None), ('stale', 'r["exit_code"]=7;r["tail"]="Ω"*10000+" newest";print(json.dumps(r))', False, ['Ω' * 8188 + ' newest']), ('stale', 'subprocess.run(["git","-C",repo,"-c","user.name=test","-c","user.email=t@e","commit","--allow-empty","-m","drift"],stdout=sys.stderr,check=True);print(json.dumps(r))', False, None), @@ -26,7 +25,7 @@ 'r["duration_s"]=float("nan");print(json.dumps(r))', 'r["exit_code"]=True;print(json.dumps(r))', 'r["network"]=1;print(json.dumps(r))', 'r["network"]=False;print(json.dumps(r))', - 'print(json.dumps(r));sys.exit(1)', 'r["not_started"]=True;print(json.dumps(r))', + 'r["not_started"]=True;print(json.dumps(r))', *[f'r["{field}"]="wrong";print(json.dumps(r))' for field in ('head', 'base', 'command', 'env_sha256', 'network', 'worktree')], ]], ]) @@ -58,10 +57,6 @@ def test_runner(git_repo, tmp_path, bwrap_log, body, verdict, tails, base_ref): assert report.ok is verdict if 'exit_code"]=7' in body: assert report.results[0].exit_code == 7 - if 'sys.exit(42)' in body: - result = report.results[0] - assert result.exit_code == 42 and result.duration_s > 0 - assert result.tail == 'Stage runner failed: process exit 42\n' + ('x' * 3000 + 'worker socket unavailable')[-2000:] if tails is not None: assert [r.tail for r in report.results] == tails if not verdict: @@ -93,9 +88,13 @@ def test_runner_unavailable(git_repo, monkeypatch, dirty, fetched_base): # noqa if dirty: (git_repo / 'dirty').write_text('x') monkeypatch.setattr(sandbox.shutil, 'which', lambda name: None) - report = sandbox.run_checks(make_config(check_runner=FALLBACK_RUNNER), git_repo) - assert not report.ok and report.dirty is dirty - assert ('bwrap binary missing' in report.results[0].tail) is not dirty + config = make_config(check_runner=FALLBACK_RUNNER) + if not dirty: + with pytest.raises(sandbox.SandboxUnavailable, match="bwrap binary missing"): + sandbox.run_checks(config, git_repo) + return + report = sandbox.run_checks(config, git_repo) + assert not report.ok and report.dirty @pytest.mark.parametrize('value', ['[]', '[""]', '[1]', '"runner"', '["./runner"]', '["tools/runner"]', '["python3","tools/run_stage.py"]', '["dispatch","--stage"]', '["dispatch","--opt=/operator/run.py"]']) @@ -148,18 +147,23 @@ def test_runner_preserves_executable_symlink(git_repo, tmp_path, monkeypatch, ba assert report.ok, report.results[0].tail -def test_runner_timeout(git_repo, monkeypatch, fetched_base): # noqa: F811 - original = sandbox._proc.run - def run(argv, **kwargs): - if argv[0] == sys.executable: - raise sandbox._proc.ProcTimeout('deadline', 'partial', duration_s=0.25) - return original(argv, **kwargs) - monkeypatch.setattr(sandbox._proc, 'run', run) - report = sandbox.run_checks(make_config(check_runner=(sys.executable,)), git_repo, timeout=0.1) - assert not report.ok - result = report.results[0] - assert result.exit_code == 124 and result.duration_s == 0.25 - assert 'partial' in result.tail and 'timed out after 0.1s' in result.tail +@pytest.mark.parametrize(("command", "diagnostic"), [ + ("exit 75", "process exit 75"), + ("printf '%03000d' 0 >&2; echo worker socket unavailable >&2; exit 42", "worker socket unavailable"), + ("exit 124", "process exit 124"), + ("kill -TERM $$", "process exit -15"), + ("exit 143", "process exit 143"), + ("exec sleep 10", "timed out after 0.1s"), +]) +def test_runner_process_failure_is_retryable(git_repo, command, diagnostic): + git(git_repo, "update-ref", "refs/remotes/origin/main", "HEAD") + config = make_config(check_runner=("/bin/sh", "-c", command)) + + with pytest.raises(sandbox.SandboxUnavailable, match="Retry") as exc: + sandbox.run_checks(config, git_repo, timeout=0.1 if command == "exec sleep 10" else 30) + + assert diagnostic in str(exc.value) + assert "elapsed" in str(exc.value) and len(str(exc.value)) < 2200 @pytest.mark.parametrize('change', ['fallback', 'base'])