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: 3 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,9 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con
5. `ready` derives readiness from the current head, its check receipt, an eligible review at that
head or an eligible review covering an ancestor, blocking findings
(unresolved threads a review publisher opened with a head-bound marker line),
target branch and required CI. The receipt must record a clean passing run
target branch and required CI. Ready and merge stop on an invalid receipt
after checking the pushed head and merge-authority hold. Status still gathers
remote gates for its diagnostics. The receipt must record a clean passing run
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
Expand Down
35 changes: 17 additions & 18 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,8 @@ def _require_task_branch(config: Config, branch: str) -> None:
)


def _require_pr(config: Config, branch: str, *, allow_merged: bool = False) -> github.PR:
pr = github.pr_for_branch(config.repo, branch)
def _require_pr(config: Config, branch: str, *, allow_merged: bool = False, list_only: bool = False) -> github.PR:
pr = github.pr_for_branch(config.repo, branch, list_only=list_only)
if pr is None:
raise CliError(f"no pull request for {branch}; run `loopzero pr` first")
if pr.state != "OPEN" and not (allow_merged and pr.state == "MERGED"):
Expand Down Expand Up @@ -283,8 +283,11 @@ def _readiness(
) -> github.Readiness:
if hold := github.merge_hold(pr.number, pr.labels):
return github.Readiness(False, (hold,))
if reviews is None:
reviews = _pr_reviews(config.repo, pr.number)
report = _load_report(wt)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

important: Revalidate the receipt before acting on passing remote gates

If another loopzero check replaces a passing receipt with a failed or incomplete one while review and CI reads are in flight, _readiness still returns success using the earlier receipt. ready can mark the PR ready, and merge --wait can merge or request Mergify admission. The poll precheck also misses this when the gates turn green on that same poll. Keep the early rejection and revalidate the current receipt before accepting readiness or performing a gated write. Add a replay that invalidates the receipt during a remote gate read.

receipt_problem = _check_report_problem(report, wt, config, head)
if receipt_problem and reviews is None:

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: Make full status diagnostics an explicit choice

Supplying preloaded reviews now also disables the receipt short-circuit. A readiness caller that starts caching reviews would silently resume CI and Mergify lookups for invalid receipts. Give status an explicit diagnostics option so review caching can change independently of gate behavior.

return github.Readiness(False, (receipt_problem,))
reviews = _pr_reviews(config.repo, pr.number) if reviews is None else reviews
publishers = config.review_publishers or (github.login(),)
review = eligibility.readiness_review(
reviews, head, publishers, repo=config.repo, number=pr.number, base_branch=config.base_branch,
Expand All @@ -306,14 +309,9 @@ def _readiness(
),
publishers=publishers,
)
report = _load_report(wt)
receipt_problem = _check_report_problem(report, wt, config, head)
if receipt_problem:
result = github.Readiness(
ready=False,
reasons=(*result.reasons, receipt_problem),
)
elif announce_receipt:
result = (github.Readiness(False, (*result.reasons, receipt_problem))
if receipt_problem else result)
if announce_receipt and not receipt_problem:
_print_receipt(wt, report, "accepted")
if config.merge_strategy == "mergify" and pr.state == "OPEN":
behind = github.behind_reason(pr, head if review else None)
Expand Down Expand Up @@ -445,7 +443,7 @@ def _load_report(wt: Path) -> CheckReport | None:
raise TypeError("dirty must be a bool")
return CheckReport(head=str(data["head"]), dirty=dirty, results=results,
settings_sha256=data.get("settings_sha256"))
except (TypeError, KeyError, ValueError) as exc:
except (OSError, TypeError, KeyError, ValueError) as exc:
print(f"warning: ignoring unreadable {path}: {exc}", file=sys.stderr)
return None

Expand Down Expand Up @@ -1247,7 +1245,8 @@ def _pr_readiness(
"""PR plus readiness; readiness is None only for an already merged PR (allow_merged)."""
head = worktree.head(wt)
_require_task_branch(config, branch)
pr = _require_pr(config, branch, allow_merged=allow_merged)
with github.bounded_reads(float("inf"), token=None):
pr = _require_pr(config, branch, allow_merged=allow_merged, list_only=True)
_require_pushed(pr, head)
if pr.state == "MERGED":
return pr, None
Expand Down Expand Up @@ -1536,8 +1535,9 @@ def _wait_for_checks(
previous = config
for _ in _poll_until(started, timeout, bounded=bounded):
if initial is not None:
readiness = initial
initial = None
readiness, initial = initial, None
elif problem := _check_report_problem(_load_report(wt), wt, config, 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.

important: Check the current workflow before diagnosing a receipt during a wait

The poll precheck compares the receipt with the configuration captured when the wait started. If the workflow changes and a fresh check passes under the new plan during the sleep, both ready --wait and merge --wait reject that valid receipt and tell the user to run checks again. The early return bypasses _verify_wait_snapshot, which already distinguishes a needed check from a needed command retry. Reload and compare the workflow before the local receipt precheck, while keeping both local checks ahead of the next PR read.

return current, github.Readiness(False, (problem,)), kicked
else:
current = github.pr_view(config.repo, pr.number)
previous = _verify_wait_snapshot(args, wt, config, pr.head_sha, current.head_sha, previous)
Expand All @@ -1555,8 +1555,7 @@ def _wait_for_checks(
pending = _pending_checks(
config, current, readiness, allow_skipped=kicked or (allow_skipped and not current.is_draft),
)
if pending or readiness.ready:
_print_wait_changes(shown, pending)
_print_wait_changes(shown, pending if pending or readiness.ready else shown)
if not pending:
return current, readiness, kicked
shown = pending
Expand Down
4 changes: 2 additions & 2 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -671,9 +671,9 @@ def _confirm_branch_pr(repo: str, branch: str, endpoint: str, number: int, state
return pr


def pr_for_branch(repo: str, branch: str, *, open_only: bool = False) -> PR | None:
def pr_for_branch(repo: str, branch: str, *, open_only: bool = False, list_only: bool = False) -> PR | None:
"""Return the open PR, falling back to the most recent closed PR unless open_only."""
endpoint, matches = _commit_branch_prs(repo, branch)
endpoint, matches = ("", ()) if list_only else _commit_branch_prs(repo, branch)
open_matches = [row for row in matches if row["state"] == "open"]
if open_matches:
newest = max(open_matches, key=lambda row: (row["created_at"], row["number"]))
Expand Down
44 changes: 43 additions & 1 deletion tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3094,13 +3094,54 @@ def test_ready_requires_clean_successful_local_report_at_head(wt, gh, capsys, co
out, _ = expect_cli(capsys, int(reason is not None), "ready")
if reason:
assert f"not ready: {reason}" in out
assert [call["argv"][:2] for call in gh.calls] == LOOKUP_CALLS[1:]
if draft:
assert "receipt accepted:" not in out
if condition in {"legacy", "incompatible"}:
assert ("Run loopzero check in this worktree at this head with the same current CLI and effective "
"settings as ready, using a local coordinator for delegated stages." in out)


@pytest.mark.parametrize("failed_read", [None, 0, 1], ids=["no-receipt", "list-503", "detail-503"])
def test_merge_missing_receipt_bounds_discovery(wt, gh, capsys, head, monkeypatch, failed_read):
commit_mergify_configuration(wt)
arm_pr(gh, head, isDraft=False)
gh.respond(branch_head_key(), {"commit": {"sha": head}})
gh.respond(f"api repos/{REPO}/commits/{head}/pulls?per_page=100&page=1", [{"head": {"ref": "lz/other"}}] * 100)
requests, diagnostic = LOOKUP_CALLS[1:], "run loopzero check at this head"
if failed_read is not None:
gh.respond(" ".join(requests[failed_read]), {}, exit=1, stderr="HTTP 503")
monkeypatch.setattr(github, "_retry_sleep", lambda *_: pytest.fail("unexpected discovery retry"))
requests, diagnostic = requests[:failed_read + 1], "HTTP 503"
expect_cli(capsys, 1, "merge", "--wait", stderr_contains=(diagnostic,))
assert [call["argv"][:2] for call in gh.calls] == requests
assert all("--method" not in call["argv"] and "--input" not in call["argv"] for call in gh.calls)


@pytest.mark.parametrize("command", [("ready",), ("merge", "--wait")])
def test_unreadable_receipt_does_not_mask_hold(wt, gh, capsys, head, command):
arm_pr(gh, head, isDraft=False, labels=[{"name": "hold"}])
(wt / ".loopzero/checks.json").mkdir()
code, out, err = run(capsys, *command)
assert code == 1 and "merge-authority hold" in out + err
assert "unreadable" not in err and "run loopzero check" not in out + err


@pytest.mark.parametrize("command", ["ready", "merge"])
def test_readiness_wait_stops_before_next_read_when_receipt_fails(wt, gh, head, capsys, monkeypatch, command):
arm_approved_pr_with_check_result(gh, head, wt, "pending", isDraft=False)
calls_at_invalidation = []

def invalidate():
calls_at_invalidation.append(len(gh.calls))
(wt / ".loopzero/checks.json").unlink()

poll_clock(monkeypatch, jitter=1.0, after_sleep=invalidate)
code, out, err = run(capsys, command, "--wait=60")
assert code == 1 and "run loopzero check at this head" in out + err
assert calls_at_invalidation == [len(gh.calls)]


@pytest.fixture
def check_environment(wt, gh, head, tmp_path):
arm_approved_ready_pr(gh, head, wt, readiness={"local_exit": None}, isDraft=False)
Expand Down Expand Up @@ -3480,7 +3521,7 @@ def membership(*_):
code, out, err = run(capsys, "merge", *(["--wait=1"] if wait else []))

calls = [c["argv"][:2] for c in gh.calls]
assert calls.count(LOOKUP_CALLS[0]) == 1
assert LOOKUP_CALLS[0] not in calls
assert calls.count(detail.split()) == 2
if outcome == "merged":
assert (code, err) == (0, "") and out.splitlines()[-1] == merged_sha
Expand Down Expand Up @@ -3865,6 +3906,7 @@ def test_merge_of_externally_merged_pr_verifies_sha_and_cleans_up(
for branch, number in (("lz/t1", 7), ("lz/other", 8)):
arm_pr(gh, head_of(wt), branch=branch, number=number, state="MERGED", isDraft=False)
gh.append(f"api repos/{REPO}/pulls/{number}", merge_json(state='MERGED', head='f' * 40 if changed else head_of(wt), sha='e' * 40))
(wt / ".loopzero/checks.json").mkdir()
code, out, err = run(capsys, "merge")
assert (code, collision.exists(), wt.exists()) == (int(changed), True, changed)
if changed:
Expand Down
Loading