Skip to content
Merged
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
3 changes: 2 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions src/loopzero/candidate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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()
Expand Down
49 changes: 41 additions & 8 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)

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: An advisory snapshot read can stall ready for up to about 97 seconds

_warn_queue_size calls mergify.queue_predecessors, which goes through api_get. That function makes three attempts, each with a 30s urlopen timeout, and sleeps 2s and then 5s between them (mergify.py:95-111). A Mergify outage or throttling can therefore block the warning for about 97 seconds before it gives up silently. Admission is unchanged, but ready stalls during that time. ready --wait=N also projects (cli.py:1343 passes the default project=True), so the stall uses up the same wait budget that the later _wait_with_deadline at cli.py:1347 needs after mark_ready. Smallest fix: give the snapshot read a single attempt with a short timeout, for example an api_get(..., retries=False) variant or a project=args.wait is None guard in cmd_ready. That would also match the ARCHITECTURE wording "without an admission deadline".

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:
Expand Down Expand Up @@ -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)
Expand Down
39 changes: 38 additions & 1 deletion src/loopzero/mergify.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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, ...]:

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: queue_predecessors has no direct unit tests for its reject paths

The CLI test covers only the ordered, empty, two-roots-ambiguous and unavailable snapshots. It does not exercise these reject branches: a multi-PR batch, a batch with a different queue_rule_name, the requester's own PR appearing in the queue, a non-serial mode or non-empty waiting_pull_requests/forming_batches, a parent id outside the snapshot (dangling parent), a cycle, the container/sub_batch skip, duplicate sources, or more than 32 batches. The acceptance also lists a 'conflicting' snapshot, which here means merge-tree exits non-zero and _git raises CliError, which is then swallowed. No test covers that case. The merge path (merge without --wait, so project=True) is never tested with a queue either. Add a small table-driven test in tests/test_mergify.py that feeds status dicts through a monkeypatched api_get, plus one CLI case where a predecessor conflicts with the PR.

"""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"

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: The new reader depends on status keys that no existing fixture contains

Admission depends on waiting_pull_requests == [] and forming_batches == []. The existing status fixtures in tests/test_cli.py:2460 and tests/test_mergify.py:97 contain only batches and mode. If the live endpoint leaves out either key, status.get(...) != [] is always true. The projection then silently never runs, and every test still passes because the new CLI fixture adds both keys itself. Before shipping, check these keys against a real /merge-queue/status response or against Mergify's API schema. Recording that response as a fixture would keep the feature from quietly turning into a no-op.

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
Expand Down
2 changes: 1 addition & 1 deletion tach.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
36 changes: 32 additions & 4 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3809,21 +3809,44 @@ 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")):
(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
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)))
Expand All @@ -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
Expand Down
Loading