Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 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
d91efd7
Append task excludes without overwriting concurrent edits
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
c215c73
Merge the safe exclude path with concurrent edit preservation
eowca Nov 26, 2026
ed981cc
Keep known model availability in partial Codex usage responses
eowca Nov 26, 2026
a457396
Keep all-unknown Codex usage in the unknown tier
eowca Nov 26, 2026
ced390b
Merge the cleanup ref lock and preserve concurrent exclude edits
eowca Nov 26, 2026
78b41a6
Merge remote-tracking branch 'origin/main' into lean178/r48-usage-parser
eowca Nov 26, 2026
6ac05fd
Keep GitHub write timeouts outside read deadlines
eowca Nov 26, 2026
b960923
Merge of PR 1685
mergify[bot] Nov 26, 2026
687dcd3
Merge of PR 1678
mergify[bot] Nov 26, 2026
dc6e685
Merge of PR 1560
mergify[bot] 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 @@ -350,7 +350,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
16 changes: 10 additions & 6 deletions scripts/ai-accounts/ai-accounts
Original file line number Diff line number Diff line change
Expand Up @@ -629,13 +629,17 @@ def check_codex(name: str) -> dict:
model_usage = data.get("model_usage")
if not isinstance(model_usage, dict) or not model_usage:
return {**result, "error": "usage response has no model usage"}
if any(not isinstance(v, dict) or not isinstance(v.get("available"), bool)
for v in model_usage.values()):
return {**result, "error": "usage response has incomplete model usage"}
models = {m: v["available"] for m, v in model_usage.items()}
# Entries without a bool `available` are unknown, not a logged-out account: skip them and
# take the tier from the entries that do report availability (response shape drifts).
models = {m: v["available"] for m, v in model_usage.items()
if isinstance(v, dict) and isinstance(v.get("available"), bool)}
unknown = sorted(m for m in model_usage if m not in models)
if not models:
return {**result, "error": "usage response has no known model availability", "models_unknown": unknown}
usable = [available for available in models.values() if available]
tier = 0 if not ok or (models and not usable) else (2 if all(models.values()) else 1)
return {**result, "tier": tier, "models": models}
tier = 0 if not ok or not usable else (2 if all(models.values()) else 1)
extra = {"models_unknown": unknown} if unknown else {}
return {**result, "tier": tier, "models": models, **extra}


def select(provider: str, results: dict[str, dict], current: str | None) -> str | None:
Expand Down
2 changes: 1 addition & 1 deletion src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -932,7 +932,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]))
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)
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
37 changes: 18 additions & 19 deletions src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,22 @@
from __future__ import annotations

import errno
import fcntl
import os
import re
import stat
import subprocess
import sys
import tempfile
from collections.abc import Iterator
from contextlib import contextmanager
from contextlib import contextmanager, suppress
from pathlib import Path
from select import select
from uuid import uuid4

from loopzero._proc import build_env, run

GIT_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "TERM", "GIT_SSH_COMMAND", "SSH_AUTH_SOCK")
_ABSOLUTE_COMMON_DIR = ("rev-parse", "--path-format=absolute", "--git-common-dir")
EXCLUDES = (".worktrees/", ".loopzero/")
EXCLUDES = (b".worktrees/", b".loopzero/")
_BASE_LINE = re.compile(r"^Base:\s*([0-9a-fA-F]{7,40})\s*$", re.MULTILINE)
_TASK_TEMPLATE = """# {title}

Expand Down Expand Up @@ -113,21 +113,20 @@ def _ensure_excludes(repo_root: Path) -> None:
if not info.is_relative_to(common) or not exclude.is_relative_to(common):
raise WorktreeError(f"Git exclude is outside its Git directory: {exclude}")
exclude.parent.mkdir(parents=True, exist_ok=True)
existing = exclude.read_text() if exclude.exists() else ""
missing = [entry for entry in EXCLUDES if entry not in existing.splitlines()]
if missing:
sep = "" if not existing or existing.endswith("\n") else "\n"
mode = stat.S_IMODE(exclude.stat().st_mode) if exclude.exists() else None
temp = exclude.with_name(f".exclude-{uuid4().hex}")
stream = temp.open("x")
try:
with stream:
stream.write(existing + sep + "\n".join(missing) + "\n")
if mode is not None:
temp.chmod(mode)
temp.replace(exclude)
finally:
temp.unlink(missing_ok=True)
while True:
fd = os.open(exclude, os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW, 0o666)
with os.fdopen(fd, "rb") as stream:
fcntl.flock(fd, fcntl.LOCK_EX)
lines = set(stream.read().splitlines())
missing = [entry for entry in EXCLUDES if entry not in lines]
if missing:
# An editor can append an unterminated line before this write.
rules = b"\n" + b"\n".join(missing) + b"\n"
if os.write(fd, rules) != len(rules):
raise WorktreeError(f"incomplete write to Git exclude: {exclude}")
with suppress(FileNotFoundError):
if os.path.samestat(os.fstat(fd), exclude.lstat()):
return


def start(repo_root: Path, slug: str, base_branch: str) -> Path:
Expand Down
13 changes: 10 additions & 3 deletions tests/test_ai_accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ def http(req):
assert ('fallback' in output and 'HTTP 403' in output) is (api == 403)


@pytest.mark.parametrize('short_reset', [None, 1793912400, 'offline'])
@pytest.mark.parametrize('short_reset', [None, 1793912400, 'offline', 'all-unknown'])
def test_codex_json_and_text_share_each_existing_window(helper, monkeypatch, capsys, short_reset):
helper.write_private(helper.codex_home('c2') / 'auth.json', '{"tokens":{"access_token":"fake"}}')
monkeypatch.setattr(helper, 'now', lambda: 10000)
Expand All @@ -396,10 +396,17 @@ def test_codex_json_and_text_share_each_existing_window(helper, monkeypatch, cap
assert 'unknown (network: offline)' in capsys.readouterr().out
return
week = {'used_percent': 96, 'limit_window_seconds': 604800, 'reset_at': 1794384770}
short = {'used_percent': 99, 'limit_window_seconds': 18000, 'reset_at': short_reset} if short_reset else None
data = {'rate_limit': {'primary_window': short or week, 'secondary_window': week if short else None}, 'model_usage': {'m': {'available': True}}}
short = {'used_percent': 99, 'limit_window_seconds': 18000, 'reset_at': short_reset} if isinstance(short_reset, int) else None
data = {'rate_limit': {'primary_window': short or week, 'secondary_window': week if short else None}, 'model_usage': {'m': {'available': True}, 'partial': {}}}
if short_reset == 'all-unknown':
del data['model_usage']['m']
monkeypatch.setattr(helper, '_http', lambda req: (200, {}, json.dumps(data).encode()))
result = helper.check_codex('c2')
assert result['models_unknown'] == ['partial']
if short_reset == 'all-unknown':
assert result['tier'] == -1 and result['error'] == 'usage response has no known model availability'
return
assert result['models'] == {'m': True}
assert result['next_reset'] == 1794384770
status = {'checked_at': 10000, 'providers': {'codex': {'active': 'c2', 'accounts': {'c2': result}}}}
helper.write_private(helper.STATE / 'status.json', json.dumps(status))
Expand Down
2 changes: 1 addition & 1 deletion tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4184,7 +4184,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 @@ -1297,28 +1297,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 @@ -1338,28 +1338,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 @@ -1369,10 +1369,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 @@ -168,7 +168,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
Loading
Loading