Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
64 changes: 41 additions & 23 deletions src/loopzero/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -48,7 +49,7 @@


class SandboxUnavailable(LoopZeroError):
"""bubblewrap is missing or cannot create a sandbox on this host."""
"""Check execution infrastructure is unavailable."""


@contextmanager
Expand Down Expand Up @@ -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-")
Expand Down Expand Up @@ -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("<worktree changed during run>", 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("<worktree changed during run>", 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 = "<checks incomplete>"
Expand Down Expand Up @@ -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")
Expand All @@ -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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Git probe timeouts are reported as runner timeouts

The except _proc.ProcTimeout handler wraps the whole _dispatch_one body, so it also catches more than the runner's own timeout. It catches a timeout from the _git calls in _stage_unchanged at lines 622, 646 and 651. It also catches a timeout from the _git calls inside the nested local-fallback run_checks (lines 96–105 and 158–159). All of these are bounded by GIT_TIMEOUT, not the stage timeout. Each one now raises SandboxUnavailable("Stage runner timed out after {timeout:g}s ..."), which names the wrong component and the wrong limit, for example "timed out after 3600s (60.00s elapsed)". The task scopes this path to an actual runner timeout. Exit 2 is still reasonable for a git timeout, so the misleading diagnostic is the only defect. The same overly broad catch existed before this change, but this change makes it user-facing as an infrastructure outage. Smallest fix: wrap only the _proc.run(argv, ...) call at line 639 in try/except _proc.ProcTimeout. Let any other ProcTimeout propagate, or convert it to SandboxUnavailable with a git-specific message.

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}"))
33 changes: 33 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: CLI test does not cover a validated failed stage keeping its receipt and publish behaviour

The new CLI test checks only the outage path, with exit 75. The acceptance criteria also require that a validated failed-stage frame keeps its existing behaviour: it writes the receipt and reports FAIL. That path now runs through _defer_runner_checkpoint, which drops pending checkpoints on normal return and relies on cmd_check saving the final report. Nothing at the CLI level checks this. To guard against a regression, add one parametrized case where the runner returns a valid frame with exit_code=7. Assert that the command exits 1, the receipt is rewritten and contains the failed stage, and stdout shows FAIL.

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:
Expand Down
46 changes: 25 additions & 21 deletions tests/test_stage_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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')],
]],
])
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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"]'])
Expand Down Expand Up @@ -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'])
Expand Down
Loading