From 5f35986e66b569a5dc8aae2bee14d50c53aa419e Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:36:56 +0100 Subject: [PATCH 1/6] Redact credentials in terminal check headings Architecture-Review: unchanged; terminal rendering uses the existing command redactor without changing execution or receipt identity. Co-Authored-By: Codex --- src/loopzero/cli.py | 5 +++-- tests/test_cli.py | 8 ++++---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index f3c59c09..03c649cb 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -630,7 +630,7 @@ def cmd_check(args: argparse.Namespace) -> int: raise config_mod.ConfigError("checks.commands must list at least one command to run checks") try: report = sandbox.run_checks(config, wt, progress=lambda command: print( - f"running: {command}", flush=True), + f"running: {github.redact_credentials(command)}", flush=True), status=lambda message: print(message, flush=True), checkpoint=lambda partial: _save_report(wt, partial), workflow=args.config or f"origin/{config.base_branch}:workflow.toml") @@ -639,7 +639,8 @@ def cmd_check(args: argparse.Namespace) -> int: return 2 for result in report.results: if result.exit_code != 0: - print(f"--- {result.command} (exit {result.exit_code}) ---", file=sys.stderr) + heading = github.redact_credentials(result.command) + print(f"--- {heading} (exit {result.exit_code}) ---", file=sys.stderr) tail = _proc.tail(result.tail) print(tail, file=sys.stderr) if not config.network and (result.command.startswith("uv sync --offline --locked") diff --git a/tests/test_cli.py b/tests/test_cli.py index f679c279..d7ff2d9c 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -544,7 +544,7 @@ def test_malformed_live_markers_do_not_mask_check_verdict( @pytest.mark.parametrize("command,exit_code,tail", [ - ("echo no; exit 3", 3, "no\n"), + ("echo no; exit 3 # https://fake-heading-secret@example.invalid", 3, "no\n"), ("seq 1 50; exit 1", 1, "".join(f"{i}\n" for i in range(11, 51)))]) def test_check_failure_reports_verdict_and_capped_tail(wt, capsys, command, exit_code, tail): (wt / "workflow.toml").write_text(WORKFLOW.replace( @@ -552,10 +552,10 @@ def test_check_failure_reports_verdict_and_capped_tail(wt, capsys, command, exit code, out, err = run(capsys, "--config", str(wt / "workflow.toml"), "check") assert code == 1 and out.endswith("FAIL\n") assert out.startswith("checks are unpinned because --config was provided\n") - assert sum(line.startswith(("stage 1/2: exit ", "exit ")) - for line in out.splitlines()) == 1 + heading = command.replace("fake-heading-secret", "[REDACTED]") + assert out.count(f"running: {heading}\n") == out.count("stage 1/2: exit ") == 1 assert f"stage 1/2: exit {exit_code} (" in out and "README.md" not in out - assert err == f"--- {command} (exit {exit_code}) ---\n{tail}" + assert err == f"--- {heading} (exit {exit_code}) ---\n{tail}" report = json.loads((wt / ".loopzero/checks.json").read_text()) assert [result["command"] for result in report["results"]] == [command] From 6ebc7002c279194fca90e21f7d7c0e7094969402 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:19:18 +0100 Subject: [PATCH 2/6] Accept check receipts across host environments Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 9 +++++---- src/loopzero/sandbox.py | 8 +++++--- tests/test_sandbox.py | 27 +++++++++++++++++---------- 3 files changed, 27 insertions(+), 17 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 49620cba..f8afff13 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -110,10 +110,11 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con at that head with the current commands and check settings digest. A settings change or an older receipt without the digest requires a fresh check. The digest covers execution and stage reuse settings without recording raw - environment values. It excludes only inherited `HEAVY_SLOT_GRANTED_CORES` - for local sandbox receipts. Explicit settings, delegated runner environments - and stage reuse keys still bind the grant. Waiters check for policy changes - on every poll. + environment values. For local sandbox receipts it omits inherited `PATH`, + `LANG`, `LC_ALL`, `TERM`, and `HEAVY_SLOT_GRANTED_CORES` so readiness can + run in a different host environment. Explicit settings, delegated runner + environments, and stage reuse keys still bind these values. Waiters check + for policy changes on every poll. Local readiness and hosted eligibility carry a review forward only across a first-parent chain of verified merges from the configured PR base. They reconstruct each merge in an isolated Git repository and compare its tree diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index 6f725e28..731604d8 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -253,9 +253,11 @@ def settings_fingerprint(config: Config, worktree: Path, *, base: str | None = N settings = _execution_settings(config, base) if config.check_runner and settings["runner_executable"] is None: return None - if not config.check_runner and "HEAVY_SLOT_GRANTED_CORES" not in config.env: - # The inherited local worker limit is transient. Stage reuse still binds it. - settings["environment"].pop("HEAVY_SLOT_GRANTED_CORES", None) + if not config.check_runner: + # Inherited host settings can differ at readiness. Stage reuse still binds them. + host_env = {"PATH", "LANG", "LC_ALL", "TERM", "HEAVY_SLOT_GRANTED_CORES"} + for name in host_env - dict(config.env).keys(): + settings["environment"].pop(name, None) payload = [settings, config.inputs] return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest() diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index 674e4d8a..39910fd3 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -749,23 +749,25 @@ def cache(config, *, clean=False, verify_reuse=False): @pytest.mark.parametrize('change', ['other', 'input', 'shared', 'command', 'network', 'environment', 'version', 'failed', 'boolean_exit_code', 'dirty_receipt', 'keyless', - 'dirty_tree', 'legacy', 'grant']) -def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, change): + 'dirty_tree', 'legacy', 'grant', 'host_environment']) +def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, change, cache_check): cfg = make_config(checks=('echo one', 'echo two'), inputs={'echo one': ('*.md',), 'echo two': ('*.md',), '*': ('shared',)}) - if change == 'grant': - cfg = replace(cfg, env_allowlist=(*cfg.env_allowlist, "HEAVY_SLOT_GRANTED_CORES")) - monkeypatch.setenv("HEAVY_SLOT_GRANTED_CORES", "2") + original_path = os.environ["PATH"] + host_env = {"HEAVY_SLOT_GRANTED_CORES": "2"} + if change == 'host_environment': + host_env.update(PATH="/opt/tools:" + original_path, LANG="en_US.UTF-8", LC_ALL="en_US.UTF-8", TERM="dumb") + if change in {'grant', 'host_environment'}: + cfg = replace(cfg, env_allowlist=tuple(dict.fromkeys((*cfg.env_allowlist, *host_env)))) + for key, value in host_env.items(): + monkeypatch.setenv(key, value) for inputs in ({}, {'*': ()}, {'*': ('uv.lock',)}): assert sandbox._input_key(replace(cfg, inputs=inputs), git_repo, 'unlisted', fetched_base) is None whole = replace(cfg, inputs={'*': ('.',)}) key = sandbox._input_key(whole, git_repo, 'unlisted', fetched_base) assert key is not None - _save_report(git_repo, sandbox.run_checks(cfg, git_repo)) + cache_check(cfg) receipt = git_repo / '.loopzero/checks.json' - git(git_repo, 'config', 'core.excludesFile', str(git_repo / '.git/info/exclude')) - with (git_repo / '.git/info/exclude').open('a') as stream: - stream.write('\n.loopzero/\n') if change in {'other', 'input', 'shared', 'dirty_tree'}: path = 'README.md' if change in {'input', 'dirty_tree'} else 'src.py' if change == 'other' else change (git_repo / path).write_text('new content') @@ -780,7 +782,12 @@ def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, ch elif change == 'environment': monkeypatch.setenv('LZ_KEEP', 'changed') assert _current_check_report(git_repo, cfg, fetched_base) is None - elif change == 'grant': + elif change in {'grant', 'host_environment'}: + for key in host_env.keys() - {"PATH", "LANG", "HEAVY_SLOT_GRANTED_CORES"}: + monkeypatch.delenv(key) + if change == 'host_environment': + monkeypatch.setenv("PATH", original_path) + monkeypatch.setenv("LANG", "C") monkeypatch.setenv("HEAVY_SLOT_GRANTED_CORES", "4") assert _current_check_report(git_repo, cfg, fetched_base) is not None monkeypatch.delenv("HEAVY_SLOT_GRANTED_CORES") From 5c82dce740078e61938b23de0642c328d46ad75b Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:39:18 +0100 Subject: [PATCH 3/6] Exercise host portability at the ready entry point Co-Authored-By: Codex --- tests/test_cli.py | 14 +++++++------- tests/test_sandbox.py | 27 ++++++++++----------------- 2 files changed, 17 insertions(+), 24 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index 5c136d5d..435939fa 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3032,12 +3032,14 @@ def test_ready_matches_effective_inherited_check_environment(capsys, monkeypatch assert code == 1 and "not ready: check receipt has an incompatible settings fingerprint." in out -@pytest.mark.parametrize("worker", ["legacy", "different-path", "matching"]) +@pytest.mark.parametrize("worker", ["legacy", "different-environment", "matching"]) def test_ready_checks_transferred_whole_job_receipt(wt, gh, capsys, head, tmp_path, monkeypatch, worker): arm_approved_ready_pr(gh, head, wt, readiness={"local_exit": None}, isDraft=False) with monkeypatch.context() as worker_env: - if worker == "different-path": + if worker == "different-environment": worker_env.setenv("PATH", str(tmp_path / "worker-bin"), prepend=":") + for name, value in {"LANG": "en_US.UTF-8", "LC_ALL": "en_US.UTF-8", "TERM": "dumb"}.items(): + worker_env.setenv(name, value) assert run(capsys, "check")[0] == 0 receipt = wt / ".loopzero/checks.json" @@ -3045,11 +3047,9 @@ def test_ready_checks_transferred_whole_job_receipt(wt, gh, capsys, head, tmp_pa if worker == "legacy": # Older producers serialize these results without a settings fingerprint. del payload["settings_sha256"] - # Whole-job transport preserves the producer's fields. - receipt.write_text(json.dumps(payload)) - assert run(capsys, "ready")[0] == (0 if worker == "matching" else 1) - - if worker != "matching": + receipt.write_text(json.dumps(payload)) + assert run(capsys, "ready")[0] == int(worker == "legacy") + if worker == "legacy": assert run(capsys, "check")[0] == 0 assert run(capsys, "ready")[0] == 0 diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index 39910fd3..674e4d8a 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -749,25 +749,23 @@ def cache(config, *, clean=False, verify_reuse=False): @pytest.mark.parametrize('change', ['other', 'input', 'shared', 'command', 'network', 'environment', 'version', 'failed', 'boolean_exit_code', 'dirty_receipt', 'keyless', - 'dirty_tree', 'legacy', 'grant', 'host_environment']) -def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, change, cache_check): + 'dirty_tree', 'legacy', 'grant']) +def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, change): cfg = make_config(checks=('echo one', 'echo two'), inputs={'echo one': ('*.md',), 'echo two': ('*.md',), '*': ('shared',)}) - original_path = os.environ["PATH"] - host_env = {"HEAVY_SLOT_GRANTED_CORES": "2"} - if change == 'host_environment': - host_env.update(PATH="/opt/tools:" + original_path, LANG="en_US.UTF-8", LC_ALL="en_US.UTF-8", TERM="dumb") - if change in {'grant', 'host_environment'}: - cfg = replace(cfg, env_allowlist=tuple(dict.fromkeys((*cfg.env_allowlist, *host_env)))) - for key, value in host_env.items(): - monkeypatch.setenv(key, value) + if change == 'grant': + cfg = replace(cfg, env_allowlist=(*cfg.env_allowlist, "HEAVY_SLOT_GRANTED_CORES")) + monkeypatch.setenv("HEAVY_SLOT_GRANTED_CORES", "2") for inputs in ({}, {'*': ()}, {'*': ('uv.lock',)}): assert sandbox._input_key(replace(cfg, inputs=inputs), git_repo, 'unlisted', fetched_base) is None whole = replace(cfg, inputs={'*': ('.',)}) key = sandbox._input_key(whole, git_repo, 'unlisted', fetched_base) assert key is not None - cache_check(cfg) + _save_report(git_repo, sandbox.run_checks(cfg, git_repo)) receipt = git_repo / '.loopzero/checks.json' + git(git_repo, 'config', 'core.excludesFile', str(git_repo / '.git/info/exclude')) + with (git_repo / '.git/info/exclude').open('a') as stream: + stream.write('\n.loopzero/\n') if change in {'other', 'input', 'shared', 'dirty_tree'}: path = 'README.md' if change in {'input', 'dirty_tree'} else 'src.py' if change == 'other' else change (git_repo / path).write_text('new content') @@ -782,12 +780,7 @@ def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, ch elif change == 'environment': monkeypatch.setenv('LZ_KEEP', 'changed') assert _current_check_report(git_repo, cfg, fetched_base) is None - elif change in {'grant', 'host_environment'}: - for key in host_env.keys() - {"PATH", "LANG", "HEAVY_SLOT_GRANTED_CORES"}: - monkeypatch.delenv(key) - if change == 'host_environment': - monkeypatch.setenv("PATH", original_path) - monkeypatch.setenv("LANG", "C") + elif change == 'grant': monkeypatch.setenv("HEAVY_SLOT_GRANTED_CORES", "4") assert _current_check_report(git_repo, cfg, fetched_base) is not None monkeypatch.delenv("HEAVY_SLOT_GRANTED_CORES") From 486f9b78a22fe141b11af187ffc88780f7d5ec5c Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:40:48 +0100 Subject: [PATCH 4/6] Keep coverage for rerunning stages across worker environments Co-Authored-By: Codex --- tests/test_sandbox.py | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index 674e4d8a..39910fd3 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -749,23 +749,25 @@ def cache(config, *, clean=False, verify_reuse=False): @pytest.mark.parametrize('change', ['other', 'input', 'shared', 'command', 'network', 'environment', 'version', 'failed', 'boolean_exit_code', 'dirty_receipt', 'keyless', - 'dirty_tree', 'legacy', 'grant']) -def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, change): + 'dirty_tree', 'legacy', 'grant', 'host_environment']) +def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, change, cache_check): cfg = make_config(checks=('echo one', 'echo two'), inputs={'echo one': ('*.md',), 'echo two': ('*.md',), '*': ('shared',)}) - if change == 'grant': - cfg = replace(cfg, env_allowlist=(*cfg.env_allowlist, "HEAVY_SLOT_GRANTED_CORES")) - monkeypatch.setenv("HEAVY_SLOT_GRANTED_CORES", "2") + original_path = os.environ["PATH"] + host_env = {"HEAVY_SLOT_GRANTED_CORES": "2"} + if change == 'host_environment': + host_env.update(PATH="/opt/tools:" + original_path, LANG="en_US.UTF-8", LC_ALL="en_US.UTF-8", TERM="dumb") + if change in {'grant', 'host_environment'}: + cfg = replace(cfg, env_allowlist=tuple(dict.fromkeys((*cfg.env_allowlist, *host_env)))) + for key, value in host_env.items(): + monkeypatch.setenv(key, value) for inputs in ({}, {'*': ()}, {'*': ('uv.lock',)}): assert sandbox._input_key(replace(cfg, inputs=inputs), git_repo, 'unlisted', fetched_base) is None whole = replace(cfg, inputs={'*': ('.',)}) key = sandbox._input_key(whole, git_repo, 'unlisted', fetched_base) assert key is not None - _save_report(git_repo, sandbox.run_checks(cfg, git_repo)) + cache_check(cfg) receipt = git_repo / '.loopzero/checks.json' - git(git_repo, 'config', 'core.excludesFile', str(git_repo / '.git/info/exclude')) - with (git_repo / '.git/info/exclude').open('a') as stream: - stream.write('\n.loopzero/\n') if change in {'other', 'input', 'shared', 'dirty_tree'}: path = 'README.md' if change in {'input', 'dirty_tree'} else 'src.py' if change == 'other' else change (git_repo / path).write_text('new content') @@ -780,7 +782,12 @@ def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, ch elif change == 'environment': monkeypatch.setenv('LZ_KEEP', 'changed') assert _current_check_report(git_repo, cfg, fetched_base) is None - elif change == 'grant': + elif change in {'grant', 'host_environment'}: + for key in host_env.keys() - {"PATH", "LANG", "HEAVY_SLOT_GRANTED_CORES"}: + monkeypatch.delenv(key) + if change == 'host_environment': + monkeypatch.setenv("PATH", original_path) + monkeypatch.setenv("LANG", "C") monkeypatch.setenv("HEAVY_SLOT_GRANTED_CORES", "4") assert _current_check_report(git_repo, cfg, fetched_base) is not None monkeypatch.delenv("HEAVY_SLOT_GRANTED_CORES") From 0c859b2ae9ece0e3183d024c01c2ead55fc90aa9 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:46:52 +0100 Subject: [PATCH 5/6] Warn when queued predecessors could exhaust a size budget Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 3 ++- src/loopzero/candidate.py | 4 ++-- src/loopzero/cli.py | 49 ++++++++++++++++++++++++++++++++------- src/loopzero/mergify.py | 39 ++++++++++++++++++++++++++++++- tach.toml | 2 +- tests/test_cli.py | 36 ++++++++++++++++++++++++---- 6 files changed, 116 insertions(+), 17 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 57956e14..bfa7d2db 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -315,7 +315,8 @@ even when the head stays the same. Merge admission rechecks the live hold. 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. +queue wait path. Readiness and new queue requests without an admission deadline can project an +advisory budget after a single known chain of queued predecessors. 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/candidate.py b/src/loopzero/candidate.py index 9179e09e..c5a23763 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -90,7 +90,7 @@ def _object(value: JsonValue, message: str) -> JsonObject: return value -def _flatten_batches(status: object) -> dict[str, JsonObject]: +def flatten_batches(status: object) -> dict[str, JsonObject]: _require(isinstance(status, dict), "Mergify status is not an object") batches = status.get("batches") _require(isinstance(batches, list), "Mergify status has no batches list") @@ -116,7 +116,7 @@ def visit(items: list[object]) -> None: def _candidate_lineage(status: JsonObject, candidate_number: int) -> tuple[str, list[int], list[str]]: - indexed = _flatten_batches(status) + indexed = flatten_batches(status) matches = [ batch for batch in indexed.values() diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 6c99472e..51442afb 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1251,7 +1251,7 @@ def _cleanup(wt: Path, pr: github.PR) -> None: def _prequeue_size_budget( - wt: Path, config: Config, pr: github.PR, readiness: github.Readiness, + wt: Path, config: Config, pr: github.PR, readiness: github.Readiness, *, project: bool = True, ) -> None: if not readiness.ready or config.merge_strategy != "mergify" or _SIZE_BUDGET not in config.checks: return @@ -1273,14 +1273,47 @@ def _prequeue_size_budget( 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) + + def evaluate(target: str) -> _proc.Completed: + tree = git("merge-tree", "--write-tree", target, pr.head_sha) + # A candidate symlink must not read files outside the temporary checkout. + git("-c", "core.symlinks=false", "read-tree", "--reset", "-u", tree) + return _proc.run(["bash", "-s", "--", base], input=script + "\n", cwd=root, + env_allowlist=("PATH",), extra_env=env, timeout=GIT_TIMEOUT, + merge_output=True) + + result = evaluate(base) if result.exit_code: raise CliError("current target size budget failed:\n" + result.stdout.rstrip()) + if project: + _warn_queue_size(config, pr, root, origin, base, git, evaluate) + + +def _warn_queue_size( + config: Config, pr: github.PR, root: Path, origin: str, base: str, + git: Callable[..., str], evaluate: Callable[[str], _proc.Completed], +) -> None: + assert config.mergify_queue is not None + try: + numbers = mergify.queue_predecessors(config.repo, config.base_branch, config.mergify_queue, pr.number) + if not numbers: + return + refs = [f"refs/pull/{number}/head:refs/loopzero/{number}" for number in numbers] + _git(root, "fetch", "--no-tags", "--no-recurse-submodules", "--", origin, *refs) + integrated = base + for number in numbers: + source = git("rev-parse", f"refs/loopzero/{number}^{{commit}}") + if git("merge-base", integrated, source) == source: + return # A queued PR may already have landed or be represented by another head. + tree = git("merge-tree", "--write-tree", integrated, source) + integrated = git("-c", "user.name=loopzero", "-c", "user.email=loopzero@localhost", + "commit-tree", tree, "-p", integrated, "-p", source, "-m", "Queue size projection") + result = evaluate(integrated) + except (LoopZeroError, OSError): + return + if result.exit_code and "size budget: FAIL" in result.stdout: + predecessors = ", ".join(f"#{number}" for number in numbers) + print(f"warning: projected size budget after {predecessors}:\n{result.stdout.rstrip()}") def cmd_ready(args: argparse.Namespace) -> int: @@ -1697,7 +1730,7 @@ def _merge_with_mergify( return sha raise closed[0] if not confirmed and not requested: - _prequeue_size_budget(wt, config, pr, readiness) + _prequeue_size_budget(wt, config, pr, readiness, project=admit_by is None) if admit_by is not None and time.monotonic() > admit_by: raise _AdmissionDeadline mergify.request(config.repo, pr.number, pr.head_sha, queue) diff --git a/src/loopzero/mergify.py b/src/loopzero/mergify.py index 347ea599..1b3a796a 100644 --- a/src/loopzero/mergify.py +++ b/src/loopzero/mergify.py @@ -16,7 +16,7 @@ from pathlib import Path from urllib.parse import quote -from . import github +from . import candidate, github from .types import LoopZeroError API = "https://api.mergify.com/v1" @@ -147,6 +147,43 @@ def membership(repo: str, number: int, queue: str) -> Membership | None: raise MergifyError("invalid Mergify queue membership response") from exc +def queue_predecessors(repo: str, branch: str, queue: str, number: int) -> tuple[int, ...]: + """Identify a single chain of one-PR batches ahead of a new request.""" + status = api_get(repo, f"/merge-queue/status?branch={quote(branch, safe='')}") + if (not isinstance(status, dict) or status.get("mode") != "serial" + or status.get("waiting_pull_requests") != [] or status.get("forming_batches") != []): + return () + try: + batches = candidate.flatten_batches(status) + successors: dict[str | None, tuple[str, int]] = {} + for batch_id, batch in batches.items(): + pulls, parents = batch["pull_requests"], batch["parent_ids"] + if pulls == [] and batch.get("sub_batches"): + continue # Container batches carry no direct source. + if (batch.get("queue_rule_name") != queue or not isinstance(pulls, list) + or len(pulls) != 1 or not isinstance(parents, list) or len(parents) > 1): + return () + source = pulls[0]["number"] + parent = next(iter(parents), None) + if type(source) is not int or source <= 0 or source == number or parent in successors: + return () + successors[parent] = batch_id, source + return _ordered_sources(successors) + except (candidate.CandidateError, KeyError, TypeError, RecursionError): + return () + + +def _ordered_sources(successors: dict[str | None, tuple[str, int]]) -> tuple[int, ...]: + if len(successors) > 32: + return () + sources = [] + cursor = None + while cursor in successors: + cursor, source = successors.pop(cursor) + sources.append(source) + return tuple(sources) if not successors and len(sources) == len(set(sources)) else () + + def _preserves_source_heads(repo: str, branch: str, queue: str) -> bool: """Read the vendor's canonical input, not a deprecated raw queue-rule default.""" import yaml diff --git a/tach.toml b/tach.toml index 58b5df60..5b4791fb 100644 --- a/tach.toml +++ b/tach.toml @@ -39,7 +39,7 @@ depends_on = ["loopzero._proc", "loopzero.runners", "loopzero.types"] [[modules]] path = "loopzero.mergify" -depends_on = ["loopzero.github", "loopzero.types"] +depends_on = ["loopzero.candidate", "loopzero.github", "loopzero.types"] [[modules]] path = "loopzero.candidate" diff --git a/tests/test_cli.py b/tests/test_cli.py index 5e41347f..0938e635 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3809,14 +3809,17 @@ def test_ready_allows_behind_only_after_configured_mergify_attestation( assert f"ready: {'yes' if attested else 'no'}" in out -@pytest.mark.parametrize("command", ["ready", "merge", "resume"]) +@pytest.mark.parametrize(("command", "queue"), [ + ("ready", None), ("merge", None), ("resume", None), ("ready", "ordered"), + ("ready", "empty"), ("ready", "ambiguous"), ("ready", "unavailable"), +]) def test_mergify_checks_current_target_before_queueing_or_resumes( - wt: Path, repo: Path, gh: FakeGh, capsys, monkeypatch, command + wt: Path, repo: Path, gh: FakeGh, capsys, monkeypatch, command, queue ) -> None: 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") + commit_file(repo, "scripts/size_budget.sh", re.sub(r"(?m)^SRC_CAP=\d+$", f"SRC_CAP={5 if queue else 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")): @@ -3824,6 +3827,26 @@ def test_mergify_checks_current_target_before_queueing_or_resumes( 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 + if queue: + main = head_of(repo) + batches = [] + for number in (1146, 1219): + git(repo, "switch", "--detach", main) + commit_file(repo, f"src/loopzero/pr_{number}.py", "# predecessor\n", f"PR {number}") + git(repo, "push", str(repo.parent / "origin.git"), f"HEAD:refs/pull/{number}/head") + batches.append({"id": str(number), "parent_ids": [batches[0]["id"]] if batches else [], + "queue_rule_name": "main", "pull_requests": [{"number": number}]}) + if queue == "ambiguous": + batches[1]["parent_ids"] = [] + + def snapshot(_repo, endpoint): + assert endpoint == "/merge-queue/status?branch=main" + if queue == "unavailable": + raise mergify.MergifyError("snapshot unavailable") + return {"mode": "serial", "waiting_pull_requests": [], "forming_batches": [], + "batches": [] if queue == "empty" else batches} + + monkeypatch.setattr(mergify, "api_get", snapshot) 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))) @@ -3834,8 +3857,13 @@ def test_mergify_checks_current_target_before_queueing_or_resumes( monkeypatch.setattr(mergify, "request", lambda *_: pytest.fail("must not submit a queue request")) args = ("merge", "--wait=1") if command == "resume" else (command,) - code, _out, err = run(capsys, *args) + code, out, err = run(capsys, *args) assert head_of(wt) == head and not (wt / "src/loopzero/upstream.py").exists() + if queue: + assert code == 0 and not err + assert ("warning: projected size budget after #1146, #1219:\nsrc=6 (base 2, delta 4, cap 5" in out + if queue == "ordered" else "warning: projected size budget" not in out) + return 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 From cadcc8d068cb5099e44f2117507d21ae0e7445c9 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:50:13 +0100 Subject: [PATCH 6/6] Prove receipt portability and stage reuse in the same check Co-Authored-By: Codex --- tests/test_cli.py | 17 ++++++++++------- tests/test_sandbox.py | 27 ++++++++++----------------- 2 files changed, 20 insertions(+), 24 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index 435939fa..b9a3c3f4 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3034,24 +3034,27 @@ def test_ready_matches_effective_inherited_check_environment(capsys, monkeypatch @pytest.mark.parametrize("worker", ["legacy", "different-environment", "matching"]) def test_ready_checks_transferred_whole_job_receipt(wt, gh, capsys, head, tmp_path, monkeypatch, worker): + policy = WORKFLOW.replace( + '[checks]', '[checks]\nenv_allowlist = ["PATH", "LANG", "LC_ALL", "TERM", "HEAVY_SLOT_GRANTED_CORES"]') + publish_workflow(wt, policy.replace('[delivery]', '[checks.inputs]\n"*" = ["."]\n\n[delivery]')) arm_approved_ready_pr(gh, head, wt, readiness={"local_exit": None}, isDraft=False) with monkeypatch.context() as worker_env: if worker == "different-environment": worker_env.setenv("PATH", str(tmp_path / "worker-bin"), prepend=":") - for name, value in {"LANG": "en_US.UTF-8", "LC_ALL": "en_US.UTF-8", "TERM": "dumb"}.items(): + for name, value in {"LANG": "en_US.UTF-8", "LC_ALL": "en_US.UTF-8", + "TERM": "dumb", "HEAVY_SLOT_GRANTED_CORES": "2"}.items(): worker_env.setenv(name, value) assert run(capsys, "check")[0] == 0 - receipt = wt / ".loopzero/checks.json" - payload = json.loads(receipt.read_bytes()) if worker == "legacy": - # Older producers serialize these results without a settings fingerprint. + receipt = wt / ".loopzero/checks.json" + payload = json.loads(receipt.read_bytes()) del payload["settings_sha256"] receipt.write_text(json.dumps(payload)) assert run(capsys, "ready")[0] == int(worker == "legacy") - if worker == "legacy": - assert run(capsys, "check")[0] == 0 - assert run(capsys, "ready")[0] == 0 + assert run(capsys, "check")[0] == 0 + assert all(bool(stage.reused_from) == (worker == "matching") for stage in cli._load_report(wt).results) + assert run(capsys, "ready")[0] == 0 def test_ready_ignores_forged_markers(wt: Path, gh: FakeGh, capsys, head) -> None: diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index 39910fd3..674e4d8a 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -749,25 +749,23 @@ def cache(config, *, clean=False, verify_reuse=False): @pytest.mark.parametrize('change', ['other', 'input', 'shared', 'command', 'network', 'environment', 'version', 'failed', 'boolean_exit_code', 'dirty_receipt', 'keyless', - 'dirty_tree', 'legacy', 'grant', 'host_environment']) -def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, change, cache_check): + 'dirty_tree', 'legacy', 'grant']) +def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, change): cfg = make_config(checks=('echo one', 'echo two'), inputs={'echo one': ('*.md',), 'echo two': ('*.md',), '*': ('shared',)}) - original_path = os.environ["PATH"] - host_env = {"HEAVY_SLOT_GRANTED_CORES": "2"} - if change == 'host_environment': - host_env.update(PATH="/opt/tools:" + original_path, LANG="en_US.UTF-8", LC_ALL="en_US.UTF-8", TERM="dumb") - if change in {'grant', 'host_environment'}: - cfg = replace(cfg, env_allowlist=tuple(dict.fromkeys((*cfg.env_allowlist, *host_env)))) - for key, value in host_env.items(): - monkeypatch.setenv(key, value) + if change == 'grant': + cfg = replace(cfg, env_allowlist=(*cfg.env_allowlist, "HEAVY_SLOT_GRANTED_CORES")) + monkeypatch.setenv("HEAVY_SLOT_GRANTED_CORES", "2") for inputs in ({}, {'*': ()}, {'*': ('uv.lock',)}): assert sandbox._input_key(replace(cfg, inputs=inputs), git_repo, 'unlisted', fetched_base) is None whole = replace(cfg, inputs={'*': ('.',)}) key = sandbox._input_key(whole, git_repo, 'unlisted', fetched_base) assert key is not None - cache_check(cfg) + _save_report(git_repo, sandbox.run_checks(cfg, git_repo)) receipt = git_repo / '.loopzero/checks.json' + git(git_repo, 'config', 'core.excludesFile', str(git_repo / '.git/info/exclude')) + with (git_repo / '.git/info/exclude').open('a') as stream: + stream.write('\n.loopzero/\n') if change in {'other', 'input', 'shared', 'dirty_tree'}: path = 'README.md' if change in {'input', 'dirty_tree'} else 'src.py' if change == 'other' else change (git_repo / path).write_text('new content') @@ -782,12 +780,7 @@ def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, ch elif change == 'environment': monkeypatch.setenv('LZ_KEEP', 'changed') assert _current_check_report(git_repo, cfg, fetched_base) is None - elif change in {'grant', 'host_environment'}: - for key in host_env.keys() - {"PATH", "LANG", "HEAVY_SLOT_GRANTED_CORES"}: - monkeypatch.delenv(key) - if change == 'host_environment': - monkeypatch.setenv("PATH", original_path) - monkeypatch.setenv("LANG", "C") + elif change == 'grant': monkeypatch.setenv("HEAVY_SLOT_GRANTED_CORES", "4") assert _current_check_report(git_repo, cfg, fetched_base) is not None monkeypatch.delenv("HEAVY_SLOT_GRANTED_CORES")