diff --git a/core/skills/diagnose/SKILL.md b/core/skills/diagnose/SKILL.md index 59d980ea..e916da21 100644 --- a/core/skills/diagnose/SKILL.md +++ b/core/skills/diagnose/SKILL.md @@ -18,6 +18,9 @@ Rank competing hypotheses from evidence. Use discriminating experiments and predicted observations to establish cause; correlation or symptom disappearance is insufficient. For intermittent failures, use enough observations to distinguish improvement from chance. Aggregate available logs before adding instrumentation. +After one retry of a check that reports `runner failure, not a check result`, +if the retry also reports runner failure, stop retrying. Report the runner exit +code, log path and host for diagnosis in the same turn. When the same check fails twice, before any requeue or rerun, diff the last green run against the first red one: runner or host, environment (ports, env vars, services, labels) and code. A host or runner change that is live ahead of diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ebb2a162..0d70c614 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -543,9 +543,11 @@ 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. A valid reported stage failure is authoritative even if the runner +also exits nonzero. Missing, extra, duplicate, malformed or mismatched fields +and interruption before a complete result are runner failures. Check preserves +the prior receipt, returns the runner status (124 for a supervisor timeout), and +does not publish a stage verdict. A receipt is eligible only for its own HEAD. `not_started=true` requires exit_code=0, duration_s=0 and empty tail, and permits only local fallback through bwrap. The runner may read `worktree` as data to execute the exact clean head, including @@ -557,11 +559,13 @@ the authoritative `checks.json` receipt. Checks lock the task state directory through execution and receipt publication. A waiter can reuse a newly published passing receipt when HEAD, settings and declared inputs match. Writers recheck HEAD and atomically replace the receipt from a synced sibling temporary file. -Successful keyed stages are checkpointed in the same receipt for reuse. -A successful stage checkpoint preserves a clean pass for the same head, -settings and commands. A failed stage replaces an existing receipt immediately. -Final worktree validation is required before publishing a pass. Runners cannot -select stages or mint receipts. Stage admission +Successful local keyed stages are checkpointed in the same receipt for reuse. +Their checkpoints preserve a clean pass for the same head, settings and +commands. A reported failed stage replaces the receipt immediately. Successful +delegated stages are checkpointed if the coordinator is interrupted, and +discarded if the runner fails. Final worktree validation is required before +publishing a pass. 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 existing local execution path is unchanged. diff --git a/src/loopzero/_cli_entry.py b/src/loopzero/_cli_entry.py index b7df2391..00c87518 100644 --- a/src/loopzero/_cli_entry.py +++ b/src/loopzero/_cli_entry.py @@ -7,4 +7,4 @@ def main(argv: list[str] | None = None) -> int: args = parse_args(build_parser(), argv) from loopzero.cli import _run - return _run(args) + return _run(args, console=True) diff --git a/src/loopzero/_proc.py b/src/loopzero/_proc.py index a7db463d..2d2dcacd 100644 --- a/src/loopzero/_proc.py +++ b/src/loopzero/_proc.py @@ -64,6 +64,14 @@ def unwind_on_sigterm(): raise +def exit_status(code: int) -> int: + if code < 0: + if -code not in (signal.SIGKILL, signal.SIGSTOP): + signal.signal(-code, signal.SIG_DFL) + signal.raise_signal(-code) + return code + + @contextmanager def defer_sigterm(): """Finish a private directory operation before unwinding.""" diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 24a62b50..f490400d 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1932,7 +1932,7 @@ def main(argv: list[str] | None = None) -> int: return _run(parse_args(build_parser(), argv)) -def _run(args: argparse.Namespace) -> int: +def _run(args: argparse.Namespace, *, console: bool = False) -> int: try: with _proc.unwind_on_sigterm(): return globals()[f"cmd_{args.command}"](args) @@ -1946,7 +1946,8 @@ def _run(args: argparse.Namespace) -> int: message = str(exc) if isinstance(exc, ReviewersUnavailable) else _one_line(exc) prefix = "unexpected response: " if isinstance(exc, UNEXPECTED) else "" print(f"loopzero {args.command}: {prefix}{message}", file=sys.stderr) - return 1 + code = exc.exit_code if isinstance(exc, sandbox.StageRunnerFailure) else 1 + return _proc.exit_status(code) if console else code except KeyboardInterrupt: print(f"loopzero {args.command}: interrupted", file=sys.stderr) return 130 @@ -1957,4 +1958,4 @@ def _one_line(exc: BaseException) -> str: if __name__ == "__main__": - sys.exit(_run(_module_args)) + sys.exit(_run(_module_args, console=True)) diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index e55efbee..444eeb33 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -60,6 +60,12 @@ class SandboxUnavailable(LoopZeroError): """bubblewrap is missing or cannot create a sandbox on this host.""" +class StageRunnerFailure(LoopZeroError): + def __init__(self, exit_code: int, detail: str): + super().__init__(f"runner failure, not a check result: {detail}") + self.exit_code = exit_code + + @contextmanager def _private_directories(): with ExitStack() as stack: @@ -109,7 +115,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(), _stage_checkpoints(checkpoint, bool(config.check_runner)) as save, + _private_directories() as stack): prefix = [] if not config.check_runner: home = _enter_private_directory(stack, "loopzero-home-") @@ -148,47 +155,54 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO result = replace(result, input_key=key) if ordinal > len(preparations) or result.exit_code: results.append(result) - _checkpoint_stage( - checkpoint, CheckReport(head, dirty, tuple(results), settings_sha256), - previous, commands[ordinal:], - ) + save(CheckReport(head, dirty, tuple(results), settings_sha256), previous, commands[ordinal:]) if status: status(f"stage {ordinal}/{len(commands)}: exit {result.exit_code} " 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) 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) else None + ) + return CheckReport(head=head, dirty=dirty, results=tuple(results), settings_sha256=settings_sha256) INCOMPLETE_CHECK_COMMAND = "" INCOMPLETE_CHECK = CheckResult(INCOMPLETE_CHECK_COMMAND, 1, 0.0, "") -def _checkpoint_stage(checkpoint: Callable[[CheckReport], None] | None, - report: CheckReport, previous: dict[str, CheckResult], - remaining: tuple[str, ...]) -> None: - if checkpoint is None: - return - stage = report.results[-1] - if stage.exit_code: - checkpoint(report) - elif stage.input_key: - # Even the last stage leaves a nonpassing receipt until final validation. - unvisited = tuple(previous[command] for command in remaining if command in previous) - checkpoint(replace(report, results=(*report.results, *unvisited, INCOMPLETE_CHECK))) +@contextmanager +def _stage_checkpoints(checkpoint: Callable[[CheckReport], None] | None, delegated: bool): + pending = None + + def save(report: CheckReport, previous: dict[str, CheckResult], remaining: tuple[str, ...]) -> None: + nonlocal pending + stage = report.results[-1] + if not stage.exit_code: + if not stage.input_key: + return + unvisited = (previous[command] for command in remaining if command in previous) + report = replace(report, results=(*report.results, *unvisited, INCOMPLETE_CHECK)) + pending = report if delegated and not stage.exit_code else None + if pending is None: + checkpoint(report) + + try: + yield save if checkpoint is not None else lambda *_: None + except (KeyboardInterrupt, _proc.Terminated): + if pending is not None: + checkpoint(pending) + raise def _previous(config: Config, worktree: Path, settings_sha256: str) -> dict[str, CheckResult]: @@ -622,7 +636,7 @@ def _runner_executable(config: Config) -> str | None: return executable if Path(executable).is_absolute() else shutil.which(executable) -def _stage_frame(stdout: str, binding: dict) -> dict: +def _stage_frame(stdout: str, binding: dict, runner_exit: int) -> dict: frame = json.loads(stdout, object_pairs_hook=_unique_fields) if (not isinstance(frame, dict) or set(frame) != {*binding, "exit_code", "duration_s", "not_started", "tail"} @@ -632,7 +646,8 @@ def _stage_frame(stdout: str, binding: dict) -> dict: or type(frame["duration_s"]) not in (int, float) or not math.isfinite(frame["duration_s"]) or frame["duration_s"] < 0 or type(frame["not_started"]) is not bool - or not isinstance(frame["tail"], str)): + or not isinstance(frame["tail"], str) + or (runner_exit and not frame["exit_code"])): raise ValueError("invalid or mismatched stage result") return frame @@ -644,6 +659,7 @@ def _dispatch_one( binding = {"worktree": str(worktree.resolve()), "head": head, "base": base, "command": command, "network": config.network, "env_sha256": hashlib.sha256(json.dumps( env, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()} + runner_exit, stderr = 0, "" try: if not _stage_unchanged(config, worktree, head): raise ValueError("Worktree changed before stage") @@ -662,21 +678,18 @@ def _dispatch_one( for path in {value, *value.split(":")} if Path(path).is_absolute() or ".." in Path(path).parts): raise ValueError("Stage runner references task worktree") - done = _proc.run(argv, cwd=cwd, env_allowlist=config.env_allowlist, timeout=timeout, - input=json.dumps({**binding, "env": env}), encoding="utf-8") - if done.exit_code: - stderr = _proc.tail(_redact_check_output(config, 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()) - frame = _stage_frame(done.stdout, binding) + try: + done = _proc.run(argv, cwd=cwd, env_allowlist=config.env_allowlist, timeout=timeout, + input=json.dumps({**binding, "env": env}), encoding="utf-8") + stdout, stderr, runner_exit = done.stdout, done.stderr, done.exit_code + except _proc.ProcTimeout as exc: + stdout, stderr, runner_exit = exc.stdout, f"timed out after {timeout:g}s\n{exc.stderr}", TIMEOUT_EXIT + frame = _stage_frame(stdout, binding, runner_exit) if not _stage_unchanged(config, worktree, head): raise ValueError("Worktree changed after stage") if frame["not_started"]: if frame["exit_code"] or frame["duration_s"] or frame["tail"]: raise ValueError("inconsistent not-started result") - if not _stage_unchanged(config, worktree, head): - raise ValueError("Worktree changed before fallback") local = run_checks(replace(config, check_runner=(), checks=(command,), inputs={}), worktree, timeout=timeout, _resolved=True) if local.dirty: @@ -684,10 +697,8 @@ def _dispatch_one( return local.results[-1] return CheckResult(command, frame["exit_code"], frame["duration_s"], _check_tail(frame["tail"], config)) - 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, config, suffix=f"\n[loopzero] timed out after {timeout:g}s")) except (LoopZeroError, ValueError, TypeError, OverflowError, RecursionError, OSError) as exc: - detail = _redact_check_output(config, str(exc)) - return CheckResult(command, 1, 0.0, _check_tail(f"Stage runner failed: {detail}")) + if runner_exit: + tail = _proc.tail(_redact_check_output(config, stderr))[-2000:] + raise StageRunnerFailure(runner_exit, f"process exit {runner_exit}\n{tail}".rstrip()) from exc + raise StageRunnerFailure(1, _check_tail(str(exc), config)) from exc diff --git a/tests/test_cli.py b/tests/test_cli.py index 44240c54..dccad535 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -679,6 +679,58 @@ def test_malformed_live_markers_do_not_mask_check_verdict( assert json.loads((wt / ".loopzero/checks.json").read_text())["results"][0]["exit_code"] == 0 +@pytest.mark.parametrize("runner_exit, new_head", [(75, False), (124, False), (-15, True), (-9, False), (0, False)]) +def test_check_receipt_requires_stage_result(wt, gh, monkeypatch, capsys, head, runner_exit, new_head): + assert run(capsys, "check")[0] == 0 + receipt = wt / ".loopzero/checks.json" + previous = receipt.read_bytes(), receipt.stat().st_mtime_ns + if new_head: + git(wt, "commit", "--allow-empty", "-m", "New candidate") + current = git(wt, "rev-parse", "HEAD").strip() + calls = list(gh.calls) + context = cli._context + script = f""" +import json, os, sys +frame = json.load(sys.stdin) +code = {runner_exit} +if frame["command"] == "echo ok": + code = 0 + stage_exit = 0 +else: + stage_exit = 7 + if code < 0: + print('{{"exit_code":', flush=True) + os.kill(os.getpid(), -code) + if code: + sys.exit(code) +del frame["env"] +print(json.dumps(dict(frame, exit_code=stage_exit, duration_s=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") + if runner_exit: + assert code == runner_exit + assert f"runner failure, not a check result: process exit {runner_exit}" in err + assert "PASS" not in out and "FAIL" not in out + assert (receipt.read_bytes(), receipt.stat().st_mtime_ns) == previous + assert gh.calls == calls + else: + assert code == 1 and out.endswith("FAIL\n") + assert cli._load_report(wt).results[-1].exit_code == 7 + assert (receipt.read_bytes(), receipt.stat().st_mtime_ns) != previous + if new_head: + arm_approved_pr_with_check_result(gh, current, wt, "success", readiness={"local_exit": None}) + out, _ = expect_cli(capsys, 1, "ready") + assert f"check receipt is for {head[:12]}" in out + assert all(c["argv"][:2] != ["pr", "ready"] for c in gh.calls) + + @pytest.mark.parametrize("receipt", ["saved", "head moved", "write failed"]) def test_check_bounds_large_failure_and_preserves_receipt(wt, head, capsys, monkeypatch, receipt): tail = 'TEST_FAILURES={"detail":"' + "é" * 7500 + '","error":"Failed to fetch package"}\n' diff --git a/tests/test_stage_runner.py b/tests/test_stage_runner.py index b3bc0f73..d862fdb6 100644 --- a/tests/test_stage_runner.py +++ b/tests/test_stage_runner.py @@ -20,7 +20,7 @@ @pytest.mark.parametrize('base_ref,body,verdict,tails', [ *[(base_ref, 'r["tail"]=" ".join((env["UV_CACHE_DIR"],env["NODE_ENV"],env["AUDIT_VALUE"],os.environ["AUDIT_VALUE"]));print(json.dumps(r))', True, ['/operator/cache production [REDACTED] [REDACTED]'] * 2) for base_ref in ('stale', 'missing', 'recorded', 'abs-link', 'path-link')], - ('stale', 'r["exit_code"]=7;r["tail"]="ok "+env["AUDIT_VALUE"];print(json.dumps(r))', False, ['ok [REDACTED]']), + ('stale', 'r["exit_code"]=7;r["tail"]="ok "+env["AUDIT_VALUE"];print(json.dumps(r));sys.exit(75)', False, ['ok [REDACTED]']), ('stale', 'print("x" * 3000 + "worker socket unavailable " + env["AUDIT_VALUE"], file=sys.stderr);sys.exit(42)', False, None), ('stale', 'r["exit_code"]=7;r["tail"]=env["AUDIT_VALUE"]+"Ω"*8183+" newest";print(json.dumps(r))', False, ['[REDACTED]' + 'Ω' * 8183 + ' newest']), @@ -69,31 +69,32 @@ def test_runner(git_repo, tmp_path, bwrap_log, monkeypatch, body, verdict, tails launcher = (link.name if base_ref == 'path-link' else str(link), str(path), 'relative/argument') path.write_text(preamble + STAGE_FIELDS.format(fallback=False, tail='ok') + '\n' + body) calls = [] - report = sandbox.run_checks(make_config(checks=('echo one', 'echo two'), - env=tuple(configured.items()), env_allowlist=("PATH", "AUDIT_VALUE"), network=True, - check_runner=launcher), git_repo, progress=calls.append) + config = make_config(checks=('echo one', 'echo two'), check_runner=launcher, network=True, + env=tuple(configured.items()), env_allowlist=("PATH", "AUDIT_VALUE")) + if tails is None: + with pytest.raises(sandbox.StageRunnerFailure) as raised: + sandbox.run_checks(config, git_repo, progress=calls.append) + assert calls == ['echo one'] + error = raised.value + assert 'runner failure, not a check result' in str(error) + if 'sys.exit(42)' in body: + assert error.exit_code == 42 + assert str(error).endswith(('x' * 3000 + 'worker socket unavailable [REDACTED]')[-2000:]) + if '* 100000' in body: + assert any(word in str(error).lower() for word in ('recursion', 'stack overflow')) + if 'drift' in body: + assert 'Worktree changed after stage' in str(error) + assert not (git_repo / '.loopzero/checks.json').exists() + return + report = sandbox.run_checks(config, git_repo, progress=calls.append) 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 [REDACTED]')[-2000:] - if tails is not None: - assert [r.tail for r in report.results] == tails + assert [r.tail for r in report.results] == tails if not verdict: assert calls == ['echo one'] assert sum(r.tail == 'ok' for r in report.results) <= 1 - if '* 100000' in body: - assert 'Stage runner failed' in report.results[0].tail - assert any(word in report.results[0].tail.lower() for word in ('recursion', 'stack overflow')) current_head = _save_report(git_repo, report) - if 'drift' in body: - assert report.dirty - assert 'Worktree changed after stage' in report.results[0].tail - assert current_head == git(git_repo, 'rev-parse', 'HEAD').strip() and current_head != report.head - assert _load_report(git_repo) != report - return assert current_head is None and _load_report(git_repo) == report receipt = json.loads((git_repo / '.loopzero/checks.json').read_text()) assert receipt.keys() == {'head', 'dirty', 'results', 'settings_sha256'} @@ -104,9 +105,14 @@ 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 + cfg = make_config(check_runner=FALLBACK_RUNNER) + if not dirty: + with pytest.raises(sandbox.StageRunnerFailure, match='bwrap binary missing'): + sandbox.run_checks(cfg, git_repo) + else: + report = sandbox.run_checks(cfg, git_repo) + assert not report.ok and report.dirty + assert 'bwrap binary missing' not in report.results[0].tail @pytest.mark.parametrize('kind', ['executable', 'argument', 'symlink', 'path', 'executable_symlink', 'option', 'option_symlink', 'short', 'list', 'parent', 'colon_link', 'colon_tree']) @@ -131,23 +137,23 @@ def test_runner_rejects_task_paths(git_repo, tmp_path, monkeypatch, kind): 'list': (sys.executable, f'/operator/safe:{runner}'), 'parent': (sys.executable, '../escape'), 'colon_link': (str(link),), 'colon_tree': (str(runner),)}[kind] - report = sandbox.run_checks(make_config(check_runner=prefix), git_repo) - assert not report.ok and 'references task worktree' in report.results[0].tail + with pytest.raises(sandbox.StageRunnerFailure, match='references task worktree'): + sandbox.run_checks(make_config(check_runner=prefix), git_repo) 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 opaque-fake-db-password', duration_s=0.25) + raise sandbox._proc.ProcTimeout('deadline', '{"exit_code":', + stderr='partial opaque-fake-db-password', duration_s=0.25) return original(argv, **kwargs) monkeypatch.setattr(sandbox._proc, 'run', run) cfg = make_config(check_runner=(sys.executable,), env=(("AUDIT_VALUE", "opaque-fake-db-password"),)) - report = sandbox.run_checks(cfg, 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 [REDACTED]' in result.tail and 'timed out after 0.1s' in result.tail + with pytest.raises(sandbox.StageRunnerFailure) as raised: + sandbox.run_checks(cfg, git_repo, timeout=0.1) + assert raised.value.exit_code == 124 + assert 'partial [REDACTED]' in str(raised.value) and 'timed out after 0.1s' in str(raised.value) @pytest.mark.parametrize('change', ['fallback', 'base'])