diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 5140e395..49620cba 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -109,9 +109,11 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con target branch and required CI. The receipt must record a clean passing run at that head with the current commands and check settings digest. A settings change or an older receipt without the digest requires a fresh check. The - digest covers execution and stage reuse settings, including the effective - allowlisted environment, without recording raw environment values. Waiters - check for policy changes on every poll. + digest covers execution and stage reuse settings without recording raw + environment values. It excludes only inherited `HEAVY_SLOT_GRANTED_CORES` + for local sandbox receipts. Explicit settings, delegated runner environments + and stage reuse keys still bind the grant. Waiters check for policy changes + on every poll. Local readiness and hosted eligibility carry a review forward only across a first-parent chain of verified merges from the configured PR base. They reconstruct each merge in an isolated Git repository and compare its tree @@ -350,7 +352,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/scripts/ai-accounts/ai-accounts b/scripts/ai-accounts/ai-accounts index 75828558..c7aeaca2 100755 --- a/scripts/ai-accounts/ai-accounts +++ b/scripts/ai-accounts/ai-accounts @@ -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: diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index f3c59c09..f1645fb8 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -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 diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 537bfa60..26e0e00c 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 @@ -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) @@ -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() @@ -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]) @@ -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, diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index 5edb2449..6f725e28 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -253,6 +253,9 @@ def settings_fingerprint(config: Config, worktree: Path, *, base: str | None = N settings = _execution_settings(config, base) if config.check_runner and settings["runner_executable"] is None: return None + if not config.check_runner and "HEAVY_SLOT_GRANTED_CORES" not in config.env: + # The inherited local worker limit is transient. Stage reuse still binds it. + settings["environment"].pop("HEAVY_SLOT_GRANTED_CORES", None) payload = [settings, config.inputs] return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest() diff --git a/tests/test_ai_accounts.py b/tests/test_ai_accounts.py index 9db4ab49..2d3037a6 100644 --- a/tests/test_ai_accounts.py +++ b/tests/test_ai_accounts.py @@ -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) @@ -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)) diff --git a/tests/test_cli.py b/tests/test_cli.py index f679c279..fea79806 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -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()) diff --git a/tests/test_github.py b/tests/test_github.py index ae33c2ee..98e0e410 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -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", @@ -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: @@ -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"), [ diff --git a/tests/test_hosted.py b/tests/test_hosted.py index 481ae5ba..f0ac65c1 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -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): diff --git a/tests/test_review_recovery.py b/tests/test_review_recovery.py index 47202ff5..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", ["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") + assert (timeouts, sleeps) == (([10, 5], [5]) if budget == 10 else ([120 if failure == "write" else 0.5], [])) @pytest.mark.parametrize("source", ["model", "repost"]) diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index ecff7435..674e4d8a 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -749,10 +749,13 @@ def cache(config, *, clean=False, verify_reuse=False): @pytest.mark.parametrize('change', ['other', 'input', 'shared', 'command', 'network', 'environment', 'version', 'failed', 'boolean_exit_code', 'dirty_receipt', 'keyless', - 'dirty_tree', 'legacy']) + 'dirty_tree', 'legacy', 'grant']) def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, change): cfg = make_config(checks=('echo one', 'echo two'), inputs={'echo one': ('*.md',), 'echo two': ('*.md',), '*': ('shared',)}) + if change == 'grant': + cfg = replace(cfg, env_allowlist=(*cfg.env_allowlist, "HEAVY_SLOT_GRANTED_CORES")) + monkeypatch.setenv("HEAVY_SLOT_GRANTED_CORES", "2") for inputs in ({}, {'*': ()}, {'*': ('uv.lock',)}): assert sandbox._input_key(replace(cfg, inputs=inputs), git_repo, 'unlisted', fetched_base) is None whole = replace(cfg, inputs={'*': ('.',)}) @@ -776,6 +779,12 @@ def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, ch cfg = replace(cfg, network=True) elif change == 'environment': monkeypatch.setenv('LZ_KEEP', 'changed') + assert _current_check_report(git_repo, cfg, fetched_base) is None + elif change == 'grant': + monkeypatch.setenv("HEAVY_SLOT_GRANTED_CORES", "4") + assert _current_check_report(git_repo, cfg, fetched_base) is not None + monkeypatch.delenv("HEAVY_SLOT_GRANTED_CORES") + assert _current_check_report(git_repo, cfg, fetched_base) is not None elif change == 'version': monkeypatch.setattr(sandbox, '__version__', 'new') else: