llmswap-cli 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. claude_swap/__init__.py +24 -0
  2. claude_swap/__main__.py +6 -0
  3. claude_swap/app_bundle.py +330 -0
  4. claude_swap/appearance.py +219 -0
  5. claude_swap/autoswitch.py +3065 -0
  6. claude_swap/cache.py +44 -0
  7. claude_swap/claude_locks.py +279 -0
  8. claude_swap/cli.py +2265 -0
  9. claude_swap/credentials.py +2156 -0
  10. claude_swap/exceptions.py +102 -0
  11. claude_swap/fsutil.py +409 -0
  12. claude_swap/json_output.py +455 -0
  13. claude_swap/launch_agent.py +862 -0
  14. claude_swap/lines.py +153 -0
  15. claude_swap/list_view.py +371 -0
  16. claude_swap/locking.py +87 -0
  17. claude_swap/logging_config.py +64 -0
  18. claude_swap/macos_keychain.py +240 -0
  19. claude_swap/mappings.py +127 -0
  20. claude_swap/menubar.py +1433 -0
  21. claude_swap/migrations.py +360 -0
  22. claude_swap/models.py +329 -0
  23. claude_swap/oauth.py +1628 -0
  24. claude_swap/pace.py +161 -0
  25. claude_swap/paths.py +250 -0
  26. claude_swap/poll_policy.py +337 -0
  27. claude_swap/printer.py +252 -0
  28. claude_swap/process_detection.py +370 -0
  29. claude_swap/session.py +2696 -0
  30. claude_swap/settings.py +827 -0
  31. claude_swap/signin.py +238 -0
  32. claude_swap/snapshot_source.py +121 -0
  33. claude_swap/spawn.py +135 -0
  34. claude_swap/subscription.py +349 -0
  35. claude_swap/switcher.py +9807 -0
  36. claude_swap/transfer.py +807 -0
  37. claude_swap/tui/__init__.py +43 -0
  38. claude_swap/tui/app.py +482 -0
  39. claude_swap/tui/autoview.py +381 -0
  40. claude_swap/tui/cswap.tcss +205 -0
  41. claude_swap/tui/dashboard.py +434 -0
  42. claude_swap/tui/data.py +194 -0
  43. claude_swap/tui/modals.py +159 -0
  44. claude_swap/tui/theme.py +88 -0
  45. claude_swap/tui/widgets.py +544 -0
  46. claude_swap/update_check.py +509 -0
  47. claude_swap/usage_bars.py +208 -0
  48. claude_swap/usage_rows.py +160 -0
  49. claude_swap/usage_store.py +1429 -0
  50. llmswap/AGENTS.md +11 -0
  51. llmswap/__init__.py +3 -0
  52. llmswap/__main__.py +4 -0
  53. llmswap/cli.py +535 -0
  54. llmswap/config.py +101 -0
  55. llmswap/httpjson.py +50 -0
  56. llmswap/jwt.py +20 -0
  57. llmswap/menubar.py +218 -0
  58. llmswap/model.py +172 -0
  59. llmswap/paths.py +41 -0
  60. llmswap/providers/AGENTS.md +12 -0
  61. llmswap/providers/base.py +619 -0
  62. llmswap/providers/claude.py +187 -0
  63. llmswap/providers/codex.py +274 -0
  64. llmswap/providers/gemini.py +80 -0
  65. llmswap/providers/registry.py +30 -0
  66. llmswap/render.py +127 -0
  67. llmswap/rotate.py +102 -0
  68. llmswap/store.py +138 -0
  69. llmswap/tui.py +182 -0
  70. llmswap/usage_cache.py +72 -0
  71. llmswap/warm/plan.py +118 -0
  72. llmswap/warm/runner.py +175 -0
  73. llmswap/warm/schedule.py +264 -0
  74. llmswap_cli-1.0.0.dist-info/METADATA +181 -0
  75. llmswap_cli-1.0.0.dist-info/RECORD +78 -0
  76. llmswap_cli-1.0.0.dist-info/WHEEL +4 -0
  77. llmswap_cli-1.0.0.dist-info/entry_points.txt +5 -0
  78. llmswap_cli-1.0.0.dist-info/licenses/LICENSE +22 -0
@@ -0,0 +1,1429 @@
1
+ """Per-account usage table: last-known-good measurements + fetch/backoff state.
2
+
3
+ Replaces the all-or-nothing 15s snapshot that previously lived in
4
+ ``cache/usage.json`` (now ``schemaVersion: 2``; a version-less legacy file is
5
+ treated as empty — its data had a 15s shelf life anyway). One failed round
6
+ trip no longer blanks every account: a failure updates the error/backoff
7
+ fields and never touches the last-good measurement (stale-on-error). The
8
+ table is shared by ``--list``/``--status`` (on-demand refresh of stale
9
+ entries) and ``cswap auto`` (scheduled polling), so each learns from the
10
+ other's fetches.
11
+
12
+ The store persists only *measurements* (``lastGood``) and *fetch state*
13
+ (failures, backoff, poll schedule). Sentinel states ("api key",
14
+ "token expired", ...) are derived fresh by the collector on every pass and
15
+ overlaid on the read model (``UsageEntry.sentinel``) — never written to disk,
16
+ so a stale sentinel can't outlive the condition that produced it.
17
+
18
+ Locking protocol (never holds the lock across network I/O):
19
+ (a) lock → read, decide/claim the fetch set (stamp ``claimUntil``) → unlock;
20
+ (b) fetch with no lock held;
21
+ (c) lock → re-read, merge outcomes, clear the claim, write → unlock.
22
+ The bounded lease lets concurrent collectors skip accounts another process is
23
+ still fetching; recording the outcome releases it and a crashed claimer ages
24
+ out. The collector records per *batch*, so a fast account's lease is held
25
+ until its batch's slowest fetch lands — the lease TTL is sized for the whole
26
+ batch, not one request.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import json
32
+ import time
33
+ import uuid
34
+ from collections.abc import Callable, Iterable
35
+ from dataclasses import dataclass, replace
36
+ from pathlib import Path
37
+
38
+ from claude_swap.locking import FileLock
39
+ from claude_swap import oauth
40
+ from claude_swap.poll_policy import (
41
+ EDGE_BACKOFF_S,
42
+ EXHAUSTED_INTERVAL_S,
43
+ JITTER_FRAC,
44
+ RECENT_429_WINDOW_S,
45
+ RESET_SLACK_S,
46
+ SERVE_TTL_S,
47
+ parse_reset_ts,
48
+ )
49
+ from claude_swap.settings import atomic_write_json
50
+
51
+ SCHEMA_VERSION = 2
52
+
53
+ # Freshness is the reader's judgment per purpose, not a global TTL.
54
+ # SERVE_TTL_S (re-exported from poll_policy — fresher than this → serve
55
+ # without fetching) doubles as the per-account sustained-rate governor: see
56
+ # poll_policy's module docstring for the measured budget it must stay under.
57
+ STALE_OK_S = 300.0 # trusted for switch decisions; older → headroom unknown
58
+ # Covers the bounded refresh + usage path, the full inventory's stagger, and
59
+ # executor queueing, so another surface cannot reclaim a request that is still
60
+ # in flight. A crashed collector waiting 90s remains below the provider-safe
61
+ # polling interval.
62
+ CLAIM_TTL_S = 90.0 # in-flight claim window: skip just-claimed accounts
63
+ LEGACY_CLAIM_TTL_S = 10.0 # additive-schema overlap with older collectors
64
+
65
+
66
+ def _live_claim(
67
+ claim_until: float | None, last_attempt_at: float | None, now: float
68
+ ) -> bool:
69
+ """Whether a collector's fetch lease on a row is still live.
70
+
71
+ ``claim_until`` (the fenced lease) wins when present; rows written by an
72
+ older process fall back to ``lastAttemptAt`` + ``LEGACY_CLAIM_TTL_S``.
73
+ The single source of truth for claim liveness — ``UsageEntry.claimed``,
74
+ ``entries()``, and ``_row_eligible`` must all agree, or concurrent
75
+ collectors double-fetch. (``record()`` deliberately checks only the
76
+ fenced form; see its comment.)
77
+ """
78
+ if claim_until is not None:
79
+ return now < claim_until
80
+ return (
81
+ last_attempt_at is not None
82
+ and (now - last_attempt_at) < LEGACY_CLAIM_TTL_S
83
+ )
84
+
85
+ # Deliberate staleness (failure backoff, scheduler-chosen cadence) extends
86
+ # decision trust past STALE_OK_S, but never past this ceiling: a forever-failing
87
+ # account must eventually read as unknown so the unknown-path machinery
88
+ # (escalate-all, unhealthy ticks, verified failover) takes back over. The
89
+ # ceiling deliberately overrides even a Retry-After longer than itself —
90
+ # trust must never be server-controlled and unbounded.
91
+ TRUST_MAX_AGE_S = 3600.0
92
+
93
+ # A usage-endpoint 429 is a polling throttle, not a change in the account's
94
+ # real model quota: the endpoint budgets *usage requests* (scope is
95
+ # regime-dependent; see poll_policy), independent of the 5h/7d limits it
96
+ # reports. It does NOT move
97
+ # the account's real windows, and usage only rises within a window (monotone
98
+ # until the window resets), so last_good is a valid lower bound on the true
99
+ # usage right up to that reset. Trust it until then — data-driven, not a fixed
100
+ # clock: flipping it to "unknown" early (the old fixed 2h ceiling) made a
101
+ # throttled account an unusable switch target and drove failover flapping /
102
+ # all-exhausted sleeps even while the account was plainly fine. Once the window
103
+ # resets, usage is zeroed and last_good is obsolete → unknown. Matches Claude
104
+ # Code's own 2.1.208 "show last-known usage when rate-limited" behavior.
105
+ #
106
+ # Fallback ceiling for 429-stale data that carries no resets_at (older stored
107
+ # rows): still bounded so it can't be trusted forever. Non-429 failures always
108
+ # use TRUST_MAX_AGE_S (a timeout/network error is no evidence last_good holds).
109
+ RATE_LIMIT_TRUST_MAX_AGE_S = 7200.0
110
+
111
+ # Failure backoff when the server sent no Retry-After: 30s · 2^(n-1), capped.
112
+ BACKOFF_BASE_S = 30.0
113
+ BACKOFF_CAP_S = 600.0
114
+ # Exponent clamp: a permanently failing account increments its failure count
115
+ # forever, and 2**n stops converting to float at n >= 1024 (OverflowError).
116
+ # The curve already saturates at BACKOFF_CAP_S by shift 5, so any cap above
117
+ # that is behaviour-preserving.
118
+ BACKOFF_MAX_SHIFT = 32
119
+
120
+ # The usage endpoint enforces a request budget on non-first-party
121
+ # User-Agents (proven 2026-07-11: an idle token, polling alone trips it;
122
+ # poll_policy documents the measured shape — an hour-scale window, exact edge
123
+ # algorithm undocumented). Nothing below depends on whether the budget is
124
+ # scoped to the account/org or to the token — the wait comes from the
125
+ # server's own deadline either way. Cumulative polling from cswap's own
126
+ # surfaces is what saturates it.
127
+ # Retry-After tells the rules apart:
128
+ # - "Retry-After: 0" = the saturated-budget edge: the trailing hour's budget
129
+ # is spent and frees only as old requests age out, so immediate retries
130
+ # mostly prolong the oscillating state. Wait at least
131
+ # poll_policy.EDGE_BACKOFF_S before probing again.
132
+ # - "Retry-After: N>0" = the burst rule (several rapid requests on one token
133
+ # → hard block; measured: accurate, counts down, not extended by probing).
134
+ # Honored as the wait, up to a safety cap so a pathological header can
135
+ # never park an account for hours.
136
+ # The cap spans the usage endpoint's ~1h rolling window: a saturating burst
137
+ # blocks the token for up to a full trailing hour, and the server's Retry-After
138
+ # reports that horizon accurately — it counts down to a fixed wall-clock
139
+ # deadline and is NOT re-armed by probing (measured: three probes in one
140
+ # episode all reported the same deadline). Capping below it (the old 900s) just
141
+ # meant re-probing two or three times inside a block that was going to last the
142
+ # full window anyway — wasted requests against the very budget we are trying to
143
+ # let recover, with no benefit. Honoring the whole Retry-After spends one
144
+ # request per block instead. The cap still bounds a pathological header to one
145
+ # window, never hours.
146
+ #
147
+ # Honoring it EXACTLY is not enough: the retry lands ON the deadline, where
148
+ # the server is not reliably ready. Measured over this machine's whole log
149
+ # (re-measured 2026-08-03, round 8 — the round-7 "21 of 36"/"2 of 38" figures
150
+ # do reproduce under the method below, on the OTHER of its two valid
151
+ # readings; round 8 switched readings, see the METHOD paragraph below for
152
+ # which and why the two differ; these figures age as the log grows —
153
+ # re-derive rather than trust them verbatim, using the method below), 20 of
154
+ # 35 lapses re-blocked within 900s
155
+ # of their own deadline (+2s..+887s), each earning a fresh full hour; the
156
+ # next one is +1004s, so the distribution is bimodal and 900s is the edge of
157
+ # the band — with only 13s of clearance (900 - 887), not the 185s an earlier,
158
+ # wrong figure implied. ("20 of 35", not "of 38": the denominator is
159
+ # restricted to the 35 POSITIVE lapse gaps, matching the numerator — 3 of the
160
+ # 38 raw gaps are negative, and mixing them into an "of 38" denominator
161
+ # understates the fraction. The negative gaps are NOT a uniform mechanism —
162
+ # measured per gap: acct2 block10→11 (no within-block revision at all, a
163
+ # single-observation block whose NEXT block's opening simply lands later);
164
+ # block11→12 (the deadline was revised BACKWARD 903s mid-block, the opposite
165
+ # of "forward"); block12→13 (deadline unchanged mid-block). None is a forward
166
+ # revision. What they share is only the effect, not the cause: each next
167
+ # block's opening observation lands before the prior block's own deadline —
168
+ # a real event, just not a lapse to measure. Excluding them from a lapse-gap
169
+ # analysis is still correct on that basis: a block that never lapsed has no
170
+ # lapse gap.) The margin is
171
+ # ABSOLUTE, not a fraction of the ask: Retry-After counts down to a fixed
172
+ # deadline, so a machine polling into a block another one opened sees only
173
+ # the remainder, and a fraction of that shrinks toward zero exactly when it
174
+ # matters.
175
+ #
176
+ # METHOD (re-derive with this, not ad hoc, to get the same numbers): parse
177
+ # ``claude-swap.log`` lines "Usage fetch failed for account N: http-429,
178
+ # retry-after Ks"; EXCLUDE K == 0 (the saturated-budget edge above, a
179
+ # different rule from the burst block this margin is sized against — 439 such
180
+ # lines in the 2026-08-03 log, and mixing them into the block counts is what
181
+ # produced the earlier wrong figures); group the remaining events per account
182
+ # into blocks by clustering on the deadline ``ts + K`` (a new block opens when
183
+ # the deadline jumps forward past a tolerance — stable for any tolerance from
184
+ # 5s to 300s). 41 blocks result, 40 of them opened at exactly K=3600; 34 of
185
+ # 75 observations land mid-block (not block-opening); the lapse gap is each
186
+ # block's next observation's timestamp minus the PRIOR block's deadline —
187
+ # where a block has more than one observation (a mid-block deadline
188
+ # revision), "the block's deadline" means its OPENING observation's deadline
189
+ # — the reading used below and the same one "40 of them opened at exactly
190
+ # K=3600" reads, so every figure in this comment stays internally consistent
191
+ # on one reading. Picking the block's LAST observation's deadline instead
192
+ # does NOT fail to reproduce: it is equally stable at every tolerance from 5s
193
+ # to 900s and gives "21 of 36"/"2 of 38", the figures this comment used to
194
+ # carry before round 8. The two readings differ on exactly ONE gap (acct2
195
+ # block11→12): its opening observation asks K=3600, but two later
196
+ # observations in the same block report a deadline 903s EARLIER, so OPENING
197
+ # reads that gap as -900.1s (excluded, negative) while LAST reads it as
198
+ # +3.0s (included, a lapse inside the band). Either reading sizes the
199
+ # constant identically — both put the band edge at +887s, so
200
+ # RETRY_AFTER_MARGIN_S = 900 clears it with 13s to spare under both.
201
+ RETRY_AFTER_MARGIN_S = 900.0
202
+ # Bounds Retry-After + MARGIN_S, so a pathological header still cannot park an
203
+ # account for hours. Sized to clear the measured shape: 40 of 41 observed
204
+ # blocks opened at exactly 3600 (re-measured 2026-08-03, method above), and
205
+ # 3600 + 900 = this. At an ask of exactly this value the margin is already
206
+ # fully eaten, and beyond it the wait is SHORTER than the server asked — a
207
+ # guaranteed 429, costing one request rather than a fresh hour (probing does
208
+ # not re-arm a block). Above 3600 the cap eats
209
+ # the margin (a 3700s ask keeps only +800s), which is deliberate — an ask past
210
+ # the measured window is already outside the evidence, and bounding it matters
211
+ # more there than preserving a margin derived from hour-scale blocks. If real
212
+ # blocks ever open above 3600, raise this with the shape rather than letting
213
+ # the cap silently shorten the margin.
214
+ RETRY_AFTER_FLOOR_CAP_S = 4500.0
215
+
216
+ # A dead refresh-token lineage (the token endpoint answered ``invalid_grant``,
217
+ # e.g. "Refresh token not found or invalid") can never recover on its own —
218
+ # only a re-login helps. One such answer is already definitive: the server
219
+ # explicitly rejected the grant, which no transient 429/timeout/network blip
220
+ # does, so there is nothing to gain by retrying (and each retry with a dead
221
+ # token just draws a fresh 401/429). At this many strikes the account is
222
+ # quarantined: no more fetches, and the collector surfaces "re-login needed".
223
+ # (``reserve``'s ``struck_ok`` is how a replacement login gets its attempt.)
224
+ # A single success — or a credential refresh via login/add — resets the count
225
+ # and lifts the quarantine. Raise to 2 if a buffer against a one-off
226
+ # misclassification is ever wanted; the trade-off is a ~10-min-slower verdict
227
+ # (the failure backoff between the two strikes).
228
+ AUTH_DEAD_STRIKES = 1
229
+
230
+ # Fetch errors that prove the stored credential is permanently unusable (vs.
231
+ # transient 429/timeout/network). Only these advance the dead-token strike
232
+ # count; everything else leaves it untouched (a transient error is no evidence
233
+ # the token is alive *or* dead). "no_refresh_token" is equally unretryable:
234
+ # a credential with no refresh token cannot be healed by any retry.
235
+ PERMANENT_AUTH_ERRORS = frozenset({"invalid_grant", "no_refresh_token"})
236
+
237
+ # (email, organizationUuid) — the identity a slot number currently maps to.
238
+ Identity = tuple[str, str]
239
+
240
+
241
+ @dataclass(frozen=True)
242
+ class FetchRecord:
243
+ """Outcome of one fetch attempt, as handed to :meth:`UsageStore.record`.
244
+
245
+ Exactly one of three shapes:
246
+ - success: ``error`` and ``sentinel`` are None (``usage`` may still be
247
+ None when the response carried no window data);
248
+ - failure: ``error`` set (with optional ``retry_after_s``);
249
+ - sentinel: ``sentinel`` set — a derived state ("token expired" with an
250
+ owner present, ...), recorded as a no-op: sentinels are re-derived every
251
+ pass and never persisted.
252
+ """
253
+
254
+ usage: dict | None = None
255
+ error: str | None = None
256
+ retry_after_s: float | None = None
257
+ sentinel: str | None = None
258
+ # Fingerprint of the credential whose refresh token was POSTed when a
259
+ # permanent auth error came back. Strikes bind to it: token_dead() holds
260
+ # only while the stored credential still fingerprints to the struck
261
+ # generation, so any credential-writing path heals the strike without a
262
+ # bespoke clear call. None on non-auth outcomes (and from writers that
263
+ # predate the field — those strikes bind unconditionally, the legacy
264
+ # behavior).
265
+ struck_fp: str | None = None
266
+ # Hash of the access token a live session's read-only fetch was refused
267
+ # with. Rides on the sentinel and is the one thing a sentinel record
268
+ # persists: later passes skip the request while the credential still
269
+ # carries that token, and a success clears it.
270
+ rejected_fp: str | None = None
271
+
272
+
273
+ @dataclass(frozen=True)
274
+ class UsageEntry:
275
+ """Read model of one account's usage state at collect time.
276
+
277
+ ``sentinel`` is the collector's live overlay (never persisted); all other
278
+ fields mirror the stored row, except ``age_s`` (the age of ``last_good``)
279
+ and ``trust_extended``, both computed at snapshot time.
280
+ """
281
+
282
+ sentinel: str | None = None
283
+ last_good: dict | None = None
284
+ fetched_at: float | None = None
285
+ age_s: float | None = None
286
+ last_attempt_at: float | None = None
287
+ consecutive_failures: int = 0
288
+ last_error: str | None = None
289
+ backoff_until: float | None = None
290
+ next_poll_at: float | None = None
291
+ poll_interval_s: float | None = None
292
+ # When this token last answered 429 (any Retry-After). Deliberately NOT
293
+ # cleared by a later success: the planner keeps the cadence floored at
294
+ # poll_policy.POST_429_MIN_INTERVAL_S until RECENT_429_WINDOW_S has
295
+ # passed, giving the saturated rolling-hour window time to age out.
296
+ last_429_at: float | None = None
297
+ # Consecutive permanent-auth failures (``invalid_grant``). At or above
298
+ # AUTH_DEAD_STRIKES the token is treated as dead: see ``token_dead``.
299
+ auth_dead_strikes: int = 0
300
+ # Fingerprint of the generation the strikes condemned (absent on legacy
301
+ # rows → strikes bind unconditionally). See ``token_dead``.
302
+ struck_fingerprint: str | None = None
303
+ # The refused access token a live session's fetch stamped (see
304
+ # ``FetchRecord.rejected_fp``); None once a fetch succeeds.
305
+ rejected_fingerprint: str | None = None
306
+ # Staleness past STALE_OK_S is still decision-trusted when it is
307
+ # *deliberate*: the server is refusing fresher data (failure state), or the
308
+ # scheduler itself chose the cadence (within nextPollAt). Capped at
309
+ # TRUST_MAX_AGE_S. Computed by UsageStore.entries().
310
+ trust_extended: bool = False
311
+ # Appended to preserve positional compatibility for the older read-model
312
+ # fields while exposing whether a fetch lease is currently live.
313
+ claim_until: float | None = None
314
+ # Until when a reading adopted from another machine (``cswap
315
+ # import-usage``) keeps every collector off this slot. Appended for the
316
+ # same positional compatibility as ``claim_until``.
317
+ held_until: float | None = None
318
+
319
+ def fresh(self, now: float, ttl: float = SERVE_TTL_S) -> bool:
320
+ return self.fetched_at is not None and (now - self.fetched_at) <= ttl
321
+
322
+ def in_backoff(self, now: float) -> bool:
323
+ return self.backoff_until is not None and now < self.backoff_until
324
+
325
+ def held(self, now: float) -> bool:
326
+ """Whether an adopted reading's hold still keeps collectors off."""
327
+ return self.held_until is not None and now < self.held_until
328
+
329
+ def recent_429(self, now: float) -> bool:
330
+ """Whether this token 429'd recently enough to keep the post-429 cadence.
331
+
332
+ Recency is measured from when the 429's honored backoff *lifts*, not
333
+ from the 429 itself. An hour-scale Retry-After is honored as one long
334
+ backoff during which no attempt runs, so the only 429 stamp is at the
335
+ block's start; measuring recency from the stamp would make the first
336
+ post-block success (which can't happen until the backoff lifts) see a
337
+ window that has already fully elapsed — the AIMD growth and the
338
+ POST_429 floor would never engage, and machines sharing the token could
339
+ not converge. Anchoring on the backoff's end keeps "recent" true across
340
+ the first post-block success while a short (``Retry-After: 0``) block
341
+ still expires normally. Bounded by ``RECENT_429_WINDOW_S`` past the
342
+ anchor so it clears once the saturated window has aged out.
343
+ """
344
+ if self.last_429_at is None:
345
+ return False
346
+ anchor = self.last_429_at
347
+ # Use the backoff anchor only while the LIVE backoff is a 429 backoff.
348
+ # last429At is never cleared, but backoffUntil/lastError are rewritten by
349
+ # any later failure — so without the lastError guard an unrelated timeout
350
+ # on a token that 429'd long ago would install a fresh backoffUntil and
351
+ # spuriously re-arm the post-429 cadence. Success clears lastError and
352
+ # backoffUntil; only a 429 sets last429At and backoffUntil together.
353
+ if (
354
+ self.last_error == "http-429"
355
+ and self.backoff_until is not None
356
+ and self.backoff_until > anchor
357
+ ):
358
+ anchor = self.backoff_until
359
+ return now < anchor + RECENT_429_WINDOW_S
360
+
361
+ def claimed(self, now: float) -> bool:
362
+ """Whether another collector's bounded fetch lease is still live."""
363
+ return _live_claim(self.claim_until, self.last_attempt_at, now)
364
+
365
+ def token_dead(
366
+ self,
367
+ threshold: int = AUTH_DEAD_STRIKES,
368
+ stored_fp: str | None = None,
369
+ ) -> bool:
370
+ """Whether the stored credential's refresh-token lineage is provably dead.
371
+
372
+ True once ``invalid_grant`` has recurred ``threshold`` times without an
373
+ intervening success. Such an account is quarantined: not fetched (see
374
+ ``due_candidate`` and the collector) and surfaced as "re-login needed".
375
+
376
+ Strikes condemn the GENERATION that was POSTed, not the slot: when
377
+ the caller passes the currently-stored credential's fingerprint and
378
+ it differs from the struck one, the credential has been replaced
379
+ since the verdict — the strike no longer applies (any writing path
380
+ heals it, mirroring #142's identity-not-slot rule). A row struck
381
+ before fingerprints were recorded binds unconditionally.
382
+ """
383
+ if self.auth_dead_strikes < threshold:
384
+ return False
385
+ if (
386
+ stored_fp is not None
387
+ and self.struck_fingerprint is not None
388
+ and stored_fp != self.struck_fingerprint
389
+ ):
390
+ return False
391
+ return True
392
+
393
+ def decision_value(self) -> dict | str | None:
394
+ """The ``dict | sentinel | None`` value switch decisions run on.
395
+
396
+ Sentinel wins; else last-good while it is recent enough to trust
397
+ (≤ ``STALE_OK_S``, or ``trust_extended`` for deliberate staleness);
398
+ else None (unknown). Display code reads ``last_good``/``age_s``
399
+ directly instead — it may show older data, annotated with its age.
400
+ """
401
+ if self.sentinel is not None:
402
+ return self.sentinel
403
+ if (
404
+ self.last_good is not None
405
+ and self.age_s is not None
406
+ and (self.age_s <= STALE_OK_S or self.trust_extended)
407
+ ):
408
+ return self.last_good
409
+ return None
410
+
411
+
412
+ def _plan_oversleeps_interval(
413
+ next_poll_at: float | None,
414
+ poll_interval_s: float | None,
415
+ now: float,
416
+ ) -> bool:
417
+ """Whether a deadline cannot have come from the bounded planner."""
418
+ if next_poll_at is None:
419
+ return False
420
+ interval = max(poll_interval_s or EXHAUSTED_INTERVAL_S, EXHAUSTED_INTERVAL_S)
421
+ latest_normal_poll = now + interval * (1.0 + JITTER_FRAC) + RESET_SLACK_S
422
+ return next_poll_at > latest_normal_poll
423
+
424
+
425
+ def plan_oversleeps_interval(entry: UsageEntry, now: float) -> bool:
426
+ """Whether a row carries an obsolete reset-parked plan.
427
+
428
+ Reset-parking releases stored a distant reset deadline while retaining the
429
+ much shorter learned interval. Detect that impossible shape structurally,
430
+ independent of the current model selection, so changing scoped models
431
+ cannot leave an otherwise usable account parked until the old reset.
432
+ """
433
+ return _plan_oversleeps_interval(
434
+ entry.next_poll_at,
435
+ entry.poll_interval_s,
436
+ now,
437
+ )
438
+
439
+
440
+ def due_candidate(
441
+ candidates: list[str], entries: dict[str, UsageEntry], now: float
442
+ ) -> str | None:
443
+ """The due candidate least recently attempted or measured, or None.
444
+
445
+ Due = past its ``nextPollAt``, not in failure backoff and not held for
446
+ another machine's reading (``UsageStore.adopt``). Sentinel
447
+ accounts (api-key / no credentials) have nothing to fetch. A
448
+ perpetually failing account can't monopolize the slot: its backoff
449
+ removes it from the due set between attempts.
450
+
451
+ The auto engine's one-alternate-per-tick pick. Poll plans
452
+ (``nextPollAt``/``pollIntervalS``) are written by whichever collector
453
+ fetched (see the plan persistence in ``_collect_usage_entries``), so
454
+ every surface inherits the same adaptive cadence.
455
+ """
456
+ due: list[tuple[float, str]] = []
457
+ for num in candidates:
458
+ entry = entries.get(num)
459
+ if entry is None:
460
+ due.append((0.0, num))
461
+ continue
462
+ if entry.sentinel is not None:
463
+ continue
464
+ if entry.token_dead():
465
+ continue # dead refresh-token: quarantined, needs a re-login
466
+ if entry.in_backoff(now):
467
+ continue
468
+ if entry.held(now):
469
+ continue
470
+ if (
471
+ entry.next_poll_at is not None
472
+ and now < entry.next_poll_at
473
+ and not plan_oversleeps_interval(entry, now)
474
+ ):
475
+ continue
476
+ # Least recently touched wins: the last attempt (``reserve`` stamps
477
+ # it on every claim) or the last measurement, whichever is later. A
478
+ # fetch-path sentinel -- a live session's expired or refused
479
+ # credential -- records no measurement, plan or backoff, so keyed on
480
+ # ``fetchedAt`` alone that slot stayed the stalest due row and took
481
+ # this pick every tick while the other alternates went unpolled;
482
+ # keyed on the attempt, a no-op pick rotates to the back and only
483
+ # fills ticks nothing else is due on, where re-deriving it costs no
484
+ # request. An adopted reading (``adopt``) moves ``fetchedAt`` with no
485
+ # attempt, hence the later of the two. A never-touched row keys 0.
486
+ due.append(
487
+ (max(entry.fetched_at or 0.0, entry.last_attempt_at or 0.0), num)
488
+ )
489
+ if not due:
490
+ return None
491
+ due.sort()
492
+ return due[0][1]
493
+
494
+
495
+ def _earliest_reset(last_good: dict | None, models: tuple[str, ...] = ()) -> float | None:
496
+ """Epoch of the soonest relevant window to roll over, or None if unknown.
497
+
498
+ The soonest one is what matters: once it resets, usage there is zeroed and
499
+ the whole snapshot is obsolete, so a later window cannot rescue it. Windows
500
+ carrying no ``resets_at`` contribute nothing rather than a guess. A
501
+ non-dict ``last_good`` needs no guard here: ``oauth.relevant_windows``
502
+ already returns ``[]`` for any non-dict input.
503
+ """
504
+ resets = [
505
+ ts
506
+ for _, _, resets_at in oauth.relevant_windows(last_good, models)
507
+ if (ts := parse_reset_ts(resets_at)) is not None
508
+ ]
509
+ return min(resets) if resets else None
510
+
511
+
512
+ def _rate_limited_trust_ok(
513
+ last_good: dict | None,
514
+ age_s: float | None,
515
+ now: float,
516
+ models: tuple[str, ...] = (),
517
+ ) -> bool:
518
+ """Whether 429-stale ``last_good`` is still trustworthy for decisions.
519
+
520
+ Usage rises monotonically within a window, so a rate-limited (frozen)
521
+ last_good is a valid lower bound until its window resets — but only up to a
522
+ client-side ceiling, so a far-future or malformed ``resets_at`` can never
523
+ grant unbounded trust. The bound is:
524
+
525
+ now < min(earliest future relevant-window reset, age-ceiling)
526
+
527
+ - **earliest** relevant-window reset (not latest): once the *soonest*
528
+ window rolls over, usage there is zeroed and the whole snapshot is
529
+ obsolete — a later window's reset can't rescue it. So if the earliest
530
+ known reset is already in the past, the value is untrusted outright,
531
+ regardless of any farther-future window.
532
+ - **age-ceiling** (``RATE_LIMIT_TRUST_MAX_AGE_S`` past ``last_good``): the
533
+ hard client-side cap. It applies whether or not any reset is known, so
534
+ even an all-``resets_at`` response — including a far-future or malformed
535
+ one — is bounded, matching the ~1h stale fallback Claude Code itself uses.
536
+ Rows with no reset info at all fall back to it alone.
537
+
538
+ A window carrying no ``resets_at`` simply contributes no timestamp; it never
539
+ extends trust, so partial metadata can only tighten the bound, never loosen
540
+ it. ``models`` selects the per-model scoped windows that also gate the
541
+ account, so their resets are considered too (matching the scheduler's view).
542
+ """
543
+ if age_s is None:
544
+ return False
545
+ ceiling = now + (RATE_LIMIT_TRUST_MAX_AGE_S - age_s)
546
+ soonest = _earliest_reset(last_good, models)
547
+ # The soonest window to roll over invalidates the snapshot; never trust past
548
+ # it, and never past the client-side ceiling.
549
+ return now < (min(soonest, ceiling) if soonest is not None else ceiling)
550
+
551
+
552
+ def _rejection_backoff_until(usage: dict | None, now: float) -> float | None:
553
+ """When a reading from a refused setup-token header probe (``rejected``
554
+ with a Retry-After, see ``oauth.request_usage_via_probe``) allows the
555
+ next request, or None. Stored as ``backoffUntil``, which every fetch
556
+ path's eligibility (``_row_eligible``, ``due_candidate``) already honors,
557
+ so no collect probes the account again before the server's deadline.
558
+ Bounded by the same park cap as a 429's ask, so an absurd value cannot
559
+ wedge the row."""
560
+ rejected = usage.get("rejected") if isinstance(usage, dict) else None
561
+ retry_after = rejected.get("retry_after_s") if isinstance(rejected, dict) else None
562
+ if not isinstance(retry_after, (int, float)) or not retry_after > 0:
563
+ return None
564
+ return now + min(float(retry_after), RETRY_AFTER_FLOOR_CAP_S)
565
+
566
+
567
+ def _rejection_deadline(usage: dict | None, now: float) -> float | None:
568
+ """Absolute end of the server's Retry-After on a confirmed probe
569
+ rejection a reading carries, bounded like
570
+ :func:`_rejection_backoff_until`, or None when it is unusable or already
571
+ past. For a reading taken on another machine (:meth:`UsageStore.adopt`)
572
+ the Retry-After was relative to that machine's fetch, so only the
573
+ absolute ``rejected.resets_at`` stamp carries over. Without a positive
574
+ ``retry_after_s`` that stamp is the quota reset the probe copied from the
575
+ unified headers, not a deadline: the local path installs no backoff for
576
+ it either, so bounded polling can still observe an early grant."""
577
+ rejected = usage.get("rejected") if isinstance(usage, dict) else None
578
+ if not isinstance(rejected, dict):
579
+ return None
580
+ retry_after = rejected.get("retry_after_s")
581
+ if not isinstance(retry_after, (int, float)) or not retry_after > 0:
582
+ return None
583
+ ts = parse_reset_ts(rejected.get("resets_at"))
584
+ if ts is None or ts <= now:
585
+ return None
586
+ return min(ts, now + RETRY_AFTER_FLOOR_CAP_S)
587
+
588
+
589
+ def _failure_backoff_s(
590
+ consecutive_failures: int,
591
+ retry_after_s: float | None,
592
+ *,
593
+ rate_limited: bool = True,
594
+ ) -> float:
595
+ """Seconds to stay in backoff after a failed fetch."""
596
+ computed = min(
597
+ BACKOFF_BASE_S * (2 ** min(max(0, consecutive_failures - 1), BACKOFF_MAX_SHIFT)),
598
+ BACKOFF_CAP_S,
599
+ )
600
+ if retry_after_s is None:
601
+ return computed
602
+ if retry_after_s == 0:
603
+ if not rate_limited:
604
+ # `Retry-After: 0` on a non-429 (e.g. a Cloudflare 503 saying
605
+ # "retry now") is not the saturated-budget edge — that rule was
606
+ # measured on the usage endpoint's 429s only (poll_policy
607
+ # docstring; see the ceiling discussion above). Fall through to
608
+ # the plain exponential curve, same as no header at all.
609
+ return computed
610
+ # Saturated-budget edge: wait before probing again.
611
+ return min(max(computed, EDGE_BACKOFF_S), BACKOFF_CAP_S)
612
+ # Burst rule: the server's ask plus a margin (bounded by the cap); our own
613
+ # curve may still wait longer. Only above BACKOFF_CAP_S, because a short
614
+ # ask was separately measured as ACCURATE — not because the curve
615
+ # out-waits it. It does not: at `failures=1` computed is 30s, so a 300s ask
616
+ # lands exactly on the server's deadline, and the claim only becomes true
617
+ # at `failures=6` where computed reaches the cap. Strict: an ask OF exactly
618
+ # BACKOFF_CAP_S is what the saturated curve already waits.
619
+ #
620
+ # RESIDUE: an hour-scale block whose REMAINDER falls under BACKOFF_CAP_S
621
+ # takes no margin and still retries near its deadline. Nothing local
622
+ # separates that ask from a genuine short burst block, so it is left open.
623
+ asked = retry_after_s
624
+ # `rate_limited` gates ONLY the margin below — whether evidence measured
625
+ # on usage-endpoint 429 blocks applies here. It does NOT gate the PARK
626
+ # BOUND a few lines down, which applies to every ask unconditionally.
627
+ # Before this bound was restored, the cap lived inside this same `if`
628
+ # (`min(ask + margin, CAP)`), so `rate_limited` silently answered two
629
+ # unrelated questions — "does the measured margin evidence apply" and
630
+ # "may this ask park a row for a day" — through one flag. Separating them
631
+ # is why the bound is now its own unconditional statement below.
632
+ if retry_after_s > BACKOFF_CAP_S and rate_limited:
633
+ # THE MARGIN IS 429-ONLY, and the ceiling is why. It was measured on
634
+ # usage-endpoint blocks, whose stale data stays decision-trusted until
635
+ # `min(earliest relevant-window reset, fetched_at +
636
+ # RATE_LIMIT_TRUST_MAX_AGE_S)` — not the age-ceiling alone. A window
637
+ # that resets before the ceiling ends trust first, so the 4500s wait
638
+ # does NOT always sit inside its own trust: an earlier reset can leave
639
+ # the row un-pollable (still in backoff) and unknown (trust expired)
640
+ # for the remainder of the wait — see
641
+ # `test_a_soon_resetting_window_can_end_trust_before_the_429_wait_releases`.
642
+ #
643
+ # AND THE EARLY RESET IS ONLY ONE WAY IN. The age-ceiling half opens
644
+ # the same gap with no early reset at all, because `record()` writes
645
+ # `fetchedAt` on SUCCESS only: a chain of failed blocks keeps measuring
646
+ # trust from the first success while each block adds another full wait.
647
+ # Measured with far-future resets only, so only the ceiling can bind:
648
+ #
649
+ # block 1 wait [ 0, 4500] trust ends 7200 blind 0s
650
+ # block 2 wait [ 4500, 9000] trust ends 7200 blind 1800s
651
+ # block 3 wait [ 9000, 13500] trust ends 7200 blind 4500s
652
+ #
653
+ # So the gap is bounded PER BLOCK and not across a chain — by block 3
654
+ # the row is blind for the whole wait. That is the tradeoff this margin
655
+ # makes in exchange for fewer requests, and it is worth stating at its
656
+ # true size rather than as a single-block figure.
657
+ #
658
+ # WHAT ACTUALLY BOUNDS IT is the identity `cap == 3600 + MARGIN` in
659
+ # `test_the_cap_sits_inside_the_trust_it_relies_on`, NOT the
660
+ # `cap <= RATE_LIMIT_TRUST_MAX_AGE_S` inequality that test also states.
661
+ # The inequality admits [4500, 7200], and at 7200 an ask of 6300s or
662
+ # more pushes the wait itself to 7200, taking the same three blocks
663
+ # from 6300s to 14400s blind (2.3x). Reason about this from blind
664
+ # time; the constant comparison does not imply it. Pinned by
665
+ # `test_consecutive_blocks_go_blind_because_fetchedAt_only_moves_on_success`.
666
+ #
667
+ # Every other failure falls back to TRUST_MAX_AGE_S = 3600s — and
668
+ # `_classify_usage_error` parses Retry-After for ANY HTTPError code,
669
+ # not just 429. A 503 carrying `Retry-After: 3600` therefore took the
670
+ # margin and waited 4500s while its last_good went untrusted at 3600s:
671
+ # 900s in which the row can neither be re-polled (still in backoff) nor
672
+ # used (unknown), and the unhealthy-tick counter reads that blindness
673
+ # as a failing account and fails over. Measured: blind window 179s ->
674
+ # 1079s, and (at a 120s tick interval, 3 unhealthy ticks) a failover
675
+ # at +3781s that main never performs.
676
+ #
677
+ # Capping the constant instead would land a 3600s ask exactly on its
678
+ # deadline — the defect this whole change exists to fix.
679
+ #
680
+ # No cap here: `min(x, RETRY_AFTER_FLOOR_CAP_S)` would be redundant
681
+ # with the PARK BOUND below, which still applies
682
+ # `RETRY_AFTER_FLOOR_CAP_S` unconditionally on this (`rate_limited`)
683
+ # arm — `min(min(x, c), c) == min(x, c)`. Re-verified after B1 (the
684
+ # PARK BOUND split by arm): still dead, because this branch is only
685
+ # reached when `rate_limited` is True, and that is exactly the arm
686
+ # the PARK BOUND still caps at `RETRY_AFTER_FLOOR_CAP_S`. Confirmed
687
+ # by mutation: adding it back (`min(x, RETRY_AFTER_FLOOR_CAP_S)`
688
+ # around the line below) survives the full suite.
689
+ asked = retry_after_s + RETRY_AFTER_MARGIN_S
690
+ # PARK BOUND — every ask is capped, but by the ceiling ITS OWN arm's trust
691
+ # actually uses, not a single shared constant. This restores nothing about
692
+ # trust: `entries()` still reads the row unknown once the relevant ceiling
693
+ # elapses past the last SUCCESS, exactly as before this line, so a capped
694
+ # ask can still be released un-pollable and unknown together. What this
695
+ # bounds is the PARK itself — how long the row can be held un-pollable —
696
+ # not whether it is trusted at the end of it.
697
+ #
698
+ # Without it BOTH arms are at risk of outliving their own trust:
699
+ # `_classify_usage_error` (oauth.py) parses Retry-After for ANY HTTPError
700
+ # code, not just 429, and the usage endpoint sits behind Cloudflare, which
701
+ # emits Retry-After on 503s as routine overload signaling. Measured: a
702
+ # `503 Retry-After: 86400` parks the row 24h, and `Retry-After: inf`
703
+ # (Python parses "inf", "Infinity", and any overflow literal like "1e400"
704
+ # to `float('inf')`) wedges the row permanently — `json.dumps` writes the
705
+ # non-standard `Infinity` literal, which survives a restart.
706
+ #
707
+ # A PRIOR REVISION reused RETRY_AFTER_FLOOR_CAP_S (4500) for both arms,
708
+ # reasoning "one answer to how long any ask can park a row". That is
709
+ # wrong for the non-429 arm: `entries()` reads a non-429 row unknown once
710
+ # TRUST_MAX_AGE_S (3600) elapses past the last success, not
711
+ # RETRY_AFTER_FLOOR_CAP_S — so a non-429 ask above 3600 parked the row
712
+ # 900s past its own trust: blind (un-pollable AND unknown) for that whole
713
+ # margin. See `test_each_arm_is_bounded_by_the_ceiling_its_own_trust_uses`.
714
+ # The 429 arm keeps RETRY_AFTER_FLOOR_CAP_S (4500), correctly inside its
715
+ # own ceiling RATE_LIMIT_TRUST_MAX_AGE_S (7200).
716
+ #
717
+ # CORRECTED 2026-08-03 — the line above does NOT close the blind window
718
+ # in general, on either arm, and an earlier version of this comment
719
+ # wrongly claimed it did ("a regression this PR introduced against
720
+ # upstream/main ... the blind window was always 0"). That is false,
721
+ # measured. The bound below compares the wrong pair of quantities:
722
+ # `asked` is a DURATION measured from the FAILURE (now), but the ceiling
723
+ # it is capped against (`RETRY_AFTER_FLOOR_CAP_S` / `TRUST_MAX_AGE_S`) is
724
+ # an AGE measured from the last SUCCESS (`fetchedAt`), which `entries()`
725
+ # actually uses. Those agree only when the row was already fresh (age 0)
726
+ # at the moment it failed. On the arm measured directly below (non-429,
727
+ # whose park cap equals the trust ceiling it is checked against) the gap
728
+ # reduces to the row's AGE AT FAILURE, up to the whole park — but that is
729
+ # an ARM-SPECIFIC coincidence, not the general rule: see the general
730
+ # closed form and the 429-arm numbers further down, where cap and
731
+ # ceiling are different constants and the identity does not hold.
732
+ # Measured end-to-end through `store.record()` / `entries().decision_
733
+ # value()`, with a control (row already fresh at failure -> no gap):
734
+ #
735
+ # age@fail ask park blind starts verdict
736
+ # 0 5000 3600 0 None ok <- CONTROL
737
+ # 1 5000 3600 0 None ok
738
+ # 120 5000 3600 119 3481.0 blind
739
+ # 300 5000 3600 299 3301.0 blind
740
+ # 1800 5000 3600 1799 1801.0 blind
741
+ # 3599 5000 3600 3598 2.0 blind
742
+ # 300 4000 3600 299 3301.0 blind
743
+ # 300 3600 3600 299 3301.0 blind
744
+ # 300 600 600 0 None ok
745
+ #
746
+ # Blind = the row is in backoff (un-pollable) AND `decision_value()` is
747
+ # None (unknown) at the same instant. Every row above is the non-429
748
+ # (`rate_limited=False`) arm, where the park cap equals TRUST_MAX_AGE_S
749
+ # (3600) exactly — the ask=4000/3600 rows show the SAME park (3600) as
750
+ # ask=5000 once the ask exceeds the ceiling, and ask=600 shows a park
751
+ # shorter than the ceiling never goes blind at all (its own curve is the
752
+ # binding constraint, not the ceiling). On THIS ARM, and only this arm,
753
+ # "the blind window equals the age at failure" holds — because the cap
754
+ # (TRUST_MAX_AGE_S) and the trust ceiling `entries()` actually reads
755
+ # against (also TRUST_MAX_AGE_S) are the SAME constant, so they cancel.
756
+ # General form, both arms: `blind = age_at_fail - (ceiling - park)`,
757
+ # where `ceiling` is RATE_LIMIT_TRUST_MAX_AGE_S (7200) on the 429 arm and
758
+ # TRUST_MAX_AGE_S (3600) on the non-429 arm above. It equals the age at
759
+ # failure only where `ceiling == park`, which is true on the non-429 arm
760
+ # (3600 == 3600) and false on the 429 arm (7200 != 4500).
761
+ #
762
+ # CORRECTED 2026-08-03 (round 8) — the paragraph that used to sit here
763
+ # said this is "PRE-EXISTING, not a regression this PR introduced",
764
+ # backed by a byte-identical table against a real upstream/main
765
+ # worktree. Both halves are true and together prove nothing about this
766
+ # PR: the table above is entirely the non-429 arm, whose cap
767
+ # (TRUST_MAX_AGE_S = 3600) this PR does not touch — of course it is
768
+ # byte-identical to upstream, whose non-429 cap is also 3600. The arm
769
+ # this PR DOES change is the 429 arm (RETRY_AFTER_FLOOR_CAP_S: upstream
770
+ # 3600 -> this PR's 4500), and there the blind window regresses. Same
771
+ # probe, `error="http-429"`, ask=3600 (so the margin-adjusted ask always
772
+ # exceeds the cap on both trees):
773
+ #
774
+ # age@fail PR park PR blind upstream park upstream blind
775
+ # 0 4500 0 3600 0
776
+ # 2701 4500 1 3600 0 <- +1s
777
+ # 3600 4500 900 3600 0 <- +900s
778
+ # 5000 4500 2300 3600 1400 <- +900s
779
+ #
780
+ # Onset moves from age 3600 (upstream) to age 2700 (this PR) — 900s
781
+ # earlier — and every age past onset is a flat +900s worse than
782
+ # upstream. This is reachable with no contrived staleness: after one 429
783
+ # block the row's age at the next failure IS the park length, so a real
784
+ # chain of blocks compounds it (see `test_park_bound_blind_window_
785
+ # equals_age_at_failure`'s 429-arm cases and the DECISION note below).
786
+ # `autoswitch.py` reads a blind row as `active_headroom is None` and
787
+ # turns it into failover pressure — the exact downstream consequence
788
+ # round 6 was written to remove, and on the 429 arm this PR makes it
789
+ # worse than upstream, not merely pre-existing.
790
+ #
791
+ # DECISION: left open in this PR, not closed, WITH the true 429 numbers
792
+ # above (not the ones an earlier round of this comment cited).
793
+ #
794
+ # CORRECTED 2026-08-03 (round 10) — this block used to defer the fix on
795
+ # the claim that it "needs `_failure_backoff_s` to know the row's age at
796
+ # the moment it failed — a real signature change" that "ripples well
797
+ # past this bound". That is false, measured: `record()` already computes
798
+ # `row["backoffUntil"] = now + _failure_backoff_s(...)` at the one call
799
+ # site (usage_store.py, in `record()`'s failure branch) and already
800
+ # holds `fetchedAt` in the same row. Clamping the PRODUCT there —
801
+ # `min(now + _failure_backoff_s(...), fetchedAt + ceiling)` — needs no
802
+ # change to this function's signature and touches none of the tests that
803
+ # call it directly:
804
+ #
805
+ # as shipped : park 4500s blind 900s
806
+ # call-site clamp min(now+wait, fetchedAt+ceiling) : park 3600s blind 0s
807
+ # _failure_backoff_s signature UNCHANGED : 4500s still returned
808
+ #
809
+ # The real reason to keep this open is the one below, not the signature
810
+ # claim: that call-site clamp is the SAME trim NO TRUST TRIM AGAINST THE
811
+ # SERVER'S DEADLINE (a few lines down) spent a full section arguing
812
+ # against removing — it bounds `backoffUntil` against
813
+ # `fetchedAt + ceiling`, exactly the quantity that section calls a no-op-
814
+ # or-futile clip. Measured driving one 3600s block at three row ages:
815
+ #
816
+ # age@open=0 AS SHIPPED 1 request, lands deadline+900s
817
+ # CLAMPED 1 request, lands deadline+900s <- no-op, matches the trim's own finding
818
+ # age@open=3600 AS SHIPPED 1 request, lands deadline+900s
819
+ # CLAMPED 1 request, lands deadline+0s <- lands ON the deadline: the defect this PR fixes
820
+ # age@open=7000 AS SHIPPED 1 request, lands deadline+900s
821
+ # CLAMPED many requests, does not cleanly converge <- the request storm the trim section measured
822
+ #
823
+ # So the clamp is not a smaller, safer version of the removed trim — past
824
+ # the ceiling it reproduces the same request-storm failure mode that trim
825
+ # was measured to cause, with the same ceiling. A follow-up landing this
826
+ # needs the same episode measurement the trim section did before it can
827
+ # ship, not merely a signature check. Tracked as a follow-up, not fixed
828
+ # here.
829
+ asked = min(asked, RETRY_AFTER_FLOOR_CAP_S if rate_limited else TRUST_MAX_AGE_S)
830
+ # NO TRUST TRIM AGAINST THE SERVER'S DEADLINE. Cutting a 429 wait back to
831
+ # the deadline when the stored trust expires first cannot salvage that
832
+ # trust — `trust < ask` is its own precondition and the floor keeps
833
+ # `wait >= ask`, so the row is untrusted at release either way (measured:
834
+ # fired 35 of 180 offsets, salvaged 0). It only lands us on the deadline,
835
+ # where 10 of 19 lapses re-block for a fresh hour (as measured when this
836
+ # was derived — the re-block fraction has since moved to 20 of 35
837
+ # (re-measured 2026-08-03, method corrected round 8: see
838
+ # RETRY_AFTER_MARGIN_S); the episode model below is not re-derived at the
839
+ # new fraction, since it concerns the removed 429 trust-trim and is out
840
+ # of the live path).
841
+ # Episode model on the original number, 3600 runs:
842
+ #
843
+ # with the trim blind 1148s requests 1.21
844
+ # without it blind 550s requests 1.00
845
+ #
846
+ # NOR AGAINST OUR OWN. A previous round clipped the wait to the row's
847
+ # remaining trust, reading `min(earliest reset, fetchedAt + ceiling)` as a
848
+ # second, independent deadline. It is not one, for two reasons.
849
+ #
850
+ # The clip is a no-op or it is futile, with no third case. Where
851
+ # `trust_left >= wait` it changes nothing; where `trust_left < wait` it
852
+ # returns `max(trust_left, computed) >= trust_left`, so the row is unknown
853
+ # at release by construction — "still trusted at release" would need
854
+ # `release < trust_left`, which that same expression forbids. Enumerated
855
+ # over every positive ask and every reachable `trust_left`: 12,188,000
856
+ # evaluations, 5,616,144 shortened a wait, 0 released with the row trusted.
857
+ #
858
+ # And the wait cannot move the deadline it was clipping against.
859
+ # `entries()` decides trust from `lastGood`/`fetchedAt`, which `record()`
860
+ # writes in the SUCCESS branch only — a 429 refreshes neither. So the
861
+ # instant the row goes unknown is fixed by the last successful fetch, and a
862
+ # shorter wait only samples that same instant more often, one request each.
863
+ # Un-pollable and unknown are independent axes; the previous round treated
864
+ # them as one window and tried to close the second by shortening the first.
865
+ #
866
+ # What the clip cost, measured over reset offsets 1..7200s against a 3600s
867
+ # block (requests spent inside the block, and seconds unknown before a poll
868
+ # could next succeed):
869
+ #
870
+ # clipped 3.95 requests (worst 10) 73525s
871
+ # unclipped 1.00 requests (worst 1) 1406s
872
+ #
873
+ # Worse on both axes, because the usage endpoint's 429 is a REQUEST-RATE
874
+ # block, not a quota-window one: `poll_policy` measured ~28-30 requests
875
+ # per trailing hour per budget identity, where "capacity returns only as
876
+ # old requests age out". A 5h/7d/scoped reset is a different axis and cannot lift it,
877
+ # while every extra retry is itself a request in that trailing hour — so
878
+ # the retries push out the very horizon they are retrying against.
879
+ return max(asked, computed)
880
+
881
+
882
+ class UsageStore:
883
+ """The ``cache/usage.json`` table. All writes go read-modify-write under
884
+ ``cache/.usage.lock``; reads are lock-free (writes are atomic replaces).
885
+
886
+ Every method takes the caller's current ``identities`` map (slot number →
887
+ ``(email, organizationUuid)``) and only ever touches rows for those slots:
888
+ a row whose stored identity differs is invisible to reads and replaced on
889
+ write, so slot reuse never serves the previous account's usage. Rows for
890
+ slots outside the map are left alone (callers like ``--status`` operate
891
+ on a single slot).
892
+ """
893
+
894
+ def __init__(self, cache_dir: Path, clock: Callable[[], float] = time.time):
895
+ self.path = cache_dir / "usage.json"
896
+ self._lock_path = cache_dir / ".usage.lock"
897
+ self.clock = clock
898
+
899
+ # -- raw I/O ------------------------------------------------------------
900
+
901
+ def _lock(self) -> FileLock:
902
+ return FileLock(self._lock_path)
903
+
904
+ def _read_rows(self) -> dict[str, dict]:
905
+ try:
906
+ raw = json.loads(self.path.read_text(encoding="utf-8"))
907
+ except (OSError, json.JSONDecodeError, UnicodeDecodeError):
908
+ return {}
909
+ if not isinstance(raw, dict) or raw.get("schemaVersion") != SCHEMA_VERSION:
910
+ return {} # legacy snapshot or future schema: start empty
911
+ rows = raw.get("accounts")
912
+ return rows if isinstance(rows, dict) else {}
913
+
914
+ def _write_rows(self, rows: dict[str, dict]) -> None:
915
+ atomic_write_json(
916
+ self.path, {"schemaVersion": SCHEMA_VERSION, "accounts": rows}
917
+ )
918
+
919
+ @staticmethod
920
+ def _matches(row: object, identity: Identity) -> bool:
921
+ return (
922
+ isinstance(row, dict)
923
+ and row.get("email") == identity[0]
924
+ and row.get("organizationUuid", "") == identity[1]
925
+ )
926
+
927
+ def _fresh_row(self, identity: Identity) -> dict:
928
+ return {"email": identity[0], "organizationUuid": identity[1]}
929
+
930
+ # -- read model -----------------------------------------------------------
931
+
932
+ def entries(
933
+ self,
934
+ identities: dict[str, Identity],
935
+ models: tuple[str, ...] = (),
936
+ ) -> dict[str, UsageEntry]:
937
+ """Identity-guarded snapshot for the given slots (empty entry when the
938
+ row is missing or belongs to a different account).
939
+
940
+ ``models`` are the configured scoped-window model names; they let the
941
+ 429-stale trust bound also honor per-model (e.g. Fable) window resets,
942
+ matching the scheduler's window view. Omitted (``()``) for callers that
943
+ only read timestamps/last-good and never consult scoped resets."""
944
+ now = self.clock()
945
+ rows = self._read_rows()
946
+ out: dict[str, UsageEntry] = {}
947
+ for num, identity in identities.items():
948
+ row = rows.get(num)
949
+ if not self._matches(row, identity):
950
+ out[num] = UsageEntry()
951
+ continue
952
+ assert isinstance(row, dict)
953
+ fetched_at = row.get("fetchedAt")
954
+ if not isinstance(fetched_at, (int, float)):
955
+ fetched_at = None
956
+ last_good = row.get("lastGood")
957
+ age_s = (now - fetched_at) if fetched_at is not None else None
958
+ consecutive_failures = int(row.get("consecutiveFailures") or 0)
959
+ next_poll_at = _num_or_none(row.get("nextPollAt"))
960
+ last_attempt_at = _num_or_none(row.get("lastAttemptAt"))
961
+ claim_until = _num_or_none(row.get("claimUntil"))
962
+ held_until = _num_or_none(row.get("heldUntil"))
963
+ # Strict < mirrors due_candidate: at nextPollAt the entry is due,
964
+ # its staleness no longer scheduler-chosen. A live claim keeps the
965
+ # trust bridge up: when another collector just won the fetch, this
966
+ # reader must not flip trusted → unknown (and e.g. count an
967
+ # unhealthy tick) for the seconds the result is in flight.
968
+ # A usage-endpoint 429 throttles polling without moving the
969
+ # account's real windows. Usage is monotone within a window, so
970
+ # last_good is a valid lower bound until that window resets: trust it
971
+ # right up to the earliest future reset (data-driven, no fixed
972
+ # clock). Rows with no reset info fall back to a bounded ceiling. A
973
+ # non-429 failure (timeout/network) is no evidence last_good still
974
+ # holds, so it always uses the general ceiling.
975
+ if row.get("lastError") == "http-429":
976
+ within_ceiling = _rate_limited_trust_ok(
977
+ last_good if isinstance(last_good, dict) else None,
978
+ age_s,
979
+ now,
980
+ models,
981
+ )
982
+ else:
983
+ within_ceiling = age_s is not None and age_s <= TRUST_MAX_AGE_S
984
+ live_claim = _live_claim(claim_until, last_attempt_at, now)
985
+ # A live hold is deliberate staleness as well: another machine
986
+ # polls this account and hands its readings over, so between two
987
+ # hand-overs the last one is what decisions should run on.
988
+ held = held_until is not None and now < held_until
989
+ trust_extended = (
990
+ within_ceiling
991
+ and (
992
+ consecutive_failures > 0
993
+ or (next_poll_at is not None and now < next_poll_at)
994
+ or live_claim
995
+ or held
996
+ )
997
+ )
998
+ out[num] = UsageEntry(
999
+ last_good=last_good if isinstance(last_good, dict) else None,
1000
+ fetched_at=fetched_at,
1001
+ age_s=age_s,
1002
+ last_attempt_at=last_attempt_at,
1003
+ consecutive_failures=consecutive_failures,
1004
+ last_error=row.get("lastError"),
1005
+ backoff_until=_num_or_none(row.get("backoffUntil")),
1006
+ next_poll_at=next_poll_at,
1007
+ poll_interval_s=_num_or_none(row.get("pollIntervalS")),
1008
+ last_429_at=_num_or_none(row.get("last429At")),
1009
+ auth_dead_strikes=int(row.get("authDeadStrikes") or 0),
1010
+ struck_fingerprint=row.get("struckFingerprint"),
1011
+ rejected_fingerprint=row.get("rejectedFingerprint"),
1012
+ trust_extended=trust_extended,
1013
+ claim_until=claim_until,
1014
+ held_until=held_until,
1015
+ )
1016
+ return out
1017
+
1018
+ # -- writes ---------------------------------------------------------------
1019
+
1020
+ def _mutate(
1021
+ self,
1022
+ identities: dict[str, Identity],
1023
+ nums: Iterable[str],
1024
+ mutator: Callable[[str, dict], None],
1025
+ ) -> None:
1026
+ """Read-modify-write rows for ``nums`` under the lock. A row whose
1027
+ stored identity mismatches is replaced with a fresh one first."""
1028
+ with self._lock():
1029
+ rows = self._read_rows()
1030
+ for num in nums:
1031
+ identity = identities[num]
1032
+ if not self._matches(rows.get(num), identity):
1033
+ rows[num] = self._fresh_row(identity)
1034
+ mutator(num, rows[num])
1035
+ self._write_rows(rows)
1036
+
1037
+ def claim(
1038
+ self, nums: Iterable[str], identities: dict[str, Identity]
1039
+ ) -> dict[str, str]:
1040
+ """Lease the slots about to be fetched, returning their fencing ids."""
1041
+ nums = list(nums)
1042
+ if not nums:
1043
+ return {}
1044
+ now = self.clock()
1045
+ claims = {num: uuid.uuid4().hex for num in nums}
1046
+ self._mutate(
1047
+ identities,
1048
+ nums,
1049
+ lambda num, row: row.update(
1050
+ lastAttemptAt=now,
1051
+ claimId=claims[num],
1052
+ claimUntil=now + CLAIM_TTL_S,
1053
+ ),
1054
+ )
1055
+ return claims
1056
+
1057
+ def reserve(
1058
+ self,
1059
+ nums: Iterable[str],
1060
+ identities: dict[str, Identity],
1061
+ *,
1062
+ respect_plans: bool,
1063
+ repair_overslept: bool = False,
1064
+ struck_ok: Iterable[str] = (),
1065
+ ) -> dict[str, str]:
1066
+ """Atomically win the right to fetch: re-check eligibility and stamp
1067
+ a bounded lease in one locked pass, returning slot → fencing id.
1068
+
1069
+ Deciding eligibility on a lock-free :meth:`entries` read and then
1070
+ claiming separately lets two collectors both pass the check and both
1071
+ fetch; the re-check under the lock closes that window. Eligibility:
1072
+ not quarantined (dead token), not in failure backoff, not held for
1073
+ another machine's reading (:meth:`adopt`), not claimed within
1074
+ ``CLAIM_TTL_S``, and then by caller mode —
1075
+
1076
+ - ``respect_plans=True`` (on-demand callers: list/status/switch,
1077
+ dashboards): the entry must be stale (older than ``SERVE_TTL_S``)
1078
+ *and* poll-due (past ``nextPollAt``, or no plan yet). When
1079
+ ``repair_overslept`` is set, a structurally obsolete reset-parked
1080
+ plan is also due; that predicate is re-checked under this lock.
1081
+ - ``respect_plans=False`` (the auto engine's deliberate schedule):
1082
+ poll-due *or* stale — a due entry may be re-fetched inside the
1083
+ serve TTL (that is how the bounded urgent cadence beats the TTL),
1084
+ and an escalation refresh may fetch a not-yet-due candidate. With
1085
+ ``repair_overslept``, this becomes the non-escalating scheduler mode:
1086
+ due plans and stale impossible plans win, but valid future plans do
1087
+ not.
1088
+
1089
+ ``struck_ok`` names slots the dead-token gate does not hold back: the
1090
+ caller has found a login for them other than the struck generation
1091
+ and will save it before it fetches. Every other gate still applies,
1092
+ so the attempt is paced like any fetch, and the strike itself is left
1093
+ for the outcome to clear.
1094
+ """
1095
+ nums = list(nums)
1096
+ if not nums:
1097
+ return {}
1098
+ struck_ok = set(struck_ok)
1099
+ now = self.clock()
1100
+ won: dict[str, str] = {}
1101
+ with self._lock():
1102
+ rows = self._read_rows()
1103
+ for num in nums:
1104
+ identity = identities[num]
1105
+ row = rows.get(num)
1106
+ if not self._matches(row, identity):
1107
+ rows[num] = row = self._fresh_row(identity)
1108
+ else:
1109
+ assert isinstance(row, dict)
1110
+ if not _row_eligible(
1111
+ row,
1112
+ now,
1113
+ respect_plans,
1114
+ repair_overslept,
1115
+ struck_ok=num in struck_ok,
1116
+ ):
1117
+ continue
1118
+ claim_id = uuid.uuid4().hex
1119
+ row["lastAttemptAt"] = now
1120
+ row["claimId"] = claim_id
1121
+ row["claimUntil"] = now + CLAIM_TTL_S
1122
+ won[num] = claim_id
1123
+ if won:
1124
+ self._write_rows(rows)
1125
+ return won
1126
+
1127
+ def record(
1128
+ self,
1129
+ outcomes: dict[str, FetchRecord],
1130
+ identities: dict[str, Identity],
1131
+ claims: dict[str, str] | None = None,
1132
+ plans: dict[str, tuple[float | None, float | None]] | None = None,
1133
+ ) -> set[str]:
1134
+ """Merge outcomes fenced by the leases that produced them.
1135
+
1136
+ A late writer whose lease or slot identity was replaced is ignored
1137
+ without touching the newer row. Success and failure are mutually
1138
+ exclusive writers: success resets the failure fields, failure never
1139
+ touches ``lastGood``/``fetchedAt``. A supplied success plan commits
1140
+ in the same transaction as its measurement. Sentinel records clear
1141
+ only the claim and are otherwise never persisted, save the refused
1142
+ credential stamp one may carry. Unfenced callers
1143
+ (no ``claims``) defer to a live lease but never to an expired one.
1144
+ Returns the accepted slots.
1145
+ """
1146
+ if not outcomes:
1147
+ return set()
1148
+ now = self.clock()
1149
+ accepted: set[str] = set()
1150
+
1151
+ def apply(num: str, row: dict) -> None:
1152
+ accepted.add(num)
1153
+ rec = outcomes[num]
1154
+ row["claimId"] = None
1155
+ row["claimUntil"] = 0.0
1156
+ if rec.sentinel is not None:
1157
+ if rec.rejected_fp is not None:
1158
+ row["rejectedFingerprint"] = rec.rejected_fp
1159
+ return
1160
+ row["lastAttemptAt"] = now
1161
+ if rec.error is None:
1162
+ row["lastGood"] = rec.usage
1163
+ row["fetchedAt"] = now
1164
+ # Replace the old, possibly due plan in the outcome transaction
1165
+ # so no collector can slip into a record→replan gap.
1166
+ plan = plans.get(num) if plans is not None else None
1167
+ if plan is not None:
1168
+ row["nextPollAt"], row["pollIntervalS"] = plan
1169
+ row["consecutiveFailures"] = 0
1170
+ row["lastError"] = None
1171
+ # A confirmed probe rejection's Retry-After is a deadline no
1172
+ # collector may fetch before (see _rejection_backoff_until).
1173
+ row["backoffUntil"] = _rejection_backoff_until(rec.usage, now)
1174
+ row["rejectedFingerprint"] = None
1175
+ row["authDeadStrikes"] = 0 # a success proves the token is alive
1176
+ else:
1177
+ failures = int(row.get("consecutiveFailures") or 0) + 1
1178
+ row["consecutiveFailures"] = failures
1179
+ row["lastError"] = rec.error
1180
+ if rec.error == "http-429":
1181
+ # Kept across later successes: the poll planner floors the
1182
+ # cadence while a 429 is recent (see UsageEntry.last_429_at).
1183
+ row["last429At"] = now
1184
+ row["backoffUntil"] = now + _failure_backoff_s(
1185
+ failures,
1186
+ rec.retry_after_s,
1187
+ rate_limited=rec.error == "http-429",
1188
+ )
1189
+ # Only a permanent-auth failure advances the dead-token count; a
1190
+ # transient error (429/timeout) leaves it as-is — it is no
1191
+ # evidence either way and must not reset a real dead-token tally.
1192
+ if rec.error in PERMANENT_AUTH_ERRORS:
1193
+ row["authDeadStrikes"] = int(row.get("authDeadStrikes") or 0) + 1
1194
+ # Additive field (absent/None = legacy unconditional
1195
+ # binding). Always overwrite: a legacy writer's strike
1196
+ # must bind unconditionally, not inherit a stale
1197
+ # fingerprint from an earlier, already-healed strike.
1198
+ row["struckFingerprint"] = rec.struck_fp
1199
+
1200
+ with self._lock():
1201
+ rows = self._read_rows()
1202
+ for num in outcomes:
1203
+ identity = identities[num]
1204
+ row = rows.get(num)
1205
+ expected: str | None = None
1206
+ if claims is not None:
1207
+ expected = claims.get(num)
1208
+ if (
1209
+ expected is None
1210
+ or not self._matches(row, identity)
1211
+ or not isinstance(row, dict)
1212
+ or row.get("claimId") != expected
1213
+ ):
1214
+ continue
1215
+ elif (
1216
+ isinstance(row, dict)
1217
+ and row.get("claimId") is not None
1218
+ # Only a live lease defers an unfenced writer; a crashed
1219
+ # claimer's leftover ticket must age out, not block forever.
1220
+ and now < (_num_or_none(row.get("claimUntil")) or 0.0)
1221
+ ):
1222
+ continue
1223
+ elif not self._matches(row, identity):
1224
+ rows[num] = row = self._fresh_row(identity)
1225
+ assert isinstance(row, dict)
1226
+ apply(num, row)
1227
+ if accepted:
1228
+ self._write_rows(rows)
1229
+ return accepted
1230
+
1231
+ def adopt(
1232
+ self,
1233
+ readings: dict[str, tuple[dict, float]],
1234
+ identities: dict[str, Identity],
1235
+ hold_s: float | None = None,
1236
+ ) -> set[str]:
1237
+ """Merge measurements another machine took for the same accounts.
1238
+
1239
+ ``readings`` maps slot → ``(usage, age_s)``: the usage dict in the
1240
+ shape :func:`oauth.build_usage_result` produces, and how old that
1241
+ measurement was when it was handed over. An age rather than a
1242
+ timestamp, so the two machines' clocks never have to agree:
1243
+ ``fetchedAt`` becomes ``now - age_s`` on this store's clock.
1244
+
1245
+ A reading replaces ``lastGood`` only when it is newer than the stored
1246
+ one, so a measurement this machine made itself is never downgraded.
1247
+ Fetch state (failures, backoff, poll plan, claim) is left alone: it
1248
+ describes this machine's own requests, and a fetch already in flight
1249
+ still records normally when it lands. The one exception is a
1250
+ confirmed probe rejection's deadline (``rejected.resets_at``, see
1251
+ :func:`_rejection_deadline`): the server's refusal binds the account
1252
+ on every machine, so an adopted one extends ``backoffUntil`` the way
1253
+ :meth:`record` does for a local probe, never shortening a later one.
1254
+
1255
+ ``hold_s`` > 0 stamps ``heldUntil``: no collector fetches the slot
1256
+ before then (``_row_eligible``, ``due_candidate``), and its last-good
1257
+ stays decision-trusted meanwhile. The hold never runs past the stored
1258
+ reading's earliest window reset, scoped windows included (after it the
1259
+ reading no longer describes that window), nor past ``TRUST_MAX_AGE_S``
1260
+ from the stored measurement, so a slot cannot sit unfetched on data
1261
+ too old to act on, and a producer that stops renewing it gets ordinary
1262
+ collection back when it lapses. The latest hold replaces an earlier
1263
+ one, so ``hold_s`` 0 lifts it; ``None`` leaves it as it is. Returns
1264
+ the slots whose ``lastGood`` was replaced.
1265
+ """
1266
+ if not readings:
1267
+ return set()
1268
+ now = self.clock()
1269
+ adopted: set[str] = set()
1270
+
1271
+ def apply(num: str, row: dict) -> None:
1272
+ usage, age_s = readings[num]
1273
+ fetched_at = now - max(0.0, age_s)
1274
+ stored = _num_or_none(row.get("fetchedAt"))
1275
+ if stored is None or fetched_at > stored:
1276
+ row["lastGood"] = usage
1277
+ row["fetchedAt"] = fetched_at
1278
+ stored = fetched_at
1279
+ adopted.add(num)
1280
+ deadline = _rejection_deadline(usage, now)
1281
+ current = _num_or_none(row.get("backoffUntil"))
1282
+ if deadline is not None and (current is None or deadline > current):
1283
+ row["backoffUntil"] = deadline
1284
+ if hold_s is None:
1285
+ return
1286
+ held_until = min(now + hold_s, stored + TRUST_MAX_AGE_S)
1287
+ # Every scoped window, not only the models this machine watches:
1288
+ # the store does not know them, and a hold lifted early costs one
1289
+ # fetch at most.
1290
+ reset_at = _earliest_reset(row.get("lastGood"), ("all",))
1291
+ if reset_at is not None:
1292
+ held_until = min(held_until, reset_at)
1293
+ if held_until > now:
1294
+ row["heldUntil"] = held_until
1295
+ else:
1296
+ row.pop("heldUntil", None)
1297
+
1298
+ self._mutate(identities, readings.keys(), apply)
1299
+ return adopted
1300
+
1301
+ def set_poll_plan(
1302
+ self,
1303
+ plans: dict[str, tuple[float | None, float | None]],
1304
+ identities: dict[str, Identity],
1305
+ ) -> None:
1306
+ """Persist the scheduler's per-slot ``(nextPollAt, pollIntervalS)``."""
1307
+ if not plans:
1308
+ return
1309
+
1310
+ def apply(num: str, row: dict) -> None:
1311
+ next_poll_at, interval = plans[num]
1312
+ row["nextPollAt"] = next_poll_at
1313
+ row["pollIntervalS"] = interval
1314
+
1315
+ self._mutate(identities, plans.keys(), apply)
1316
+
1317
+ def clear_dead_token(
1318
+ self,
1319
+ nums: Iterable[str],
1320
+ identities: dict[str, Identity],
1321
+ *,
1322
+ claims: dict[str, str] | None = None,
1323
+ ) -> set[str]:
1324
+ """Lift the dead-token quarantine for slots whose credential was refreshed.
1325
+
1326
+ Called after a re-login/add rewrites a slot's stored credential: the
1327
+ strike count (and the failure/backoff state riding with it) no longer
1328
+ reflects reality, and the account must become fetch-eligible again so the
1329
+ next pass can prove the new token good. A no-op for rows with no strikes.
1330
+
1331
+ Without ``claims`` the row's lease goes with the strike: the caller
1332
+ replaced the credential itself, and a fetch still in flight on the old
1333
+ one must not record.
1334
+
1335
+ A collector passes ``claims``, the slot → lease ids it holds itself
1336
+ (empty when it holds none). It clears on what it read, so it must not
1337
+ take a row away from a fetch in flight:
1338
+
1339
+ - a slot named in ``claims`` is cleared only while that lease is still
1340
+ the row's, and the lease is kept: :meth:`record` then accepts the
1341
+ holder's outcome, and the backoff a failure sets is the row's own;
1342
+ - any other slot is cleared only when it still carries a strike and
1343
+ no live lease is on it. Under a lease, the holder clears it, or a
1344
+ later pass does once the lease has ended. With no strike left,
1345
+ someone else cleared it since the caller looked, and the failure
1346
+ state now on the row belongs to a newer fetch.
1347
+
1348
+ Returns the slots cleared.
1349
+ """
1350
+ nums = list(nums)
1351
+ if not nums:
1352
+ return set()
1353
+ now = self.clock()
1354
+ cleared: set[str] = set()
1355
+
1356
+ def apply(num: str, row: dict) -> None:
1357
+ if claims is None:
1358
+ row["claimId"] = None
1359
+ row["claimUntil"] = 0.0
1360
+ elif num in claims:
1361
+ if row.get("claimId") != claims[num]:
1362
+ return
1363
+ elif not int(row.get("authDeadStrikes") or 0) or _live_claim(
1364
+ _num_or_none(row.get("claimUntil")),
1365
+ _num_or_none(row.get("lastAttemptAt")),
1366
+ now,
1367
+ ):
1368
+ return
1369
+ cleared.add(num)
1370
+ row["authDeadStrikes"] = 0
1371
+ row["struckFingerprint"] = None
1372
+ row["consecutiveFailures"] = 0
1373
+ row["lastError"] = None
1374
+ row["backoffUntil"] = None
1375
+
1376
+ self._mutate(identities, nums, apply)
1377
+ return cleared
1378
+
1379
+
1380
+ def _num_or_none(value: object) -> float | None:
1381
+ return float(value) if isinstance(value, (int, float)) else None
1382
+
1383
+
1384
+ def _row_eligible(
1385
+ row: dict,
1386
+ now: float,
1387
+ respect_plans: bool,
1388
+ repair_overslept: bool = False,
1389
+ *,
1390
+ struck_ok: bool = False,
1391
+ ) -> bool:
1392
+ """Fetch eligibility of a stored row, evaluated under the write lock
1393
+ (see :meth:`UsageStore.reserve` for the two caller modes and
1394
+ ``struck_ok``)."""
1395
+ if not struck_ok and int(row.get("authDeadStrikes") or 0) >= AUTH_DEAD_STRIKES:
1396
+ return False
1397
+ backoff_until = _num_or_none(row.get("backoffUntil"))
1398
+ if backoff_until is not None and now < backoff_until:
1399
+ return False
1400
+ held_until = _num_or_none(row.get("heldUntil"))
1401
+ if held_until is not None and now < held_until:
1402
+ return False
1403
+ if _live_claim(
1404
+ _num_or_none(row.get("claimUntil")),
1405
+ _num_or_none(row.get("lastAttemptAt")),
1406
+ now,
1407
+ ):
1408
+ return False
1409
+ fetched_at = _num_or_none(row.get("fetchedAt"))
1410
+ stale = fetched_at is None or (now - fetched_at) > SERVE_TTL_S
1411
+ next_poll_at = _num_or_none(row.get("nextPollAt"))
1412
+ poll_due = next_poll_at is not None and now >= next_poll_at
1413
+ overslept = repair_overslept and _plan_oversleeps_interval(
1414
+ next_poll_at,
1415
+ _num_or_none(row.get("pollIntervalS")),
1416
+ now,
1417
+ )
1418
+ if respect_plans:
1419
+ return stale and (poll_due or next_poll_at is None or overslept)
1420
+ if repair_overslept:
1421
+ return poll_due or (stale and (next_poll_at is None or overslept))
1422
+ return poll_due or stale
1423
+
1424
+
1425
+ def with_sentinel(entry: UsageEntry, sentinel: str | None) -> UsageEntry:
1426
+ """Overlay a derived sentinel state on a stored entry (read model only)."""
1427
+ if sentinel is None:
1428
+ return entry
1429
+ return replace(entry, sentinel=sentinel)