From a09e54266b2a977f6c60f3b09f83f4b13f1279a4 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:52:26 +0100 Subject: [PATCH 1/6] Check size budgets on the current target before queueing Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 4 ++++ src/loopzero/cli.py | 47 ++++++++++++++++++++++++++++++++++++++++---- tests/test_cli.py | 42 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 89 insertions(+), 4 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 49620cba..57956e14 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -312,6 +312,10 @@ merge-authority holds. Adding or removing a hold refreshes source eligibility even when the head stays the same. Merge admission rechecks the live hold. [Mergify](MERGIFY.md) describes optional source-preserving queue integration; [candidate validation](../src/loopzero/candidate.py) belongs at that boundary. +When delivery uses the existing size checker, local readiness and new Mergify +requests evaluate a temporary integration with the freshly fetched target. The +target supplies the checker and baseline. Existing requests continue to the +queue wait path. Candidate lineage reads wait on zero or multiple live batch matches with exponential backoff capped at 30 seconds and a shared 90-second retry-admission deadline across both reads and all attestation attempts. Each wait revalidates the candidate before diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index f1645fb8..a04291d9 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -18,6 +18,7 @@ import random import re import sys +import tempfile import time from collections.abc import Callable, Iterator from contextlib import contextmanager, suppress @@ -73,9 +74,10 @@ def review_marker(head: str, kind: str, source: str = "model") -> str: # --------------------------------------------------------------------------- git / context -def _git(cwd: Path, *args: str, timeout: float = GIT_TIMEOUT, paths: bool = False) -> str: +def _git(cwd: Path, *args: str, timeout: float = GIT_TIMEOUT, paths: bool = False, + extra_env: dict[str, str] | None = None) -> str: done = _proc.run( - ["git", *args], cwd=cwd, env_allowlist=worktree.GIT_ENV, timeout=timeout, + ["git", *args], cwd=cwd, env_allowlist=worktree.GIT_ENV, timeout=timeout, extra_env=extra_env, preserve_newlines=paths, encoding=sys.getfilesystemencoding() if paths else None, ) if done.exit_code != 0: @@ -1213,6 +1215,41 @@ def _cleanup(wt: Path, pr: github.PR) -> None: print(f"warning: merged but worktree cleanup failed: {exc}{retry}", file=sys.stderr) +_SIZE_BUDGET = "scripts/size_budget.sh" + + +def _prequeue_size_budget( + wt: Path, config: Config, pr: github.PR, readiness: github.Readiness, +) -> None: + if not readiness.ready or config.merge_strategy != "mergify" or _SIZE_BUDGET not in config.checks: + return + origin = _git(wt, "remote", "get-url", "origin") + with tempfile.TemporaryDirectory(prefix="loopzero-size-") as directory: + root = Path(directory) + env = {"GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", "GIT_NO_REPLACE_OBJECTS": "1", "PYTHON": sys.executable} + git = partial(_git, root, extra_env=env) + git("clone", "--shared", "--no-checkout", "--template=", str(wt), ".") + # Fetch with the user's credential configuration for private origins. + fetched = _proc.run( + ["git", "fetch", "--no-tags", "--no-recurse-submodules", "--", + origin, f"refs/heads/{config.base_branch}"], + cwd=root, env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT, + ) + if fetched.exit_code != 0: + raise CliError(f"could not fetch {config.base_branch} from origin for the size budget check") + base = git("rev-parse", "FETCH_HEAD^{commit}") + script = git("show", f"{base}:{_SIZE_BUDGET}") + tree = git("merge-tree", "--write-tree", base, pr.head_sha) + # A candidate symlink must not read files outside the temporary checkout. + git("-c", "core.symlinks=false", "read-tree", "--reset", "-u", tree) + result = _proc.run(["bash", "-s", "--", base], input=script + "\n", cwd=root, + env_allowlist=("PATH",), extra_env=env, timeout=GIT_TIMEOUT, + merge_output=True) + if result.exit_code: + raise CliError("current target size budget failed:\n" + result.stdout.rstrip()) + + def cmd_ready(args: argparse.Namespace) -> int: wt, config = _context(args, pin_checks=True) pr, readiness = _pr_readiness(wt, config, workflow_wait=args.wait is not None) @@ -1237,6 +1274,7 @@ def cmd_ready(args: argparse.Namespace) -> int: return 3 pr, readiness, kicked = waited assert readiness is not None + _prequeue_size_budget(wt, config, pr, readiness) if readiness.ready and pr.is_draft and not kicked: github.mark_ready(config.repo, pr.number) if args.wait is not None: @@ -1589,7 +1627,7 @@ class _AdmissionDeadline(Exception): def _merge_with_mergify( - config: Config, pr: github.PR, + wt: Path, config: Config, pr: github.PR, readiness: github.Readiness, deadline: float | None, admit_by: float | None = None, ) -> str | None: """Request Mergify after readiness verifies the source gates and queue configuration.""" @@ -1616,6 +1654,7 @@ def _merge_with_mergify( return sha raise closed[0] if not confirmed and not requested: + _prequeue_size_budget(wt, config, pr, readiness) if admit_by is not None and time.monotonic() > admit_by: raise _AdmissionDeadline mergify.request(config.repo, pr.number, pr.head_sha, queue) @@ -1667,7 +1706,7 @@ def cmd_merge(args: argparse.Namespace) -> int: print(f"PR #{pr.number} was already merged as {sha[:12]}; cleaning up") elif config.merge_strategy == "mergify": try: - sha = _merge_with_mergify(config, pr, readiness, deadline, admit_by) + sha = _merge_with_mergify(wt, config, pr, readiness, deadline, admit_by) except _AdmissionDeadline: print(f"timed out before requesting Mergify for PR #{pr.number}") return 3 diff --git a/tests/test_cli.py b/tests/test_cli.py index fea79806..e1191412 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4855,3 +4855,45 @@ def test_pr_marks_legacy_same_head_check_unverified(wt, gh, capsys, refresh): assert "unverified" not in draft assert f"Recorded for `{head[:12]}`\n- `echo ok`: exit 0" in draft assert "Manual validation evidence." in draft + + +@pytest.mark.parametrize("command", ["ready", "merge", "resume"]) +def test_prequeue_size_budget_replays_1230(wt, repo, gh, capsys, monkeypatch, command): + # PR #1230 fit its fork point at 7,482. Current main added 26 independent lines. + checker = Path(__file__).resolve().parents[1] / "scripts/size_budget.sh" + cap = int(re.search(r"^SRC_CAP=(\d+)$", checker.read_text(), re.MULTILINE)[1]) + (repo / "scripts").mkdir() + shutil.copyfile(checker, repo / "scripts/size_budget.sh") + policy = (repo / "workflow.toml").read_text().replace( + 'merge = "squash"', 'merge = "mergify"\nmergify_queue = "main"' + ).replace('commands = ["echo ok", "test -f README.md"]', 'commands = ["scripts/size_budget.sh"]') + git(repo, "add", "scripts") + publish_workflow(wt, policy) + fork = head_of(repo) + git(wt, "merge", "--no-edit", fork) + for checkout, name, lines in [(wt, "feature", cap - 18), (repo, "upstream", 26)]: + folder = checkout / "src/loopzero" + folder.mkdir(parents=True) + (folder / f"{name}.py").write_text("# counted line\n" * lines) + git(checkout, "add", "src") + git(checkout, "commit", "-qm", name) + # Deliberately leave origin/main stale in the source repository. + git(repo, "push", "--no-verify", str(repo.parent / "origin.git"), "main") + git(repo, "update-ref", "refs/remotes/origin/main", fork) + head = head_of(wt) + arm_approved_pr_with_check_result(gh, head, wt, "success", isDraft=False) + monkeypatch.setattr(mergify, "configured", lambda *_: True) + monkeypatch.setattr(mergify, "markers", lambda *_: (command == "resume", False)) + monkeypatch.setattr(mergify, "membership", lambda *_: None) + monkeypatch.setattr(mergify, "request", lambda *_: pytest.fail("must not request admission")) + monkeypatch.setattr(cli, "_wait_for_mergify", lambda *_: None) + + args = ("merge", "--wait=0") if command == "resume" else (command,) + code, out, err = run(capsys, *args) + + if command == "resume": + assert code == 3 and "size budget" not in out + err + else: + assert code == 1 and f"src={cap + 8} (base 26, delta {cap - 18}, cap {cap}" in out + err + assert head_of(wt) == head + assert not (wt / "src/loopzero/upstream.py").exists() From 31472383d8fcf7164326a580ddb705de543ef543 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:56:05 +0100 Subject: [PATCH 2/6] Isolate the trusted budget checker from candidate Python modules Architecture-Review: unchanged; the candidate is still counted with the trusted target checker. Co-Authored-By: Codex --- src/loopzero/cli.py | 3 ++- tests/test_cli.py | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index a04291d9..e7f000a5 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1227,7 +1227,8 @@ def _prequeue_size_budget( with tempfile.TemporaryDirectory(prefix="loopzero-size-") as directory: root = Path(directory) env = {"GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull, - "GIT_ATTR_NOSYSTEM": "1", "GIT_NO_REPLACE_OBJECTS": "1", "PYTHON": sys.executable} + "GIT_ATTR_NOSYSTEM": "1", "GIT_NO_REPLACE_OBJECTS": "1", + "PYTHON": sys.executable, "PYTHONSAFEPATH": "1"} git = partial(_git, root, extra_env=env) git("clone", "--shared", "--no-checkout", "--template=", str(wt), ".") # Fetch with the user's credential configuration for private origins. diff --git a/tests/test_cli.py b/tests/test_cli.py index e1191412..c8a6531f 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4877,6 +4877,10 @@ def test_prequeue_size_budget_replays_1230(wt, repo, gh, capsys, monkeypatch, co (folder / f"{name}.py").write_text("# counted line\n" * lines) git(checkout, "add", "src") git(checkout, "commit", "-qm", name) + # The trusted checker must import standard modules, not candidate files. + (wt / "ast.py").write_text("raise AssertionError('candidate module loaded')\n") + git(wt, "add", "ast.py") + git(wt, "commit", "-qm", "add candidate module shadow") # Deliberately leave origin/main stale in the source repository. git(repo, "push", "--no-verify", str(repo.parent / "origin.git"), "main") git(repo, "update-ref", "refs/remotes/origin/main", fork) @@ -4895,5 +4899,6 @@ def test_prequeue_size_budget_replays_1230(wt, repo, gh, capsys, monkeypatch, co assert code == 3 and "size budget" not in out + err else: assert code == 1 and f"src={cap + 8} (base 26, delta {cap - 18}, cap {cap}" in out + err + assert "candidate module loaded" not in out + err assert head_of(wt) == head assert not (wt / "src/loopzero/upstream.py").exists() From 68705f1ec93f566cef7270a52b89f0a1ac8e4cff Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:15:27 +0100 Subject: [PATCH 3/6] Bound check failures and elapsed-time updates Architecture-Review: unchanged; the command data flow and delivery roles still apply. Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 4 +-- src/loopzero/cli.py | 38 ++++++++++++++++--------- src/loopzero/sandbox.py | 7 +++-- tests/test_cli.py | 62 +++++++++++++++++++++++++++++++++++++++++ tests/test_sandbox.py | 5 ++-- 5 files changed, 96 insertions(+), 20 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 49620cba..5a9581c2 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -76,8 +76,8 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con source sandbox. It inventories Git object stores only when alternates may be present. Its simple-command preflight catches missing local scripts, prepares recognized uv dependency groups offline in that sandbox and prints - progress before each command, metadata-only stage heartbeats every 30 seconds - (including silent children), and exit code/duration immediately after each stage. + progress before each command, a metadata-only heartbeat after 30 seconds and every + five minutes thereafter, and exit code/duration immediately after each stage. Heartbeats stop on completion or cancellation and never supply a verdict. Local stages drain merged child output and retain a bounded diagnostic tail. Trusted-base commands remain authoritative; diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index f1645fb8..bb4ef726 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -624,6 +624,20 @@ def cmd_start(args: argparse.Namespace) -> int: return 0 +def _check_failure_preview(tail: str, limit: int = 1536) -> str: + if len(tail.encode()) <= limit: + return tail + edge = limit // 8 + lines = (line.encode() for line in tail.splitlines()) + preview = b"\n".join( + line if len(line) <= 2 * edge else line[:edge] + b" [...] " + line[-edge:] + for line in lines + ) + if len(preview) > limit: + preview = b"[...]\n" + preview[6 - limit:] + return preview.decode(errors="ignore") + + def cmd_check(args: argparse.Namespace) -> int: wt, config = _context(args, pin_checks=True) if not config.checks: @@ -637,32 +651,30 @@ def cmd_check(args: argparse.Namespace) -> int: except sandbox.SandboxUnavailable as exc: print(f"sandbox unavailable: {exc}", file=sys.stderr) return 2 + shortened = False for result in report.results: if result.exit_code != 0: print(f"--- {result.command} (exit {result.exit_code}) ---", file=sys.stderr) tail = _proc.tail(result.tail) - print(tail, file=sys.stderr) + preview = _check_failure_preview(tail) + shortened |= preview != tail + print(preview, file=sys.stderr) if not config.network and (result.command.startswith("uv sync --offline --locked") or OFFLINE_FAILURE_RE.search(tail)): - env = { - **sandbox.SANDBOX_ENV, - **_proc.build_env(config.env_allowlist), - **dict(config.env), - } + env = sandbox.SANDBOX_ENV | _proc.build_env(config.env_allowlist) | dict(config.env) print( "\nThe sandbox has no network because `[checks] network = false`; " f"the effective UV_CACHE_DIR inside the sandbox is {env['UV_CACHE_DIR']}. " - "To prepare offline, run UV_CACHE_DIR= uv sync --group dev " - "(use the groups your checks require) on the host, or the same commands, so the cache " - "under `[checks] writable` is warm, or set `[checks] env` UV_CACHE_DIR to " - "that cache.", - file=sys.stderr, + "Run UV_CACHE_DIR= uv sync --group dev on the host " + "(use the required groups) so the cache under `[checks] writable` is warm, " + "or set `[checks] env` UV_CACHE_DIR to a warm cache.", file=sys.stderr, ) - current_head = _save_report(wt, report) - if current_head is not None: + if (current_head := _save_report(wt, report)) is not None: print(f"check result discarded: checked HEAD {report.head}, current HEAD {current_head}", file=sys.stderr) return 1 + if shortened: + print(f"Full diagnostic tail: {CHECKS_FILE} (head {report.head})", file=sys.stderr) if report.ok and report.settings_sha256 is None: print("check stages passed but the receipt is unverified; rerun loopzero check from the task " "worktree with a stable, readable configured runner before running ready", file=sys.stderr) diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index 6f725e28..663784be 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -31,7 +31,8 @@ TIMEOUT_EXIT = 124 CHECK_SHELL = ("/bin/bash", "--posix", "-o", "pipefail", "-c") CHECK_TAIL_BYTES = 16 * 1024 -HEARTBEAT_INTERVAL = 30.0 +FIRST_HEARTBEAT_DELAY = 30.0 +HEARTBEAT_INTERVAL = 300.0 SANDBOX_HOME = "/tmp/home" # Only these system directories are exposed read-only by default; home tool paths # require explicit `[checks] ro_paths`. Host homes, sockets and processes stay hidden. @@ -325,9 +326,11 @@ def _stage_status(status: Callable[[str], None] | None, ordinal: int, total: int started = time.monotonic() def heartbeat(): - while not stopped.wait(HEARTBEAT_INTERVAL): + delay = FIRST_HEARTBEAT_DELAY + while not stopped.wait(delay): status(f"stage {ordinal}/{total}: running " f"({time.monotonic() - started:.1f}s elapsed)") + delay = HEARTBEAT_INTERVAL reporter = threading.Thread(target=heartbeat, daemon=True) if status else None if reporter: diff --git a/tests/test_cli.py b/tests/test_cli.py index 5c136d5d..1a0e5abf 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -358,6 +358,68 @@ def expect_cli(capsys, exit_code, *argv, stdout=None, stderr=None, stdout_contai return out, err +# Transcript size regressions +@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' + tail += "migration failed: relation widgets already exists\nAssertionError: assert " + "x" * 1000 + monkeypatch.setattr(cli.sandbox, "run_checks", lambda *a, **k: CheckReport( + "a" * 40 if receipt == "head moved" else head, False, + (CheckResult("apply migrations", 7, 0.1, tail),), + )) + if receipt == "write failed": + monkeypatch.setattr(cli, "_save_report", Mock(side_effect=PermissionError("receipt write denied"))) + code, out, err = run(capsys, "check") + assert len((out + err).encode()) < 2500 + assert code == 1 and "apply migrations (exit 7)" in err + assert all(text in err for text in ("migration failed: relation widgets already exists", "AssertionError: assert", "[...]")) + assert "uv sync --group dev" in err + if receipt == "saved": + assert out.endswith("FAIL\n") and ".loopzero/checks.json" in err and head in err + assert json.loads((wt / ".loopzero/checks.json").read_text())["results"][0]["tail"] == tail + else: + assert ".loopzero/checks.json" not in err + assert ("current HEAD" if receipt == "head moved" else "receipt write denied") in err + + +def test_check_hour_long_stage_transcript(wt, head, gh, capsys, monkeypatch): + sandbox = cli.sandbox + clock = poll_clock(monkeypatch) + deadline = 0.0 + + def wait(seconds): + clock.now += seconds + return clock.now >= deadline + + monkeypatch.setattr(sandbox.threading, "Event", lambda: Mock(wait=wait)) + monkeypatch.setattr(sandbox.threading, "Thread", lambda *, target, daemon: Mock(start=target)) + + def run_checks(cfg, path, *, progress, status, checkpoint, workflow): + nonlocal deadline + results = [] + for ordinal in range(1, 25): + command = f"run tool {ordinal:02d}" + duration = 3600.0 if ordinal == 1 else 0.1 + deadline = clock.now + duration + progress(command) + with sandbox._stage_status(status, ordinal, 24): + pass + status(f"stage {ordinal}/24: exit 0 ({duration:.1f}s)") + results.append(CheckResult(command, 0, duration, "")) + return CheckReport(head, False, tuple(results), sandbox.settings_fingerprint(cfg, path)) + + monkeypatch.setattr(sandbox, "run_checks", run_checks) + code, out, err = run(capsys, "check") + assert len((out + err).encode()) < 2400 + assert (code, err, gh.calls) == (0, "", []) and out.endswith("PASS\n") + assert f"receipt produced: head={head}" in out and "stage 24/24: exit 0" in out + assert out.count("running: run tool") == 24 + assert [float(seconds) for seconds in re.findall(r"running \(([\d.]+)s elapsed\)", out)] == list( + range(30, 3600, 300) + ) + assert out.rindex("s elapsed)") < out.index("stage 1/24: exit 0 (3600.0s)") + + # --- start / check -------------------------------------------------------------------- diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index 674e4d8a..705d3f7c 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -542,7 +542,7 @@ def _pairs(argv: list[str], flag: str) -> list[tuple[str, str]]: @pytest.fixture def heartbeat_log(monkeypatch): - monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03) + monkeypatch.setattr(sandbox, "FIRST_HEARTBEAT_DELAY", 0.03) observed, events, reporters = Event(), [], set() def status(message): @@ -600,7 +600,6 @@ def run_stage(config, worktree, prefix, stage_command, timeout): def test_early_failure_reports_actual_exit_without_heartbeat(git_repo, bwrap_log, monkeypatch): - monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 30.0) events = [] report = sandbox.run_checks( make_config(checks=("echo secret; exit 17", "echo never")), git_repo, @@ -685,7 +684,7 @@ def status(message): if mode == "blocked-heartbeat": threading.Event().wait() -sandbox.HEARTBEAT_INTERVAL = 0.03 +sandbox.FIRST_HEARTBEAT_DELAY = 0.03 repo = Path.cwd() command = "echo complete" if mode in {"dispatch", "removal"} else "exec sleep 30" report = sandbox.run_checks(make_config(checks=(command,)), repo, status=status) From f27a50e36076ca0e54504f9d95adaf6ac812e7ec Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:16:27 +0100 Subject: [PATCH 4/6] Keep regression proof within fifteen net test lines Co-Authored-By: Codex --- tests/test_cli.py | 78 ++++++++++++++--------------------------------- 1 file changed, 23 insertions(+), 55 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index c8a6531f..1a0ce7c5 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3944,21 +3944,36 @@ def test_ready_allows_behind_only_after_configured_mergify_attestation( assert f"ready: {'yes' if attested else 'no'}" in out -def test_mergify_wait_resume_does_not_resubmit_and_reports_ejection( - wt: Path, gh: FakeGh, capsys, monkeypatch +@pytest.mark.parametrize("command", ["ready", "merge", "resume"]) +def test_mergify_checks_current_target_before_queueing_or_resumes( + wt: Path, repo: Path, gh: FakeGh, capsys, monkeypatch, command ) -> None: - head = commit_mergify_configuration(wt) + commit_mergify_configuration(wt) + checker = (Path(__file__).resolve().parents[1] / "scripts/size_budget.sh").read_text() + (repo / "scripts").mkdir() + commit_file(repo, "scripts/size_budget.sh", re.sub(r"(?m)^SRC_CAP=\d+$", "SRC_CAP=3", checker), "add budget") + publish_workflow(wt, (repo / "workflow.toml").read_text().replace( + 'commands = ["echo ok", "test -f README.md"]', 'commands = ["scripts/size_budget.sh"]')) + for checkout, filename in ((wt, "feature"), (repo, "upstream")): + (checkout / "src/loopzero").mkdir(parents=True) + commit_file(checkout, f"src/loopzero/{filename}.py", "# first line\n# second line\n", filename) + commit_file(wt, "ast.py", "raise AssertionError('loaded candidate module')\n", "add candidate module") + git(repo, "push", str(repo.parent / "origin.git"), "main") # leave origin/main stale locally + head = head_of(wt) arm_approved_ready_pr(gh, head, wt, isDraft=False) gh.append(f"api repos/{REPO}/pulls/7", rest_pr_json(pr_json(headRefOid=head, isDraft=False))) gh.append(f"api repos/{REPO}/pulls/7", merge_json(state='OPEN', head=head, sha=None)) monkeypatch.setattr(mergify, "configured", lambda *_: True) - monkeypatch.setattr(mergify, "markers", lambda *_: (True, True)) + monkeypatch.setattr(mergify, "markers", lambda *_: (command == "resume",) * 2) monkeypatch.setattr(mergify, "membership", lambda *_: None) - monkeypatch.setattr( - mergify, "request", lambda *_: pytest.fail("resume must not submit another command") - ) + monkeypatch.setattr(mergify, "request", lambda *_: pytest.fail("must not submit a queue request")) - code, _out, err = run(capsys, "merge", "--wait=1") + args = ("merge", "--wait=1") if command == "resume" else (command,) + code, _out, err = run(capsys, *args) + assert head_of(wt) == head and not (wt / "src/loopzero/upstream.py").exists() + if command != "resume": + assert code == 1 and "src=4 (base 2, delta 2, cap 3" in err and "loaded candidate module" not in err + return assert 'Read Mergify\'s "Left the queue" comment' in err assert code == 1 and "post `@mergifyio queue` as the whole PR comment (same login), then rerun `loopzero merge --wait`" in err @@ -4855,50 +4870,3 @@ def test_pr_marks_legacy_same_head_check_unverified(wt, gh, capsys, refresh): assert "unverified" not in draft assert f"Recorded for `{head[:12]}`\n- `echo ok`: exit 0" in draft assert "Manual validation evidence." in draft - - -@pytest.mark.parametrize("command", ["ready", "merge", "resume"]) -def test_prequeue_size_budget_replays_1230(wt, repo, gh, capsys, monkeypatch, command): - # PR #1230 fit its fork point at 7,482. Current main added 26 independent lines. - checker = Path(__file__).resolve().parents[1] / "scripts/size_budget.sh" - cap = int(re.search(r"^SRC_CAP=(\d+)$", checker.read_text(), re.MULTILINE)[1]) - (repo / "scripts").mkdir() - shutil.copyfile(checker, repo / "scripts/size_budget.sh") - policy = (repo / "workflow.toml").read_text().replace( - 'merge = "squash"', 'merge = "mergify"\nmergify_queue = "main"' - ).replace('commands = ["echo ok", "test -f README.md"]', 'commands = ["scripts/size_budget.sh"]') - git(repo, "add", "scripts") - publish_workflow(wt, policy) - fork = head_of(repo) - git(wt, "merge", "--no-edit", fork) - for checkout, name, lines in [(wt, "feature", cap - 18), (repo, "upstream", 26)]: - folder = checkout / "src/loopzero" - folder.mkdir(parents=True) - (folder / f"{name}.py").write_text("# counted line\n" * lines) - git(checkout, "add", "src") - git(checkout, "commit", "-qm", name) - # The trusted checker must import standard modules, not candidate files. - (wt / "ast.py").write_text("raise AssertionError('candidate module loaded')\n") - git(wt, "add", "ast.py") - git(wt, "commit", "-qm", "add candidate module shadow") - # Deliberately leave origin/main stale in the source repository. - git(repo, "push", "--no-verify", str(repo.parent / "origin.git"), "main") - git(repo, "update-ref", "refs/remotes/origin/main", fork) - head = head_of(wt) - arm_approved_pr_with_check_result(gh, head, wt, "success", isDraft=False) - monkeypatch.setattr(mergify, "configured", lambda *_: True) - monkeypatch.setattr(mergify, "markers", lambda *_: (command == "resume", False)) - monkeypatch.setattr(mergify, "membership", lambda *_: None) - monkeypatch.setattr(mergify, "request", lambda *_: pytest.fail("must not request admission")) - monkeypatch.setattr(cli, "_wait_for_mergify", lambda *_: None) - - args = ("merge", "--wait=0") if command == "resume" else (command,) - code, out, err = run(capsys, *args) - - if command == "resume": - assert code == 3 and "size budget" not in out + err - else: - assert code == 1 and f"src={cap + 8} (base 26, delta {cap - 18}, cap {cap}" in out + err - assert "candidate module loaded" not in out + err - assert head_of(wt) == head - assert not (wt / "src/loopzero/upstream.py").exists() From 8534210211515bc33c81ae3c6ac0d2298c25f2ac Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:16:50 +0100 Subject: [PATCH 5/6] Place output regression tests next to their command coverage Co-Authored-By: Codex --- tests/test_cli.py | 122 +++++++++++++++++++++++----------------------- 1 file changed, 61 insertions(+), 61 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index 1a0e5abf..8ac87bbe 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -359,67 +359,6 @@ def expect_cli(capsys, exit_code, *argv, stdout=None, stderr=None, stdout_contai # Transcript size regressions -@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' - tail += "migration failed: relation widgets already exists\nAssertionError: assert " + "x" * 1000 - monkeypatch.setattr(cli.sandbox, "run_checks", lambda *a, **k: CheckReport( - "a" * 40 if receipt == "head moved" else head, False, - (CheckResult("apply migrations", 7, 0.1, tail),), - )) - if receipt == "write failed": - monkeypatch.setattr(cli, "_save_report", Mock(side_effect=PermissionError("receipt write denied"))) - code, out, err = run(capsys, "check") - assert len((out + err).encode()) < 2500 - assert code == 1 and "apply migrations (exit 7)" in err - assert all(text in err for text in ("migration failed: relation widgets already exists", "AssertionError: assert", "[...]")) - assert "uv sync --group dev" in err - if receipt == "saved": - assert out.endswith("FAIL\n") and ".loopzero/checks.json" in err and head in err - assert json.loads((wt / ".loopzero/checks.json").read_text())["results"][0]["tail"] == tail - else: - assert ".loopzero/checks.json" not in err - assert ("current HEAD" if receipt == "head moved" else "receipt write denied") in err - - -def test_check_hour_long_stage_transcript(wt, head, gh, capsys, monkeypatch): - sandbox = cli.sandbox - clock = poll_clock(monkeypatch) - deadline = 0.0 - - def wait(seconds): - clock.now += seconds - return clock.now >= deadline - - monkeypatch.setattr(sandbox.threading, "Event", lambda: Mock(wait=wait)) - monkeypatch.setattr(sandbox.threading, "Thread", lambda *, target, daemon: Mock(start=target)) - - def run_checks(cfg, path, *, progress, status, checkpoint, workflow): - nonlocal deadline - results = [] - for ordinal in range(1, 25): - command = f"run tool {ordinal:02d}" - duration = 3600.0 if ordinal == 1 else 0.1 - deadline = clock.now + duration - progress(command) - with sandbox._stage_status(status, ordinal, 24): - pass - status(f"stage {ordinal}/24: exit 0 ({duration:.1f}s)") - results.append(CheckResult(command, 0, duration, "")) - return CheckReport(head, False, tuple(results), sandbox.settings_fingerprint(cfg, path)) - - monkeypatch.setattr(sandbox, "run_checks", run_checks) - code, out, err = run(capsys, "check") - assert len((out + err).encode()) < 2400 - assert (code, err, gh.calls) == (0, "", []) and out.endswith("PASS\n") - assert f"receipt produced: head={head}" in out and "stage 24/24: exit 0" in out - assert out.count("running: run tool") == 24 - assert [float(seconds) for seconds in re.findall(r"running \(([\d.]+)s elapsed\)", out)] == list( - range(30, 3600, 300) - ) - assert out.rindex("s elapsed)") < out.index("stage 1/24: exit 0 (3600.0s)") - - # --- start / check -------------------------------------------------------------------- @@ -646,6 +585,67 @@ 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("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' + tail += "migration failed: relation widgets already exists\nAssertionError: assert " + "x" * 1000 + monkeypatch.setattr(cli.sandbox, "run_checks", lambda *a, **k: CheckReport( + "a" * 40 if receipt == "head moved" else head, False, + (CheckResult("apply migrations", 7, 0.1, tail),), + )) + if receipt == "write failed": + monkeypatch.setattr(cli, "_save_report", Mock(side_effect=PermissionError("receipt write denied"))) + code, out, err = run(capsys, "check") + assert len((out + err).encode()) < 2500 + assert code == 1 and "apply migrations (exit 7)" in err + assert all(text in err for text in ("migration failed: relation widgets already exists", "AssertionError: assert", "[...]")) + assert "uv sync --group dev" in err + if receipt == "saved": + assert out.endswith("FAIL\n") and ".loopzero/checks.json" in err and head in err + assert json.loads((wt / ".loopzero/checks.json").read_text())["results"][0]["tail"] == tail + else: + assert ".loopzero/checks.json" not in err + assert ("current HEAD" if receipt == "head moved" else "receipt write denied") in err + + +def test_check_hour_long_stage_transcript(wt, head, gh, capsys, monkeypatch): + sandbox = cli.sandbox + clock = poll_clock(monkeypatch) + deadline = 0.0 + + def wait(seconds): + clock.now += seconds + return clock.now >= deadline + + monkeypatch.setattr(sandbox.threading, "Event", lambda: Mock(wait=wait)) + monkeypatch.setattr(sandbox.threading, "Thread", lambda *, target, daemon: Mock(start=target)) + + def run_checks(cfg, path, *, progress, status, checkpoint, workflow): + nonlocal deadline + results = [] + for ordinal in range(1, 25): + command = f"run tool {ordinal:02d}" + duration = 3600.0 if ordinal == 1 else 0.1 + deadline = clock.now + duration + progress(command) + with sandbox._stage_status(status, ordinal, 24): + pass + status(f"stage {ordinal}/24: exit 0 ({duration:.1f}s)") + results.append(CheckResult(command, 0, duration, "")) + return CheckReport(head, False, tuple(results), sandbox.settings_fingerprint(cfg, path)) + + monkeypatch.setattr(sandbox, "run_checks", run_checks) + code, out, err = run(capsys, "check") + assert len((out + err).encode()) < 2400 + assert (code, err, gh.calls) == (0, "", []) and out.endswith("PASS\n") + assert f"receipt produced: head={head}" in out and "stage 24/24: exit 0" in out + assert out.count("running: run tool") == 24 + assert [float(seconds) for seconds in re.findall(r"running \(([\d.]+)s elapsed\)", out)] == list( + range(30, 3600, 300) + ) + assert out.rindex("s elapsed)") < out.index("stage 1/24: exit 0 (3600.0s)") + + @pytest.mark.parametrize("command,exit_code,tail", [ ("echo no; exit 3", 3, "no\n"), ("seq 1 50; exit 1", 1, "".join(f"{i}\n" for i in range(11, 51)))]) From 5d924132195d46b7abd156961597fed203f3a20e Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:17:19 +0100 Subject: [PATCH 6/6] Keep the shared test helper section unchanged Co-Authored-By: Codex --- tests/test_cli.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index 8ac87bbe..f51f214b 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -358,7 +358,6 @@ def expect_cli(capsys, exit_code, *argv, stdout=None, stderr=None, stdout_contai return out, err -# Transcript size regressions # --- start / check --------------------------------------------------------------------