Skip to content
Closed
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 @@ -282,6 +282,10 @@ PR writes. [Hosted dispatch](../src/loopzero/hosted.py) and
[eligibility](../src/loopzero/eligibility.py) evaluate trusted review evidence.
[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
44 changes: 39 additions & 5 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,12 @@ def review_marker(head: str, kind: str, source: str = "model") -> str:
# --------------------------------------------------------------------------- git / context


def _git(cwd: Path, *args: str, timeout: float = GIT_TIMEOUT) -> str:
done = _proc.run(["git", *args], cwd=cwd, env_allowlist=worktree.GIT_ENV, timeout=timeout)
def _git(cwd: Path, *args: str, timeout: float = GIT_TIMEOUT,
extra_env: dict[str, str] | None = None) -> str:
done = _proc.run(["git", *args], cwd=cwd, env_allowlist=worktree.GIT_ENV,
timeout=timeout, extra_env=extra_env)
if done.exit_code != 0:
raise CliError(f"git {' '.join(args)} failed: {_proc.tail(done.stderr, 1)}")
raise CliError(f"git {' '.join(args)} failed: {_proc.tail(done.stderr or done.stdout, 1)}")
return done.stdout.strip()


Expand Down Expand Up @@ -1148,6 +1150,36 @@ 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.
_git(root, "fetch", "--no-tags", "--no-recurse-submodules", "--",

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 skips the hardened scratch environment without saying why

Every other git call in the scratch repo goes through the git partial with GIT_CONFIG_NOSYSTEM, GIT_CONFIG_GLOBAL=/dev/null and the related settings. The fetch calls _git(root, ...) directly. That is probably on purpose, so the user's credential helper can authenticate to origin, but the code doesn't say so. A later edit could 'fix' it to use git and break private-repo fetches. Add a one-line comment explaining that the fetch needs the user's global config for credentials.

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)

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: Merge conflict with the fresh target gives an unclear error

If the PR head no longer merges cleanly with the freshly fetched target, git merge-tree --write-tree exits 1. It writes the conflict details to stdout, not stderr. _git builds its error from the stderr tail, so the user sees only git merge-tree --write-tree <base> <head> failed: with nothing after it. This can happen even when GitHub's mergeable is still UNKNOWN or stale and readiness passed. It fails closed, so nothing unsafe gets through, but the user isn't told why. Smallest fix: run merge-tree with _proc.run and, when it exits 1, raise CliError("PR head conflicts with current <base_branch>; update the branch").

# 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 @@ -1172,6 +1204,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 re-runs the budget for PRs already in the queue

In cmd_ready, the check runs whenever readiness is ready and the strategy is mergify. It doesn't look at Mergify markers or queue membership. So if loopzero ready is run again on a PR that is already requested or queued, and the target has moved since, it now exits 1 with a budget failure. The PR stays in the queue, so the output contradicts the queue state. The acceptance asks for this only for ready and new merge requests, and merge already sends existing requests to the wait path. If ready should report on candidates before admission only, skip the check when mergify.markers shows a request. Otherwise, document that ready always re-checks against the current target.

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 @@ -1479,7 +1512,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 @@ -1506,6 +1539,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)
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 @@ -1557,7 +1591,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
42 changes: 42 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4734,3 +4734,45 @@ def test_pr_marks_legacy_same_head_check_unverified(wt, gh, capsys):
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()
Loading