From 3eca5fd6118fb4766cfe486896fafad32533293e Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:30:32 +0100 Subject: [PATCH 01/17] Keep hosted eligibility pending during GitHub outages Architecture-Review: unchanged; remains fail-closed while trusted evidence is unavailable, with the same status context and publisher. Co-Authored-By: Codex --- src/loopzero/eligibility.py | 2 ++ src/loopzero/github.py | 38 ++++++++++++++++++------- src/loopzero/hosted.py | 10 +++++-- tests/test_hosted.py | 56 ++++++++++++++++++------------------- 4 files changed, 65 insertions(+), 41 deletions(-) diff --git a/src/loopzero/eligibility.py b/src/loopzero/eligibility.py index 41de7f3c..274703a1 100644 --- a/src/loopzero/eligibility.py +++ b/src/loopzero/eligibility.py @@ -121,6 +121,8 @@ def _clean_base_merges(repo: str, number: int, reviewed: str, head: str, base_br return False cursor = first return cursor == reviewed + except github.GhUnavailable: + raise except (candidate.CandidateError, github.GhError, KeyError, OSError, TypeError, ValueError): return False diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 45fb8ce2..d9ac8ae8 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -68,7 +68,11 @@ def __init__(self, command: tuple[str, ...], tail: str, *, super().__init__(f"{command_text} failed: {self.tail.strip()[-600:]}") -class ReadDeadline(GhError): +class GhUnavailable(GhError): + """GitHub could not supply a result because of a transient fault or limit.""" + + +class ReadDeadline(GhUnavailable): """A shared GitHub read deadline elapsed.""" @@ -305,12 +309,26 @@ def _select_token(token: str | None, scope: tuple[float, str | None, bool] | Non return selected if selected is not None else (app_token() if read_only else "") -def _transient_error(tail: str, retry_idempotent: bool) -> bool: - return bool(TRANSIENT_RE.search(tail)) or ( +def _transient_error(tail: str, retry_idempotent: bool, status: str | None = None) -> bool: + return (status or "").startswith("5") or bool(TRANSIENT_RE.search(tail)) or ( retry_idempotent and "something went wrong while executing your query" in tail.lower() ) +def _request_error(transient: bool) -> type[GhError]: + return GhUnavailable if transient else GhError + + +def _rate_limited(status: str | None, headers: dict[str, str], tail: str) -> bool: + return (status == "429" + or (status == "403" and (headers.get("x-ratelimit-remaining") == "0" or "retry-after" in headers)) + or bool(re.search(r"rate limit|HTTP 429", tail, re.IGNORECASE))) + + +def _retry_delays(scope: tuple[float, str | None, bool] | None, diagnostic: bool) -> tuple: + return (None,) if scope and not scope[2] else (*(RETRY_DELAYS[:1] if diagnostic else RETRY_DELAYS), None) + + def _pr_list_error_guidance(args: tuple[str, ...], stderr: str, using_app: bool) -> str: if (using_app and len(args) > 1 and args[0] == "api" and re.fullmatch(r"repos/[^/]+/[^/]+/pulls\?.+", args[1]) @@ -332,7 +350,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, read_only = _read_only(args) retryable = read_only or retry_idempotent scope = _read_scope.get() if read_only else None - delays = (None,) if scope and not scope[2] else (*RETRY_DELAYS, None) + delays = _retry_delays(scope, diagnostic_api) for delay in delays: selected = _select_token(token, scope, read_only) # a retry backoff can outlive the app token try: @@ -355,16 +373,16 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, status, headers, body = (_included_response(done.stdout) if rest_api or diagnostic_api else (None, {}, done.stdout)) tail = "\n".join(part for part in (done.stderr, body if rest_api else done.stdout) if part) - if done.exit_code and ((rest_api and status == "429") - or re.search(r"rate limit|HTTP 429", tail, re.IGNORECASE)): + if done.exit_code and _rate_limited(status, headers, tail): guidance = (_redact_tokens(_rest_rate_limit(headers), selected) if rest_api else _graphql_reset(args, tail, cwd, selected) + RATE_LIMIT_GUIDANCE) if diagnostic_api or patch_error: detail = _api_error_detail(args, done.stdout if diagnostic_api else "", done.stderr, selected, message_tail=None if diagnostic_api else tail) - raise GhError(("GitHub API request",), detail, token=selected, guidance=guidance) - raise GhError(argv, tail, token=selected, guidance=guidance) - if done.exit_code == 0 or delay is None or not retryable or not _transient_error(tail, retry_idempotent): + raise GhUnavailable(("GitHub API request",), detail, token=selected, guidance=guidance) + raise GhUnavailable(argv, tail, token=selected, guidance=guidance) + transient = _transient_error(tail, retry_idempotent, status) + if done.exit_code == 0 or delay is None or not retryable or not transient: break _retry_sleep(_read_timeout(delay) if scope else delay) if done.exit_code != 0: @@ -375,7 +393,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, if "gh auth login" in tail or "not logged in" in tail.lower(): raise GhAuth(error_command, error_tail.rstrip(), token=selected, guidance=f"\n{GH_AUTH_REMEDY}") guidance = _pr_list_error_guidance(args, done.stderr, bool(read_only and selected and token is None)) - raise GhError(error_command, error_tail, token=selected, guidance=guidance) + raise _request_error(transient)(error_command, error_tail, token=selected, guidance=guidance) return body diff --git a/src/loopzero/hosted.py b/src/loopzero/hosted.py index 3b963850..e257ae5b 100644 --- a/src/loopzero/hosted.py +++ b/src/loopzero/hosted.py @@ -36,8 +36,12 @@ def main() -> int: except config.ConfigError as exc: print(exc, file=sys.stderr) return 1 - with github.api_error_diagnostics(): - return _run(cfg) + try: + with github.api_error_diagnostics(): + return _run(cfg) + except (github.GhUnavailable, github.ProcTimeout) as exc: + print(f"Eligibility unconfirmed: GitHub evidence unavailable ({exc})", file=sys.stderr) + return 0 def _run(cfg: Config) -> int: @@ -111,7 +115,7 @@ def _publish_verdict(repo: str, head: str, state: str, description: str) -> None def _mark_refresh_failed(publish: Callable[[str, str], None], exc: Exception) -> None: - if not isinstance(exc, github.StatusLimitReached): + if not isinstance(exc, (github.GhUnavailable, github.ProcTimeout, github.StatusLimitReached)): with suppress(Exception): publish("failure", "Eligibility refresh failed; inspect workflow logs") diff --git a/tests/test_hosted.py b/tests/test_hosted.py index f9295795..1b0d5306 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -53,8 +53,7 @@ def test_event_selection(event, number): def publisher(tmp_path, fake_bin, monkeypatch): monkeypatch.chdir(tmp_path) monkeypatch.setenv("GITHUB_REPOSITORY", REPO) - event = tmp_path / "event.json" - event.write_text(json.dumps({"pull_request": {"number": 7}})) + (event := tmp_path / "event.json").write_text(json.dumps({"pull_request": {"number": 7}})) 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) @@ -64,6 +63,7 @@ def publisher(tmp_path, fake_bin, monkeypatch): gh.respond_pr_view(pr_json()) 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", []) return gh @@ -143,28 +143,29 @@ def lose_reply(repo, head, context, value, description): assert [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] == ["pending", state] -@pytest.mark.parametrize("error", ["api", "head", "publication", "config"]) -def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, error): - monkeypatch.setattr(github, "_retry_sleep", lambda _: None) - publisher.respond(f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1", []) - if error == "api": - publisher.respond(f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1", - {"stdout": "HTTP/2.0 503 Service Unavailable\r\nX-GitHub-Request-Id: GHREQ-8774\r\n\r\n{\"message\":\"Service unavailable github_pat_1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ\"}", "stderr": "gh: Service unavailable (HTTP 503)", "exit": 1}) +@pytest.mark.parametrize("error", ["api", "recover", "head", "publication", "config"]) +def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, capsys, error): + sleeps = [] + monkeypatch.setattr(github, "_retry_sleep", sleeps.append) + reviews = f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1" + if error in {"api", "recover"}: + 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(reviews, 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)) 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}/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") - with pytest.raises((github.GhError, hosted.LoopZeroError), match=(r"method=GET endpoint=/repos/acme/widgets/pulls/7/reviews status=503 request_id=GHREQ-8774 message=Service unavailable \[REDACTED\]" if error == "api" else None)) as raised: - hosted.main() - if error == "publication": - assert "invalid description (HTTP 422)" in str(raised.value) - statuses = [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] - assert statuses == ([] if error == "config" else ["pending", "pending"] - if error == "publication" else ["pending", "failure"]) + if error in {"api", "recover"}: + assert hosted.main() == 0 and sleeps == [5] + assert ("method=GET endpoint=/repos/acme/widgets/pulls/7/reviews status=503 request_id=GHREQ-8774 message=Service unavailable [REDACTED]" in capsys.readouterr().err) == (error == "api") + else: + with pytest.raises(hosted.LoopZeroError, match="invalid description" if error == "publication" else None): + hosted.main() + states = {"config": [], "head": ["pending", "failure"], "api": ["pending"], "recover": ["pending", "success"]} + assert [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] == states.get(error, ["pending", "pending"]) @pytest.mark.parametrize("case,error,message", [ @@ -174,15 +175,15 @@ def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, er ("race", CandidateRaceError, "metadata changed"), ("malformed", CandidateError, "invalid payload"), ("head", hosted.LoopZeroError, "head changed"), ("publisher", CandidateError, "not open"), - ("interrupt", KeyboardInterrupt, ""), + ("interrupt", KeyboardInterrupt, ""), ("api", None, ""), ("manual", hosted.LoopZeroError, "pull_request_target creation"), ("metadata", None, ""), ("stale", hosted.LoopZeroError, "head is no longer current"), ("untrusted", CandidateError, "head event was not sent"), ]) def test_candidate_publication_and_event_controls(tmp_path, fake_bin, monkeypatch, case, error, message): event = candidate_event() - event["action"] = "edited" if case == "metadata" else event["action"] - event["sender"]["id"] = 1 if case == "untrusted" else event["sender"]["id"] + event["action"], event["sender"]["id"] = ( + "edited" if case == "metadata" else event["action"], 1 if case == "untrusted" else event["sender"]["id"]) values = candidate_payloads(event) if case in {"valid", "hold"}: gh = FakeGh(fake_bin, tmp_path) @@ -201,11 +202,11 @@ def test_candidate_publication_and_event_controls(tmp_path, fake_bin, monkeypatc values["/repos/owner/repo/pulls/900"]["head"]["sha"] = "d" * 40 if case == "malformed": values["/repos/owner/repo/pulls/101"] = [] - (event_path := tmp_path / "event.json").write_text(json.dumps(event)) + (tmp_path / "event.json").write_text(json.dumps(event)) (tmp_path / "workflow.toml").write_text('[repo]\nname="owner/repo"\nbase="main"\n[delivery]\nreview_publishers=["trusted-publisher"]\n') monkeypatch.chdir(tmp_path) monkeypatch.setenv("GITHUB_REPOSITORY", "owner/repo") - monkeypatch.setenv("GITHUB_EVENT_PATH", str(event_path)) + monkeypatch.setenv("GITHUB_EVENT_PATH", str(tmp_path / "event.json")) attempts, sleeps = [], [] def api_get(path): @@ -227,15 +228,14 @@ def publish(*args): if args[3] == "failure" and case == "publisher": raise RuntimeError("publication details must not replace attestation error") monkeypatch.setattr(github, "commit_status", publish) - evaluated = [] - real_evaluate = hosted.eligibility.evaluate + evaluated, real_evaluate = [], hosted.eligibility.evaluate def evaluate(repo, number, head, base, publishers): evaluated.append((repo, number, head, base, publishers)) if case in {"valid", "hold"}: return real_evaluate(repo, number, head, base, publishers) - if case == "interrupt": - raise KeyboardInterrupt() + if fault := {"interrupt": KeyboardInterrupt(), "api": github.GhUnavailable(("gh",), "HTTP 503")}.get(case): + raise fault reasons = (github.MISSING_REVIEW_REASON,) if case == "policy" else () return github.Readiness(not reasons, reasons) if case not in {"valid", "hold"}: @@ -248,7 +248,7 @@ def evaluate(repo, number, head, base, publishers): hosted.main() else: assert hosted.main() == 0 - terminal = [] if case in {"manual", "metadata", "stale", "interrupt"} else ["failure"] + 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) if case == "valid": From d26ca8bbab1f66d9f7a2e9ad7d11fc9d06a5213b Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:30:32 +0100 Subject: [PATCH 02/17] Keep hosted eligibility pending during GitHub outages Architecture-Review: unchanged; remains fail-closed while trusted evidence is unavailable, with the same status context and publisher. Co-Authored-By: Codex --- src/loopzero/eligibility.py | 2 ++ src/loopzero/github.py | 38 ++++++++++++++++++------- src/loopzero/hosted.py | 10 +++++-- tests/test_hosted.py | 56 ++++++++++++++++++------------------- 4 files changed, 65 insertions(+), 41 deletions(-) diff --git a/src/loopzero/eligibility.py b/src/loopzero/eligibility.py index 41de7f3c..274703a1 100644 --- a/src/loopzero/eligibility.py +++ b/src/loopzero/eligibility.py @@ -121,6 +121,8 @@ def _clean_base_merges(repo: str, number: int, reviewed: str, head: str, base_br return False cursor = first return cursor == reviewed + except github.GhUnavailable: + raise except (candidate.CandidateError, github.GhError, KeyError, OSError, TypeError, ValueError): return False diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 45fb8ce2..d9ac8ae8 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -68,7 +68,11 @@ def __init__(self, command: tuple[str, ...], tail: str, *, super().__init__(f"{command_text} failed: {self.tail.strip()[-600:]}") -class ReadDeadline(GhError): +class GhUnavailable(GhError): + """GitHub could not supply a result because of a transient fault or limit.""" + + +class ReadDeadline(GhUnavailable): """A shared GitHub read deadline elapsed.""" @@ -305,12 +309,26 @@ def _select_token(token: str | None, scope: tuple[float, str | None, bool] | Non return selected if selected is not None else (app_token() if read_only else "") -def _transient_error(tail: str, retry_idempotent: bool) -> bool: - return bool(TRANSIENT_RE.search(tail)) or ( +def _transient_error(tail: str, retry_idempotent: bool, status: str | None = None) -> bool: + return (status or "").startswith("5") or bool(TRANSIENT_RE.search(tail)) or ( retry_idempotent and "something went wrong while executing your query" in tail.lower() ) +def _request_error(transient: bool) -> type[GhError]: + return GhUnavailable if transient else GhError + + +def _rate_limited(status: str | None, headers: dict[str, str], tail: str) -> bool: + return (status == "429" + or (status == "403" and (headers.get("x-ratelimit-remaining") == "0" or "retry-after" in headers)) + or bool(re.search(r"rate limit|HTTP 429", tail, re.IGNORECASE))) + + +def _retry_delays(scope: tuple[float, str | None, bool] | None, diagnostic: bool) -> tuple: + return (None,) if scope and not scope[2] else (*(RETRY_DELAYS[:1] if diagnostic else RETRY_DELAYS), None) + + def _pr_list_error_guidance(args: tuple[str, ...], stderr: str, using_app: bool) -> str: if (using_app and len(args) > 1 and args[0] == "api" and re.fullmatch(r"repos/[^/]+/[^/]+/pulls\?.+", args[1]) @@ -332,7 +350,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, read_only = _read_only(args) retryable = read_only or retry_idempotent scope = _read_scope.get() if read_only else None - delays = (None,) if scope and not scope[2] else (*RETRY_DELAYS, None) + delays = _retry_delays(scope, diagnostic_api) for delay in delays: selected = _select_token(token, scope, read_only) # a retry backoff can outlive the app token try: @@ -355,16 +373,16 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, status, headers, body = (_included_response(done.stdout) if rest_api or diagnostic_api else (None, {}, done.stdout)) tail = "\n".join(part for part in (done.stderr, body if rest_api else done.stdout) if part) - if done.exit_code and ((rest_api and status == "429") - or re.search(r"rate limit|HTTP 429", tail, re.IGNORECASE)): + if done.exit_code and _rate_limited(status, headers, tail): guidance = (_redact_tokens(_rest_rate_limit(headers), selected) if rest_api else _graphql_reset(args, tail, cwd, selected) + RATE_LIMIT_GUIDANCE) if diagnostic_api or patch_error: detail = _api_error_detail(args, done.stdout if diagnostic_api else "", done.stderr, selected, message_tail=None if diagnostic_api else tail) - raise GhError(("GitHub API request",), detail, token=selected, guidance=guidance) - raise GhError(argv, tail, token=selected, guidance=guidance) - if done.exit_code == 0 or delay is None or not retryable or not _transient_error(tail, retry_idempotent): + raise GhUnavailable(("GitHub API request",), detail, token=selected, guidance=guidance) + raise GhUnavailable(argv, tail, token=selected, guidance=guidance) + transient = _transient_error(tail, retry_idempotent, status) + if done.exit_code == 0 or delay is None or not retryable or not transient: break _retry_sleep(_read_timeout(delay) if scope else delay) if done.exit_code != 0: @@ -375,7 +393,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, if "gh auth login" in tail or "not logged in" in tail.lower(): raise GhAuth(error_command, error_tail.rstrip(), token=selected, guidance=f"\n{GH_AUTH_REMEDY}") guidance = _pr_list_error_guidance(args, done.stderr, bool(read_only and selected and token is None)) - raise GhError(error_command, error_tail, token=selected, guidance=guidance) + raise _request_error(transient)(error_command, error_tail, token=selected, guidance=guidance) return body diff --git a/src/loopzero/hosted.py b/src/loopzero/hosted.py index 3b963850..e257ae5b 100644 --- a/src/loopzero/hosted.py +++ b/src/loopzero/hosted.py @@ -36,8 +36,12 @@ def main() -> int: except config.ConfigError as exc: print(exc, file=sys.stderr) return 1 - with github.api_error_diagnostics(): - return _run(cfg) + try: + with github.api_error_diagnostics(): + return _run(cfg) + except (github.GhUnavailable, github.ProcTimeout) as exc: + print(f"Eligibility unconfirmed: GitHub evidence unavailable ({exc})", file=sys.stderr) + return 0 def _run(cfg: Config) -> int: @@ -111,7 +115,7 @@ def _publish_verdict(repo: str, head: str, state: str, description: str) -> None def _mark_refresh_failed(publish: Callable[[str, str], None], exc: Exception) -> None: - if not isinstance(exc, github.StatusLimitReached): + if not isinstance(exc, (github.GhUnavailable, github.ProcTimeout, github.StatusLimitReached)): with suppress(Exception): publish("failure", "Eligibility refresh failed; inspect workflow logs") diff --git a/tests/test_hosted.py b/tests/test_hosted.py index f9295795..1b0d5306 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -53,8 +53,7 @@ def test_event_selection(event, number): def publisher(tmp_path, fake_bin, monkeypatch): monkeypatch.chdir(tmp_path) monkeypatch.setenv("GITHUB_REPOSITORY", REPO) - event = tmp_path / "event.json" - event.write_text(json.dumps({"pull_request": {"number": 7}})) + (event := tmp_path / "event.json").write_text(json.dumps({"pull_request": {"number": 7}})) 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) @@ -64,6 +63,7 @@ def publisher(tmp_path, fake_bin, monkeypatch): gh.respond_pr_view(pr_json()) 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", []) return gh @@ -143,28 +143,29 @@ def lose_reply(repo, head, context, value, description): assert [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] == ["pending", state] -@pytest.mark.parametrize("error", ["api", "head", "publication", "config"]) -def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, error): - monkeypatch.setattr(github, "_retry_sleep", lambda _: None) - publisher.respond(f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1", []) - if error == "api": - publisher.respond(f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1", - {"stdout": "HTTP/2.0 503 Service Unavailable\r\nX-GitHub-Request-Id: GHREQ-8774\r\n\r\n{\"message\":\"Service unavailable github_pat_1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ\"}", "stderr": "gh: Service unavailable (HTTP 503)", "exit": 1}) +@pytest.mark.parametrize("error", ["api", "recover", "head", "publication", "config"]) +def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, capsys, error): + sleeps = [] + monkeypatch.setattr(github, "_retry_sleep", sleeps.append) + reviews = f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1" + if error in {"api", "recover"}: + 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(reviews, 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)) 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}/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") - with pytest.raises((github.GhError, hosted.LoopZeroError), match=(r"method=GET endpoint=/repos/acme/widgets/pulls/7/reviews status=503 request_id=GHREQ-8774 message=Service unavailable \[REDACTED\]" if error == "api" else None)) as raised: - hosted.main() - if error == "publication": - assert "invalid description (HTTP 422)" in str(raised.value) - statuses = [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] - assert statuses == ([] if error == "config" else ["pending", "pending"] - if error == "publication" else ["pending", "failure"]) + if error in {"api", "recover"}: + assert hosted.main() == 0 and sleeps == [5] + assert ("method=GET endpoint=/repos/acme/widgets/pulls/7/reviews status=503 request_id=GHREQ-8774 message=Service unavailable [REDACTED]" in capsys.readouterr().err) == (error == "api") + else: + with pytest.raises(hosted.LoopZeroError, match="invalid description" if error == "publication" else None): + hosted.main() + states = {"config": [], "head": ["pending", "failure"], "api": ["pending"], "recover": ["pending", "success"]} + assert [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] == states.get(error, ["pending", "pending"]) @pytest.mark.parametrize("case,error,message", [ @@ -174,15 +175,15 @@ def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, er ("race", CandidateRaceError, "metadata changed"), ("malformed", CandidateError, "invalid payload"), ("head", hosted.LoopZeroError, "head changed"), ("publisher", CandidateError, "not open"), - ("interrupt", KeyboardInterrupt, ""), + ("interrupt", KeyboardInterrupt, ""), ("api", None, ""), ("manual", hosted.LoopZeroError, "pull_request_target creation"), ("metadata", None, ""), ("stale", hosted.LoopZeroError, "head is no longer current"), ("untrusted", CandidateError, "head event was not sent"), ]) def test_candidate_publication_and_event_controls(tmp_path, fake_bin, monkeypatch, case, error, message): event = candidate_event() - event["action"] = "edited" if case == "metadata" else event["action"] - event["sender"]["id"] = 1 if case == "untrusted" else event["sender"]["id"] + event["action"], event["sender"]["id"] = ( + "edited" if case == "metadata" else event["action"], 1 if case == "untrusted" else event["sender"]["id"]) values = candidate_payloads(event) if case in {"valid", "hold"}: gh = FakeGh(fake_bin, tmp_path) @@ -201,11 +202,11 @@ def test_candidate_publication_and_event_controls(tmp_path, fake_bin, monkeypatc values["/repos/owner/repo/pulls/900"]["head"]["sha"] = "d" * 40 if case == "malformed": values["/repos/owner/repo/pulls/101"] = [] - (event_path := tmp_path / "event.json").write_text(json.dumps(event)) + (tmp_path / "event.json").write_text(json.dumps(event)) (tmp_path / "workflow.toml").write_text('[repo]\nname="owner/repo"\nbase="main"\n[delivery]\nreview_publishers=["trusted-publisher"]\n') monkeypatch.chdir(tmp_path) monkeypatch.setenv("GITHUB_REPOSITORY", "owner/repo") - monkeypatch.setenv("GITHUB_EVENT_PATH", str(event_path)) + monkeypatch.setenv("GITHUB_EVENT_PATH", str(tmp_path / "event.json")) attempts, sleeps = [], [] def api_get(path): @@ -227,15 +228,14 @@ def publish(*args): if args[3] == "failure" and case == "publisher": raise RuntimeError("publication details must not replace attestation error") monkeypatch.setattr(github, "commit_status", publish) - evaluated = [] - real_evaluate = hosted.eligibility.evaluate + evaluated, real_evaluate = [], hosted.eligibility.evaluate def evaluate(repo, number, head, base, publishers): evaluated.append((repo, number, head, base, publishers)) if case in {"valid", "hold"}: return real_evaluate(repo, number, head, base, publishers) - if case == "interrupt": - raise KeyboardInterrupt() + if fault := {"interrupt": KeyboardInterrupt(), "api": github.GhUnavailable(("gh",), "HTTP 503")}.get(case): + raise fault reasons = (github.MISSING_REVIEW_REASON,) if case == "policy" else () return github.Readiness(not reasons, reasons) if case not in {"valid", "hold"}: @@ -248,7 +248,7 @@ def evaluate(repo, number, head, base, publishers): hosted.main() else: assert hosted.main() == 0 - terminal = [] if case in {"manual", "metadata", "stale", "interrupt"} else ["failure"] + 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) if case == "valid": From 9d9d15f1f90dbe5cc28b0c180f4bd91136fb8ee7 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:34:12 +0100 Subject: [PATCH 03/17] Retry safe GitHub observations once within their budget Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 3 ++- src/loopzero/cli.py | 2 +- src/loopzero/github.py | 45 +++++++++++++++++++++++------------ tests/test_github.py | 35 +++++++++++++-------------- tests/test_review_recovery.py | 14 +++++------ 5 files changed, 57 insertions(+), 42 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c474e6e7..50212366 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -331,7 +331,8 @@ The current CLI writes PR bodies only when content changes, excluding volatile check timing from the generated validation block. Keep refreshes idempotent: one state transition should not become repeated writes that trigger policy CI. GitHub reads and the idempotent thread resolution mutation retry transient -failures up to three times (5/20/60 seconds) and stop on rate limits. Mergify +failures once after five seconds. They stop on exhausted quota and honor a +secondary limit’s Retry-After when the delay fits the read budget. Mergify reads retry server errors, throttling and failed reads up to twice (2/5 seconds). Waits use bounded backoff. See the [contract's waiter and polling rules](../core/CONTRACT.md#failure). diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 48a64159..eb3d5461 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -891,7 +891,7 @@ def _repost_prefix(result: ReviewResult) -> str: def _recover_review(wt: Path, config: Config, pr: github.PR, result: ReviewResult, publisher: str, token: str) -> tuple[bool, list[dict]]: - with github.bounded_reads(time.monotonic() + 30, token=token): + with github.bounded_reads(time.monotonic() + 30, token=token, retry=True): reviews = _pr_reviews(config.repo, pr.number) return _confirm_review(wt, config, pr, result, publisher, reviews), reviews diff --git a/src/loopzero/github.py b/src/loopzero/github.py index d9ac8ae8..36951688 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -14,6 +14,7 @@ from contextvars import ContextVar from dataclasses import dataclass from datetime import UTC, datetime +from email.utils import parsedate_to_datetime from pathlib import Path from typing import Literal from urllib.parse import quote @@ -119,7 +120,7 @@ class Readiness: TRANSIENT_RE = re.compile(r"HTTP 5\d\d|timed out|TLS handshake timeout|i/o timeout|" r"connection reset|no server is currently|error connecting to api\.github\.com|" r"unexpected end of JSON input|Something went wrong while executing your query", re.IGNORECASE) -RETRY_DELAYS = (5.0, 20.0, 60.0) +RETRY_DELAY = 5.0 _retry_sleep = time.sleep _read_scope: ContextVar[tuple[float, str | None, bool] | None] = ContextVar("github_reads", default=None) _api_error_diagnostics: ContextVar[bool] = ContextVar("github_api_error_diagnostics", default=False) @@ -325,8 +326,22 @@ def _rate_limited(status: str | None, headers: dict[str, str], tail: str) -> boo or bool(re.search(r"rate limit|HTTP 429", tail, re.IGNORECASE))) -def _retry_delays(scope: tuple[float, str | None, bool] | None, diagnostic: bool) -> tuple: - return (None,) if scope and not scope[2] else (*(RETRY_DELAYS[:1] if diagnostic else RETRY_DELAYS), None) +def _retry_pause(delay: float | None, limit: float) -> bool: + if delay is None or delay >= _read_timeout(limit): + return False + _retry_sleep(delay) + return True + + +def _rate_limit_delay(headers: dict[str, str], delay: float | None) -> float | None: + if delay is None or headers.get("x-ratelimit-remaining") == "0": + return None + value = headers.get("retry-after", "") + try: + wait = int(value) if re.fullmatch(r"[0-9]{1,18}", value) else parsedate_to_datetime(value).timestamp() - time.time() + except (OverflowError, OSError, ValueError): + return None + return max(delay, wait) def _pr_list_error_guidance(args: tuple[str, ...], stderr: str, using_app: bool) -> str: @@ -343,14 +358,15 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, rest_api = args[:1] == ("api",) and args[:2] != ("api", "graphql") patch_error = args[:1] == ("api",) and _api_method(args) == "PATCH" request_args = args - if (rest_api or diagnostic_api) and not {"--include", "-i"} & set(args): + api = args[:1] == ("api",) + if api and not {"--include", "-i"} & set(args): request_args = (*args, "--include") argv = ("gh", *request_args) cwd = cwd or Path("/") read_only = _read_only(args) retryable = read_only or retry_idempotent scope = _read_scope.get() if read_only else None - delays = _retry_delays(scope, diagnostic_api) + delays = (RETRY_DELAY, None) if retryable and (not scope or scope[2]) else (None,) for delay in delays: selected = _select_token(token, scope, read_only) # a retry backoff can outlive the app token try: @@ -361,30 +377,29 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, raise GhMissing(argv, str(exc), token=selected, guidance=f"\nInstall GitHub CLI, then {GH_AUTH_REMEDY}") from exc except ProcTimeout as exc: - if scope and scope[2]: - _read_timeout(timeout) - if delay is None or not retryable: + _read_timeout(timeout) + if not _retry_pause(delay, timeout): raise ProcTimeout( _redact_tokens(str(exc), selected), _redact_tokens(exc.stdout, selected), stderr=_redact_tokens(exc.stderr, selected), duration_s=exc.duration_s, ) from None - _retry_sleep(_read_timeout(delay) if scope else delay) continue - status, headers, body = (_included_response(done.stdout) if rest_api or diagnostic_api + status, headers, body = (_included_response(done.stdout) if api else (None, {}, done.stdout)) - tail = "\n".join(part for part in (done.stderr, body if rest_api else done.stdout) if part) + tail = "\n".join(part for part in (done.stderr, body) if part) if done.exit_code and _rate_limited(status, headers, tail): - guidance = (_redact_tokens(_rest_rate_limit(headers), selected) if rest_api + if _retry_pause(_rate_limit_delay(headers, delay), timeout): + continue + guidance = (_redact_tokens(_rest_rate_limit(headers), selected) if rest_api or headers else _graphql_reset(args, tail, cwd, selected) + RATE_LIMIT_GUIDANCE) if diagnostic_api or patch_error: detail = _api_error_detail(args, done.stdout if diagnostic_api else "", done.stderr, selected, message_tail=None if diagnostic_api else tail) raise GhUnavailable(("GitHub API request",), detail, token=selected, guidance=guidance) - raise GhUnavailable(argv, tail, token=selected, guidance=guidance) + raise GhUnavailable(("gh", *args), tail, token=selected, guidance=guidance) transient = _transient_error(tail, retry_idempotent, status) - if done.exit_code == 0 or delay is None or not retryable or not transient: + if done.exit_code == 0 or not transient or not _retry_pause(delay, timeout): break - _retry_sleep(_read_timeout(delay) if scope else delay) if done.exit_code != 0: error_command = ("GitHub API request",) if diagnostic_api or patch_error else argv error_tail = (_api_error_detail(args, done.stdout if diagnostic_api else "", done.stderr, selected, diff --git a/tests/test_github.py b/tests/test_github.py index c961f43e..6dee2514 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -1273,28 +1273,28 @@ def test_merge_rejects_unknown_strategy(gh: FakeGh) -> None: (("api", "repos/acme/widgets/pulls/1"), 2, ""), (("api", "repos/acme/widgets/commits/x/check-runs", "--method", "GET", "-F", "per_page=100"), 2, "dial tcp 140.82.121.5:443: i/o timeout"), (("api", "graphql", "-f", "query=query { viewer { login } }"), 2, "net/http: TLS handshake timeout"), - (("api", "repos/acme/widgets/pulls/7"), 2, "error connecting to api.github.com"), + (("api", "repos/acme/widgets/pulls/7"), 2, "connection reset by peer"), (("api", "repos/acme/widgets/pulls/7/reviews"), 2, "unexpected end of JSON input"), (("api", "graphql", "-f", "query=query { viewer { login } }"), 2, "gh: Something went wrong while executing your query"), (("api", "repos/acme/widgets/issues/1/comments", "-f", "body=x"), 1, "HTTP 503"), (("api", "graphql", "-f", "query=mutation { resolve }"), 1, "HTTP 503"), ]) def test_gh_retries_only_transient_reads(monkeypatch, args, attempts, error): - seen: list[list[str]] = [] + seen, sleeps = [], [] def run(argv, **_): seen.append(argv) - failed = len(seen) == 1 + failed = len(seen) == 1 or "connection reset" in error if failed and "pulls/1" in argv[2]: raise github.ProcTimeout("gh api timed out") return type("Done", (), {"exit_code": int(failed), "stdout": "ok", "stderr": error * failed}) monkeypatch.setattr(github, "run", run) - monkeypatch.setattr(github, "_retry_sleep", lambda _: None) - if attempts == 2: + monkeypatch.setattr(github, "_retry_sleep", sleeps.append) + if attempts == 2 and "connection reset" not in error: assert github._gh(*args) == "ok" else: with pytest.raises(github.GhError): github._gh(*args) - assert len(seen) == attempts + assert len(seen) == attempts and sleeps == ([5] if attempts == 2 else []) @pytest.mark.parametrize("error", ["API rate limit exceeded", "API rate limit already exceeded", @@ -1314,28 +1314,28 @@ def test_rest_rate_limit_is_not_retried_or_probed(gh, monkeypatch, tmp_path, err @pytest.mark.parametrize(("remaining", "retry_after", "hint"), [ - ("0", "", "hourly quota exhausted: retry after 2026-11-25T21:03:14+00:00"), + ("0", "90", "hourly quota exhausted: retry after 2026-11-25T21:03:14+00:00"), ("4676", "90", "short-window limit: retry after 90 s"), ("4676", "", "short-window limit: retry after ~60 s"), ("", "90", "short-window limit: retry after 90 s"), ("", "Wed, 25 Nov 2026 21:03:14 GMT", "short-window limit: retry after Wed, 25 Nov 2026 21:03:14 GMT"), ("", "", "Rate limited: retry after GitHub's reset or Retry-After; No automatic retry."), ]) -def test_rest_rate_limit_uses_failed_response_headers(gh, remaining, retry_after, hint): +def test_rest_rate_limit_uses_failed_response_headers(gh, monkeypatch, remaining, retry_after, hint): + sleeps = [] + monkeypatch.setattr(github, "_retry_sleep", sleeps.append) + monkeypatch.setattr(github.time, "time", lambda: 1795640554) headers = "HTTP/2.0 403 Forbidden\r\nX-Unrelated: never print this\r\n" if remaining: - headers += ( - f"X-RateLimit-Resource: core\r\nX-RateLimit-Remaining: {remaining}\r\n" - "X-RateLimit-Reset: 1795640594\r\n" - ) + headers += f"X-RateLimit-Resource: core\r\nX-RateLimit-Remaining: {remaining}\r\nX-RateLimit-Reset: 1795640594\r\n" if retry_after: headers += f"Retry-After: {retry_after}\r\n" gh.respond(pr_list_key("lz/x"), headers + '\r\n{"message":"API rate limit exceeded"}', exit=1, stderr="gh: API rate limit exceeded for installation ID 123 (HTTP 403)") - with pytest.raises(github.GhError) as info: + budget = 50 if remaining == "4676" else 100 + with github.bounded_reads(github.time.monotonic() + budget, retry=True), pytest.raises(github.GhError) as info: github.pr_for_branch(REPO, "lz/x") - error = str(info.value) assert hint in error if remaining: @@ -1345,10 +1345,9 @@ def test_rest_rate_limit_uses_failed_response_headers(gh, remaining, retry_after if retry_after: assert f"Retry-After: {retry_after}" in error assert "never print this" not in error - assert [call["argv"] for call in gh.calls] == [ - [*branch_head_key("lz/x").split(), "--include"], - [*pr_list_key("lz/x").split(), "--include"], - ] + assert sleeps == ([90 if retry_after.isdigit() else 40] if retry_after and not remaining else []) + assert [call["argv"] for call in gh.calls] == ( + [[*branch_head_key("lz/x").split(), "--include"]] + [[*pr_list_key("lz/x").split(), "--include"]] * (1 + len(sleeps))) @pytest.mark.parametrize(("diagnostic", "verified"), [ diff --git a/tests/test_review_recovery.py b/tests/test_review_recovery.py index 0518066e..664583f4 100644 --- a/tests/test_review_recovery.py +++ b/tests/test_review_recovery.py @@ -225,20 +225,20 @@ def rejected(endpoint, payload, **kwargs): assert support.marker(head, "primary", "repost") in support.posted_review(gh)["body"] -@pytest.mark.parametrize("failure", ["timeout", "transient"]) -def test_recovery_transport_caps_request_time_and_does_not_retry(monkeypatch, failure): - timeouts = [] +@pytest.mark.parametrize("failure,budget", [("timeout", 0.5), ("transient", 0.5), ("transient", 10)]) +def test_recovery_transport_retries_only_within_deadline(monkeypatch, failure, budget): + timeouts, sleeps = [], [] def request(argv, **kwargs): timeouts.append(kwargs["timeout"]) if failure == "timeout": raise _proc.ProcTimeout("timeout") return _proc.Completed(1, "", "HTTP 503", 0) monkeypatch.setattr(github, "run", request) - monkeypatch.setattr(github, "app_token", lambda: "") - monkeypatch.setattr(github.time, "monotonic", lambda: 10.0) - with github.bounded_reads(github.time.monotonic() + 0.5), pytest.raises((github.GhError, _proc.ProcTimeout)): + monkeypatch.setattr(github, "_retry_sleep", sleeps.append) + monkeypatch.setattr(github.time, "monotonic", lambda: 10.0 + sum(sleeps)) + with github.bounded_reads(10 + budget, retry=True), pytest.raises((github.GhError, _proc.ProcTimeout)): github.api_get("repos/acme/widgets/pulls/7/reviews") - assert timeouts == [0.5] + assert (timeouts, sleeps) == (([10, 5], [5]) if budget == 10 else ([0.5], [])) @pytest.mark.parametrize("source", ["model", "repost"]) From 44e7683bf903d132ef2142ddfef3b69c706c3881 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:38:42 +0100 Subject: [PATCH 04/17] Expect one retry for idempotent finding resolution Co-Authored-By: Codex --- tests/test_cli.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index b5536583..8617b491 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4147,7 +4147,7 @@ def test_resolve_reports_recovery_when_followup_read_fails(finding_pr, gh, capsy @pytest.mark.parametrize("recovers", [True, False]) def test_resolve_retries_only_thread_resolution(finding_pr, gh: FakeGh, capsys, monkeypatch, recovers) -> None: failure = {"stdout": "", "stderr": "gh: Something went wrong while executing your query", "exit_code": 1} - outcomes = [failure, THREAD_RESOLVED] if recovers else [failure] * 4 + outcomes = [failure, THREAD_RESOLVED] if recovers else [failure] * 2 gh.respond("api graphql", threads_json(finding_pr), REPLY_ACCEPTED, *outcomes) if recovers: gh.append("api graphql", threads_json()) From 9b2fdeb52d0789c95623fa70b405d656582714f0 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:41:38 +0100 Subject: [PATCH 05/17] Keep hosted refresh failures observable before pending publication Architecture-Review: unchanged; evidence and publication failures remain distinguishable within the existing hosted trust boundary. Co-Authored-By: Codex --- src/loopzero/candidate.py | 15 ++++++++++++--- src/loopzero/github.py | 6 +----- src/loopzero/hosted.py | 38 +++++++++++++++++++++++--------------- tests/test_hosted.py | 16 ++++++++-------- 4 files changed, 44 insertions(+), 31 deletions(-) diff --git a/src/loopzero/candidate.py b/src/loopzero/candidate.py index 8edf4afc..673842e0 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -289,6 +289,15 @@ def _attest_source( return source_sha +def _require_git_exit(operation: str, returncode: int) -> None: + if operation == "fetch" and returncode: + from loopzero import github + + raise github.GhUnavailable(("git", "fetch"), "GitHub objects unavailable") + _require(returncode == 0, f"git {operation} exited {returncode}: objects unavailable, " + "resource bound hit, or integration conflict") + + @contextlib.contextmanager def fetched_git(repo: str, heads: list[str]) -> Iterator[Callable[..., str]]: """Run bounded Git commands on fetched objects in an isolated bare repository.""" @@ -298,6 +307,8 @@ def fetched_git(repo: str, heads: list[str]) -> Iterator[Callable[..., str]]: if not token: try: token = github.auth_token() + except github.GhUnavailable: + raise except github.GhError: raise CandidateError("GitHub fetch authentication unavailable") from None _require(bool(token), "GitHub fetch authentication unavailable") @@ -341,9 +352,7 @@ def store_size() -> int: # Git renames temporaries: skip files that vanish _require(time.monotonic() < deadline, "Git time bound exceeded") with contextlib.suppress(subprocess.TimeoutExpired): process.wait(timeout=0.02) - _require(process.returncode == 0, - f"git {args[0]} exited {process.returncode}: objects unavailable, " - "resource bound hit, or integration conflict") + _require_git_exit(args[0], process.returncode) _require(store_size() <= _TREE_BYTES, "Git object/size bound exceeded") output.seek(0) result = output.read(_TREE_OUTPUT + 1) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index d9ac8ae8..15e66155 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -325,10 +325,6 @@ def _rate_limited(status: str | None, headers: dict[str, str], tail: str) -> boo or bool(re.search(r"rate limit|HTTP 429", tail, re.IGNORECASE))) -def _retry_delays(scope: tuple[float, str | None, bool] | None, diagnostic: bool) -> tuple: - return (None,) if scope and not scope[2] else (*(RETRY_DELAYS[:1] if diagnostic else RETRY_DELAYS), None) - - def _pr_list_error_guidance(args: tuple[str, ...], stderr: str, using_app: bool) -> str: if (using_app and len(args) > 1 and args[0] == "api" and re.fullmatch(r"repos/[^/]+/[^/]+/pulls\?.+", args[1]) @@ -350,7 +346,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, read_only = _read_only(args) retryable = read_only or retry_idempotent scope = _read_scope.get() if read_only else None - delays = _retry_delays(scope, diagnostic_api) + delays = ((RETRY_DELAYS[0], None) if scope[2] else (None,)) if scope else (*RETRY_DELAYS, None) for delay in delays: selected = _select_token(token, scope, read_only) # a retry backoff can outlive the app token try: diff --git a/src/loopzero/hosted.py b/src/loopzero/hosted.py index e257ae5b..0f39becf 100644 --- a/src/loopzero/hosted.py +++ b/src/loopzero/hosted.py @@ -37,11 +37,25 @@ def main() -> int: print(exc, file=sys.stderr) return 1 try: - with github.api_error_diagnostics(): + with github.api_error_diagnostics(), github.bounded_reads(float("inf"), token=None, retry=True): return _run(cfg) except (github.GhUnavailable, github.ProcTimeout) as exc: - print(f"Eligibility unconfirmed: GitHub evidence unavailable ({exc})", file=sys.stderr) - return 0 + print(f"Eligibility unconfirmed before pending status publication: {exc}", file=sys.stderr) + return 1 + + +def _candidate_event(event: dict, head: str) -> bool: + event_pr = event.get("pull_request") + if not isinstance(event_pr, dict): + raise LoopZeroError("candidate eligibility requires a pull_request_target " + "creation or head-update event") + if event.get("action") not in {"opened", "synchronize"}: + print("ignored candidate metadata event") + return False + event_head = event_pr.get("head") + if not isinstance(event_head, dict) or event_head.get("sha") != head: + raise LoopZeroError("candidate event head is no longer current") + return True def _run(cfg: Config) -> int: @@ -55,17 +69,8 @@ def _run(cfg: Config) -> int: or pr["user"]["login"] == "mergify[bot]") if not candidate and pr.get("merged") is True: return 0 # A landed source needs no new verdict; a late refresh must not turn it red. - if candidate: - event_pr = event.get("pull_request") - if not isinstance(event_pr, dict): - raise LoopZeroError("candidate eligibility requires a pull_request_target " - "creation or head-update event") - if event.get("action") not in {"opened", "synchronize"}: - print("ignored candidate metadata event") - return 0 - event_head = event_pr.get("head") - if not isinstance(event_head, dict) or event_head.get("sha") != head: - raise LoopZeroError("candidate event head is no longer current") + if candidate and not _candidate_event(event, head): + return 0 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") @@ -93,6 +98,9 @@ def policy(source_number: int, source: dict) -> None: if not candidate and not ready and result.reasons == (github.MISSING_REVIEW_REASON,): message = "Awaiting trusted review of current source head" state = "pending" + except (github.GhUnavailable, github.ProcTimeout) as exc: + print(f"Eligibility pending: evidence unavailable ({exc})", file=sys.stderr) + return 0 except Exception as exc: _mark_refresh_failed(publish, exc) raise @@ -115,7 +123,7 @@ def _publish_verdict(repo: str, head: str, state: str, description: str) -> None def _mark_refresh_failed(publish: Callable[[str, str], None], exc: Exception) -> None: - if not isinstance(exc, (github.GhUnavailable, github.ProcTimeout, github.StatusLimitReached)): + if not isinstance(exc, github.StatusLimitReached): with suppress(Exception): publish("failure", "Eligibility refresh failed; inspect workflow logs") diff --git a/tests/test_hosted.py b/tests/test_hosted.py index 1b0d5306..e781cfdc 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -143,14 +143,14 @@ def lose_reply(repo, head, context, value, description): assert [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] == ["pending", state] -@pytest.mark.parametrize("error", ["api", "recover", "head", "publication", "config"]) +@pytest.mark.parametrize("error", ["api", "recover", "head", "publication", "config", "before"]) def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, capsys, error): sleeps = [] monkeypatch.setattr(github, "_retry_sleep", sleeps.append) - reviews = f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1" - if error in {"api", "recover"}: + endpoint = f"api repos/{REPO}/pulls/7" + ("" if error == "before" else "/reviews?per_page=100&page=1") + 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(reviews, fault, [{"state": "APPROVED", "commit_id": HEAD, "user": {"login": "trusted-publisher"}, "body": f"\nreview: **approve**"}] if error == "recover" else fault) + 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)) elif error == "publication": @@ -158,13 +158,13 @@ def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, ca publisher.respond(f"api repos/{REPO}/commits/{HEAD}/statuses", [{"context": "other"}]) else: monkeypatch.setenv("GITHUB_REPOSITORY", "other/repo") - if error in {"api", "recover"}: - assert hosted.main() == 0 and sleeps == [5] - assert ("method=GET endpoint=/repos/acme/widgets/pulls/7/reviews status=503 request_id=GHREQ-8774 message=Service unavailable [REDACTED]" in capsys.readouterr().err) == (error == "api") + 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") else: with pytest.raises(hosted.LoopZeroError, match="invalid description" if error == "publication" else None): hosted.main() - states = {"config": [], "head": ["pending", "failure"], "api": ["pending"], "recover": ["pending", "success"]} + states = {"before": [], "config": [], "head": ["pending", "failure"], "api": ["pending"], "recover": ["pending", "success"]} assert [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] == states.get(error, ["pending", "pending"]) From 71a8ff7c9413ea93b5f0d52690a532f41ae44ce1 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:43:54 +0100 Subject: [PATCH 06/17] Preserve genuine missing-object failures during candidate fetch Architecture-Review: unchanged; transient fetch diagnostics remain inside the existing isolated checkout. Co-Authored-By: Codex --- src/loopzero/candidate.py | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/src/loopzero/candidate.py b/src/loopzero/candidate.py index 673842e0..ed75999b 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -18,7 +18,7 @@ import time from collections.abc import Callable, Iterator from pathlib import Path -from typing import Any +from typing import Any, BinaryIO MERGIFY_APP_ID = 10562 MERGIFY_APP_OWNER = "Mergifyio" @@ -289,18 +289,18 @@ def _attest_source( return source_sha -def _require_git_exit(operation: str, returncode: int) -> None: +def _require_git_exit(operation: str, returncode: int, output: BinaryIO) -> None: if operation == "fetch" and returncode: from loopzero import github - raise github.GhUnavailable(("git", "fetch"), "GitHub objects unavailable") + output.seek(0) + if github._transient_error(output.read(_TREE_OUTPUT).decode(errors="replace"), False): + raise github.GhUnavailable(("git", "fetch"), "GitHub objects temporarily unavailable") _require(returncode == 0, f"git {operation} exited {returncode}: objects unavailable, " "resource bound hit, or integration conflict") -@contextlib.contextmanager -def fetched_git(repo: str, heads: list[str]) -> Iterator[Callable[..., str]]: - """Run bounded Git commands on fetched objects in an isolated bare repository.""" +def _fetch_token() -> str: from loopzero import github token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") @@ -312,6 +312,13 @@ def fetched_git(repo: str, heads: list[str]) -> Iterator[Callable[..., str]]: except github.GhError: raise CandidateError("GitHub fetch authentication unavailable") from None _require(bool(token), "GitHub fetch authentication unavailable") + return token + + +@contextlib.contextmanager +def fetched_git(repo: str, heads: list[str]) -> Iterator[Callable[..., str]]: + """Run bounded Git commands on fetched objects in an isolated bare repository.""" + token = _fetch_token() with tempfile.TemporaryDirectory(prefix="loopzero-candidate-") as directory: root = Path(directory) env = { @@ -335,7 +342,8 @@ def git(*args: str, command_env: dict[str, str] = env) -> str: [sys.executable, "-I", "-S", "-c", _LIMITED_GIT, str(_TREE_BYTES), "git", "-c", "core.hooksPath=/dev/null", "-c", "gc.auto=0", "-c", "maintenance.auto=false", *args], cwd=root, env=command_env, - stdin=subprocess.DEVNULL, stdout=output, stderr=subprocess.DEVNULL, + stdin=subprocess.DEVNULL, stdout=output, + stderr=output if args[0] == "fetch" else subprocess.DEVNULL, start_new_session=True, ) def store_size() -> int: # Git renames temporaries: skip files that vanish @@ -352,7 +360,7 @@ def store_size() -> int: # Git renames temporaries: skip files that vanish _require(time.monotonic() < deadline, "Git time bound exceeded") with contextlib.suppress(subprocess.TimeoutExpired): process.wait(timeout=0.02) - _require_git_exit(args[0], process.returncode) + _require_git_exit(args[0], process.returncode, output) _require(store_size() <= _TREE_BYTES, "Git object/size bound exceeded") output.seek(0) result = output.read(_TREE_OUTPUT + 1) From d2614ec1c6d0f0a68ffa07d078e5b594cbadbb67 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:47:31 +0100 Subject: [PATCH 07/17] Honor Retry-After on Mergify queue observations Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 4 ++-- src/loopzero/cli.py | 6 +++--- src/loopzero/github.py | 18 ++++++++++++------ src/loopzero/mergify.py | 39 +++++++++++++++++++++++++-------------- tests/test_cli.py | 2 +- tests/test_mergify.py | 40 ++++++++++++++++++++-------------------- 6 files changed, 63 insertions(+), 46 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 50212366..90630f7c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -333,8 +333,8 @@ one state transition should not become repeated writes that trigger policy CI. GitHub reads and the idempotent thread resolution mutation retry transient failures once after five seconds. They stop on exhausted quota and honor a secondary limit’s Retry-After when the delay fits the read budget. Mergify -reads retry server errors, throttling and failed -reads up to twice (2/5 seconds). Waits use bounded backoff. See the +queue reads retry once after two seconds, subject to Retry-After and the +remaining queue wait budget. See the [contract's waiter and polling rules](../core/CONTRACT.md#failure). The optional host ai-accounts helper owns managed credential selection and exact-model eligibility under its existing lock. Its Claude exec reserve guard (including pinned diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index eb3d5461..d0a6a19e 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1497,9 +1497,9 @@ def _wait_for_mergify( sha = _landed(config, pr, closed) if sha: return sha - if not mergify.configured(config.repo, config.base_branch, queue): + if not mergify.configured(config.repo, config.base_branch, queue, started + timeout): raise CliError("Mergify queue configuration became unsafe or unavailable while waiting") - state = mergify.membership(config.repo, pr.number, queue) + state = mergify.membership(config.repo, pr.number, queue, started + timeout) deferred_landing_read = confirmed and state is not None and not closed if not deferred_landing_read and (sha := _landed(config, pr, closed)): return sha @@ -1537,7 +1537,7 @@ def _merge_with_mergify( requested, confirmed_marker = mergify.markers( config.repo, pr.number, pr.head_sha, queue ) - state = mergify.membership(config.repo, pr.number, queue) + state = mergify.membership(config.repo, pr.number, queue, deadline) if sha := github.merged_sha( config.repo, pr.number, expected_head=pr.head_sha, check_hold=not requested and state is None, ): diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 36951688..3fac89f8 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -333,15 +333,21 @@ def _retry_pause(delay: float | None, limit: float) -> bool: return True -def _rate_limit_delay(headers: dict[str, str], delay: float | None) -> float | None: - if delay is None or headers.get("x-ratelimit-remaining") == "0": - return None - value = headers.get("retry-after", "") +def retry_after(value: str) -> float | None: try: - wait = int(value) if re.fullmatch(r"[0-9]{1,18}", value) else parsedate_to_datetime(value).timestamp() - time.time() + if re.fullmatch(r"[0-9]{1,18}", value): + return float(value) + date = parsedate_to_datetime(value) + return max(0.0, date.timestamp() - time.time()) if date.tzinfo is not None else None except (OverflowError, OSError, ValueError): return None - return max(delay, wait) + + +def _rate_limit_delay(headers: dict[str, str], delay: float | None) -> float | None: + if delay is None or headers.get("x-ratelimit-remaining") == "0": + return None + wait = retry_after(headers.get("retry-after", "")) + return None if wait is None else max(delay, wait) def _pr_list_error_guidance(args: tuple[str, ...], stderr: str, using_app: bool) -> str: diff --git a/src/loopzero/mergify.py b/src/loopzero/mergify.py index eb21eef7..270d4edb 100644 --- a/src/loopzero/mergify.py +++ b/src/loopzero/mergify.py @@ -76,7 +76,14 @@ def _open(request: urllib.request.Request): return urllib.request.build_opener(_NoRedirect).open(request, timeout=30) -def api_get(repo: str, suffix: str) -> object | None: +def _wait_to_retry(delay: float, deadline: float | None) -> bool: + if deadline is not None and time.monotonic() + delay >= deadline: + return False + _retry_sleep(delay) + return deadline is None or time.monotonic() < deadline + + +def api_get(repo: str, suffix: str, deadline: float | None = None) -> object | None: """GET one documented endpoint below this repository's fixed Mergify API path.""" if not suffix.startswith("/") or "://" in suffix or ".." in suffix: raise ValueError("Mergify API suffix must be a repository-relative absolute path") @@ -87,22 +94,26 @@ def api_get(repo: str, suffix: str) -> object | None: headers={"Accept": "application/json", "User-Agent": "loopzero", "Authorization": f"Bearer {_credential()}"}, ) - for delay in (2.0, 5.0, None): # reads retry server errors, throttling and dropped reads + for retry in (True, False): + delay = 2.0 try: with _open(request) as response: return json.load(response) except urllib.error.HTTPError as exc: if exc.code == 404: return None - if delay is None or not (exc.code >= 500 or exc.code == 429): - raise MergifyError(f"Mergify queue lookup failed with HTTP {exc.code}") from exc - except (OSError, ValueError, http.client.IncompleteRead) as exc: - if delay is None: - raise MergifyError("Mergify queue lookup returned no valid JSON") from exc - _retry_sleep(delay) + wait = github.retry_after(exc.headers.get("Retry-After", "")) if exc.headers else None + delay = max(delay, wait or 0.0) + detail = f"HTTP {exc.code}" + (f"; Retry-After: {wait:g}s" if wait is not None else "") + transient = exc.code >= 500 or exc.code == 429 or (exc.code == 403 and wait is not None) + except (OSError, ValueError, http.client.IncompleteRead): + detail, transient = "transport or invalid JSON response", True + if not retry or not transient: + raise MergifyError(f"Mergify queue lookup failed with {detail}") + if not _wait_to_retry(delay, deadline): + raise MergifyError(f"Mergify queue lookup failed with {detail}; retry delay exceeds the wait budget") return None - def _unmet_conditions(node: object) -> tuple[str, ...]: if not isinstance(node, dict) or node.get("match") is not False: return () @@ -113,8 +124,8 @@ def _unmet_conditions(node: object) -> tuple[str, ...]: return (label,) if isinstance(label, str) and label.isprintable() else () -def membership(repo: str, number: int, queue: str) -> Membership | None: - data = api_get(repo, f"/merge-queue/pull/{number}") +def membership(repo: str, number: int, queue: str, deadline: float | None = None) -> Membership | None: + data = api_get(repo, f"/merge-queue/pull/{number}", deadline) if data is None: return None try: @@ -183,12 +194,12 @@ def construct_mapping(self, node, deep=False): and isinstance(metadata, dict) and metadata.get("default_branch") == branch) -def configured(repo: str, branch: str, queue: str) -> bool: +def configured(repo: str, branch: str, queue: str, deadline: float | None = None) -> bool: """Require live queue identity and stable canonical speculative configuration.""" - status_data = api_get(repo, f"/merge-queue/status?branch={quote(branch, safe='')}") + status_data = api_get(repo, f"/merge-queue/status?branch={quote(branch, safe='')}", deadline) if status_data is None: return False - rules_data = api_get(repo, "/queues/configuration") + rules_data = api_get(repo, "/queues/configuration", deadline) if not isinstance(status_data, dict) or not isinstance(rules_data, dict): return False if not isinstance(status_data.get("batches"), list): diff --git a/tests/test_cli.py b/tests/test_cli.py index 3230334d..901a3ede 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2484,7 +2484,7 @@ def source_queue_api(gh, monkeypatch): }) vendor_calls = [] - def get(_repo, path): + def get(_repo, path, *_): vendor_calls.append(path) return { "/merge-queue/status?branch=main": {"batches": [], "mode": "serial"}, diff --git a/tests/test_mergify.py b/tests/test_mergify.py index 518c6002..3631b90e 100644 --- a/tests/test_mergify.py +++ b/tests/test_mergify.py @@ -82,7 +82,7 @@ def open_(request): # a transient failure must not repeat the write @pytest.fixture def queue_api(monkeypatch): - monkeypatch.setattr(mergify, "api_get", lambda _repo, suffix: ( + monkeypatch.setattr(mergify, "api_get", lambda _repo, suffix, *_: ( {"batches": [], "mode": "serial"} if suffix.startswith("/merge-queue/status") else {"configuration": [{"name": "main", "config": {"allow_inplace_checks": True}}]} )) @@ -154,7 +154,7 @@ def malformed(path): def test_legacy_false_does_not_license_single_check_source_updates(queue_api, monkeypatch): queue_api(SAFE_CONFIG.replace("checks: 3", "checks: 1")) - monkeypatch.setattr(mergify, "api_get", lambda _repo, suffix: ( + monkeypatch.setattr(mergify, "api_get", lambda _repo, suffix, *_: ( {"batches": [], "mode": "serial"} if suffix.startswith("/merge-queue/status") else {"configuration": [{"name": "main", "config": {"allow_inplace_checks": False}}]} )) @@ -229,24 +229,24 @@ def test_hosted_import_does_not_load_yaml(): assert result.returncode == 0, result.stderr -@pytest.mark.parametrize("failure", ["http503", "dropped_read", "truncated"]) -def test_api_get_retries_transient_reads(monkeypatch, failure): - calls = [] - - class Body(io.BytesIO): - def read(self, *args): - if len(calls) == 1 and failure != "http503": # body read fails once - raise {"dropped_read": ConnectionResetError(), "truncated": mergify.http.client.IncompleteRead(b"{")}[failure] - return super().read(*args) - +@pytest.mark.parametrize("failure,status,budget,wait", [ + ("http", 503, None, 2), ("reset", None, None, 2), ("truncated", None, None, 2), + ("http", 429, None, 40), ("http", 403, 20, None), ("http", 429, 20, None)]) +def test_api_get_retries_transient_reads(monkeypatch, failure, status, budget, wait): + calls, sleeps = [], [] def fake_open(request): - calls.append(request.get_method()) - if failure == "http503" and len(calls) == 1: - raise urllib.error.HTTPError(request.full_url, 503, "x", {}, None) - return Body(b"{}") - + calls.append((request.get_method(), sum(sleeps))) + if status in {403, 429} or len(calls) == 1: + if status: + raise urllib.error.HTTPError(request.full_url, status, "x", {"Retry-After": "40"} if status < 500 else {}, None) + raise ConnectionResetError() if failure == "reset" else mergify.http.client.IncompleteRead(b"{") + return io.BytesIO(b"{}") monkeypatch.setattr(mergify, "_open", fake_open) - monkeypatch.setattr(mergify, "_retry_sleep", lambda _: None) + monkeypatch.setattr(mergify, "_retry_sleep", sleeps.append) monkeypatch.setattr(mergify, "_credential", lambda: "k") - assert mergify.api_get("acme/widgets", "/merge-queue/status") == {} - assert calls == ["GET", "GET"] + if status in {403, 429}: + with pytest.raises(mergify.MergifyError, match="Retry-After: 40s" + ("; retry delay exceeds" if budget else "")): + mergify.api_get("acme/widgets", "/merge-queue/status", None if budget is None else mergify.time.monotonic() + budget) + else: + assert mergify.api_get("acme/widgets", "/merge-queue/status") == {} + assert calls == ([("GET", 0)] if wait is None else [("GET", 0), ("GET", wait)]) From b60a084bb8e8b9646951e84479e53eec6f53534a Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:48:24 +0100 Subject: [PATCH 08/17] Verify the same deadline reaches every queue observation Co-Authored-By: Codex --- tests/test_cli.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index f79a503d..1d210536 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4298,7 +4298,7 @@ def configured(*args): assert cli._wait_for_mergify(config, pr, 60, confirmed=True) == "e" * 40 assert sleeps == [30, 30] - assert configurations == [(REPO, "main", "main")] * 3 + assert configurations == [(REPO, "main", "main", 60)] * 3 assert reads_at_membership == [1, 2, 3] assert [c["argv"][:2] for c in gh.calls] == [detail] * 4 From 0234af9bd3e99a6dac7fb2c3d183cbcbf077b9ae Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:50:05 +0100 Subject: [PATCH 09/17] Recognize HTTP outages in Git fetch diagnostics Architecture-Review: unchanged; hosted eligibility still requires verified Git objects before accepting inherited evidence. Co-Authored-By: Codex --- src/loopzero/candidate.py | 3 ++- tests/test_candidate.py | 30 +++++++++++++++--------------- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/src/loopzero/candidate.py b/src/loopzero/candidate.py index ed75999b..e202c0fc 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -294,7 +294,8 @@ def _require_git_exit(operation: str, returncode: int, output: BinaryIO) -> None from loopzero import github output.seek(0) - if github._transient_error(output.read(_TREE_OUTPUT).decode(errors="replace"), False): + diagnostic = output.read(_TREE_OUTPUT).decode(errors="replace") + if github._transient_error(diagnostic, False) or re.search(r"returned error: (?:429|5\d\d)", diagnostic): raise github.GhUnavailable(("git", "fetch"), "GitHub objects temporarily unavailable") _require(returncode == 0, f"git {operation} exited {returncode}: objects unavailable, " "resource bound hit, or integration conflict") diff --git a/tests/test_candidate.py b/tests/test_candidate.py index 28dfdc6e..b630962b 100644 --- a/tests/test_candidate.py +++ b/tests/test_candidate.py @@ -9,6 +9,7 @@ from __future__ import annotations import base64 +from contextlib import nullcontext import subprocess from copy import deepcopy from importlib import import_module @@ -17,7 +18,7 @@ import pytest -from loopzero import candidate +from loopzero import candidate, github from loopzero.candidate import CandidateError, CandidateRaceError, attest_candidate from loopzero.types import LoopZeroError @@ -684,18 +685,16 @@ def run(): assert clock[0] == {"closed": 2, "ambiguous": 90, "slow": 100 * (1 + second), "oversleep": 100}[stop] -@pytest.mark.parametrize("exceeds_bound", [False, True]) -def test_fetched_git_waits_for_exit_or_resumes_size_checks(monkeypatch, exceeds_bound): - waits = [] - killed = [] - +@pytest.mark.parametrize("outcome", ["normal", "bound", "fetch"]) +def test_fetched_git_waits_for_exit_or_resumes_size_checks(monkeypatch, outcome): + waits, killed = [], [] class Child: pid = 123 - returncode = 0 - def __init__(self, argv, cwd, **kwargs): - self.root = cwd - self.running = "test-command" in argv + self.root, self.running = cwd, "test-command" in argv + self.returncode = 128 if outcome == "fetch" and "fetch" in argv else 0 + if self.returncode: + kwargs["stderr"].write(b"fatal: The requested URL returned error: 503") def poll(self): return None if self.running else self.returncode @@ -703,7 +702,7 @@ def poll(self): def wait(self, timeout=None): if self.running: waits.append(timeout) - if timeout is not None and exceeds_bound: + if timeout is not None and outcome == "bound": (self.root / "oversized").write_bytes(b"x" * 65) raise subprocess.TimeoutExpired("test-command", timeout) self.running = False @@ -715,12 +714,13 @@ def wait(self, timeout=None): monkeypatch.setattr(candidate.os, "killpg", lambda pid, sig: killed.append((pid, sig))) monkeypatch.setattr(candidate.time, "sleep", lambda _: pytest.fail("used a fixed delay")) - with candidate.fetched_git("owner/repo", []) as git: - if exceeds_bound: + error = pytest.raises(github.GhUnavailable, match="temporarily unavailable") if outcome == "fetch" else nullcontext() + with error, candidate.fetched_git("owner/repo", []) as git: + if outcome == "bound": with pytest.raises(CandidateError, match="Git object/size bound exceeded"): git("test-command") else: assert git("test-command") == "" - assert waits == ([0.02, None] if exceeds_bound else [0.02]) - assert killed == ([(123, candidate.signal.SIGKILL)] if exceeds_bound else []) + assert waits == {"bound": [0.02, None], "normal": [0.02], "fetch": []}[outcome] + assert killed == ([(123, candidate.signal.SIGKILL)] if outcome == "bound" else []) From 1aae039df95b20418eeb4d7984dad4f761a9fb78 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:30:32 +0100 Subject: [PATCH 10/17] Keep hosted eligibility pending during GitHub outages Architecture-Review: unchanged; remains fail-closed while trusted evidence is unavailable, with the same status context and publisher. Co-Authored-By: Codex --- src/loopzero/eligibility.py | 2 ++ src/loopzero/github.py | 38 ++++++++++++++++++------- src/loopzero/hosted.py | 10 +++++-- tests/test_hosted.py | 56 ++++++++++++++++++------------------- 4 files changed, 65 insertions(+), 41 deletions(-) diff --git a/src/loopzero/eligibility.py b/src/loopzero/eligibility.py index 41de7f3c..274703a1 100644 --- a/src/loopzero/eligibility.py +++ b/src/loopzero/eligibility.py @@ -121,6 +121,8 @@ def _clean_base_merges(repo: str, number: int, reviewed: str, head: str, base_br return False cursor = first return cursor == reviewed + except github.GhUnavailable: + raise except (candidate.CandidateError, github.GhError, KeyError, OSError, TypeError, ValueError): return False diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 171efcb9..458bcf57 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -68,7 +68,11 @@ def __init__(self, command: tuple[str, ...], tail: str, *, super().__init__(f"{command_text} failed: {self.tail.strip()[-600:]}") -class ReadDeadline(GhError): +class GhUnavailable(GhError): + """GitHub could not supply a result because of a transient fault or limit.""" + + +class ReadDeadline(GhUnavailable): """A shared GitHub read deadline elapsed.""" @@ -305,12 +309,26 @@ def _select_token(token: str | None, scope: tuple[float, str | None, bool] | Non return selected if selected is not None else (app_token() if read_only else "") -def _transient_error(tail: str, retry_idempotent: bool) -> bool: - return bool(TRANSIENT_RE.search(tail)) or ( +def _transient_error(tail: str, retry_idempotent: bool, status: str | None = None) -> bool: + return (status or "").startswith("5") or bool(TRANSIENT_RE.search(tail)) or ( retry_idempotent and "something went wrong while executing your query" in tail.lower() ) +def _request_error(transient: bool) -> type[GhError]: + return GhUnavailable if transient else GhError + + +def _rate_limited(status: str | None, headers: dict[str, str], tail: str) -> bool: + return (status == "429" + or (status == "403" and (headers.get("x-ratelimit-remaining") == "0" or "retry-after" in headers)) + or bool(re.search(r"rate limit|HTTP 429", tail, re.IGNORECASE))) + + +def _retry_delays(scope: tuple[float, str | None, bool] | None, diagnostic: bool) -> tuple: + return (None,) if scope and not scope[2] else (*(RETRY_DELAYS[:1] if diagnostic else RETRY_DELAYS), None) + + def _pr_list_error_guidance(args: tuple[str, ...], stderr: str, using_app: bool) -> str: if (using_app and len(args) > 1 and args[0] == "api" and re.fullmatch(r"repos/[^/]+/[^/]+/pulls\?.+", args[1]) @@ -332,7 +350,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, read_only = _read_only(args) retryable = read_only or retry_idempotent scope = _read_scope.get() if read_only else None - delays = (None,) if scope and not scope[2] else (*RETRY_DELAYS, None) + delays = _retry_delays(scope, diagnostic_api) for delay in delays: selected = _select_token(token, scope, read_only) # a retry backoff can outlive the app token try: @@ -355,16 +373,16 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, status, headers, body = (_included_response(done.stdout) if rest_api or diagnostic_api else (None, {}, done.stdout)) tail = "\n".join(part for part in (done.stderr, body if rest_api else done.stdout) if part) - if done.exit_code and ((rest_api and status == "429") - or re.search(r"rate limit|HTTP 429", tail, re.IGNORECASE)): + if done.exit_code and _rate_limited(status, headers, tail): guidance = (_redact_tokens(_rest_rate_limit(headers), selected) if rest_api else _graphql_reset(args, tail, cwd, selected) + RATE_LIMIT_GUIDANCE) if diagnostic_api or patch_error: detail = _api_error_detail(args, done.stdout if diagnostic_api else "", done.stderr, selected, message_tail=None if diagnostic_api else tail) - raise GhError(("GitHub API request",), detail, token=selected, guidance=guidance) - raise GhError(argv, tail, token=selected, guidance=guidance) - if done.exit_code == 0 or delay is None or not retryable or not _transient_error(tail, retry_idempotent): + raise GhUnavailable(("GitHub API request",), detail, token=selected, guidance=guidance) + raise GhUnavailable(argv, tail, token=selected, guidance=guidance) + transient = _transient_error(tail, retry_idempotent, status) + if done.exit_code == 0 or delay is None or not retryable or not transient: break _retry_sleep(_read_timeout(delay) if scope else delay) if done.exit_code != 0: @@ -375,7 +393,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, if "gh auth login" in tail or "not logged in" in tail.lower(): raise GhAuth(error_command, error_tail.rstrip(), token=selected, guidance=f"\n{GH_AUTH_REMEDY}") guidance = _pr_list_error_guidance(args, done.stderr, bool(read_only and selected and token is None)) - raise GhError(error_command, error_tail, token=selected, guidance=guidance) + raise _request_error(transient)(error_command, error_tail, token=selected, guidance=guidance) return body diff --git a/src/loopzero/hosted.py b/src/loopzero/hosted.py index 3b963850..e257ae5b 100644 --- a/src/loopzero/hosted.py +++ b/src/loopzero/hosted.py @@ -36,8 +36,12 @@ def main() -> int: except config.ConfigError as exc: print(exc, file=sys.stderr) return 1 - with github.api_error_diagnostics(): - return _run(cfg) + try: + with github.api_error_diagnostics(): + return _run(cfg) + except (github.GhUnavailable, github.ProcTimeout) as exc: + print(f"Eligibility unconfirmed: GitHub evidence unavailable ({exc})", file=sys.stderr) + return 0 def _run(cfg: Config) -> int: @@ -111,7 +115,7 @@ def _publish_verdict(repo: str, head: str, state: str, description: str) -> None def _mark_refresh_failed(publish: Callable[[str, str], None], exc: Exception) -> None: - if not isinstance(exc, github.StatusLimitReached): + if not isinstance(exc, (github.GhUnavailable, github.ProcTimeout, github.StatusLimitReached)): with suppress(Exception): publish("failure", "Eligibility refresh failed; inspect workflow logs") diff --git a/tests/test_hosted.py b/tests/test_hosted.py index f9295795..1b0d5306 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -53,8 +53,7 @@ def test_event_selection(event, number): def publisher(tmp_path, fake_bin, monkeypatch): monkeypatch.chdir(tmp_path) monkeypatch.setenv("GITHUB_REPOSITORY", REPO) - event = tmp_path / "event.json" - event.write_text(json.dumps({"pull_request": {"number": 7}})) + (event := tmp_path / "event.json").write_text(json.dumps({"pull_request": {"number": 7}})) 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) @@ -64,6 +63,7 @@ def publisher(tmp_path, fake_bin, monkeypatch): gh.respond_pr_view(pr_json()) 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", []) return gh @@ -143,28 +143,29 @@ def lose_reply(repo, head, context, value, description): assert [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] == ["pending", state] -@pytest.mark.parametrize("error", ["api", "head", "publication", "config"]) -def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, error): - monkeypatch.setattr(github, "_retry_sleep", lambda _: None) - publisher.respond(f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1", []) - if error == "api": - publisher.respond(f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1", - {"stdout": "HTTP/2.0 503 Service Unavailable\r\nX-GitHub-Request-Id: GHREQ-8774\r\n\r\n{\"message\":\"Service unavailable github_pat_1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ\"}", "stderr": "gh: Service unavailable (HTTP 503)", "exit": 1}) +@pytest.mark.parametrize("error", ["api", "recover", "head", "publication", "config"]) +def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, capsys, error): + sleeps = [] + monkeypatch.setattr(github, "_retry_sleep", sleeps.append) + reviews = f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1" + if error in {"api", "recover"}: + 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(reviews, 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)) 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}/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") - with pytest.raises((github.GhError, hosted.LoopZeroError), match=(r"method=GET endpoint=/repos/acme/widgets/pulls/7/reviews status=503 request_id=GHREQ-8774 message=Service unavailable \[REDACTED\]" if error == "api" else None)) as raised: - hosted.main() - if error == "publication": - assert "invalid description (HTTP 422)" in str(raised.value) - statuses = [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] - assert statuses == ([] if error == "config" else ["pending", "pending"] - if error == "publication" else ["pending", "failure"]) + if error in {"api", "recover"}: + assert hosted.main() == 0 and sleeps == [5] + assert ("method=GET endpoint=/repos/acme/widgets/pulls/7/reviews status=503 request_id=GHREQ-8774 message=Service unavailable [REDACTED]" in capsys.readouterr().err) == (error == "api") + else: + with pytest.raises(hosted.LoopZeroError, match="invalid description" if error == "publication" else None): + hosted.main() + states = {"config": [], "head": ["pending", "failure"], "api": ["pending"], "recover": ["pending", "success"]} + assert [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] == states.get(error, ["pending", "pending"]) @pytest.mark.parametrize("case,error,message", [ @@ -174,15 +175,15 @@ def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, er ("race", CandidateRaceError, "metadata changed"), ("malformed", CandidateError, "invalid payload"), ("head", hosted.LoopZeroError, "head changed"), ("publisher", CandidateError, "not open"), - ("interrupt", KeyboardInterrupt, ""), + ("interrupt", KeyboardInterrupt, ""), ("api", None, ""), ("manual", hosted.LoopZeroError, "pull_request_target creation"), ("metadata", None, ""), ("stale", hosted.LoopZeroError, "head is no longer current"), ("untrusted", CandidateError, "head event was not sent"), ]) def test_candidate_publication_and_event_controls(tmp_path, fake_bin, monkeypatch, case, error, message): event = candidate_event() - event["action"] = "edited" if case == "metadata" else event["action"] - event["sender"]["id"] = 1 if case == "untrusted" else event["sender"]["id"] + event["action"], event["sender"]["id"] = ( + "edited" if case == "metadata" else event["action"], 1 if case == "untrusted" else event["sender"]["id"]) values = candidate_payloads(event) if case in {"valid", "hold"}: gh = FakeGh(fake_bin, tmp_path) @@ -201,11 +202,11 @@ def test_candidate_publication_and_event_controls(tmp_path, fake_bin, monkeypatc values["/repos/owner/repo/pulls/900"]["head"]["sha"] = "d" * 40 if case == "malformed": values["/repos/owner/repo/pulls/101"] = [] - (event_path := tmp_path / "event.json").write_text(json.dumps(event)) + (tmp_path / "event.json").write_text(json.dumps(event)) (tmp_path / "workflow.toml").write_text('[repo]\nname="owner/repo"\nbase="main"\n[delivery]\nreview_publishers=["trusted-publisher"]\n') monkeypatch.chdir(tmp_path) monkeypatch.setenv("GITHUB_REPOSITORY", "owner/repo") - monkeypatch.setenv("GITHUB_EVENT_PATH", str(event_path)) + monkeypatch.setenv("GITHUB_EVENT_PATH", str(tmp_path / "event.json")) attempts, sleeps = [], [] def api_get(path): @@ -227,15 +228,14 @@ def publish(*args): if args[3] == "failure" and case == "publisher": raise RuntimeError("publication details must not replace attestation error") monkeypatch.setattr(github, "commit_status", publish) - evaluated = [] - real_evaluate = hosted.eligibility.evaluate + evaluated, real_evaluate = [], hosted.eligibility.evaluate def evaluate(repo, number, head, base, publishers): evaluated.append((repo, number, head, base, publishers)) if case in {"valid", "hold"}: return real_evaluate(repo, number, head, base, publishers) - if case == "interrupt": - raise KeyboardInterrupt() + if fault := {"interrupt": KeyboardInterrupt(), "api": github.GhUnavailable(("gh",), "HTTP 503")}.get(case): + raise fault reasons = (github.MISSING_REVIEW_REASON,) if case == "policy" else () return github.Readiness(not reasons, reasons) if case not in {"valid", "hold"}: @@ -248,7 +248,7 @@ def evaluate(repo, number, head, base, publishers): hosted.main() else: assert hosted.main() == 0 - terminal = [] if case in {"manual", "metadata", "stale", "interrupt"} else ["failure"] + 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) if case == "valid": From 0c68daf89197460d9cc4a772712714ca7a716bc5 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:41:38 +0100 Subject: [PATCH 11/17] Keep hosted refresh failures observable before pending publication Architecture-Review: unchanged; evidence and publication failures remain distinguishable within the existing hosted trust boundary. Co-Authored-By: Codex --- src/loopzero/candidate.py | 15 ++++++++++++--- src/loopzero/github.py | 6 +----- src/loopzero/hosted.py | 38 +++++++++++++++++++++++--------------- tests/test_hosted.py | 16 ++++++++-------- 4 files changed, 44 insertions(+), 31 deletions(-) diff --git a/src/loopzero/candidate.py b/src/loopzero/candidate.py index 8edf4afc..673842e0 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -289,6 +289,15 @@ def _attest_source( return source_sha +def _require_git_exit(operation: str, returncode: int) -> None: + if operation == "fetch" and returncode: + from loopzero import github + + raise github.GhUnavailable(("git", "fetch"), "GitHub objects unavailable") + _require(returncode == 0, f"git {operation} exited {returncode}: objects unavailable, " + "resource bound hit, or integration conflict") + + @contextlib.contextmanager def fetched_git(repo: str, heads: list[str]) -> Iterator[Callable[..., str]]: """Run bounded Git commands on fetched objects in an isolated bare repository.""" @@ -298,6 +307,8 @@ def fetched_git(repo: str, heads: list[str]) -> Iterator[Callable[..., str]]: if not token: try: token = github.auth_token() + except github.GhUnavailable: + raise except github.GhError: raise CandidateError("GitHub fetch authentication unavailable") from None _require(bool(token), "GitHub fetch authentication unavailable") @@ -341,9 +352,7 @@ def store_size() -> int: # Git renames temporaries: skip files that vanish _require(time.monotonic() < deadline, "Git time bound exceeded") with contextlib.suppress(subprocess.TimeoutExpired): process.wait(timeout=0.02) - _require(process.returncode == 0, - f"git {args[0]} exited {process.returncode}: objects unavailable, " - "resource bound hit, or integration conflict") + _require_git_exit(args[0], process.returncode) _require(store_size() <= _TREE_BYTES, "Git object/size bound exceeded") output.seek(0) result = output.read(_TREE_OUTPUT + 1) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 458bcf57..70b7f128 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -325,10 +325,6 @@ def _rate_limited(status: str | None, headers: dict[str, str], tail: str) -> boo or bool(re.search(r"rate limit|HTTP 429", tail, re.IGNORECASE))) -def _retry_delays(scope: tuple[float, str | None, bool] | None, diagnostic: bool) -> tuple: - return (None,) if scope and not scope[2] else (*(RETRY_DELAYS[:1] if diagnostic else RETRY_DELAYS), None) - - def _pr_list_error_guidance(args: tuple[str, ...], stderr: str, using_app: bool) -> str: if (using_app and len(args) > 1 and args[0] == "api" and re.fullmatch(r"repos/[^/]+/[^/]+/pulls\?.+", args[1]) @@ -350,7 +346,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, read_only = _read_only(args) retryable = read_only or retry_idempotent scope = _read_scope.get() if read_only else None - delays = _retry_delays(scope, diagnostic_api) + delays = ((RETRY_DELAYS[0], None) if scope[2] else (None,)) if scope else (*RETRY_DELAYS, None) for delay in delays: selected = _select_token(token, scope, read_only) # a retry backoff can outlive the app token try: diff --git a/src/loopzero/hosted.py b/src/loopzero/hosted.py index e257ae5b..0f39becf 100644 --- a/src/loopzero/hosted.py +++ b/src/loopzero/hosted.py @@ -37,11 +37,25 @@ def main() -> int: print(exc, file=sys.stderr) return 1 try: - with github.api_error_diagnostics(): + with github.api_error_diagnostics(), github.bounded_reads(float("inf"), token=None, retry=True): return _run(cfg) except (github.GhUnavailable, github.ProcTimeout) as exc: - print(f"Eligibility unconfirmed: GitHub evidence unavailable ({exc})", file=sys.stderr) - return 0 + print(f"Eligibility unconfirmed before pending status publication: {exc}", file=sys.stderr) + return 1 + + +def _candidate_event(event: dict, head: str) -> bool: + event_pr = event.get("pull_request") + if not isinstance(event_pr, dict): + raise LoopZeroError("candidate eligibility requires a pull_request_target " + "creation or head-update event") + if event.get("action") not in {"opened", "synchronize"}: + print("ignored candidate metadata event") + return False + event_head = event_pr.get("head") + if not isinstance(event_head, dict) or event_head.get("sha") != head: + raise LoopZeroError("candidate event head is no longer current") + return True def _run(cfg: Config) -> int: @@ -55,17 +69,8 @@ def _run(cfg: Config) -> int: or pr["user"]["login"] == "mergify[bot]") if not candidate and pr.get("merged") is True: return 0 # A landed source needs no new verdict; a late refresh must not turn it red. - if candidate: - event_pr = event.get("pull_request") - if not isinstance(event_pr, dict): - raise LoopZeroError("candidate eligibility requires a pull_request_target " - "creation or head-update event") - if event.get("action") not in {"opened", "synchronize"}: - print("ignored candidate metadata event") - return 0 - event_head = event_pr.get("head") - if not isinstance(event_head, dict) or event_head.get("sha") != head: - raise LoopZeroError("candidate event head is no longer current") + if candidate and not _candidate_event(event, head): + return 0 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") @@ -93,6 +98,9 @@ def policy(source_number: int, source: dict) -> None: if not candidate and not ready and result.reasons == (github.MISSING_REVIEW_REASON,): message = "Awaiting trusted review of current source head" state = "pending" + except (github.GhUnavailable, github.ProcTimeout) as exc: + print(f"Eligibility pending: evidence unavailable ({exc})", file=sys.stderr) + return 0 except Exception as exc: _mark_refresh_failed(publish, exc) raise @@ -115,7 +123,7 @@ def _publish_verdict(repo: str, head: str, state: str, description: str) -> None def _mark_refresh_failed(publish: Callable[[str, str], None], exc: Exception) -> None: - if not isinstance(exc, (github.GhUnavailable, github.ProcTimeout, github.StatusLimitReached)): + if not isinstance(exc, github.StatusLimitReached): with suppress(Exception): publish("failure", "Eligibility refresh failed; inspect workflow logs") diff --git a/tests/test_hosted.py b/tests/test_hosted.py index 1b0d5306..e781cfdc 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -143,14 +143,14 @@ def lose_reply(repo, head, context, value, description): assert [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] == ["pending", state] -@pytest.mark.parametrize("error", ["api", "recover", "head", "publication", "config"]) +@pytest.mark.parametrize("error", ["api", "recover", "head", "publication", "config", "before"]) def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, capsys, error): sleeps = [] monkeypatch.setattr(github, "_retry_sleep", sleeps.append) - reviews = f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1" - if error in {"api", "recover"}: + endpoint = f"api repos/{REPO}/pulls/7" + ("" if error == "before" else "/reviews?per_page=100&page=1") + 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(reviews, fault, [{"state": "APPROVED", "commit_id": HEAD, "user": {"login": "trusted-publisher"}, "body": f"\nreview: **approve**"}] if error == "recover" else fault) + 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)) elif error == "publication": @@ -158,13 +158,13 @@ def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, ca publisher.respond(f"api repos/{REPO}/commits/{HEAD}/statuses", [{"context": "other"}]) else: monkeypatch.setenv("GITHUB_REPOSITORY", "other/repo") - if error in {"api", "recover"}: - assert hosted.main() == 0 and sleeps == [5] - assert ("method=GET endpoint=/repos/acme/widgets/pulls/7/reviews status=503 request_id=GHREQ-8774 message=Service unavailable [REDACTED]" in capsys.readouterr().err) == (error == "api") + 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") else: with pytest.raises(hosted.LoopZeroError, match="invalid description" if error == "publication" else None): hosted.main() - states = {"config": [], "head": ["pending", "failure"], "api": ["pending"], "recover": ["pending", "success"]} + states = {"before": [], "config": [], "head": ["pending", "failure"], "api": ["pending"], "recover": ["pending", "success"]} assert [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] == states.get(error, ["pending", "pending"]) From b945542e6081be09088d2a35f8df6a7031cc840d Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:43:54 +0100 Subject: [PATCH 12/17] Preserve genuine missing-object failures during candidate fetch Architecture-Review: unchanged; transient fetch diagnostics remain inside the existing isolated checkout. Co-Authored-By: Codex --- src/loopzero/candidate.py | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/src/loopzero/candidate.py b/src/loopzero/candidate.py index 673842e0..ed75999b 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -18,7 +18,7 @@ import time from collections.abc import Callable, Iterator from pathlib import Path -from typing import Any +from typing import Any, BinaryIO MERGIFY_APP_ID = 10562 MERGIFY_APP_OWNER = "Mergifyio" @@ -289,18 +289,18 @@ def _attest_source( return source_sha -def _require_git_exit(operation: str, returncode: int) -> None: +def _require_git_exit(operation: str, returncode: int, output: BinaryIO) -> None: if operation == "fetch" and returncode: from loopzero import github - raise github.GhUnavailable(("git", "fetch"), "GitHub objects unavailable") + output.seek(0) + if github._transient_error(output.read(_TREE_OUTPUT).decode(errors="replace"), False): + raise github.GhUnavailable(("git", "fetch"), "GitHub objects temporarily unavailable") _require(returncode == 0, f"git {operation} exited {returncode}: objects unavailable, " "resource bound hit, or integration conflict") -@contextlib.contextmanager -def fetched_git(repo: str, heads: list[str]) -> Iterator[Callable[..., str]]: - """Run bounded Git commands on fetched objects in an isolated bare repository.""" +def _fetch_token() -> str: from loopzero import github token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") @@ -312,6 +312,13 @@ def fetched_git(repo: str, heads: list[str]) -> Iterator[Callable[..., str]]: except github.GhError: raise CandidateError("GitHub fetch authentication unavailable") from None _require(bool(token), "GitHub fetch authentication unavailable") + return token + + +@contextlib.contextmanager +def fetched_git(repo: str, heads: list[str]) -> Iterator[Callable[..., str]]: + """Run bounded Git commands on fetched objects in an isolated bare repository.""" + token = _fetch_token() with tempfile.TemporaryDirectory(prefix="loopzero-candidate-") as directory: root = Path(directory) env = { @@ -335,7 +342,8 @@ def git(*args: str, command_env: dict[str, str] = env) -> str: [sys.executable, "-I", "-S", "-c", _LIMITED_GIT, str(_TREE_BYTES), "git", "-c", "core.hooksPath=/dev/null", "-c", "gc.auto=0", "-c", "maintenance.auto=false", *args], cwd=root, env=command_env, - stdin=subprocess.DEVNULL, stdout=output, stderr=subprocess.DEVNULL, + stdin=subprocess.DEVNULL, stdout=output, + stderr=output if args[0] == "fetch" else subprocess.DEVNULL, start_new_session=True, ) def store_size() -> int: # Git renames temporaries: skip files that vanish @@ -352,7 +360,7 @@ def store_size() -> int: # Git renames temporaries: skip files that vanish _require(time.monotonic() < deadline, "Git time bound exceeded") with contextlib.suppress(subprocess.TimeoutExpired): process.wait(timeout=0.02) - _require_git_exit(args[0], process.returncode) + _require_git_exit(args[0], process.returncode, output) _require(store_size() <= _TREE_BYTES, "Git object/size bound exceeded") output.seek(0) result = output.read(_TREE_OUTPUT + 1) From db8a6950b5cdb7ffa9e3c77aae44198d3d1e0280 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:50:05 +0100 Subject: [PATCH 13/17] Recognize HTTP outages in Git fetch diagnostics Architecture-Review: unchanged; hosted eligibility still requires verified Git objects before accepting inherited evidence. Co-Authored-By: Codex --- src/loopzero/candidate.py | 3 ++- tests/test_candidate.py | 30 +++++++++++++++--------------- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/src/loopzero/candidate.py b/src/loopzero/candidate.py index ed75999b..e202c0fc 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -294,7 +294,8 @@ def _require_git_exit(operation: str, returncode: int, output: BinaryIO) -> None from loopzero import github output.seek(0) - if github._transient_error(output.read(_TREE_OUTPUT).decode(errors="replace"), False): + diagnostic = output.read(_TREE_OUTPUT).decode(errors="replace") + if github._transient_error(diagnostic, False) or re.search(r"returned error: (?:429|5\d\d)", diagnostic): raise github.GhUnavailable(("git", "fetch"), "GitHub objects temporarily unavailable") _require(returncode == 0, f"git {operation} exited {returncode}: objects unavailable, " "resource bound hit, or integration conflict") diff --git a/tests/test_candidate.py b/tests/test_candidate.py index 28dfdc6e..b630962b 100644 --- a/tests/test_candidate.py +++ b/tests/test_candidate.py @@ -9,6 +9,7 @@ from __future__ import annotations import base64 +from contextlib import nullcontext import subprocess from copy import deepcopy from importlib import import_module @@ -17,7 +18,7 @@ import pytest -from loopzero import candidate +from loopzero import candidate, github from loopzero.candidate import CandidateError, CandidateRaceError, attest_candidate from loopzero.types import LoopZeroError @@ -684,18 +685,16 @@ def run(): assert clock[0] == {"closed": 2, "ambiguous": 90, "slow": 100 * (1 + second), "oversleep": 100}[stop] -@pytest.mark.parametrize("exceeds_bound", [False, True]) -def test_fetched_git_waits_for_exit_or_resumes_size_checks(monkeypatch, exceeds_bound): - waits = [] - killed = [] - +@pytest.mark.parametrize("outcome", ["normal", "bound", "fetch"]) +def test_fetched_git_waits_for_exit_or_resumes_size_checks(monkeypatch, outcome): + waits, killed = [], [] class Child: pid = 123 - returncode = 0 - def __init__(self, argv, cwd, **kwargs): - self.root = cwd - self.running = "test-command" in argv + self.root, self.running = cwd, "test-command" in argv + self.returncode = 128 if outcome == "fetch" and "fetch" in argv else 0 + if self.returncode: + kwargs["stderr"].write(b"fatal: The requested URL returned error: 503") def poll(self): return None if self.running else self.returncode @@ -703,7 +702,7 @@ def poll(self): def wait(self, timeout=None): if self.running: waits.append(timeout) - if timeout is not None and exceeds_bound: + if timeout is not None and outcome == "bound": (self.root / "oversized").write_bytes(b"x" * 65) raise subprocess.TimeoutExpired("test-command", timeout) self.running = False @@ -715,12 +714,13 @@ def wait(self, timeout=None): monkeypatch.setattr(candidate.os, "killpg", lambda pid, sig: killed.append((pid, sig))) monkeypatch.setattr(candidate.time, "sleep", lambda _: pytest.fail("used a fixed delay")) - with candidate.fetched_git("owner/repo", []) as git: - if exceeds_bound: + error = pytest.raises(github.GhUnavailable, match="temporarily unavailable") if outcome == "fetch" else nullcontext() + with error, candidate.fetched_git("owner/repo", []) as git: + if outcome == "bound": with pytest.raises(CandidateError, match="Git object/size bound exceeded"): git("test-command") else: assert git("test-command") == "" - assert waits == ([0.02, None] if exceeds_bound else [0.02]) - assert killed == ([(123, candidate.signal.SIGKILL)] if exceeds_bound else []) + assert waits == {"bound": [0.02, None], "normal": [0.02], "fetch": []}[outcome] + assert killed == ([(123, candidate.signal.SIGKILL)] if outcome == "bound" else []) From 6c65b6aac76e71321dda5f9286ee963b4c18d510 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:00:14 +0100 Subject: [PATCH 14/17] Keep retry timing scoped to its follow-up change Architecture-Review: unchanged; the evidence outcome changes while the existing retry and wait behavior remains in force until #1502. Co-Authored-By: Codex --- src/loopzero/github.py | 2 +- src/loopzero/hosted.py | 2 +- tests/test_hosted.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 70b7f128..7d90c5a4 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -346,7 +346,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, read_only = _read_only(args) retryable = read_only or retry_idempotent scope = _read_scope.get() if read_only else None - delays = ((RETRY_DELAYS[0], None) if scope[2] else (None,)) if scope else (*RETRY_DELAYS, None) + delays = (None,) if scope and not scope[2] else (*RETRY_DELAYS, None) for delay in delays: selected = _select_token(token, scope, read_only) # a retry backoff can outlive the app token try: diff --git a/src/loopzero/hosted.py b/src/loopzero/hosted.py index 0f39becf..2f723a65 100644 --- a/src/loopzero/hosted.py +++ b/src/loopzero/hosted.py @@ -37,7 +37,7 @@ def main() -> int: print(exc, file=sys.stderr) return 1 try: - with github.api_error_diagnostics(), github.bounded_reads(float("inf"), token=None, retry=True): + with github.api_error_diagnostics(): return _run(cfg) except (github.GhUnavailable, github.ProcTimeout) as exc: print(f"Eligibility unconfirmed before pending status publication: {exc}", file=sys.stderr) diff --git a/tests/test_hosted.py b/tests/test_hosted.py index e781cfdc..ec23f866 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -159,7 +159,7 @@ def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, ca 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 hosted.main() == (1 if error == "before" else 0) and sleeps == ([5] if error == "recover" else list(github.RETRY_DELAYS)) assert ("status=503 request_id=GHREQ-8774 message=Service unavailable [REDACTED]" in capsys.readouterr().err) == (error != "recover") else: with pytest.raises(hosted.LoopZeroError, match="invalid description" if error == "publication" else None): From c1d8bb702d1a23abad48c2ac08a81b43faea5800 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:38:55 +0100 Subject: [PATCH 15/17] Preserve the trusted-publisher fixture on the retry branch Co-Authored-By: Codex --- tests/test_hosted.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_hosted.py b/tests/test_hosted.py index e781cfdc..1bd6cb3c 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -89,7 +89,8 @@ def test_source_publication_is_bound_to_live_review(publisher, case, blocker, st if blocker == "conflict": publisher.respond(f"api repos/{REPO}/pulls/7", fixtures.rest_pr_json(pr_json(mergeable="CONFLICTING"))) if blocker == "important": - publisher.respond("api graphql", threads_json(fixtures.thread(fixtures.marker("important") + "\nFinding"))) + publisher.respond("api graphql", threads_json(fixtures.thread(fixtures.marker("important") + "\nFinding", + author="trusted-publisher"))) assert hosted.main() == (1 if status == "failure" else 0) statuses = [json.loads(c["--input"]) for c in publisher.calls if "--input" in c] assert ([s["state"] for s in statuses] == ["pending", status] From 6ac05fda4af5301a0f3a7ed62fa78f4705271d83 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:07:30 +0100 Subject: [PATCH 16/17] Keep GitHub write timeouts outside read deadlines Architecture-Review: unchanged; scoped deadlines are still applied only to reads, and non-idempotent writes keep their original outcomes. Co-Authored-By: Codex --- src/loopzero/github.py | 18 +++++++++--------- tests/test_review_recovery.py | 13 +++++++------ 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index a48ea1c2..e085b13d 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -144,8 +144,8 @@ def bounded_reads(deadline: float, token: str | None = "", *, retry: bool = Fals _read_scope.reset(scope) -def _read_timeout(limit: float) -> float: - scope = _read_scope.get() +def _read_timeout(limit: float, *, scoped: bool = True) -> float: + scope = _read_scope.get() if scoped else None if scope is None: return limit remaining = scope[0] - time.monotonic() @@ -327,8 +327,8 @@ def _rate_limited(status: str | None, headers: dict[str, str], tail: str) -> boo or bool(re.search(r"rate limit|HTTP 429", tail, re.IGNORECASE))) -def _retry_pause(delay: float | None, limit: float) -> bool: - if delay is None or delay >= _read_timeout(limit): +def _retry_pause(delay: float | None, limit: float, *, scoped: bool = True) -> bool: + if delay is None or delay >= _read_timeout(limit, scoped=scoped): return False _retry_sleep(delay) return True @@ -373,13 +373,13 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, try: done = run(list(argv), cwd=cwd, env_allowlist=GH_ENV, extra_env={"GH_TOKEN": selected} if selected else None, - timeout=_read_timeout(timeout) if scope else timeout) + timeout=_read_timeout(timeout, scoped=read_only)) except ToolMissing as exc: raise GhMissing(argv, str(exc), token=selected, guidance=f"\nInstall GitHub CLI, then {GH_AUTH_REMEDY}") from exc except ProcTimeout as exc: - _read_timeout(timeout) - if not _retry_pause(delay, timeout): + _read_timeout(timeout, scoped=bool(scope and scope[2])) + if not _retry_pause(delay, timeout, scoped=read_only): raise ProcTimeout( _redact_tokens(str(exc), selected), _redact_tokens(exc.stdout, selected), stderr=_redact_tokens(exc.stderr, selected), duration_s=exc.duration_s, @@ -389,7 +389,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, else (None, {}, done.stdout)) tail = "\n".join(part for part in (done.stderr, body) if part) if done.exit_code and _rate_limited(status, headers, tail): - if _retry_pause(_rate_limit_delay(headers, delay), timeout): + if _retry_pause(_rate_limit_delay(headers, delay), timeout, scoped=read_only): continue guidance = (_redact_tokens(_rest_rate_limit(headers), selected) if rest_api or headers else _graphql_reset(args, tail, cwd, selected) + RATE_LIMIT_GUIDANCE) @@ -399,7 +399,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, raise GhUnavailable(("GitHub API request",), detail, token=selected, guidance=guidance) raise GhUnavailable(("gh", *args), tail, token=selected, guidance=guidance) transient = _transient_error(tail, retry_idempotent, status) - if done.exit_code == 0 or not transient or not _retry_pause(delay, timeout): + if done.exit_code == 0 or not transient or not _retry_pause(delay, timeout, scoped=read_only): break if done.exit_code != 0: error_command = ("GitHub API request",) if diagnostic_api or patch_error else argv diff --git a/tests/test_review_recovery.py b/tests/test_review_recovery.py index be796c3c..0ec3586e 100644 --- a/tests/test_review_recovery.py +++ b/tests/test_review_recovery.py @@ -226,20 +226,21 @@ def rejected(endpoint, payload, **kwargs): assert support.marker(head, "primary", "repost") in support.posted_review(gh)["body"] -@pytest.mark.parametrize("failure,budget", [("timeout", 0.5), ("transient", 0.5), ("transient", 10)]) +@pytest.mark.parametrize("failure,budget", [("timeout", 0.5), ("transient", 0.5), ("transient", 10), ("write", 0.5)]) def test_recovery_transport_retries_only_within_deadline(monkeypatch, failure, budget): timeouts, sleeps = [], [] def request(argv, **kwargs): timeouts.append(kwargs["timeout"]) - if failure == "timeout": + if failure in {"timeout", "write"}: raise _proc.ProcTimeout("timeout") return _proc.Completed(1, "", "HTTP 503", 0) monkeypatch.setattr(github, "run", request) monkeypatch.setattr(github, "_retry_sleep", sleeps.append) - monkeypatch.setattr(github.time, "monotonic", lambda: 10.0 + sum(sleeps)) - with github.bounded_reads(10 + budget, retry=True), pytest.raises((github.GhError, _proc.ProcTimeout)): - github.api_get("repos/acme/widgets/pulls/7/reviews") - assert (timeouts, sleeps) == (([10, 5], [5]) if budget == 10 else ([0.5], [])) + monkeypatch.setattr(github.time, "monotonic", lambda: 10.0 + sum(sleeps) + int(failure == "write" and bool(timeouts))) + error = github.GhError if failure == "transient" else _proc.ProcTimeout + with pytest.raises(error), github.bounded_reads(10 + budget, retry=True): + github.mark_ready("acme/widgets", 7) if failure == "write" else github.api_get("repos/acme/widgets/pulls/7/reviews") + assert (timeouts, sleeps) == (([10, 5], [5]) if budget == 10 else ([120 if failure == "write" else 0.5], [])) @pytest.mark.parametrize("source", ["model", "repost"]) From f52c6f7fd9e69e5a8f26fa7d8c5501faea38eae2 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:15:31 +0100 Subject: [PATCH 17/17] Keep Mergify backoff within readiness and default budgets Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 3 ++- src/loopzero/cli.py | 18 ++++++++++-------- src/loopzero/mergify.py | 3 ++- tests/test_cli.py | 6 +++--- tests/test_mergify.py | 4 ++-- 5 files changed, 19 insertions(+), 15 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 981d5eaa..75cba6e6 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -353,7 +353,8 @@ GitHub reads and the idempotent thread resolution mutation retry transient failures once after five seconds. They stop on exhausted quota and honor a secondary limit’s Retry-After when the delay fits the read budget. Mergify queue reads retry once after two seconds, subject to Retry-After and the -remaining queue wait budget. See the +remaining queue wait budget. Calls without a deadline allow less than five +seconds of backoff. See the [contract's waiter and polling rules](../core/CONTRACT.md#failure). The optional host ai-accounts helper owns managed credential selection and exact-model eligibility under its existing lock. Its Claude exec reserve guard (including pinned diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index cd98bb5f..2069a1d3 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -277,7 +277,7 @@ def _decide_kind(markers: list[Marker], head: str) -> tuple[str, str | None]: def _readiness( wt: Path, config: Config, pr: github.PR, head: str, reviews: list[dict] | None = None, - *, workflow_wait: bool = False, announce_receipt: bool = False, + *, workflow_wait: bool = False, announce_receipt: bool = False, mergify_deadline: float | None = None, ) -> github.Readiness: if hold := github.merge_hold(pr.number, pr.labels): return github.Readiness(False, (hold,)) @@ -316,7 +316,7 @@ def _readiness( if config.merge_strategy == "mergify" and pr.state == "OPEN": behind = github.behind_reason(pr, head if review else None) reasons = result.reasons - if mergify.configured(config.repo, config.base_branch, config.mergify_queue or ""): + if mergify.configured(config.repo, config.base_branch, config.mergify_queue or "", mergify_deadline): reasons = tuple(reason for reason in reasons if reason != behind) else: reasons = (*reasons, "Mergify queue configuration is unverified or permits in-place head updates") @@ -1184,7 +1184,8 @@ def _load_review(wt: Path, head: str, kind: str) -> ReviewResult: def _pr_readiness( - wt: Path, config: Config, *, allow_merged: bool = False, workflow_wait: bool = False + wt: Path, config: Config, *, allow_merged: bool = False, workflow_wait: bool = False, + mergify_deadline: float | None = None, ) -> tuple[github.PR, github.Readiness | None]: """PR plus readiness; readiness is None only for an already merged PR (allow_merged).""" branch, head = worktree.branch(wt), worktree.head(wt) @@ -1194,7 +1195,7 @@ def _pr_readiness( if pr.state == "MERGED": return pr, None return pr, _readiness(wt, config, pr, head, workflow_wait=workflow_wait, - announce_receipt=True) + announce_receipt=True, mergify_deadline=mergify_deadline) CLEANUP_RETRY = "; fix the cause, then rerun `loopzero merge` in this worktree to finish cleanup" @@ -1405,7 +1406,8 @@ def _wait_for_checks( previous = _verify_wait_snapshot(args, wt, config, pr.head_sha, current.head_sha, previous) if allow_merged and current.state == "MERGED": return current, None, kicked - readiness = _readiness(wt, config, current, pr.head_sha, workflow_wait=True) + readiness = _readiness(wt, config, current, pr.head_sha, workflow_wait=True, + mergify_deadline=started + timeout) if not kicked and _draft_checks_waiting(config, current, readiness): github.mark_ready(config.repo, pr.number) print("marked ready; " + "; ".join(readiness.reasons)) @@ -1642,11 +1644,11 @@ def cmd_merge(args: argparse.Namespace) -> int: mergify.dequeue(config.repo, pr.number) print(f"requested removal of PR #{pr.number} from Mergify") return 0 - pr, readiness = _pr_readiness( - wt, config, allow_merged=True, workflow_wait=args.wait is not None - ) started = time.monotonic() deadline = None if args.wait is None else started + args.wait + pr, readiness = _pr_readiness( + wt, config, allow_merged=True, workflow_wait=args.wait is not None, mergify_deadline=deadline, + ) # --wait=0 observes once; a positive budget also bounds merge or queue admission. admit_by = deadline if args.wait else None if readiness is not None and args.wait is not None and _pending_checks(config, pr, readiness): diff --git a/src/loopzero/mergify.py b/src/loopzero/mergify.py index 09980bb7..8994d3af 100644 --- a/src/loopzero/mergify.py +++ b/src/loopzero/mergify.py @@ -81,7 +81,8 @@ def _open(request: urllib.request.Request): def _wait_to_retry(delay: float, deadline: float | None) -> bool: - if deadline is not None and time.monotonic() + delay >= deadline: + remaining = 5.0 if deadline is None else deadline - time.monotonic() + if delay >= remaining: return False _retry_sleep(delay) return deadline is None or time.monotonic() < deadline diff --git a/tests/test_cli.py b/tests/test_cli.py index 6587f797..adb55d89 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4382,8 +4382,8 @@ def test_mergify_wait_outcomes_preserve_unmerged_work(wt, repo, gh, capsys, monk gh.append(f"api repos/{REPO}/pulls/7", merge_json(state='OPEN', head=head), merge_json(state='MERGED', head='f' * 40, sha='e' * 40)) configurations = [] - def configured(*_): - configurations.append(True) + def configured(*args): + configurations.append(args[-1]) if len(configurations) > 1: if outcome == "config_error": raise mergify.MergifyError("configuration HTTP 503") @@ -4430,7 +4430,7 @@ def remove_worktree_then_poll(*args): assert sleeps == ([30, 60, 120, 40] if jitter == 1 else [27, 54, 108, 61]) assert sum(c["argv"][:2] == PR_LIST_READ for c in gh.calls) == 1 assert sum(c["argv"][:2] == ["api", "graphql"] for c in gh.calls) == 2 - assert requests == ([(REPO, 7, head, "main")] if outcome == "requested_head_changed" else []) + assert requests == ([(REPO, 7, head, "main")] if outcome == "requested_head_changed" else []) and all(deadline == (250 if outcome == "timeout" else 0) for deadline in configurations) if outcome in {"merged", "already_merged", "worktree_removed"}: assert code == 0 and "e" * 40 in out and not wt.exists(), err if outcome == "worktree_removed": diff --git a/tests/test_mergify.py b/tests/test_mergify.py index 754ff3f5..d09a633a 100644 --- a/tests/test_mergify.py +++ b/tests/test_mergify.py @@ -231,7 +231,7 @@ def test_hosted_import_does_not_load_yaml(): @pytest.mark.parametrize("failure,status,budget,wait", [ ("http", 503, None, 2), ("reset", None, None, 2), ("truncated", None, None, 2), - ("http", 429, None, 40), ("http", 403, 20, None), ("http", 429, 20, None)]) + ("http", 429, 100, 40), ("http", 429, None, None), ("http", 403, 20, None), ("http", 429, 20, None)]) def test_api_get_retries_transient_reads(monkeypatch, failure, status, budget, wait): calls, sleeps = [], [] def fake_open(request): @@ -245,7 +245,7 @@ def fake_open(request): monkeypatch.setattr(mergify, "_retry_sleep", sleeps.append) monkeypatch.setattr(mergify, "_credential", lambda: "k") if status in {403, 429}: - with pytest.raises(mergify.MergifyError, match="Retry-After: 40s" + ("; retry delay exceeds" if budget else "")): + with pytest.raises(mergify.MergifyError, match="Retry-After: 40s" + ("; retry delay exceeds" if wait is None else "")): mergify.api_get("acme/widgets", "/merge-queue/status", None if budget is None else mergify.time.monotonic() + budget) else: assert mergify.api_get("acme/widgets", "/merge-queue/status") == {}