diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index efb9567c..f86942a3 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -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 diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index e6012622..122f618d 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -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"): @@ -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) + receipt_problem = _check_report_problem(report, wt, config, head) + if receipt_problem and reviews is None: + 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, @@ -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) @@ -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 @@ -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 @@ -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): + 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) @@ -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 diff --git a/src/loopzero/github.py b/src/loopzero/github.py index e40611b9..cc9fef95 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -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"])) diff --git a/tests/test_cli.py b/tests/test_cli.py index a44ef2d3..f6901809 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3094,6 +3094,7 @@ 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"}: @@ -3101,6 +3102,46 @@ def test_ready_requires_clean_successful_local_report_at_head(wt, gh, capsys, co "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) @@ -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 @@ -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: