Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
3eca5fd
Keep hosted eligibility pending during GitHub outages
eowca Nov 26, 2026
d26ca8b
Keep hosted eligibility pending during GitHub outages
eowca Nov 26, 2026
9d9d15f
Retry safe GitHub observations once within their budget
eowca Nov 26, 2026
44e7683
Expect one retry for idempotent finding resolution
eowca Nov 26, 2026
9b2fdeb
Keep hosted refresh failures observable before pending publication
eowca Nov 26, 2026
71a4432
Merge remote-tracking branch 'origin/main' into lean178/1497-eligibil…
eowca Nov 26, 2026
71a8ff7
Preserve genuine missing-object failures during candidate fetch
eowca Nov 26, 2026
67df7d4
Merge branch 'lean178/1497-eligibility-outages' into lean178/1502-saf…
eowca Nov 26, 2026
da45c03
Merge remote-tracking branch 'origin/main' into lean178/1502-safe-obs…
eowca Nov 26, 2026
0234af9
Recognize HTTP outages in Git fetch diagnostics
eowca Nov 26, 2026
2cd175e
Merge branch 'lean178/1497-eligibility-outages' into lean178/1502-saf…
eowca Nov 26, 2026
1aae039
Keep hosted eligibility pending during GitHub outages
eowca Nov 26, 2026
0c68daf
Keep hosted refresh failures observable before pending publication
eowca Nov 26, 2026
b945542
Preserve genuine missing-object failures during candidate fetch
eowca Nov 26, 2026
db8a695
Recognize HTTP outages in Git fetch diagnostics
eowca Nov 26, 2026
6c65b6a
Keep retry timing scoped to its follow-up change
eowca Nov 26, 2026
251719a
Merge branch 'lean178/1497-eligibility-outages-v2' into lean178/1502-…
eowca Nov 26, 2026
e780406
Merge remote-tracking branch 'origin/main' into lean178/1502-safe-obs…
eowca Nov 26, 2026
1e7cd89
Merge remote-tracking branch 'origin/main' into lean178/1502-safe-obs…
eowca Nov 26, 2026
c1d8bb7
Preserve the trusted-publisher fixture on the retry branch
eowca Nov 26, 2026
6ac05fd
Keep GitHub write timeouts outside read deadlines
eowca Nov 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,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).
Expand Down
2 changes: 1 addition & 1 deletion src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -913,7 +913,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

Expand Down
51 changes: 35 additions & 16 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -120,7 +121,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)
Expand All @@ -143,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()
Expand Down Expand Up @@ -326,6 +327,24 @@ 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, *, scoped: bool = True) -> bool:
if delay is None or delay >= _read_timeout(limit, scoped=scoped):
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:
if (using_app and len(args) > 1 and args[0] == "api"
and re.fullmatch(r"repos/[^/]+/[^/]+/pulls\?.+", args[1])
Expand All @@ -340,48 +359,48 @@ 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 = (None,) if scope and not scope[2] else (*RETRY_DELAYS, None)
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:
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:
if scope and scope[2]:
_read_timeout(timeout)
if delay is None or not retryable:
_read_timeout(timeout, scoped=bool(scope and scope[2]))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: Post-timeout deadline check now differs from the run-timeout clamp in non-retry read scopes

The timeout passed to run is clamped with scoped=read_only (line 376), so the shared deadline still limits reads inside bounded_reads(..., retry=False). But after a ProcTimeout, the check uses scoped=bool(scope and scope[2]). When such a read times out past the deadline, it now raises a plain ProcTimeout. Before this change it raised ReadDeadline. No production code hits this today: both bounded_reads callers (cli.py:916 and cli.py:1328) pass retry=True. Still, the code now uses two different rules for 'does the deadline apply', and they could drift apart. The smallest fix is scoped=read_only on line 381, the same rule as lines 376, 382, 392 and 402. Writes would still skip the check, because scope is None for them. Alternatively, add a comment explaining why non-retry scopes should surface a raw ProcTimeout.

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,
) 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, 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)
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: Rate-limit guidance says "No automatic retry" even when a retry was attempted, and the error argv differs from the general error path

_rest_rate_limit still ends with "No automatic retry.". After this change a secondary limit may already have been retried once after Retry-After, so the message is misleading. Also, the rate-limit raise now uses ("gh", *args) without --include, but the general error path at line 405 still reports argv, which includes --include. The same request is therefore described differently depending on the failure type. Consider rewording the guidance (for example, "retry once honored" / "not retried: delay exceeds budget") and using one command representation in both raise sites.

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, scoped=read_only):
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,
Expand Down
2 changes: 1 addition & 1 deletion tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4183,7 +4183,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())
Expand Down
35 changes: 17 additions & 18 deletions tests/test_github.py
Original file line number Diff line number Diff line change
Expand Up @@ -1295,28 +1295,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",
Expand All @@ -1336,28 +1336,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:
Expand All @@ -1367,10 +1367,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"), [
Expand Down
2 changes: 1 addition & 1 deletion tests/test_hosted.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,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] if error == "recover" else list(github.RETRY_DELAYS))
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):
Expand Down
19 changes: 10 additions & 9 deletions tests/test_review_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -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", ["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), ("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, "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)):
github.api_get("repos/acme/widgets/pulls/7/reviews")
assert timeouts == [0.5]
monkeypatch.setattr(github, "_retry_sleep", sleeps.append)
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")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: The new 'write' case covers only the ProcTimeout path, not the scoped=read_only changes to _retry_pause

mark_ready is a non-idempotent write, so it gets delays=(None,) and _retry_pause returns before it reads the scope. The case does catch the line-381 regression: before the fix it would have raised ReadDeadline instead of ProcTimeout. But the scoped=read_only edits at lines 382, 392 and 402 only change behaviour for retry_idempotent writes (thread resolution) inside a bounded_reads scope, and nothing tests that. No caller combines the two today, so this isn't blocking. Also, the monotonic lambda that leans on bool(timeouts) is hard to read. A named clock stub would make it clearer without adding test lines.

assert (timeouts, sleeps) == (([10, 5], [5]) if budget == 10 else ([120 if failure == "write" else 0.5], []))


@pytest.mark.parametrize("source", ["model", "repost"])
Expand Down
Loading