diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index cfff3fc5..b47e6031 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -285,7 +285,8 @@ PR writes. [Hosted dispatch](../src/loopzero/hosted.py) and 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 8edf4afc..8544d7cc 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -95,7 +95,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") @@ -124,7 +124,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 6247360b..5b26cd8b 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1153,7 +1153,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 @@ -1169,14 +1169,46 @@ def _prequeue_size_budget( origin, f"refs/heads/{config.base_branch}") 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: @@ -1538,7 +1570,7 @@ def _merge_with_mergify( return sha raise CliError(f"PR #{pr.number} left Mergify queue {queue} unmerged. {MERGIFY_DEQUEUE_HINT}") 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 2bcc90f1..fad21cba 100644 --- a/src/loopzero/mergify.py +++ b/src/loopzero/mergify.py @@ -14,7 +14,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" @@ -137,6 +137,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 442c5302..46a8bdf1 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 d1ae0263..469a0893 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4698,9 +4698,7 @@ def test_pr_marks_legacy_same_head_check_unverified(wt, gh, capsys): 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. +def size_budget_fixture(wt, repo, headroom): 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() @@ -4712,7 +4710,7 @@ def test_prequeue_size_budget_replays_1230(wt, repo, gh, capsys, monkeypatch, co 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)]: + for checkout, name, lines in [(wt, "feature", cap - headroom), (repo, "upstream", 26)]: folder = checkout / "src/loopzero" folder.mkdir(parents=True) (folder / f"{name}.py").write_text("# counted line\n" * lines) @@ -4721,6 +4719,13 @@ def test_prequeue_size_budget_replays_1230(wt, repo, gh, capsys, monkeypatch, co # 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) + return cap + + +@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. + cap = size_budget_fixture(wt, repo, 18) head = head_of(wt) arm_approved_pr_with_check_result(gh, head, wt, "success", isDraft=False) monkeypatch.setattr(mergify, "configured", lambda *_: True) @@ -4738,3 +4743,59 @@ def test_prequeue_size_budget_replays_1230(wt, repo, gh, capsys, monkeypatch, co 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() + + +@pytest.mark.parametrize(("command", "queue_state"), [ + ("ready", "ordered"), ("merge", "ordered"), ("resume", "ordered"), + ("ready", "empty"), ("ready", "ambiguous"), ("ready", "unavailable"), + ("ready", "waiting"), ("ready", "conflicting"), ("timed", "unavailable"), +]) +def test_prequeue_size_warning_replays_1238(wt, repo, gh, capsys, monkeypatch, command, queue_state): + cap = size_budget_fixture(wt, repo, 48) + main = head_of(repo) + batches = [] + for number, parents in [(1146, []), (1219, ["1146"])]: + git(repo, "switch", "--detach", main) + name = "feature" if number == 1219 and queue_state == "conflicting" else f"pr_{number}" + path = repo / f"src/loopzero/{name}.py" + path.write_text("# counted line\n" * 13) + git(repo, "add", str(path)) + git(repo, "commit", "-qm", f"PR {number}") + git(repo, "push", str(repo.parent / "origin.git"), f"HEAD:refs/pull/{number}/head") + batches.append({"id": str(number), "parent_ids": parents, "queue_rule_name": "main", + "pull_requests": [{"number": number}], "sub_batches": []}) + + def snapshot(_repo, suffix): + assert command != "timed", "advisory lookup must not spend the admission deadline" + assert suffix == "/merge-queue/status?branch=main" + if queue_state == "unavailable": + raise mergify.MergifyError("queue status unavailable") + if queue_state == "ambiguous": + batches[1]["parent_ids"] = [] + return { + "mode": "serial", "batches": [] if queue_state == "empty" else batches[::-1], + "waiting_pull_requests": [{"number": 1220}] if queue_state == "waiting" else [], + "forming_batches": [], + } + + 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, "api_get", snapshot) + requested = [] + monkeypatch.setattr(mergify, "request", lambda *args: requested.append(args)) + monkeypatch.setattr(cli, "_wait_for_mergify", lambda *_: None) + args = { + "resume": ("merge", "--wait=0"), "timed": ("merge", "--wait=60"), + }.get(command, (command,)) + code, out, err = run(capsys, *args) + + assert code == (3 if command in {"timed", "resume"} else 0) + assert requested == ([(REPO, 7, head, "main")] if command in {"timed", "merge"} else []) + if queue_state == "ordered" and command != "resume": + assert "#1146, #1219" in out + err + assert f"src={cap + 4} (base 26, delta {cap - 22}, cap {cap}" in out + err + else: + assert "projected size budget" not in out + err