Repository navigation
Preserve check receipts when a stage runner fails #1960
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
70db6ff
383a0bc
5a9d967
1b3e724
ab7376f
83d82b0
2fa6b3a
d074f85
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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("<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) 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) else None | ||
| ) | ||
| return CheckReport(head=head, dirty=dirty, results=tuple(results), settings_sha256=settings_sha256) | ||
|
|
||
|
|
||
| INCOMPLETE_CHECK_COMMAND = "<checks incomplete>" | ||
| 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,32 +678,27 @@ 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") | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion: Worktree drift is now reported as a runner failure Before this change, a clean exit 0 runner followed by a worktree change produced a dirty CheckReport, and |
||
| 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: | ||
| raise ValueError("Local fallback failed") | ||
| 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 | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion: Unwrapped long lines in the rewritten paragraphs
The new text
...does not publish a stage verdict. A receipt is eligible only for its own HEAD. \not_started=true` requires exit_code=0,andfor reuse. Delegated results are published only after the check completes. A checkpoint cannot replace...` go well past the wrap width the rest of the file uses. Rewrap these paragraphs to keep the diffs reviewable.