From 6e91c778eb37c9bed5390c02200504183b017c06 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:32:00 +0100 Subject: [PATCH 1/2] Reuse source snapshots around hosted eligibility Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 3 ++ src/loopzero/candidate.py | 4 +++ src/loopzero/eligibility.py | 17 +++++++---- src/loopzero/github.py | 6 ++-- src/loopzero/hosted.py | 19 +++++++++--- tests/test_github.py | 12 ++++---- tests/test_hosted.py | 58 ++++++++++++++++++------------------- 7 files changed, 71 insertions(+), 48 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 49620cba..3b0e31e0 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -310,6 +310,9 @@ PR writes. [Hosted dispatch](../src/loopzero/hosted.py) and Local readiness and hosted source and candidate eligibility reject PRs with merge-authority holds. Adding or removing a hold refreshes source eligibility even when the head stays the same. Merge admission rechecks the live hold. +Hosted evaluation uses the source snapshot already fetched by dispatch or +candidate attestation. The caller rechecks the source fields that affect the +verdict before publication. Standalone evaluation performs its own PR reads. [Mergify](MERGIFY.md) describes optional source-preserving queue integration; [candidate validation](../src/loopzero/candidate.py) belongs at that boundary. Candidate lineage reads wait on zero or multiple live batch matches with exponential diff --git a/src/loopzero/candidate.py b/src/loopzero/candidate.py index 9179e09e..1370a25a 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -217,6 +217,10 @@ def _source_fingerprint(source: JsonObject) -> tuple[object, ...]: base = source.get("base") base_repo = base.get("repo") if isinstance(base, dict) else None return ( + source.get("number"), + source.get("merged"), + source.get("mergeable") is False, + tuple(label["name"] for label in source.get("labels", [])), source.get("state"), source.get("draft"), source.get("body"), diff --git a/src/loopzero/eligibility.py b/src/loopzero/eligibility.py index 3f2ab78a..19f6b698 100644 --- a/src/loopzero/eligibility.py +++ b/src/loopzero/eligibility.py @@ -163,13 +163,18 @@ def readiness_review(reviews: list[dict], head: str, publishers: tuple[str, ...] return latest +def source_fingerprint(pr: github.PR) -> tuple[object, ...]: + return (pr.number, pr.head_sha, pr.base_ref, pr.state, pr.mergeable == "CONFLICTING", + github.merge_hold(pr.number, pr.labels)) + + def evaluate(repo: str, number: int, head: str, base: str, - publishers: tuple[str, ...]) -> github.Readiness: - """Re-fetch reviews and threads; no local receipts, CI identity or source execution.""" + publishers: tuple[str, ...], *, snapshot: github.PR | None = None) -> github.Readiness: + """Evaluate live review evidence. Callers supplying a snapshot own the final source check.""" if not publishers or not re.fullmatch(r"[0-9a-f]{40}", head): raise LoopZeroError("eligibility requires trusted publishers and a full source SHA") - pr = github.pr_view(repo, number) - if pr.head_sha != head: + pr = snapshot if snapshot is not None else github.pr_view(repo, number) + if pr.number != number or pr.head_sha != head: return github.Readiness(False, ("source head changed; refresh eligibility",)) if hold := github.merge_hold(pr.number, pr.labels): return github.Readiness(False, (hold,)) @@ -190,8 +195,8 @@ def evaluate(repo: str, number: int, head: str, base: str, result = github.readiness(repo, pr, base, (), head if review else None, allow_behind=True, ancestor_review=review is not None and review["commit_id"] != head, publishers=publishers) - if github.pr_view(repo, number).head_sha != head: - return github.Readiness(False, ("source head changed during eligibility refresh",)) + if snapshot is None and source_fingerprint(github.pr_view(repo, number)) != source_fingerprint(pr): + return github.Readiness(False, ("source changed during eligibility refresh",)) return result diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 23200686..e40611b9 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -570,7 +570,7 @@ def _pr_labels(data: dict) -> tuple[str, ...]: return tuple(label["name"] for label in data.get("labels", [])) -def _pr_from_rest(data: object) -> PR: +def pr_from_rest(data: object) -> PR: """Normalize one REST pull detail without treating absent merge evidence as clean.""" try: if not isinstance(data, dict): @@ -609,7 +609,7 @@ def _pr_from_rest(data: object) -> PR: def _pr_detail(repo: str, number: int) -> tuple[PR, dict]: data = api_get(f"repos/{repo}/pulls/{number}") - pr = _pr_from_rest(data) + pr = pr_from_rest(data) if pr.number != number: raise GhError(("gh", "api", f"repos/{repo}/pulls/{number}"), f"PR detail number {pr.number} differs from requested {number}") @@ -753,7 +753,7 @@ def create_draft_pr(repo: str, branch: str, base: str, title: str, body: str) -> detail = _api( f"repos/{repo}/pulls", {"head": branch, "base": base, "title": title, "body": body, "draft": True}) - pr = _pr_from_rest(detail) + pr = pr_from_rest(detail) source_repo = detail["head"].get("repo") or {} if (pr.state != "OPEN" or not pr.is_draft or pr.base_ref != base or detail["head"].get("ref") != branch diff --git a/src/loopzero/hosted.py b/src/loopzero/hosted.py index 08a2177f..302c1636 100644 --- a/src/loopzero/hosted.py +++ b/src/loopzero/hosted.py @@ -78,11 +78,13 @@ def _run(cfg: Config) -> int: def publish(state: str, message: str) -> None: github.commit_status(cfg.repo, head, eligibility.CONTEXT, state, message[:140]) publish("pending", "Refreshing live source review evidence") + snapshot = None try: if candidate: def policy(source_number: int, source: dict) -> None: result = eligibility.evaluate(cfg.repo, source_number, source["head"]["sha"], - cfg.base_branch, cfg.review_publishers) + cfg.base_branch, cfg.review_publishers, + snapshot=github.pr_from_rest(source)) if not result.ready: raise _SourcePolicyRejection(f"source #{source_number}: " + "; ".join(result.reasons)) candidate_mod.attest_candidate( @@ -94,10 +96,11 @@ def policy(source_number: int, source: dict) -> None: ) ready, message = True, "All attested candidate sources are reviewed" else: - result = eligibility.evaluate(cfg.repo, number, head, cfg.base_branch, cfg.review_publishers) + snapshot = github.pr_from_rest(pr) + result = eligibility.evaluate(cfg.repo, number, head, cfg.base_branch, cfg.review_publishers, + snapshot=snapshot) ready, message = result.ready, "; ".join(result.reasons) or "Reviewed source head" - if github.pr_view(cfg.repo, number).head_sha != head: - raise LoopZeroError("head changed before publication; refresh eligibility") + _verify_publication_snapshot(cfg.repo, number, head, snapshot) state = "success" if ready else "failure" if not candidate and not ready and result.reasons == (github.MISSING_REVIEW_REASON,): message = "Awaiting trusted review of current source head" @@ -113,6 +116,14 @@ def policy(source_number: int, source: dict) -> None: return 0 if ready or state == "pending" else 1 +def _verify_publication_snapshot(repo: str, number: int, head: str, snapshot: github.PR | None) -> None: + current = github.pr_view(repo, number) + if current.head_sha != head: + raise LoopZeroError("head changed before publication; refresh eligibility") + if snapshot is not None and eligibility.source_fingerprint(current) != eligibility.source_fingerprint(snapshot): + raise LoopZeroError("source metadata changed before publication; refresh eligibility") + + def _publish_verdict(repo: str, head: str, state: str, description: str) -> None: context = eligibility.CONTEXT try: diff --git a/tests/test_github.py b/tests/test_github.py index c2515c48..7041b7c5 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -636,7 +636,7 @@ def timeout(*args, **kwargs): def test_post_review_posts_comment_directly_for_own_pr(gh: FakeGh, verdict: str, supplied: bool) -> None: details = f"api repos/{REPO}/pulls/7" arm_review(gh, author="someone-else" if supplied else "bot-user") - pr = github._pr_from_rest(rest_pr_json(pr_json(author={"login": "bot-user"}))) if supplied else None + pr = github.pr_from_rest(rest_pr_json(pr_json(author={"login": "bot-user"}))) if supplied else None github.post_review(REPO, 7, HEAD, review(verdict=verdict, findings=FINDINGS[:1]), pr=pr) (payload,) = review_payloads(gh) assert payload["event"] == "COMMENT" @@ -958,7 +958,7 @@ def arm_workflow_check(gh: FakeGh, *checks: dict, statuses=(), threads=()) -> No def readiness(*, reviewed=HEAD, workflow_wait=False): - pr = github._pr_from_rest(rest_pr_json(pr_json())) + pr = github.pr_from_rest(rest_pr_json(pr_json())) return github.readiness(REPO, pr, "main", ("checks",), reviewed, workflow_wait=workflow_wait, publishers=PUBLISHERS) @@ -1034,7 +1034,7 @@ def test_readiness_uses_head_or_non_outdated_rule_and_resolved_never_blocks( def test_readiness_missing_and_failed_checks(gh: FakeGh, failure, wait, grace) -> None: arm_readiness(gh, runs={"checks": failure}) r = github.readiness( - REPO, github._pr_from_rest(rest_pr_json(pr_json())), "main", ("checks", "e2e"), HEAD, workflow_wait=wait, review_grace=grace, + REPO, github.pr_from_rest(rest_pr_json(pr_json())), "main", ("checks", "e2e"), HEAD, workflow_wait=wait, review_grace=grace, publishers=PUBLISHERS, ) assert r.reasons == ( @@ -1155,14 +1155,14 @@ def test_readiness_rerun_attempt_requires_start_after_old_failure( ], ids=["behind-base", "merge-conflict", "merged-pr"]) def test_readiness_metadata_blocker(gh: FakeGh, metadata: dict, reason: str) -> None: arm_readiness(gh) - pr = github._pr_from_rest(rest_pr_json(pr_json(**metadata))) + pr = github.pr_from_rest(rest_pr_json(pr_json(**metadata))) r = github.readiness(REPO, pr, "main", ("checks",), HEAD, publishers=PUBLISHERS) assert r.reasons == (reason,) def test_readiness_without_required_ci_skips_check_lookup(gh: FakeGh) -> None: gh.respond("api graphql", threads_json()) - assert github.readiness(REPO, github._pr_from_rest(rest_pr_json(pr_json())), "main", (), HEAD, + assert github.readiness(REPO, github.pr_from_rest(rest_pr_json(pr_json())), "main", (), HEAD, publishers=PUBLISHERS).ready assert [c["argv"][:2] for c in gh.calls] == [["api", "graphql"]] @@ -1467,7 +1467,7 @@ def test_readiness_at_check_suite_limit(gh: FakeGh, unrelated, legacy_success, c runs.append({"name": "required-ci", "conclusion": "failure", "check_suite": {"id": 1}}) gh.respond(f"api repos/{REPO}/commits/{HEAD}/check-runs", *({"check_runs": runs[i:i + 100]} for i in range(0, len(runs) + 1, 100))) - result = github.readiness(REPO, github._pr_from_rest(rest_pr_json(pr_json())), + result = github.readiness(REPO, github.pr_from_rest(rest_pr_json(pr_json())), "main", ("required-ci",), HEAD, publishers=PUBLISHERS) reasons = { diff --git a/tests/test_hosted.py b/tests/test_hosted.py index 7b494a94..87906f1f 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -57,10 +57,7 @@ def publisher(tmp_path, fake_bin, monkeypatch): monkeypatch.setenv("GITHUB_EVENT_PATH", str(event)) Path("workflow.toml").write_text(f'[repo]\nname="{REPO}"\nbase="main"\n[delivery]\nreview_publishers=["trusted-publisher"]\n') gh = FakeGh(fake_bin, tmp_path) - gh.respond(f"api repos/{REPO}/pulls/7", { - "head": {"sha": HEAD, "ref": "lz/task"}, "user": {"login": "author"}, - }) - gh.respond_pr_view(pr_json()) + gh.respond_pr_view(pr_json(), branch="lz/task") gh.respond("api graphql", threads_json()) gh.respond(f"api repos/{REPO}/statuses/{HEAD}", {}) gh.respond(f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1", []) @@ -103,6 +100,7 @@ def test_source_publication_is_bound_to_live_review(publisher, case, blocker, st statuses = written_statuses(publisher) assert ([s["state"] for s in statuses] == ["pending", status] and all(s["context"] == "Loop-zero Eligibility" for s in statuses)) + assert status != "success" or sum(c["argv"][1] != "graphql" for c in publisher.calls) <= 5 assert status != "pending" or statuses[-1]["description"] == "Awaiting trusted review of current source head" @@ -131,7 +129,7 @@ def test_merged_source_refresh_publishes_nothing(publisher): def test_final_status_lost_reply(publisher, monkeypatch, state, readback): ready = state == "success" monkeypatch.setattr(hosted.eligibility, "evaluate", - lambda *_: github.Readiness(ready, () if ready else ("Blocking finding",))) + lambda *_, **__: github.Readiness(ready, () if ready else ("Blocking finding",))) post = github.commit_status endpoint = f"api repos/{REPO}/commits/{HEAD}/statuses" monkeypatch.setattr(github, "_retry_sleep", lambda _: None) @@ -162,16 +160,19 @@ def lose_reply(repo, head, context, value, description): assert written_states(publisher) == ["pending", state] -@pytest.mark.parametrize("error", ["api", "recover", "head", "publication", "config", "before"]) +@pytest.mark.parametrize("error", ["api", "recover", "head", "metadata", "publication", "config", "before"]) def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, capsys, error): sleeps = [] monkeypatch.setattr(github, "_retry_sleep", sleeps.append) endpoint = f"api repos/{REPO}/pulls/7" + ("" if error == "before" else "/reviews?per_page=100&page=1") + approval = [{"state": "APPROVED", "commit_id": HEAD, "user": {"login": "trusted-publisher"}, "body": f"\nreview: **approve**"}] if error in {"api", "recover", "before"}: fault = {"stdout": "HTTP/2.0 503 Service Unavailable\r\nX-GitHub-Request-Id: GHREQ-8774\r\n\r\n{\"message\":\"Service unavailable github_pat_1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ\"}", "exit": 1} - publisher.respond(endpoint, fault, [{"state": "APPROVED", "commit_id": HEAD, "user": {"login": "trusted-publisher"}, "body": f"\nreview: **approve**"}] if error == "recover" else fault) - elif error == "head": - publisher.respond_pr_view(pr_json(), pr_json(headRefOid="b" * 40)) + publisher.respond(endpoint, fault, approval if error == "recover" else fault) + elif error in {"head", "metadata"}: + changed = pr_json(headRefOid="b" * 40) if error == "head" else pr_json(labels=[{"name": "hold"}]) + publisher.respond_pr_view(changed) + publisher.respond(endpoint, approval) elif error == "publication": publisher.respond(f"api repos/{REPO}/statuses/{HEAD}", {}, {"stdout": "", "exit": 1, "stderr": "invalid description (HTTP 422)"}) publisher.respond(f"api repos/{REPO}/commits/{HEAD}/statuses", [{"context": "other"}]) @@ -183,7 +184,7 @@ def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, ca else: with pytest.raises(hosted.LoopZeroError, match="invalid description" if error == "publication" else None): hosted.main() - states = {"before": [], "config": [], "head": ["pending", "failure"], "api": ["pending"], "recover": ["pending", "success"]} + states = {"before": [], "config": [], "head": ["pending", "failure"], "metadata": ["pending", "failure"], "api": ["pending"], "recover": ["pending", "success"]} assert written_states(publisher) == states.get(error, ["pending", "pending"]) @@ -207,16 +208,16 @@ def test_candidate_publication_and_event_controls(tmp_path, fake_bin, monkeypatc if case in {"valid", "hold"}: gh = FakeGh(fake_bin, tmp_path) gh.respond("api graphql", threads_json()) - for number, sha in [(101, "1" * 40), (102, "2" * 40), (900, "c" * 40)]: - path = f"/repos/owner/repo/pulls/{number}" - values[path] = fixtures.rest_pr_json(pr_json( - number=number, headRefOid=sha, isDraft=False, - labels=[{"name": "hold"}] if case == "hold" and number == 101 else [], - )) | values[path] - values[f"{path}/reviews?per_page=100&page=1"] = [{ - "state": "APPROVED", "commit_id": sha, "user": {"login": "trusted-publisher"}, - "body": f"\nreview: **approve**", - }] + for number, sha in [(101, "1" * 40), (102, "2" * 40), (900, "c" * 40)]: + path = f"/repos/owner/repo/pulls/{number}" + values[path] = fixtures.rest_pr_json(pr_json( + number=number, headRefOid=sha, isDraft=False, + labels=[{"name": "hold"}] if case == "hold" and number == 101 else [], + )) | values[path] + values[f"{path}/reviews?per_page=100&page=1"] = [{ + "state": "APPROVED", "commit_id": sha, "user": {"login": "trusted-publisher"}, + "body": f"\nreview: **approve**", + }] if case == "stale": values["/repos/owner/repo/pulls/900"]["head"]["sha"] = "d" * 40 if case == "malformed": @@ -226,13 +227,11 @@ def test_candidate_publication_and_event_controls(tmp_path, fake_bin, monkeypatc monkeypatch.chdir(tmp_path) monkeypatch.setenv("GITHUB_REPOSITORY", "owner/repo") monkeypatch.setenv("GITHUB_EVENT_PATH", str(tmp_path / "event.json")) - attempts, sleeps = [], [] - + sleeps, rest_calls = [], [] def api_get(path): - if path == "apps/mergify": - attempts.append(path) + rest_calls.append(path) if case == "race" and path == "repos/owner/repo/pulls/101": - values["/" + path]["body"] += " changed" + values["/" + path]["labels"].append({"name": "changed"}) return event["repository"] if path == "repos/owner/repo" else values["/" + path] monkeypatch.setattr(github, "api_get", api_get) monkeypatch.setattr("loopzero.candidate._retry_sleep", sleeps.append) @@ -249,10 +248,10 @@ def publish(*args): monkeypatch.setattr(github, "commit_status", publish) evaluated, real_evaluate = [], hosted.eligibility.evaluate - def evaluate(repo, number, head, base, publishers): + def evaluate(repo, number, head, base, publishers, *, snapshot): evaluated.append((repo, number, head, base, publishers)) if case in {"valid", "hold"}: - return real_evaluate(repo, number, head, base, publishers) + return real_evaluate(repo, number, head, base, publishers, snapshot=snapshot) if fault := {"interrupt": KeyboardInterrupt(), "api": github.GhUnavailable(("gh",), "HTTP 503")}.get(case): raise fault reasons = (github.MISSING_REVIEW_REASON,) if case == "policy" else () @@ -269,8 +268,9 @@ def evaluate(repo, number, head, base, publishers): assert hosted.main() == 0 terminal = [] if case in {"manual", "metadata", "stale", "interrupt", "api"} else ["failure"] expected = [] if case in {"manual", "metadata", "stale"} else ["pending", *terminal] - assert case != "race" or (len(attempts) == 3 and sleeps == [2, 2] and len(evaluated) == 6) + assert case != "race" or (rest_calls.count("apps/mergify") == 3 and sleeps == [2, 2] and len(evaluated) == 6) if case == "valid": + assert len(rest_calls) + len(published) <= 16 assert evaluated == [("owner/repo", 101, "1" * 40, "main", ("trusted-publisher",)), ("owner/repo", 102, "2" * 40, "main", ("trusted-publisher",))] assert published == [("owner/repo", "c" * 40, "Loop-zero Eligibility", "pending", @@ -331,7 +331,7 @@ def test_source_status_limit(publisher, monkeypatch, capsys, prior): pages = [statuses[i:i + 100] for i in range(0, 1001, 100)] publisher.respond(f"api repos/{REPO}/commits/{HEAD}/statuses", *pages, *pages) - monkeypatch.setattr(hosted.eligibility, "evaluate", lambda *args: SimpleNamespace( + monkeypatch.setattr(hosted.eligibility, "evaluate", lambda *args, **kwargs: SimpleNamespace( ready=True, reasons=(), )) From 94ae8dff3fc072580b584b1263d4bfa6079d6b77 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:43:12 +0100 Subject: [PATCH 2/2] Skip hosted source verdict when the same head has landed Architecture-Review: unchanged; hosted eligibility stays bound to the same live source and skips merged sources. Co-Authored-By: Codex --- src/loopzero/candidate.py | 5 ++++- src/loopzero/hosted.py | 13 +++++++++---- tests/test_hosted.py | 16 ++++++++-------- 3 files changed, 21 insertions(+), 13 deletions(-) diff --git a/src/loopzero/candidate.py b/src/loopzero/candidate.py index 1370a25a..454fbfff 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -216,11 +216,14 @@ def _source_fingerprint(source: JsonObject) -> tuple[object, ...]: head = source.get("head") base = source.get("base") base_repo = base.get("repo") if isinstance(base, dict) else None + labels = source.get("labels", []) + if not isinstance(labels, list) or any(not isinstance(label, dict) or not isinstance(label.get("name"), str) for label in labels): + raise CandidateError("invalid source PR labels") return ( source.get("number"), source.get("merged"), source.get("mergeable") is False, - tuple(label["name"] for label in source.get("labels", [])), + tuple(label["name"] for label in labels), source.get("state"), source.get("draft"), source.get("body"), diff --git a/src/loopzero/hosted.py b/src/loopzero/hosted.py index 302c1636..24046c22 100644 --- a/src/loopzero/hosted.py +++ b/src/loopzero/hosted.py @@ -100,7 +100,8 @@ def policy(source_number: int, source: dict) -> None: result = eligibility.evaluate(cfg.repo, number, head, cfg.base_branch, cfg.review_publishers, snapshot=snapshot) ready, message = result.ready, "; ".join(result.reasons) or "Reviewed source head" - _verify_publication_snapshot(cfg.repo, number, head, snapshot) + if _landed_before_publication(cfg.repo, number, head, snapshot): + return 0 state = "success" if ready else "failure" if not candidate and not ready and result.reasons == (github.MISSING_REVIEW_REASON,): message = "Awaiting trusted review of current source head" @@ -116,12 +117,16 @@ def policy(source_number: int, source: dict) -> None: return 0 if ready or state == "pending" else 1 -def _verify_publication_snapshot(repo: str, number: int, head: str, snapshot: github.PR | None) -> None: +def _landed_before_publication(repo: str, number: int, head: str, snapshot: github.PR | None) -> bool: current = github.pr_view(repo, number) if current.head_sha != head: raise LoopZeroError("head changed before publication; refresh eligibility") - if snapshot is not None and eligibility.source_fingerprint(current) != eligibility.source_fingerprint(snapshot): - raise LoopZeroError("source metadata changed before publication; refresh eligibility") + if snapshot is not None: + if current.state == "MERGED": + return True + if eligibility.source_fingerprint(current) != eligibility.source_fingerprint(snapshot): + raise LoopZeroError("source metadata changed before publication; refresh eligibility") + return False def _publish_verdict(repo: str, head: str, state: str, description: str) -> None: diff --git a/tests/test_hosted.py b/tests/test_hosted.py index 87906f1f..bc8d116d 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -160,7 +160,7 @@ def lose_reply(repo, head, context, value, description): assert written_states(publisher) == ["pending", state] -@pytest.mark.parametrize("error", ["api", "recover", "head", "metadata", "publication", "config", "before"]) +@pytest.mark.parametrize("error", ["api", "recover", "head", "metadata", "merged", "publication", "config", "before"]) def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, capsys, error): sleeps = [] monkeypatch.setattr(github, "_retry_sleep", sleeps.append) @@ -169,22 +169,22 @@ def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, ca if error in {"api", "recover", "before"}: fault = {"stdout": "HTTP/2.0 503 Service Unavailable\r\nX-GitHub-Request-Id: GHREQ-8774\r\n\r\n{\"message\":\"Service unavailable github_pat_1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ\"}", "exit": 1} publisher.respond(endpoint, fault, approval if error == "recover" else fault) - elif error in {"head", "metadata"}: - changed = pr_json(headRefOid="b" * 40) if error == "head" else pr_json(labels=[{"name": "hold"}]) - publisher.respond_pr_view(changed) + elif error in {"head", "metadata", "merged"}: + changes = {"head": {"headRefOid": "b" * 40}, "metadata": {"labels": [{"name": "hold"}]}, "merged": {"state": "MERGED"}} + publisher.respond_pr_view(pr_json(**changes[error])) publisher.respond(endpoint, approval) elif error == "publication": publisher.respond(f"api repos/{REPO}/statuses/{HEAD}", {}, {"stdout": "", "exit": 1, "stderr": "invalid description (HTTP 422)"}) publisher.respond(f"api repos/{REPO}/commits/{HEAD}/statuses", [{"context": "other"}]) else: monkeypatch.setenv("GITHUB_REPOSITORY", "other/repo") - if error in {"api", "recover", "before"}: - assert hosted.main() == (1 if error == "before" else 0) and sleeps == [5] - assert ("status=503 request_id=GHREQ-8774 message=Service unavailable [REDACTED]" in capsys.readouterr().err) == (error != "recover") + if error in {"api", "recover", "before", "merged"}: + assert hosted.main() == (1 if error == "before" else 0) and sleeps == ([] if error == "merged" else [5]) + assert ("status=503 request_id=GHREQ-8774 message=Service unavailable [REDACTED]" in capsys.readouterr().err) == (error in {"api", "before"}) else: with pytest.raises(hosted.LoopZeroError, match="invalid description" if error == "publication" else None): hosted.main() - states = {"before": [], "config": [], "head": ["pending", "failure"], "metadata": ["pending", "failure"], "api": ["pending"], "recover": ["pending", "success"]} + states = {"before": [], "config": [], "head": ["pending", "failure"], "metadata": ["pending", "failure"], "merged": ["pending"], "api": ["pending"], "recover": ["pending", "success"]} assert written_states(publisher) == states.get(error, ["pending", "pending"])