Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(model-hub): honor Claude subscription cap resets (#2974)

Call White5513e296e674
diff --git a/core/handlers/model_hub/classification.py b/core/handlers/model_hub/classification.py
index 199311c37..f0e6c1a29 100644
--- a/core/handlers/model_hub/classification.py
+++ b/core/handlers/model_hub/classification.py
@@ -4,9 +4,11 @@ from __future__ import annotations
import re
from dataclasses import dataclass, replace
+from datetime import datetime
from typing import Final, Literal, Mapping, Optional
from .adapter import RawCallOutcome, RawOutcomeKind
+from .claude_rate_limits import claude_subscription_reset
ResolutionAction = Literal["return", "surface", "refresh", "fallback"]
MachineErrorFamily = Literal["auth", "request", "server", "transient", "terminal"]
@@ -186,6 +188,8 @@ class ResolutionDecision:
error_code: Optional[str] = None
cooldown_seconds: int = 0
downstream_status: int | None = None
+ # Derived upstream advice only; no header values cross classification.
+ retry_at: datetime | None = None
_TERMINAL_OUTCOME_CATEGORIES: Mapping[
@@ -359,6 +363,10 @@ def classify_outcome(
outcome,
refresh_attempted=refresh_attempted,
)
+ if decision.reason == "rate_limited":
+ retry_at = claude_subscription_reset(outcome)
+ if retry_at is not None:
+ decision = replace(decision, reason="quota_exhausted", cooldown_seconds=300, retry_at=retry_at)
if not outcome.stream_started:
return decision
# Output already reached the caller, so replay is terminal. Retain a
diff --git a/core/handlers/model_hub/claude_rate_limits.py b/core/handlers/model_hub/claude_rate_limits.py
new file mode 100644
index 000000000..126366c1b
--- /dev/null
+++ b/core/handlers/model_hub/claude_rate_limits.py
@@ -0,0 +1,85 @@
+"""Interpret the bounded Claude header projection, never raw response headers."""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta, timezone
+from decimal import Decimal, InvalidOperation
+from email.utils import parsedate_to_datetime
+
+from .adapter import RawCallOutcome, RawOutcomeKind
+
+
+_MAX_RESET_WINDOW = timedelta(days=7, hours=1)
+_PREFIX = "anthropic-ratelimit-unified-"
+_SHARED_WINDOWS = ("5h", "7d")
+_ALLOWED = {"allowed", "allowed_warning"}
+
+
+def _reset_deadline(raw: str | None, received: datetime) -> datetime | None:
+ """Accept future Unix/aware ISO/HTTP dates within the recoverable window."""
+
+ if not isinstance(raw, str) or not raw or len(raw) > 128 or not raw.isascii():
+ return None
+ try:
+ upper = received + _MAX_RESET_WINDOW
+ try:
+ numeric = Decimal(raw)
+ except InvalidOperation:
+ try:
+ deadline = datetime.fromisoformat(raw.replace("Z", "+00:00"))
+ except ValueError:
+ deadline = parsedate_to_datetime(raw)
+ else:
+ # Bound before float conversion: finite-looking exponents and epoch
+ # milliseconds must not overflow or turn into a far-future cooldown.
+ if not numeric.is_finite() or not Decimal(received.timestamp()) < numeric <= Decimal(upper.timestamp()):
+ return None
+ deadline = datetime.fromtimestamp(float(numeric), timezone.utc)
+ if deadline.tzinfo is not None and received < deadline <= upper:
+ return deadline.astimezone(timezone.utc)
+ except (ValueError, TypeError, OverflowError, OSError):
+ pass
+ return None
+
+
+def claude_subscription_reset(outcome: RawCallOutcome) -> datetime | None:
+ """Return the latest valid active shared-cap reset, or no refinement.
+
+ L1 already restricts these facts to Claude Sources and an exact header
+ allow-list. Shared-window rejection is stronger than an aggregate hint;
+ overage/7d_oi alone cannot establish a Source-wide subscription cooldown.
+ Missing/ambiguous evidence keeps ordinary 429 policy, including Retry-After.
+ """
+
+ received = outcome.response_received_at
+ if (
+ outcome.kind != RawOutcomeKind.HTTP_ERROR or outcome.http_status != 429
+ or received is None or received.tzinfo is None
+ ):
+ return None
+ headers = dict(outcome.claude_rate_limit_headers)
+ statuses = {window: headers.get(f"{_PREFIX}{window}-status") for window in _SHARED_WINDOWS}
+ active = {window for window, status in statuses.items() if status == "rejected"}
+ rejected = headers.get(f"{_PREFIX}status") == "rejected"
+ claim = headers.get(f"{_PREFIX}representative-claim", "").lower()
+ if rejected and claim in _SHARED_WINDOWS and statuses[claim] is None:
+ active.add(claim)
+
+ resets = [headers.get(f"{_PREFIX}{window}-reset") for window in active]
+ non_shared = (
+ claim not in ("", *_SHARED_WINDOWS)
+ or headers.get(f"{_PREFIX}7d_oi-status") == "rejected"
+ or headers.get(f"{_PREFIX}overage-status") == "rejected"
+ or bool(headers.get(f"{_PREFIX}overage-disabled-reason"))
+ )
+ # An aggregate reset can describe a billing period rather than the shared
+ # subscription. Use it only with shared evidence and no conflicting claim.
+ aggregate_shared = bool(active) or (
+ rejected and not all(status in _ALLOWED for status in statuses.values())
+ )
+ claim_allowed = claim in _SHARED_WINDOWS and statuses[claim] in _ALLOWED
+ if aggregate_shared and not non_shared and not claim_allowed:
+ resets.append(headers.get(f"{_PREFIX}reset"))
+
+ deadlines = [deadline for raw in resets if (deadline := _reset_deadline(raw, received)) is not None]
+ return max(deadlines) if deadlines else None
diff --git a/core/handlers/model_hub/retry.py b/core/handlers/model_hub/retry.py
index d56b5c6cf..391581464 100644
--- a/core/handlers/model_hub/retry.py
+++ b/core/handlers/model_hub/retry.py
@@ -262,6 +262,7 @@ class RecoveryPolicy:
retry_after: str | None = None,
retry_after_ms: int | None = None,
response_received_at: datetime | None = None,
+ upstream_retry_at: datetime | None = None,
) -> tuple[datetime, bool]:
state = self._state(source)
if state is not None and state.failed_generation is not None and generation <= state.failed_generation:
@@ -279,7 +280,7 @@ class RecoveryPolicy:
received,
milliseconds=retry_after_ms,
)
- deadline = max(now + timedelta(seconds=local), upstream or now)
+ deadline = max(now + timedelta(seconds=local), upstream or now, upstream_retry_at or now)
eligible_at = mono + (deadline - now).total_seconds()
if state is not None:
eligible_at = max(eligible_at, state.eligible_at)
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index dbfafe9c8..dbe99ea0a 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -10350,6 +10350,7 @@ class ModelHubService:
retry_after=outcome.retry_after if outcome is not None else None,
retry_after_ms=getattr(outcome, "retry_after_ms", None) if outcome is not None else None,
response_received_at=outcome.response_received_at if outcome is not None else None,
+ upstream_retry_at=decision.retry_at,
)
if not changed:
return event_reason, False
diff --git a/docs/plans/claude-subscription-cap-cooldown.md b/docs/plans/claude-subscription-cap-cooldown.md
new file mode 100644
index 000000000..34d0244aa
--- /dev/null
+++ b/docs/plans/claude-subscription-cap-cooldown.md
@@ -0,0 +1,70 @@
+# Claude subscription-cap cooldowns (#2530)
+
+## Change contract
+
+Consume only the existing Claude-only `RawCallOutcome.claude_rate_limit_headers`
+projection. A generic HTTP 429 becomes the existing `quota_exhausted` cooldown
+only with a shared subscription rejection and a valid active reset. Carry the
+absolute deadline through classification into existing recovery admission and
+settlement; select the latest of local delay, valid upstream advice, and the
+existing Source deadline. No schema, enum, adapter contract, engine, scheduler,
+credential, deployment, or UI changes.
+
+## Evidence and bounded interpretation
+
+The managed engine's upstream implementation (`CLIProxyAPI` v8.0.23,
+`internal/runtime/executor/helps/claude_ratelimit.go`, cited by #2530) distinguishes
+shared 5h/7d rejection from overage/model-specific rejection, parses Unix/aware
+ISO/HTTP dates, and bounds recoverable resets to seven days plus one hour.
+Avibe owns policy and does not copy its random grace period or engine cooling.
+
+- Explicit rejected shared 5h/7d windows activate their own reset.
+- A rejected aggregate with an exact 5h/7d representative claim can activate
+ that window when its status is omitted (not when explicitly allowed).
+- An aggregate reset is usable for shared rejection only when it is not
+ attributed to overage/model-specific claims. Aggregate-only evidence must not
+ contradict explicit healthy shared windows or name an overage-only refusal.
+- Inactive window resets, utilization alone, overage billing resets and
+ model-specific 7d_oi resets cannot independently cool a whole Source.
+- Select the latest valid active deadline, bounded relative to the captured
+ response receipt. Missing, malformed, expired, negative, excessive, or
+ ambiguous evidence leaves ordinary 429 classification/advice unchanged.
+- Explicit machine-code remedies remain authoritative; only ordinary
+ `rate_limited` decisions are refined. Post-output terminal semantics remain.
+
+Only the derived deadline and existing reason enter recovery/Source state.
+Raw header values never enter events, diagnostics or provenance.
+
+## Validation plan
+
+1. Classifier table: shared and aggregate/claim rejection, active-window
+ selection, date syntax/bounds, malformed/ambiguous/overage/model-only cases,
+ unrelated HTTP results and stronger machine-code remedies. Existing tests
+ cover header projection, but none consume it in classification.
+2. Production loopback engine -> client -> classifier -> gateway recovery ->
+ persistence/provenance -> Source/chain projection. Verify one upstream
+ attempt, no short-ladder retries, restoration from persisted cooldown,
+ later-deadline semantics, Retry-After/Ms precedence, and no header leakage.
+ Existing subscription lifecycle coverage exercises only ChatGPT body resets.
+3. Reproduce the primary regression on the unmodified implementation before
+ fixing it; run focused suites, changed Python Ruff, structure/authority
+ guards, and diff checks before pushing. Leave full CI to GitHub.
+
+## Validation evidence
+
+- Pre-fix classifier regression: rejected 5h header plus valid reset returned
+ `rate_limited/60`, failing the expected `quota_exhausted/300` assertion.
+- Focused classifier, retry advice/policy/lifecycle, engine header boundary,
+ resolution, config/authority, structure guards, and scenario catalog:
+ **977 passed**. Includes 24 real loopback lifecycle cases across Claude/Codex
+ callers and buffered/streaming requests.
+- Worktree-local Python 3.12 environment from the frozen lockfile; no package,
+ live runtime, external service or real account mutation. Full CI runs in the
+ PR; no user/runtime regression operation is authorized for this lane.
+
+## Delivery
+
+Independent branch `fix/claude-cap-reset-2530` from
+`c7f55dc62a28a0964db3b0b74571f53899566685`. Non-draft PR, one owner-specific
+persistent PR/CI Watch, exact-head Codex pass, CI and zero unresolved threads.
+Report Merge-ready to the orchestrator; do not merge or operate a runtime.
diff --git a/docs/plans/model-hub-retry-experience.md b/docs/plans/model-hub-retry-experience.md
index 8e2a33559..d397a6e05 100644
--- a/docs/plans/model-hub-retry-experience.md
+++ b/docs/plans/model-hub-retry-experience.md
@@ -192,6 +192,17 @@ upstream advice. A Source deadline must not move earlier due to another failure.
Invalid, overflowing, or past values cannot cause a tight loop; fall back to
the local policy and record only a sanitized diagnostic.
+For Claude HTTP 429s, the existing bounded unified-header projection can refine
+an ordinary rate limit to `quota_exhausted` when a shared 5h/7d rejection has a
+valid active reset. Ignore inactive windows and overage/model-only rejections;
+accept future resets no more than seven days plus one hour after header receipt.
+The latest valid shared reset joins `Retry-After`, `Retry-After-Ms`, local backoff,
+and the existing deadline in the same later-deadline policy. Invalid or ambiguous
+unified evidence preserves ordinary rate-limit handling and valid retry advice.
+Only the existing quota reason and derived deadline reach Source state, never
+raw unified headers. See `claude-subscription-cap-cooldown.md` for the evidence
+rules and validation contract.
+
Do not clamp a valid long upstream delay down to the local cap and retry early.
If it is outside this request's window, terminate this request truthfully while
keeping the advisory deadline. Compare aware timestamps using the existing
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index a74b56ded..2fb6dea6d 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -843,6 +843,14 @@ scenarios:
kind: recovery
layer: unit
test: tests/test_model_hub_retry_lifecycle.py::test_a_plan_or_billing_429_settles_its_source_by_the_code_that_names_it
+ - id: MH-RETRY-ADVICE-004
+ name: Shared Claude cap resets persist as quota cooldowns without early probes or raw header disclosure
+ status: covered
+ kind: recovery
+ layer: unit
+ test: tests/test_model_hub_retry_lifecycle.py::test_claude_cap_headers_drive_persisted_recovery_without_early_probes
+ related_tests:
+ - tests/test_model_hub_claude_caps.py
- id: MH-RETRY-EVIDENCE-001
name: Unknown buffered success passes through without proving recovery
status: covered
diff --git a/tests/test_model_hub_claude_caps.py b/tests/test_model_hub_claude_caps.py
new file mode 100644
index 000000000..417e420dc
--- /dev/null
+++ b/tests/test_model_hub_claude_caps.py
@@ -0,0 +1,123 @@
+"""Shared Claude subscription windows refine only ordinary rate-limit outcomes."""
+
+from dataclasses import replace
+from datetime import datetime, timedelta, timezone
+from email.utils import format_datetime
+
+import pytest
+
+from core.handlers.model_hub.adapter import RawCallOutcome, RawOutcomeKind
+from core.handlers.model_hub.classification import classify_outcome
+
+
+RECEIVED = datetime(2026, 10, 25, 12, tzinfo=timezone.utc)
+FIVE_HOURS = RECEIVED + timedelta(hours=5)
+WEEK = RECEIVED + timedelta(days=7)
+
+
+def cap_outcome(headers):
+ return RawCallOutcome(
+ kind=RawOutcomeKind.HTTP_ERROR, http_status=429, error_code=None,
+ error_type="rate_limit_error", redacted_message=None, stream_started=False,
+ source_id="src_claudecap", model_id="claude-model",
+ response_received_at=RECEIVED,
+ claude_rate_limit_headers=tuple(
+ (f"anthropic-ratelimit-unified-{name}", value) for name, value in headers.items()
+ ),
+ )
+
+
[email protected]("headers,expected", [
+ ({"5h-status": "rejected", "5h-reset": str(FIVE_HOURS.timestamp())}, FIVE_HOURS),
+ ({"7d-status": "rejected", "7d-reset": str(WEEK.timestamp())}, WEEK),
+ ({"5h-status": "rejected", "5h-reset": FIVE_HOURS.isoformat(),
+ "7d-status": "rejected", "7d-reset": format_datetime(WEEK)}, WEEK),
+ ({"5h-status": "rejected", "5h-reset": FIVE_HOURS.isoformat(),
+ "7d-status": "allowed_warning", "7d-reset": WEEK.isoformat()}, FIVE_HOURS),
+ ({"status": "rejected", "representative-claim": "5h", "5h-reset": FIVE_HOURS.isoformat(),
+ "7d-reset": WEEK.isoformat()}, FIVE_HOURS),
+ ({"status": "rejected", "representative-claim": "7d", "7d-reset": WEEK.isoformat()}, WEEK),
+ ({"status": "rejected", "reset": WEEK.isoformat()}, WEEK),
+ ({"5h-status": "rejected", "5h-reset": "bad",
+ "7d-status": "rejected", "7d-reset": WEEK.isoformat()}, WEEK),
+ ({"5h-status": "rejected", "5h-reset": FIVE_HOURS.isoformat(),
+ "status": "rejected", "reset": WEEK.isoformat()}, WEEK),
+ ({"5h-status": "rejected", "5h-reset": FIVE_HOURS.isoformat(),
+ "status": "rejected", "representative-claim": "overage", "reset": WEEK.isoformat(),
+ "overage-reset": WEEK.isoformat()}, FIVE_HOURS),
+ ({"7d-status": "rejected", "7d-reset": (WEEK + timedelta(hours=1)).isoformat()},
+ WEEK + timedelta(hours=1)),
+ ({"5h-status": "rejected", "5h-reset": FIVE_HOURS.astimezone(timezone(timedelta(hours=8))).isoformat()},
+ FIVE_HOURS),
+ ({"5h-status": "rejected", "5h-reset": str(FIVE_HOURS.timestamp() + .25)},
+ FIVE_HOURS + timedelta(seconds=.25)),
+])
+def test_only_active_shared_resets_refine_a_generic_429(headers, expected):
+ """Regression: generic rate_limit_error used to ignore all unified evidence."""
+ decision = classify_outcome(cap_outcome(headers))
+ assert (decision.action, decision.reason, decision.cooldown_seconds) == ("fallback", "quota_exhausted", 300)
+ assert decision.retry_at == expected
+
+
+ "", "garbage", "-1", "0", "NaN", "Infinity", "1e9999", "9" * 129,
+ "123", RECEIVED.isoformat(), (RECEIVED - timedelta(seconds=1)).isoformat(),
+ (WEEK + timedelta(hours=1, seconds=1)).isoformat(),
+ str(int(FIVE_HOURS.timestamp()) * 1000), FIVE_HOURS.replace(tzinfo=None).isoformat(),
+])
+def test_invalid_or_out_of_window_reset_preserves_the_rate_limit_fallback(reset):
+ decision = classify_outcome(cap_outcome({"5h-status": "rejected", "5h-reset": reset}))
+ assert (decision.reason, decision.cooldown_seconds) == ("rate_limited", 60)
+ assert decision.retry_at is None
+
+
[email protected]("headers", [
+ {}, {"5h-reset": FIVE_HOURS.isoformat()},
+ {"5h-status": "rejected"},
+ {"status": "rejected", "5h-reset": FIVE_HOURS.isoformat()}, # no active-window witness
+ {"5h-utilization": "1.0", "5h-reset": FIVE_HOURS.isoformat()},
+ {"5h-status": "allowed", "5h-reset": FIVE_HOURS.isoformat()},
+ {"status": "allowed", "reset": WEEK.isoformat()},
+ {"status": "rejected", "representative-claim": "5h", "5h-status": "allowed",
+ "5h-reset": FIVE_HOURS.isoformat(), "reset": FIVE_HOURS.isoformat()},
+ {"status": "rejected", "5h-status": "allowed", "7d-status": "allowed_warning", "reset": WEEK.isoformat()},
+ {"status": "rejected", "representative-claim": "overage", "reset": WEEK.isoformat()},
+ {"status": "rejected", "overage-status": "rejected", "reset": WEEK.isoformat()},
+ {"status": "rejected", "overage-disabled-reason": "billing", "reset": WEEK.isoformat()},
+ {"status": "rejected", "7d_oi-status": "rejected", "7d_oi-reset": WEEK.isoformat(), "reset": WEEK.isoformat()},
+ {"status": "rejected", "representative-claim": "unknown", "reset": WEEK.isoformat()},
+])
+def test_ambiguous_or_non_shared_rejection_never_sets_a_subscription_cooldown(headers):
+ decision = classify_outcome(cap_outcome(headers))
+ assert decision.reason == "rate_limited"
+ assert decision.retry_at is None
+
+
[email protected]("changes,reason", [
+ ({"http_status": 503, "error_type": "server_error"}, "server_error"),
+ ({"http_status": 200, "kind": RawOutcomeKind.SUCCESS}, None),
+ ({"error_code": "usage_not_included"}, "plan_excludes_product"),
+ ({"error_code": "credit_balance_exhausted"}, "balance_exhausted"),
+ ({"error_code": "organization_spend_limit_exceeded"}, "spend_limit_reached"),
+ ({"response_received_at": None}, "rate_limited"),
+ ({"response_received_at": RECEIVED.replace(tzinfo=None)}, "rate_limited"),
+])
+def test_shared_header_evidence_does_not_override_other_contracts(changes, reason):
+ outcome = replace(cap_outcome({"5h-status": "rejected", "5h-reset": FIVE_HOURS.isoformat()}), **changes)
+ decision = classify_outcome(outcome)
+ assert decision.reason == reason
+ assert decision.retry_at is None
+
+
[email protected]("error_type", [None, "rate_limit_error", "rate_limit_exceeded", "invalid_request_error"])
[email protected]("stream_started", [False, True])
+def test_refinement_keeps_status_fallback_and_post_output_terminal_semantics(error_type, stream_started):
+ outcome = replace(
+ cap_outcome({"5h-status": "rejected", "5h-reset": FIVE_HOURS.isoformat()}),
+ error_type=error_type, stream_started=stream_started,
+ )
+ decision = classify_outcome(outcome)
+ assert decision.reason == "quota_exhausted"
+ assert decision.retry_at == FIVE_HOURS
+ assert decision.action == ("surface" if stream_started else "fallback")
+ assert decision.error_code == ("stream_interrupted" if stream_started else None)
diff --git a/tests/test_model_hub_retry_lifecycle.py b/tests/test_model_hub_retry_lifecycle.py
index 98ccb734d..2e1b8a2b5 100644
--- a/tests/test_model_hub_retry_lifecycle.py
+++ b/tests/test_model_hub_retry_lifecycle.py
@@ -443,6 +443,108 @@ def test_a_usage_cap_cools_its_source_as_quota_until_the_upstream_reset(tmp_path
asyncio.run(run())
[email protected]("stream", [False, True])
[email protected]("backend", ["claude", "codex"])
[email protected]("windows,advice,expected", [
+ ({"5h": 18000}, {}, 18000),
+ ({"7d": 604800}, {}, 604800),
+ ({"5h": 18000, "7d": 604800}, {"Retry-After": "60"}, 604800),
+ ({"5h": 18000}, {"Retry-After": "24000", "Retry-After-Ms": "25000000"}, 25000),
+ ({"5h": 18000}, {"Retry-After": "25000", "Retry-After-Ms": "24000000"}, 25000),
+ ({"5h": 20}, {}, 300), # A short upstream reset cannot shorten the quota ladder.
+])
+def test_claude_cap_headers_drive_persisted_recovery_without_early_probes(
+ tmp_path, monkeypatch, caplog, stream, backend, windows, advice, expected,
+):
+ """MH-RETRY-ADVICE-004: shared Claude caps survive settlement/restart without short-ladder probes or raw headers."""
+ async def run():
+ source = _source("src_claudecap", "Claude", vendor="anthropic", protocol="anthropic")
+ service, clock, models = configured_service(tmp_path, sources=[source])
+ receipt = clock.now()
+ deadline = receipt + timedelta(seconds=expected)
+
+ class ReceiptClock(datetime):
+ @classmethod
+ def now(cls, tz=None):
+ return clock.now()
+
+ monkeypatch.setattr(engine_client_module, "datetime", ReceiptClock)
+ raw_headers = {
+ "aNtHrOpIc-Ratelimit-Unified-Status": "rejected",
+ "Authorization": "private-upstream-credential",
+ "Set-Cookie": "private-upstream-cookie",
+ "Organization-Id": "private-upstream-org",
+ "Anthropic-Ratelimit-Unified-Unknown": "private-unknown-value",
+ **advice,
+ }
+ for window, delay in windows.items():
+ raw_headers[f"Anthropic-Ratelimit-Unified-{window}-Status"] = "rejected"
+ raw_headers[f"Anthropic-Ratelimit-Unified-{window}-Reset"] = str(int(receipt.timestamp()) + delay)
+ calls = []
+
+ async def respond(request):
+ calls.append(await request.json())
+ if clock.now() < deadline:
+ return web.json_response({"error": {"type": "rate_limit_error", "message": "Rate limited"}},
+ status=429, headers=raw_headers)
+ metadata, output, terminal, buffered = WIRE[BACKENDS[backend][1]]
+ return web.Response(body=metadata + output + terminal if stream else buffered,
+ content_type="text/event-stream" if stream else "application/json")
+
+ async with loopback_engine(tmp_path, service, respond):
+ service.store = FreshStore(service.store.load())
+ async with gateway_client(service, backend, models[backend]) as (gateway, client, url, headers):
+ async with client.post(url, headers=headers, json={"model": "shared-model", "stream": stream}) as response:
+ body = await response.json()
+ assert body["error"]["cause"] == "quota_exhausted"
+ assert body["error"]["code"] == RECOVERY_EXHAUSTED_CODE
+ assert not any(name.lower() in response.headers for name in raw_headers)
+ gateway.correlation.settle("turn_lifecycle", settled_by=SETTLED_BY_TERMINAL_RESULT)
+ record = service.provenance.get("turn_lifecycle")
+ assert record["failed_attempts"] == [{
+ "source_id": source.id, "configured_model_id": "shared-model", "channel": "hub",
+ "reason": "quota_exhausted", "http_status": 429, "upstream_detail": "Rate limited",
+ }]
+ stored = service.store.load().sources[0].state
+ assert (stored.status, stored.detail_key, stored.retry_at) == (
+ "cooldown", "models.source.cooldown.quota_exhausted", deadline.isoformat(),
+ )
+ assert len(calls) == 1 and clock.delays == []
+ assert service.events.list()[0]["reason"] == "quota_exhausted"
+ surfaces = json.dumps([
+ body, record, service.list_events(), service.list_sources(), service.store.persisted, caplog.text,
+ ])
+ assert "anthropic-ratelimit" not in surfaces.lower()
+ for secret in ("private-upstream-credential", "private-upstream-cookie", "private-upstream-org", "private-unknown-value"):
+ assert secret not in surfaces
+
+ # A new policy restores eligibility from fresh persisted config,
+ # never from this request's header projection or live retry streak.
+ service.recovery = clock.policy()
+ clock.advance(expected - 121)
+ with pytest.raises(ModelHubError):
+ await service.resolve_with_recovery(backend=backend, model_id=models[backend], request={})
+ assert len(calls) == 1 and clock.delays == []
+ chain = service.agent_chain(backend, models[backend])
+ assert chain["supply_state"] == "waiting"
+ assert chain["chain"][0]["retry_at"] == deadline.isoformat()
+ assert chain["chain"][0]["runnable"] is False
+ _assert_valid("agent-chain.schema.json", chain)
+ # A concurrent later-completing short failure cannot pull it forward.
+ await fail(service, service.store.load().sources[0], "rate_limited")
+ assert service.store.load().sources[0].state.retry_at == deadline.isoformat()
+ assert service.store.load().sources[0].state.detail_key == "models.source.cooldown.quota_exhausted"
+ clock.advance(121)
+ assert service.store.load().sources[0].state.status == "cooldown"
+ async with gateway_client(service, backend, models[backend]) as (_gateway, client, url, headers):
+ async with client.post(url, headers=headers, json={"model": "shared-model", "stream": stream}) as response:
+ assert response.status == 200
+ await response.read()
+ assert len(calls) == 2
+ assert service.store.load().sources[0].state.status == "standby"
+ asyncio.run(run())
+
+
@pytest.mark.parametrize("engine_refuses", [True, False], ids=["engine", "upstream"])
def test_a_401_the_engine_itself_gave_spares_the_source(tmp_path, engine_refuses):
"""MH-RUNTIME-015: the engine's own 401 is told from an upstream's by a witness no upstream answers (#2755).