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
4 changes: 4 additions & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
48 changes: 44 additions & 4 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -1213,6 +1215,42 @@ 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:

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 checker is detected by an exact string match

_SIZE_BUDGET not in config.checks only matches a check command that is exactly scripts/size_budget.sh. Commands like bash scripts/size_budget.sh or scripts/size_budget.sh origin/main skip the pre-queue check silently, and nothing tells the user. The repo's own workflow.toml uses the exact form, so this works today. Consider matching on the first shlex token, or say in the ARCHITECTURE note that the check only runs for that exact command.

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, "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.
fetched = _proc.run(

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 fetch duplicates _git instead of reusing it

The fetch calls _proc.run directly and repeats the exit-code check, only to leave out extra_env. That is why its error message drops stderr. Calling _git(root, "fetch", ...) with no extra_env, the same environment the direct call uses, removes the duplication and keeps git's stderr tail in the error.

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

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: A merge conflict with the current target gives an error with no cause

git merge-tree --write-tree exits 1 when the merge conflicts. It writes the conflict details to stdout and nothing to stderr. _git builds its error only from the stderr tail, so the user sees git merge-tree --write-tree <base> <head> failed: with nothing after it. This can happen when GitHub's mergeability is stale against a target that moved. Blocking is still correct here, so this is about the message. Smallest fix: run merge-tree through _proc.run and, on exit 1, raise CliError(f"PR head conflicts with current {config.base_branch}; rebase before queueing"). The fetch at lines 1235-1241 has the same problem: it throws away fetched.stderr, so a credential failure looks the same as a network failure. Add _proc.tail(fetched.stderr, 1) to that message.

# 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)
Expand All @@ -1237,6 +1275,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)

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: ready --wait on a draft can mark the PR ready before the budget check fails

On the waiting path, github.mark_ready runs at line 1262 before _prequeue_size_budget at line 1278. So a draft PR that fails the current-target budget can still be flipped to ready-for-review before the command exits 1. This is not Mergify admission, so it is within the acceptance criteria. If you want draft PRs to stay draft when the budget fails, run the check before the kick, or note this behavior.

if readiness.ready and pr.is_draft and not kicked:
github.mark_ready(config.repo, pr.number)
if args.wait is not None:
Expand Down Expand Up @@ -1589,7 +1628,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."""
Expand All @@ -1616,6 +1655,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)
Expand Down Expand Up @@ -1667,7 +1707,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
Expand Down
31 changes: 23 additions & 8 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3776,21 +3776,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
Expand Down
Loading