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,3065 @@
1
+ """Auto-switch engine: poll usage, switch accounts before they hit rate limits.
2
+
3
+ ``AutoSwitchEngine`` is UI-agnostic — no printing, no argparse, no TUI
4
+ imports. It composes a :class:`ClaudeAccountSwitcher`, evaluates a threshold
5
+ policy each :meth:`~AutoSwitchEngine.tick`, and reports everything through
6
+ typed events handed to an ``on_event`` callback; the CLI renders them as
7
+ human lines or JSONL, and any future frontend (TUI dashboard, menubar) can
8
+ consume the same stream.
9
+
10
+ Policy in one paragraph: when any of the active account's usage windows (5h,
11
+ 7d, and the per-model windows named by ``settings.model``) reaches its own
12
+ switch line — that account's **effective threshold** (its per-account
13
+ override where one is set, otherwise ``settings.threshold``), or
14
+ ``settings.weekly_threshold`` for the windows that reset weekly once that is
15
+ set — switch to the candidate with the most headroom measured against its
16
+ own lines (see ``lines.py``; with one line it is plain ``100 - max pct``) —
17
+ proactively, so the old account is
18
+ still valid while a running Claude Code picks the new one up (this is what
19
+ makes the macOS ~30s Keychain cache latency harmless). Candidates must sit
20
+ below every one of their lines and beat the active account by
21
+ ``hysteresis_pct`` points so two accounts hovering at a line never
22
+ ping-pong, and a ``cooldown_seconds`` floor bounds the switch rate (bypassed
23
+ only when the active account is hard at its limit). Physical questions —
24
+ exhausted, at its limit, when does quota return — read the raw percentages. Before
25
+ activation the target's token is *freshened* (refreshed if it expires within
26
+ 10 minutes — twice Claude Code's refresh buffer, so a running Claude Code's
27
+ under-lock re-read sees a fresh token and aborts its own refresh); a target
28
+ whose refresh token is dead gets quarantined instead of activated. When the
29
+ active account's own usage becomes unreadable for ``unhealthy_ticks``
30
+ consecutive ticks, the engine fails over to any healthy candidate. When it is
31
+ a 429 that keeps the active account's usage from being refreshed, the engine
32
+ instead leaves only for an account it has just measured with room to spare
33
+ (``_active_reading_blind``).
34
+
35
+ Cooldown and quarantine persist in ``<backup_root>/autoswitch_state.json``
36
+ (so cron-driven ``cswap auto --once`` ticks behave across processes), mutated
37
+ read-modify-write under a dedicated file lock.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import enum
43
+ import json
44
+ import logging
45
+ import math
46
+ import random
47
+ import threading
48
+ import time
49
+ from collections.abc import Callable, Mapping, Sequence
50
+ from dataclasses import dataclass, field, replace
51
+ from datetime import datetime, timedelta, timezone
52
+ from pathlib import Path
53
+ from typing import ClassVar
54
+
55
+ from claude_swap import oauth, poll_policy
56
+ from claude_swap.exceptions import ClaudeSwitchError
57
+ from claude_swap.json_output import SCHEMA_VERSION, USAGE_TOKEN_EXPIRED
58
+ from claude_swap.lines import BindingWindow, binding_window, line_room, window_line
59
+ from claude_swap.locking import FileLock
60
+ from claude_swap.models import AccountPolicy
61
+ from claude_swap.poll_policy import (
62
+ ESCALATION_MARGIN_PCT,
63
+ RESET_SLACK_S,
64
+ binding_pct,
65
+ )
66
+ from claude_swap.settings import (
67
+ AutoSwitchSettings,
68
+ atomic_write_json,
69
+ log_unrecognized_keys,
70
+ parse_model_names,
71
+ )
72
+ from claude_swap.switcher import ClaudeAccountSwitcher
73
+ from claude_swap.usage_store import (
74
+ STALE_OK_S,
75
+ UsageEntry,
76
+ due_candidate,
77
+ plan_oversleeps_interval,
78
+ )
79
+
80
+ STATE_FILENAME = "autoswitch_state.json"
81
+ STATE_SCHEMA_VERSION = 1
82
+
83
+ _logger = logging.getLogger("claude-swap")
84
+
85
+ # Systemic freshen refusals, MOST ACTIONABLE FIRST. Deterministic conditions
86
+ # that every candidate hits identically, so the tick reports one of them —
87
+ # and the order decides which, because reporting the wrong one is how a cause
88
+ # needing a human hides behind one that clears itself. store-unmirrored and
89
+ # invalid_client stay until somebody unsets an env var or fixes a client
90
+ # registration, and stash-unreadable until they unlock a keychain, fix a mode,
91
+ # or purge the row; consume-busy is gone by the next pass. stash-unreadable is
92
+ # the one that is per-SLOT rather than global, which costs nothing here: this
93
+ # message is only ever emitted when NO candidate freshened, so naming the real
94
+ # cause of the only slot that had one beats "(network?)".
95
+ _SYSTEMIC_MESSAGES = {
96
+ "store-unmirrored": "CLAUDE_SECURESTORAGE_CONFIG_DIR is set — unset it or "
97
+ "run cswap from a normal shell",
98
+ "invalid_client": "cswap's OAuth client was rejected — systemic, not this "
99
+ "account",
100
+ "stash-unreadable": "a stashed successor is unreadable — unlock the "
101
+ "keychain or fix the file, then retry; "
102
+ "`cswap unclaimed` inspects it",
103
+ "consume-busy": "another cswap surface holds the slot — retries next pass",
104
+ }
105
+ # Insertion order IS the precedence order, so the remedy and its rank cannot
106
+ # drift apart.
107
+ _SYSTEMIC_STATUSES = tuple(_SYSTEMIC_MESSAGES)
108
+
109
+ # Freshen targets whose access token expires within this window: twice Claude
110
+ # Code's own 5-minute refresh buffer, so its post-lock "abort refresh if not
111
+ # expired" re-read holds with margin after our swap.
112
+ FRESHEN_BUFFER_MS = 10 * 60 * 1000
113
+
114
+ # Sleep caps around a known quota reset (RESET_SLACK_S lives in poll_policy
115
+ # with the rest of the cadence numbers). Recheck at the exhausted-account poll
116
+ # cadence: providers can grant quota before the previously reported reset, and
117
+ # a long engine sleep must not suppress the fetch that discovers it.
118
+ MAX_SLEEP_S = poll_policy.EXHAUSTED_INTERVAL_S
119
+ NO_RESET_FALLBACK_S = 300.0
120
+
121
+ # Idle-hold cap (elapsed, not ticks — the hold itself slows the cadence to
122
+ # NO_RESET_FALLBACK_S): an owned-and-expired token normally means Claude Code
123
+ # is idle and will self-heal on next use, but a *dead* refresh token with an
124
+ # active user would look identical forever, so after this long the engine
125
+ # falls back to normal unhealthy counting.
126
+ IDLE_HOLD_MAX_S = 30 * 60.0
127
+
128
+ # Margin on the reset axis for the no-return bar's release
129
+ # (`_left_account_recovered`): the account we left counts as recovered only
130
+ # once its binding reset has moved at least this much nearer. Five minutes is
131
+ # comfortably longer than one poll cycle, so measurement jitter on a reset
132
+ # timestamp cannot release the bar.
133
+ RECOVERY_HYSTERESIS_S = 300.0
134
+
135
+ # How near a peer's binding reset must be for the failover release in
136
+ # `_left_account_recovered` to trust it when the active's own reset reads
137
+ # unknown. A 5h window can be up to 5h from resetting, so 4h keeps most of a
138
+ # five-hour cycle inside it.
139
+ RECOVERY_HORIZON_S = 4 * 3600.0
140
+
141
+ # Anti-flap margin when every account is over its own switch lines, as a
142
+ # RATIO rather than percentage points: strictly-more is no margin at all — one
143
+ # point moves the engine, the target burns it back, and it ping-pongs. The cap
144
+ # below lets the reverse margin reopen after ordinary burn, so the no-return
145
+ # bar (`_no_return_account`), not this ratio, keeps the move one-way.
146
+ #
147
+ # CAPPED at SPENT_HEADROOM_PCT points (`_all_above_margin_met`). Uncapped, the
148
+ # ratio's margin grows with the active's headroom, so with the threshold at 80
149
+ # an active holding 10 points refused a peer holding 19: the engine stayed at
150
+ # 90% while an 81% account sat idle, and both lie above the line, where the
151
+ # only question left is which account has the most room. Below the cap the
152
+ # ratio is the smaller margin and still decides.
153
+ HORIZON_HEADROOM_RATIO = 2.0
154
+
155
+ # A headroom edge smaller than this is noise: a point is under ten minutes of
156
+ # work, less than two poll intervals. It caps the anti-flap margin above, and
157
+ # the no-return bar's release asks the account we left to have gained at least
158
+ # this much.
159
+ SPENT_HEADROOM_PCT = 3.0
160
+
161
+
162
+ def _all_above_margin_met(candidate_headroom: float, active_headroom: float) -> bool:
163
+ """Does a candidate beat the active by enough to move, every account over
164
+ its own switch lines?
165
+
166
+ The margin is ``HORIZON_HEADROOM_RATIO`` times the active's headroom, capped
167
+ at ``SPENT_HEADROOM_PCT`` points. Either alone fails a measured case:
168
+
169
+ no margin active 5 pts, peer 6: moves, burns the point back,
170
+ and moves again (four switches in 35 minutes)
171
+ ratio alone active 10 pts, peer 19: holds a 90% account while an
172
+ 81% one sits idle
173
+
174
+ Both sides are RAW headroom (``100 - max pct``), never line headroom: past
175
+ its lines an account's line headroom is its room rescaled by how much room
176
+ its line reserved, and a ratio against a line every account has already
177
+ crossed measures the policy, not the quota (the reason the ratio and
178
+ ``SPENT_HEADROOM_PCT`` stay raw everywhere else).
179
+
180
+ The cap leaves the move one-way: the return leg is the no-return bar's call
181
+ (`_no_return_account`), and burn on the new active opens that bar only once
182
+ the active is down to a sliver (`_left_account_recovered`).
183
+
184
+ The no-return bar's release (`_no_return_account`) reuses this margin in
185
+ every regime, so a recovered account that clears it is never still barred.
186
+ """
187
+ required = min(
188
+ active_headroom * HORIZON_HEADROOM_RATIO,
189
+ active_headroom + SPENT_HEADROOM_PCT,
190
+ )
191
+ return candidate_headroom >= required
192
+
193
+
194
+ # Adaptive scheduling: the baseline request volume is O(1) per tick — the
195
+ # active account plus ONE due candidate (stalest data first) — instead of
196
+ # every account in parallel, and the per-account cadence itself (movement,
197
+ # threshold distance, urgent mode, 429 recovery) lives in poll_policy, is
198
+ # persisted in the usage store by whichever collector fetched, and is shared
199
+ # by every surface. The engine escalates to a full candidate refresh only
200
+ # when a switch could actually be near: one of the active account's windows
201
+ # within ESCALATION_MARGIN_PCT of its own switch line, or active usage unknown
202
+ # (failover needs fresh candidate data). The consume-first trigger can fire outside
203
+ # that escalation band; there it decides provisionally on the stored
204
+ # snapshot and escalates at commit time, when a switch would actually fire
205
+ # (the two-phase commit in _tick_inner).
206
+
207
+
208
+ def _now_iso() -> str:
209
+ return (
210
+ datetime.now(timezone.utc)
211
+ .isoformat(timespec="seconds")
212
+ .replace("+00:00", "Z")
213
+ )
214
+
215
+
216
+ def pct_label(value: float) -> str:
217
+ """A percentage for display, as configured: 85.555555 stays itself
218
+ (never a rounded "85.5556") and 99.9 never becomes a lying "100" the
219
+ way ``.0f`` renders it. Ten significant digits still absorb IEEE float
220
+ noise (~15th digit) in computed utilizations (100.0 - headroom).
221
+ Displayed comparisons must format BOTH sides with this helper — mixing
222
+ formatters can render an impossible "85.5556% < 85.555555%"."""
223
+ return f"{value:.10g}"
224
+
225
+
226
+ def _below_line_detail(
227
+ binding: BindingWindow | None, active_headroom: float, threshold: float
228
+ ) -> str:
229
+ """The below-threshold hold, quoting the comparison the engine made: the
230
+ binding window's own pct against its own line ("7d 93% < 97%"), so the
231
+ detail cannot read as a contradiction once the lines differ. The
232
+ account-wide form is only for an account with no readable window, which
233
+ a readable headroom rules out."""
234
+ if binding is None:
235
+ return f"{pct_label(100.0 - active_headroom)}% < {pct_label(threshold)}%"
236
+ return f"{binding.label} {pct_label(binding.pct)}% < {pct_label(binding.line)}%"
237
+
238
+
239
+ # ---------------------------------------------------------------------------
240
+ # Events
241
+ # ---------------------------------------------------------------------------
242
+
243
+
244
+ @dataclass(frozen=True)
245
+ class AutoSwitchEvent:
246
+ """Base event. ``to_json()`` payloads are additive: consumers must ignore
247
+ unknown ``event`` kinds and unknown fields."""
248
+
249
+ kind: ClassVar[str] = "event"
250
+ ts: str = field(default_factory=_now_iso, kw_only=True)
251
+
252
+ def _fields(self) -> dict:
253
+ return {}
254
+
255
+ def to_json(self) -> dict:
256
+ return {
257
+ "schemaVersion": SCHEMA_VERSION,
258
+ "event": self.kind,
259
+ "ts": self.ts,
260
+ **self._fields(),
261
+ }
262
+
263
+ def human(self) -> str: # pragma: no cover - overridden
264
+ return self.kind
265
+
266
+
267
+ @dataclass(frozen=True)
268
+ class PollEvent(AutoSwitchEvent):
269
+ kind: ClassVar[str] = "poll"
270
+ active: dict | None # account_ref shape, or None
271
+ headroom: dict[str, float | None] # account number → headroom pct (None=unknown)
272
+ threshold: float
273
+ # account number → last fetch-error cause ("http-429", "timeout", ...) for
274
+ # accounts whose usage is unknown this tick. Additive field.
275
+ fetch_errors: dict[str, str] = field(default_factory=dict)
276
+ # account number → ordered window label → utilization pct ("5h", "7d",
277
+ # then scoped model display names). Additive field: the binding pct alone
278
+ # (e.g. "89%") hides which window binds — #115 was reported off that
279
+ # ambiguity.
280
+ windows: dict[str, dict[str, float]] = field(default_factory=dict)
281
+ # The switch line of the weekly windows (7d and per-model) when one is
282
+ # configured; ``threshold`` stays the 5h window's. Additive field, emitted
283
+ # only when set. Every pct above stays RAW: the lines are applied where
284
+ # the engine compares, never to the numbers it logs.
285
+ weekly_threshold: float | None = None
286
+
287
+ def _fields(self) -> dict:
288
+ fields = {
289
+ "active": self.active,
290
+ "headroomPct": self.headroom,
291
+ "threshold": self.threshold,
292
+ }
293
+ if self.fetch_errors:
294
+ fields["fetchErrors"] = self.fetch_errors
295
+ if self.windows:
296
+ fields["windowsPct"] = self.windows
297
+ if self.weekly_threshold is not None:
298
+ fields["weeklyThreshold"] = self.weekly_threshold
299
+ return fields
300
+
301
+ def _describe(self, num: str) -> str:
302
+ wins = self.windows.get(num)
303
+ if wins:
304
+ return " · ".join(f"{name} {pct:.0f}%" for name, pct in wins.items())
305
+ h = self.headroom.get(num)
306
+ if h is not None:
307
+ return f"{100 - h:.0f}%"
308
+ err = self.fetch_errors.get(num)
309
+ return f"? ({err})" if err else "?"
310
+
311
+ def human(self) -> str:
312
+ if self.active is None:
313
+ return "poll: no active account"
314
+ num = self.active.get("number")
315
+ h = self.headroom.get(str(num))
316
+ line = self.threshold
317
+ wins = self.windows.get(str(num))
318
+ if wins:
319
+ # Name the binding window and quote ITS line: "93% used (switch
320
+ # at 85%)" reads as a contradiction once the weekly window has a
321
+ # line of its own, and the bare pct hid which window bound (the
322
+ # #115 ambiguity). Same rule as the engine's trigger.
323
+ binding = binding_window(
324
+ ((label, pct, None) for label, pct in wins.items()),
325
+ self.threshold,
326
+ self.weekly_threshold,
327
+ )
328
+ used = f"{binding.label} {binding.pct:.0f}% used"
329
+ line = binding.line
330
+ elif h is not None:
331
+ used = f"{100 - h:.0f}% used"
332
+ else:
333
+ err = self.fetch_errors.get(str(num))
334
+ used = f"usage unknown ({err})" if err else "usage unknown"
335
+ others = ", ".join(
336
+ f"#{n}: {self._describe(n)}"
337
+ for n in self.headroom
338
+ if n != str(num)
339
+ )
340
+ tail = f" | others: {others}" if others else ""
341
+ return (
342
+ f"Account-{num} ({self.active.get('email')}): {used} "
343
+ f"(switch at {pct_label(line)}%){tail}"
344
+ )
345
+
346
+
347
+ @dataclass(frozen=True)
348
+ class SwitchEvent(AutoSwitchEvent):
349
+ kind: ClassVar[str] = "switch"
350
+ # "proactive" | "at-limit" | "failover" | "consume-first" | "priority"
351
+ # | "active-stale"
352
+ trigger: str
353
+ from_ref: dict | None
354
+ to_ref: dict | None
355
+ warnings: list[str] = field(default_factory=list)
356
+ dry_run: bool = False
357
+
358
+ def _fields(self) -> dict:
359
+ return {
360
+ "trigger": self.trigger,
361
+ "from": self.from_ref,
362
+ "to": self.to_ref,
363
+ "warnings": self.warnings,
364
+ "dryRun": self.dry_run,
365
+ }
366
+
367
+ def human(self) -> str:
368
+ src = (
369
+ f"Account-{self.from_ref.get('number')}" if self.from_ref else "(none)"
370
+ )
371
+ dst = (
372
+ f"Account-{self.to_ref.get('number')} ({self.to_ref.get('email')})"
373
+ if self.to_ref
374
+ else "?"
375
+ )
376
+ prefix = "[dry-run] would switch" if self.dry_run else "Switched"
377
+ return f"{prefix} {src} -> {dst} ({self.trigger})"
378
+
379
+
380
+ @dataclass(frozen=True)
381
+ class NoSwitchEvent(AutoSwitchEvent):
382
+ kind: ClassVar[str] = "no-switch"
383
+ reason: str
384
+ detail: str = ""
385
+
386
+ def _fields(self) -> dict:
387
+ return {"reason": self.reason, "detail": self.detail}
388
+
389
+ def human(self) -> str:
390
+ return f"no switch: {self.reason}" + (f" ({self.detail})" if self.detail else "")
391
+
392
+
393
+ @dataclass(frozen=True)
394
+ class QuarantineEvent(AutoSwitchEvent):
395
+ kind: ClassVar[str] = "account-quarantined"
396
+ number: str
397
+ email: str
398
+ reason: str
399
+
400
+ def _fields(self) -> dict:
401
+ return {"number": self.number, "email": self.email, "reason": self.reason}
402
+
403
+ def human(self) -> str:
404
+ return (
405
+ f"Account-{self.number} ({self.email}) quarantined: {self.reason}. "
406
+ f"Log in with it and run 'cswap --add-account --slot {self.number}' "
407
+ "to recover."
408
+ )
409
+
410
+
411
+ @dataclass(frozen=True)
412
+ class UnquarantineEvent(AutoSwitchEvent):
413
+ kind: ClassVar[str] = "account-unquarantined"
414
+ number: str
415
+ email: str
416
+ reason: str = "credentials-replaced"
417
+
418
+ def _fields(self) -> dict:
419
+ return {"number": self.number, "email": self.email, "reason": self.reason}
420
+
421
+ def human(self) -> str:
422
+ return f"Account-{self.number} ({self.email}) back in rotation ({self.reason})"
423
+
424
+
425
+ @dataclass(frozen=True)
426
+ class AllExhaustedEvent(AutoSwitchEvent):
427
+ kind: ClassVar[str] = "all-exhausted"
428
+ earliest_reset_at: str | None
429
+
430
+ def _fields(self) -> dict:
431
+ return {"earliestResetAt": self.earliest_reset_at}
432
+
433
+ def human(self) -> str:
434
+ if self.earliest_reset_at:
435
+ return f"all accounts exhausted; earliest reset {self.earliest_reset_at}"
436
+ return "all accounts exhausted; no reset time known"
437
+
438
+
439
+ @dataclass(frozen=True)
440
+ class SleepEvent(AutoSwitchEvent):
441
+ kind: ClassVar[str] = "sleep"
442
+ seconds: float
443
+ until: str
444
+
445
+ def _fields(self) -> dict:
446
+ return {"seconds": round(self.seconds, 1), "until": self.until}
447
+
448
+ def human(self) -> str:
449
+ return f"sleeping {self.seconds / 60:.0f}m (until {self.until})"
450
+
451
+
452
+ @dataclass(frozen=True)
453
+ class ErrorEvent(AutoSwitchEvent):
454
+ kind: ClassVar[str] = "error"
455
+ message: str
456
+ transient: bool = True
457
+
458
+ def _fields(self) -> dict:
459
+ return {"message": self.message, "transient": self.transient}
460
+
461
+ def human(self) -> str:
462
+ return f"error: {self.message}" + (" (will retry)" if self.transient else "")
463
+
464
+
465
+ @dataclass(frozen=True)
466
+ class ConfigWarningEvent(AutoSwitchEvent):
467
+ """A configuration value is syntactically fine but provably inert (e.g.
468
+ an ``autoswitch.model`` name no account reports). Not an error: the
469
+ engine keeps running on the axes that do exist."""
470
+
471
+ kind: ClassVar[str] = "config-warning"
472
+ message: str
473
+
474
+ def _fields(self) -> dict:
475
+ return {"message": self.message}
476
+
477
+ def human(self) -> str:
478
+ return f"warning: {self.message}"
479
+
480
+
481
+ # ---------------------------------------------------------------------------
482
+ # Engine
483
+ # ---------------------------------------------------------------------------
484
+
485
+
486
+ class TickOutcome(enum.Enum):
487
+ """Outcome of one evaluation tick; values double as --once exit codes."""
488
+
489
+ SWITCHED = 0
490
+ ERROR = 1
491
+ NO_ACTION = 2
492
+ BLOCKED = 3 # wanted to switch but no viable target / all exhausted
493
+
494
+
495
+ # Quarantine state persisted fingerprints from a local refresh-token-only
496
+ # helper; oauth.credential_fingerprint is identical for refresh-token creds.
497
+ # Setup-token quarantines stored None where the shared helper now yields a
498
+ # full-content hash — those release once on first recheck and re-quarantine on
499
+ # the next dead freshen (one harmless extra cycle, migration only).
500
+ _refresh_fingerprint = oauth.credential_fingerprint
501
+
502
+
503
+ def _window_pcts(
504
+ usage: dict | None, models: tuple[str, ...] = ()
505
+ ) -> dict[str, float]:
506
+ """Ordered window label → pct: "5h", "7d", then configured scoped names.
507
+
508
+ Deliberately restricted to the windows the *decision* reads (same
509
+ ``models`` filter): showing an unconfigured scoped window at 100% next
510
+ to a switch onto that account would look like a bug, when the engine
511
+ correctly ignored it. Full per-model usage lives in ``cswap list``.
512
+ """
513
+ return {
514
+ name: pct for name, pct, _ in oauth.relevant_windows(usage, models)
515
+ }
516
+
517
+
518
+ # Reset math moved to poll_policy with the cadence numbers; aliased for the
519
+ # engine's sleep scheduling and the test suite.
520
+ _limiting_reset_ts = poll_policy.limiting_reset_ts
521
+ _earliest_future_reset_ts = poll_policy.earliest_future_reset_ts
522
+ _parse_reset_ts = poll_policy.parse_reset_ts
523
+
524
+
525
+ def _seven_day_reset_ts(usage: dict | str | None, now: float) -> float | None:
526
+ """Epoch of an account's 7-day (weekly) window reset, or None if unknown
527
+ or already past.
528
+
529
+ The consume-first strategy ranks by this — the weekly window is the
530
+ perishable quota (the 5-hour one recycles too fast to be worth planning
531
+ around). A stale snapshot can carry a ``resets_at`` that has since
532
+ elapsed; treated as a real instant it would sort the *just-rolled-over*
533
+ account (the least perishable quota of all) as "soonest", so past ==
534
+ unknown. Plain ``ts <= now``: RESET_SLACK_S is poll-scheduling lag
535
+ tolerance, not ranking input — padding here would turn a genuinely
536
+ imminent reset into a false reset-unknown hold.
537
+ """
538
+ if isinstance(usage, dict):
539
+ window = usage.get("seven_day")
540
+ if isinstance(window, dict):
541
+ ts = _parse_reset_ts(window.get("resets_at"))
542
+ if ts is not None and ts > now:
543
+ return ts
544
+ return None
545
+
546
+
547
+ def _binding_recovery_ts(
548
+ usage: dict | str | None,
549
+ models: Sequence[str],
550
+ now: float,
551
+ *,
552
+ threshold: float | None = None,
553
+ weekly_threshold: float | None = None,
554
+ scale: float | None = None,
555
+ ) -> float:
556
+ """When this account's *binding* window comes back, as a sort key.
557
+
558
+ The binding window is the one holding the account back — the window with
559
+ the least headroom against its own switch line (``lines.binding_window``),
560
+ which with one line is simply the highest utilization among the windows
561
+ that gate it (the same set ``account_headroom`` measures, so ranking and
562
+ headroom can never disagree about which window matters). Its reset is the
563
+ moment the account becomes useful again. With a weekly line both lines
564
+ are required; without one the threshold cannot change the answer.
565
+
566
+ Not the weekly window: with every account in the 90s the thing that
567
+ decides where to go is which 5-hour window rolls over first, and that is
568
+ routinely minutes away while the weekly one is days away.
569
+
570
+ Returns ``inf`` when unknown or already past, so such accounts sort last
571
+ rather than masquerading as "back immediately" — a stale ``resets_at``
572
+ would otherwise rank a snapshot nobody has refreshed above a measured,
573
+ genuinely imminent one.
574
+ """
575
+ # Pick the BINDING window first, then ask for its reset. Filtering on the
576
+ # reset before the max lets a lower window win whenever the binding one's
577
+ # reset is unknown or past — measured: 7d at 95% with no resets_at and 5h
578
+ # at 40% resetting in an hour returned "back in an hour", which is the
579
+ # opposite of what binds. An account whose binding window has no usable
580
+ # reset is one we cannot schedule around, and inf sorts it last.
581
+ windows = list(oauth.relevant_windows(usage, models))
582
+ if not windows:
583
+ return float("inf")
584
+ if weekly_threshold is None:
585
+ _label, _pct, resets_at = max(windows, key=lambda w: w[1])
586
+ else:
587
+ if threshold is None:
588
+ raise ValueError("threshold is required alongside weekly_threshold")
589
+ resets_at = binding_window(
590
+ windows, threshold, weekly_threshold, scale=scale
591
+ ).resets_at
592
+ ts = _parse_reset_ts(resets_at)
593
+ return ts if ts is not None and ts > now else float("inf")
594
+
595
+
596
+ class ThresholdMap(dict):
597
+ """Effective switch threshold per account number — total by construction.
598
+
599
+ Every account with a per-account override maps to that override; every
600
+ other account, including one that is not in the fleet at all, reads the
601
+ global ``autoswitch.threshold``. Totality lives here rather than at each
602
+ of the ten call sites: they subscript directly (``thresholds[num]``), and
603
+ a ``.get(num, default)`` convention would be one forgotten default away
604
+ from a ``KeyError`` mid-tick, in a code path that runs unattended.
605
+ """
606
+
607
+ def __init__(self, overrides: Mapping[str, float], default: float) -> None:
608
+ super().__init__(overrides)
609
+ self.default = default
610
+
611
+ def __missing__(self, key: str) -> float:
612
+ return self.default
613
+
614
+
615
+ def _every_candidate_above_threshold(
616
+ candidates: Sequence[str],
617
+ over: dict[str, bool | None],
618
+ ) -> bool:
619
+ """Whether every measured candidate is at or over its own switch lines.
620
+
621
+ An unmeasured candidate (``None`` = no readable window) does not block the
622
+ verdict (it may be healthy, but it cannot be *chosen* either — the caller
623
+ skips unreadable rows) as long as at least one candidate was measured.
624
+ """
625
+ # Each flag is that account's verdict against ITS OWN lines, so a fleet is
626
+ # only "all above" when no account has room under the rule it is actually
627
+ # governed by. One account with a higher line still sitting under it is a
628
+ # real landing spot, and the all-above regime must not swallow it.
629
+ measured = [over.get(n) for n in candidates if over.get(n) is not None]
630
+ if not measured:
631
+ return False
632
+ return all(measured)
633
+
634
+
635
+ def _every_account_above_threshold(
636
+ candidates: Sequence[str],
637
+ over: dict[str, bool | None],
638
+ active_over: bool | None,
639
+ ) -> bool:
640
+ """Whether the active account AND every measured candidate are at or over
641
+ their own switch lines — the state where "land somewhere healthy" has no
642
+ answer.
643
+
644
+ Requires the active account's own verdict to be known (``None`` = no
645
+ readable window): without it we do not know we are in this state, and
646
+ guessing here would relax the landing rule on an ordinary tick. Reads the
647
+ same per-window verdict as the trigger and the landing gate, so the three
648
+ cannot disagree about what "above the threshold" means.
649
+ """
650
+ if not active_over:
651
+ return False
652
+ return _every_candidate_above_threshold(candidates, over)
653
+
654
+
655
+ def _ref(number: str, email: str) -> dict:
656
+ return {"number": int(number), "email": email}
657
+
658
+
659
+ def _headroom_by_account(
660
+ usage: dict[str, dict | str | None], models: tuple[str, ...]
661
+ ) -> dict[str, float | None]:
662
+ """Per-account headroom derived from decision values."""
663
+ return {
664
+ num: oauth.account_headroom(
665
+ value if isinstance(value, dict) else None, models
666
+ )
667
+ for num, value in usage.items()
668
+ }
669
+
670
+
671
+ def _active_reading_blind(entry: UsageEntry | None, now: float) -> bool:
672
+ """Whether a 429 is keeping the ACTIVE account's usage from being read.
673
+
674
+ True while the account's usage refresh is being refused with a 429 and
675
+ the reading it left behind is older than ``STALE_OK_S``, or there is
676
+ none.
677
+
678
+ The store keeps such a reading decision-trusted until its window resets,
679
+ because usage only rises within a window: the reading is a lower bound.
680
+ A lower bound can show that an account has reached its line. It cannot
681
+ show that the account is still below it, and the active account is the
682
+ one being spent while its refresh is refused (#208: a frozen 70% under a
683
+ 90 line while the account stood at 96%).
684
+
685
+ So the engine reads the stored value in one direction only. At or over a
686
+ line it acts on it like any other reading. Below every line, or with the
687
+ store's trust gone (the window reset during the backoff), the tick counts
688
+ toward ``unhealthy_ticks`` and the engine then leaves under the
689
+ ``active-stale`` trigger: after the cooldown, and only for an account
690
+ ``_rank_verified_landings`` accepts. With no such account it stays, since
691
+ an account it cannot measure is no better a place to be.
692
+
693
+ One 429 starts the count. A ``Retry-After: 3600`` is honored as a
694
+ 75-minute backoff (``usage_store._failure_backoff_s``), so waiting for a
695
+ second refusal would wait that long.
696
+
697
+ A reading another machine hands over (``cswap import-usage``) is being
698
+ refreshed there, so it is not blind. A failure other than a 429 keeps the
699
+ store's own trust rules and, once those lapse, the failover.
700
+ """
701
+ return (
702
+ entry is not None
703
+ and entry.sentinel is None
704
+ and entry.last_error == "http-429"
705
+ and (entry.age_s is None or entry.age_s > STALE_OK_S)
706
+ and not entry.held(now)
707
+ )
708
+
709
+
710
+ def _reading_verified(entry: UsageEntry | None, now: float) -> bool:
711
+ """Whether an account's stored reading is a current measurement: taken
712
+ within the serve TTL, with no failed refresh since. ``fresh`` alone reads
713
+ the time of the last success, which a later 429 does not move."""
714
+ return (
715
+ entry is not None
716
+ and entry.sentinel is None
717
+ and entry.consecutive_failures == 0
718
+ and entry.fresh(now)
719
+ )
720
+
721
+
722
+ def _blind_detail(binding: BindingWindow | None, entry: UsageEntry | None) -> str:
723
+ """What the engine last knew of an active account that is
724
+ ``_active_reading_blind``, for the events that explain a hold or a move."""
725
+ if binding is None or entry is None or entry.age_s is None:
726
+ return "no current reading, usage refresh rate-limited"
727
+ return (
728
+ f"{binding.label} {pct_label(binding.pct)}% read "
729
+ f"{round(entry.age_s / 60)}m ago, usage refresh rate-limited"
730
+ )
731
+
732
+
733
+ class AutoSwitchEngine:
734
+ """Threshold-policy auto-switcher over a :class:`ClaudeAccountSwitcher`.
735
+
736
+ ``on_event`` receives every :class:`AutoSwitchEvent`; exceptions it raises
737
+ are not caught (a broken frontend should fail loudly in tests). ``clock``
738
+ is wall time (persisted cooldown timestamps must survive processes).
739
+ """
740
+
741
+ def __init__(
742
+ self,
743
+ switcher: ClaudeAccountSwitcher,
744
+ settings: AutoSwitchSettings,
745
+ on_event: Callable[[AutoSwitchEvent], None],
746
+ *,
747
+ dry_run: bool = False,
748
+ state_path: Path | None = None,
749
+ clock: Callable[[], float] = time.time,
750
+ ):
751
+ self.switcher = switcher
752
+ self.settings = settings
753
+ # Model(s) whose per-model weekly limit also binds the switch decision
754
+ # (empty = account-wide 5h/7d only). ``settings.model`` is a comma-
755
+ # separated list ("Fable", "Opus,Sonnet", "all"); parse once here and
756
+ # pass everywhere usage windows are read — decisions, cadence, and
757
+ # reset scheduling must all see the same axes.
758
+ self._models = parse_model_names(settings.model)
759
+ # Poll plans written by the collector must key on the same lines/
760
+ # models the engine decides with (CLI overrides included), not on
761
+ # whatever the settings file happens to say.
762
+ # The fleet MINIMUM, not the global: poll_policy's urgent mode fires
763
+ # at `new_pct >= threshold - 15`, so the lowest line in the fleet is
764
+ # the one that decides when collection must already be tight. Taking
765
+ # the minimum can only make collection earlier, never lazier — the
766
+ # safe direction when accounts disagree about where their line is.
767
+ switcher.set_poll_policy_inputs(
768
+ self._min_effective_threshold(), settings.weekly_threshold, self._models
769
+ )
770
+ self.on_event = on_event
771
+ self.dry_run = dry_run
772
+ self.state_path = state_path or (switcher.backup_dir / STATE_FILENAME)
773
+ self.clock = clock
774
+ self._stop = threading.Event()
775
+ # Cuts the current inter-tick sleep short (a session threshold change
776
+ # from the TUI should show a fresh decision now, not next interval).
777
+ self._wake = threading.Event()
778
+ self._unhealthy_ticks = 0
779
+ self._health_account: str | None = None
780
+ # Both set per tick: a known-reset sleep target, and whether a BLOCKED
781
+ # outcome is static enough (truly exhausted / no candidates) to wait
782
+ # longer than the normal interval.
783
+ self._sleep_until_ts: float | None = None
784
+ self._blocked_wait_long = False
785
+ # Idle-hold: when the active token expired while Claude Code owns it
786
+ # (and is therefore idle), crawl instead of counting unhealthy ticks.
787
+ # ``_idle_hold_since`` survives across ticks (elapsed-time cap);
788
+ # ``_idle_hold_slow`` is per-tick like ``_blocked_wait_long``.
789
+ self._idle_hold_since: float | None = None
790
+ self._idle_hold_slow = False
791
+ # One-shot typo guard for ``autoswitch.model``: resolved (and possibly
792
+ # warned) on the first tick where every relevant account has readable
793
+ # usage — adaptive polling legitimately leaves gaps before that.
794
+ self._model_check_done = not self._models
795
+
796
+ # -- state file ---------------------------------------------------------
797
+
798
+ def _state_lock(self) -> FileLock:
799
+ return FileLock(self.state_path.parent / ".autoswitch_state.lock")
800
+
801
+ def _read_state(self) -> dict:
802
+ try:
803
+ raw = json.loads(self.state_path.read_text(encoding="utf-8"))
804
+ except (OSError, json.JSONDecodeError, UnicodeDecodeError):
805
+ return {}
806
+ return raw if isinstance(raw, dict) else {}
807
+
808
+ def _mutate_state(self, mutator: Callable[[dict], None]) -> dict:
809
+ """Read-modify-write the state file under its lock; returns new state.
810
+
811
+ The lock prevents two concurrent engines (loop + cron ``--once``) from
812
+ overwriting each other's quarantine/cooldown updates. Never called
813
+ while any other lock is held.
814
+ """
815
+ with self._state_lock():
816
+ state = self._read_state()
817
+ state["schemaVersion"] = STATE_SCHEMA_VERSION
818
+ mutator(state)
819
+ atomic_write_json(self.state_path, state)
820
+ return state
821
+
822
+ # -- quarantine -----------------------------------------------------------
823
+
824
+ def _quarantine(self, number: str, email: str, reason: str) -> None:
825
+ creds = self.switcher.read_account_credentials(number, email)
826
+ fingerprint = _refresh_fingerprint(creds) if creds else None
827
+
828
+ def add(state: dict) -> None:
829
+ state.setdefault("quarantine", {})[number] = {
830
+ "email": email,
831
+ "reason": reason,
832
+ "at": _now_iso(),
833
+ "refreshTokenFingerprint": fingerprint,
834
+ }
835
+
836
+ self._mutate_state(add)
837
+ self._emit(QuarantineEvent(number=number, email=email, reason=reason))
838
+
839
+ def _release_recovered_quarantines(self, state: dict) -> dict:
840
+ """Drop quarantine entries whose credential was replaced since.
841
+
842
+ A changed refresh-token fingerprint (or a removed/re-added slot) means
843
+ the user re-logged in and re-captured the account — the dead lineage
844
+ is gone, so it re-enters rotation.
845
+ """
846
+ quarantine = state.get("quarantine")
847
+ if not isinstance(quarantine, dict) or not quarantine:
848
+ return state
849
+ to_release: list[tuple[str, str, str]] = []
850
+ for number, entry in quarantine.items():
851
+ email_now = self.switcher.account_email(number)
852
+ if not email_now or email_now != entry.get("email"):
853
+ to_release.append(
854
+ (number, entry.get("email", ""), "account-replaced")
855
+ )
856
+ continue
857
+ creds = self.switcher.read_account_credentials(number, email_now)
858
+ fingerprint = _refresh_fingerprint(creds) if creds else None
859
+ if fingerprint != entry.get("refreshTokenFingerprint"):
860
+ to_release.append((number, email_now, "credentials-replaced"))
861
+ if not to_release:
862
+ return state
863
+
864
+ def drop(s: dict) -> None:
865
+ q = s.get("quarantine")
866
+ if isinstance(q, dict):
867
+ for number, _, _ in to_release:
868
+ q.pop(number, None)
869
+
870
+ state = self._mutate_state(drop)
871
+ for number, email, reason in to_release:
872
+ self._emit(UnquarantineEvent(number=number, email=email, reason=reason))
873
+ return state
874
+
875
+ # -- freshening -----------------------------------------------------------
876
+
877
+ def _freshen_target(self, number: str, email: str) -> str:
878
+ """Ensure a candidate's stored token outlives Claude Code's 5-min
879
+ refresh buffer before it gets activated.
880
+
881
+ Returns ``"ok"``, ``"invalid_grant"`` (dead lineage — quarantine),
882
+ ``"identity-conflict"`` (alive but authenticates as a different
883
+ account — quarantine, do not activate), ``"transient"`` (network
884
+ trouble — try again next tick), ``"skip-live-session"`` or
885
+ ``"skip-live-login"`` (the live login already holds this slot's
886
+ grant). Only ever touches the slot's *backup* store; the active
887
+ credential belongs to Claude Code.
888
+ """
889
+ if self.switcher.account_kind_for(number) == "api_key":
890
+ return "ok" # API keys don't expire/refresh
891
+ if self.switcher.live_session_pids_for(number, email):
892
+ # A live `cswap run` session owns this account's token in its own
893
+ # profile. Auto-activating it as the default login too would put
894
+ # one rotating refresh token in two config dirs (the stale-copy
895
+ # failure class) with nobody reading the warning — and its quota
896
+ # is already being consumed by that session anyway. Manual
897
+ # switch_to keeps its warn-and-proceed behavior; auto skips.
898
+ return "skip-live-session"
899
+ creds = self.switcher.read_account_credentials(number, email)
900
+ if not creds:
901
+ return "transient"
902
+ data = oauth.extract_oauth_data(creds)
903
+ if not data:
904
+ return "invalid_grant"
905
+ expires_at = data.get("expiresAt")
906
+ now_ms = self.clock() * 1000
907
+ near_expiry = (
908
+ isinstance(expires_at, (int, float))
909
+ and now_ms + FRESHEN_BUFFER_MS >= expires_at
910
+ )
911
+ if not near_expiry:
912
+ return "ok"
913
+ # The consume gate serializes every backup-rt POST (the recovery
914
+ # branch in `_fetch_active_usage` is a second call site, under the
915
+ # same per-slot consume lock):
916
+ # it re-reads under the slot lock (our snapshot may be superseded),
917
+ # consults the session profile for a newer generation, and persists
918
+ # via fingerprint CAS — so a freshen racing the collector (or a
919
+ # sibling surface) can no longer double-consume one grant.
920
+ outcome = self.switcher.consume_backup_grant(number, email, creds)
921
+ if outcome.error is None and outcome.credentials:
922
+ # The gate already persisted the successor (or adopted a racing
923
+ # writer's newer lineage) under its own lock.
924
+ if self._note_token_identity(number, outcome.token_account):
925
+ # The slot's stored credential authenticates as a *different*
926
+ # account — activating it would put the user on the wrong
927
+ # account with every gauge reading normal. Not a viable
928
+ # target; the caller quarantines it (released automatically
929
+ # once the credential is replaced by a re-add).
930
+ return "identity-conflict"
931
+ return "ok"
932
+ if outcome.error in ("invalid_grant", "no_refresh_token"):
933
+ return "invalid_grant"
934
+ if outcome.error == "live-login":
935
+ # The live login already holds this slot's grant, so the gate
936
+ # left it to Claude Code. Not network trouble and not a dead
937
+ # token: pass over the candidate for this tick.
938
+ return "skip-live-login"
939
+ if outcome.error in _SYSTEMIC_STATUSES:
940
+ # Deterministic conditions, not network trouble: every candidate
941
+ # refuses identically and keeps refusing until something outside
942
+ # this process changes — the shell for store-unmirrored (an
943
+ # inherited CLAUDE_SECURESTORAGE_CONFIG_DIR), our OAuth client
944
+ # registration for invalid_client. Reported distinctly so the tick
945
+ # error names the real cause instead of "(network?)", which would
946
+ # send the user to check a connection that is fine.
947
+ return outcome.error
948
+ return "transient"
949
+
950
+ def _note_token_identity(
951
+ self, number: str, token_account: dict | None
952
+ ) -> bool:
953
+ """Use the token endpoint's free identity to verify/backfill a slot.
954
+
955
+ The refresh grant just ran against the slot's own stored credential,
956
+ so ``token_account`` (when the server includes it) names who that
957
+ credential really is. Returns True on a *conflict*: the credential
958
+ authenticates under a different organization than the slot records
959
+ (org compared first, whenever both sides record one), or as a
960
+ different account uuid. An empty slot uuid (blank-uuid records from
961
+ older versions, add-token placeholders) is backfilled — but only
962
+ when no org conflict exists: a wrong-org credential is evidence the
963
+ slot holds the wrong account, and backfilling *its* uuid would
964
+ poison the slot's identity record (backfill never rewrites a
965
+ non-empty uuid, so that corruption would be sticky).
966
+
967
+ ``_parse_token_account`` already enforces a strict boundary, but this
968
+ identity is opportunistic — re-check types here so malformed data can
969
+ never break the freshen that carried it (the successor credential is
970
+ already persisted by the time this runs).
971
+ """
972
+ if not isinstance(token_account, dict):
973
+ return False
974
+ ta_uuid = token_account.get("uuid")
975
+ if not isinstance(ta_uuid, str) or not ta_uuid.strip():
976
+ return False
977
+ ta_uuid = ta_uuid.strip()
978
+ slot_identity = self.switcher.account_identity(number)
979
+ ta_org = token_account.get("organizationUuid")
980
+ slot_org = slot_identity.get("organizationUuid") or ""
981
+ if isinstance(ta_org, str) and ta_org and slot_org and ta_org != slot_org:
982
+ return True
983
+ if not slot_identity.get("uuid"):
984
+ try:
985
+ self.switcher.backfill_account_uuid(number, ta_uuid)
986
+ except Exception as e: # never let bookkeeping break a freshen
987
+ _logger.debug("uuid backfill failed for account %s: %r", number, e)
988
+ return False
989
+ return slot_identity["uuid"] != ta_uuid
990
+
991
+ # -- tick -----------------------------------------------------------------
992
+
993
+ def tick(self) -> TickOutcome:
994
+ """Evaluate once: poll usage, maybe switch. Never raises."""
995
+ try:
996
+ outcome = self._tick_inner()
997
+ self._persist_health_counters(self._health_account)
998
+ return outcome
999
+ except ClaudeSwitchError as e:
1000
+ self._emit(ErrorEvent(message=str(e), transient=True))
1001
+ return TickOutcome.ERROR
1002
+ except Exception as e: # pragma: no cover - safety net
1003
+ self._emit(
1004
+ ErrorEvent(message=f"{type(e).__name__}: {e}", transient=True)
1005
+ )
1006
+ return TickOutcome.ERROR
1007
+
1008
+ def _resolve_thresholds(
1009
+ self, settings: AutoSwitchSettings | None = None,
1010
+ *, policies: Mapping[str, AccountPolicy] | None = None,
1011
+ ) -> ThresholdMap:
1012
+ """The effective threshold for every account, resolved once per tick.
1013
+
1014
+ Resolution is ``policy(n).threshold if set else settings.threshold``.
1015
+ The result is passed DOWN as a parameter rather than looked up where
1016
+ it is needed: ``_rank_candidates`` is documented pure and runs twice
1017
+ per tick under the consume-first two-phase commit, so a store read
1018
+ inside it could decide phase 1 and phase 2 on different lines.
1019
+
1020
+ The ``settings`` argument exists so a tick resolves against the same
1021
+ snapshot it gates with, even if ``apply_threshold()`` lands mid-tick.
1022
+ """
1023
+ effective = settings or self.settings
1024
+ if policies is None:
1025
+ policies = self.switcher.account_policies()
1026
+ return ThresholdMap(
1027
+ {
1028
+ num: policy.threshold
1029
+ for num, policy in policies.items()
1030
+ if policy.threshold is not None
1031
+ },
1032
+ effective.threshold,
1033
+ )
1034
+
1035
+ def _min_effective_threshold(
1036
+ self, thresholds: ThresholdMap | None = None
1037
+ ) -> float:
1038
+ """The lowest effective threshold across switchable accounts.
1039
+
1040
+ Used only for poll cadence (``set_poll_policy_inputs``), never for a
1041
+ switch decision — cadence is fleet-wide, so it has to be tight enough
1042
+ for whichever account crosses its own line first. With no overrides
1043
+ this is exactly ``settings.threshold``.
1044
+
1045
+ ``thresholds`` lets a tick reuse the map it already resolved, so the
1046
+ cadence it pins and the lines it gates on come from one store read of
1047
+ one snapshot. Callers outside a tick (construction, ``apply_threshold``)
1048
+ omit it and resolve their own.
1049
+ """
1050
+ thresholds = thresholds if thresholds is not None else self._resolve_thresholds()
1051
+ values = [
1052
+ thresholds[num]
1053
+ for num in self.switcher.switchable_account_numbers()
1054
+ ]
1055
+ return min(values) if values else self.settings.threshold
1056
+
1057
+ def _refresh_poll_policy_inputs(self, thresholds: ThresholdMap) -> None:
1058
+ """Re-pin poll cadence from this tick's threshold map.
1059
+
1060
+ ``set_poll_policy_inputs`` used to be called in exactly two places,
1061
+ ``__init__`` and ``apply_threshold()``. Neither is on the path a
1062
+ *persisted* policy write takes: ``cswap threshold 1 50`` runs in a
1063
+ separate process from ``cswap auto``, so a running engine re-read the
1064
+ new line for its DECISION every tick (``_resolve_thresholds``) while
1065
+ its CADENCE stayed pinned to the minimum as it stood at boot.
1066
+
1067
+ That defeats the reason the cadence is pinned to the fleet minimum at
1068
+ all. The minimum is chosen because ``poll_policy``'s urgent mode
1069
+ fires at ``new_pct >= threshold - 15``, so the fleet minimum can only
1070
+ make collection *earlier* — never lazier, and no crossing is missed.
1071
+ A stale 90 against a live 50 goes urgent at 75% instead of 35%, which
1072
+ is lazier in exactly the direction that reason rules out, on every
1073
+ tick until the process restarts.
1074
+
1075
+ Called before ``_collect_scheduled_usage`` so the tick that discovers
1076
+ the change also plans on it. The pin itself is a bare attribute write
1077
+ (``ClaudeAccountSwitcher.set_poll_policy_inputs``); the only added
1078
+ per-tick cost is one ``switchable_account_numbers()`` read, which
1079
+ ``_tick_inner`` already performs for candidate construction.
1080
+ """
1081
+ self.switcher.set_poll_policy_inputs(
1082
+ self._min_effective_threshold(thresholds),
1083
+ self.settings.weekly_threshold,
1084
+ self._models,
1085
+ )
1086
+
1087
+ def _load_health_counters(self, state: dict, current: str) -> None:
1088
+ """Seed the unreadable-active counters from the state file.
1089
+
1090
+ They are persisted so a fresh engine per tick (``auto --once``) keeps
1091
+ counting toward failover instead of restarting at zero. Counters left
1092
+ by another account, or by a tick longer ago than twice the idle-hold cap,
1093
+ are dropped. Until the managed active account changes the in-memory values
1094
+ are authoritative, so dry-run (which never persists) and long gaps
1095
+ between loop ticks keep their progress.
1096
+ """
1097
+ ticks = state.get("unhealthyTicks")
1098
+ since = state.get("idleHoldSince")
1099
+ at = state.get("healthTickAt")
1100
+ fresh = (
1101
+ state.get("healthAccount") == current
1102
+ and isinstance(at, (int, float))
1103
+ and not isinstance(at, bool)
1104
+ and 0 <= self.clock() - at <= 2 * IDLE_HOLD_MAX_S
1105
+ )
1106
+ self._unhealthy_ticks = (
1107
+ ticks
1108
+ if fresh
1109
+ and isinstance(ticks, int)
1110
+ and not isinstance(ticks, bool)
1111
+ and ticks > 0
1112
+ else 0
1113
+ )
1114
+ self._idle_hold_since = (
1115
+ float(since)
1116
+ if fresh
1117
+ and isinstance(since, (int, float))
1118
+ and not isinstance(since, bool)
1119
+ else None
1120
+ )
1121
+
1122
+ def _persist_health_counters(self, current: str | None) -> None:
1123
+ if self.dry_run:
1124
+ return
1125
+ ticks, since = self._unhealthy_ticks, self._idle_hold_since
1126
+ now = self.clock()
1127
+
1128
+ def store(state: dict) -> None:
1129
+ if current is not None and (ticks or since is not None):
1130
+ state["unhealthyTicks"] = ticks
1131
+ state["idleHoldSince"] = since
1132
+ state["healthAccount"] = current
1133
+ state["healthTickAt"] = now
1134
+ else:
1135
+ for key in (
1136
+ "unhealthyTicks", "idleHoldSince", "healthAccount",
1137
+ "healthTickAt",
1138
+ ):
1139
+ state.pop(key, None)
1140
+
1141
+ stored = self._read_state()
1142
+ if not (ticks or since is not None) and "healthAccount" not in stored:
1143
+ return
1144
+ self._mutate_state(store)
1145
+
1146
+ def _tick_inner(self) -> TickOutcome:
1147
+ self._sleep_until_ts = None
1148
+ self._blocked_wait_long = False
1149
+ self._idle_hold_slow = False
1150
+ settings = self.settings
1151
+ priority_mode = settings.strategy == "priority-consume-first"
1152
+ state = self._read_state()
1153
+ if not self.dry_run:
1154
+ # Dry-run must not write anything, so recovered quarantines are
1155
+ # only released (state mutation) on real ticks.
1156
+ state = self._release_recovered_quarantines(state)
1157
+ quarantined = set(
1158
+ state.get("quarantine", {})
1159
+ if isinstance(state.get("quarantine"), dict)
1160
+ else {}
1161
+ )
1162
+
1163
+ current = self.switcher.current_account_number()
1164
+ # A tick with no managed active account keeps the current context;
1165
+ # a different account reseeds from the state file so its counts are
1166
+ # never inherited from the previous one.
1167
+ if current is not None and current != self._health_account:
1168
+ self._load_health_counters(state, current)
1169
+ self._health_account = current
1170
+ if current is None:
1171
+ self._emit(
1172
+ PollEvent(
1173
+ active=None,
1174
+ headroom={},
1175
+ threshold=settings.threshold,
1176
+ weekly_threshold=settings.weekly_threshold,
1177
+ )
1178
+ )
1179
+ if self.switcher.has_live_login():
1180
+ # Live login exists but cswap doesn't manage it: never act —
1181
+ # a switch would overwrite it without a backup.
1182
+ self._emit(
1183
+ NoSwitchEvent(
1184
+ reason="unmanaged-active-account",
1185
+ detail="run 'cswap --add-account' to include it in rotation",
1186
+ )
1187
+ )
1188
+ else:
1189
+ self._emit(
1190
+ NoSwitchEvent(
1191
+ reason="no-active-account",
1192
+ detail="log in and run 'cswap --add-account' first",
1193
+ )
1194
+ )
1195
+ return TickOutcome.NO_ACTION
1196
+
1197
+ current_email = self.switcher.account_email(current)
1198
+ active_ref = _ref(current, current_email) if current_email else {
1199
+ "number": int(current),
1200
+ "email": "",
1201
+ }
1202
+
1203
+ # One resolution per tick, threaded down as a parameter from here on.
1204
+ # Every gate below reads `thresholds[...]`; the map is total, so an
1205
+ # account absent from it (never sequenced, just removed) reads the
1206
+ # global rather than raising mid-tick.
1207
+ policies = self.switcher.account_policies()
1208
+ thresholds = self._resolve_thresholds(settings, policies=policies)
1209
+ # Cadence follows the same snapshot, and does so BEFORE collection is
1210
+ # planned below — see `_refresh_poll_policy_inputs`.
1211
+ self._refresh_poll_policy_inputs(thresholds)
1212
+ entries, usage, headroom = self._collect_scheduled_usage(
1213
+ current,
1214
+ quarantined,
1215
+ threshold=thresholds[current],
1216
+ weekly_threshold=settings.weekly_threshold,
1217
+ )
1218
+ self._emit(
1219
+ PollEvent(
1220
+ active=active_ref,
1221
+ headroom=headroom,
1222
+ # The active account's own line: the number the CLI and TUI
1223
+ # render as "the threshold" must be the one the departure
1224
+ # gate below actually used, or the UI contradicts the engine.
1225
+ threshold=thresholds[current],
1226
+ weekly_threshold=settings.weekly_threshold,
1227
+ fetch_errors={
1228
+ num: entry.last_error
1229
+ for num, entry in entries.items()
1230
+ if usage.get(num) is None and entry.last_error
1231
+ },
1232
+ windows={
1233
+ num: pcts
1234
+ for num, value in usage.items()
1235
+ if (pcts := _window_pcts(
1236
+ value if isinstance(value, dict) else None, self._models
1237
+ ))
1238
+ },
1239
+ )
1240
+ )
1241
+
1242
+ if not self._model_check_done:
1243
+ self._check_model_names(quarantined, usage)
1244
+
1245
+ if (
1246
+ self.switcher.account_kind_for(current) == "api_key"
1247
+ and not settings.include_api_key_accounts
1248
+ ):
1249
+ self._emit(
1250
+ NoSwitchEvent(
1251
+ reason="active-api-key",
1252
+ detail="API-key accounts have no quota to watch",
1253
+ )
1254
+ )
1255
+ return TickOutcome.NO_ACTION
1256
+
1257
+ active_headroom = headroom.get(current)
1258
+ active_binding: BindingWindow | None = None
1259
+ below = False
1260
+ if active_headroom is not None:
1261
+ # Each window against its OWN line, the closest one decides (see
1262
+ # lines.py). A readable headroom means a readable window, so the
1263
+ # account-wide fallback is unreachable; kept as the exact old test.
1264
+ active_binding = self._binding(
1265
+ usage.get(current), settings, thresholds[current]
1266
+ )
1267
+ below = (
1268
+ not active_binding.over
1269
+ if active_binding is not None
1270
+ else (100.0 - active_headroom) < thresholds[current]
1271
+ )
1272
+ active_entry = entries.get(current)
1273
+ if (active_headroom is None or below) and _active_reading_blind(
1274
+ active_entry, self.clock()
1275
+ ):
1276
+ # A reading at or over its line never comes here: a crossing the
1277
+ # store still trusts is acted on below, at once.
1278
+ self._idle_hold_since = None
1279
+ self._unhealthy_ticks += 1
1280
+ if self._unhealthy_ticks < settings.unhealthy_ticks:
1281
+ self._emit(
1282
+ NoSwitchEvent(
1283
+ reason="active-usage-stale",
1284
+ detail=(
1285
+ f"{_blind_detail(active_binding, active_entry)}; "
1286
+ f"{self._unhealthy_ticks}/{settings.unhealthy_ticks} "
1287
+ "before moving to an account with a recent reading"
1288
+ ),
1289
+ )
1290
+ )
1291
+ return TickOutcome.NO_ACTION
1292
+ trigger = "active-stale"
1293
+ elif active_headroom is not None:
1294
+ self._unhealthy_ticks = 0
1295
+ self._idle_hold_since = None
1296
+ if below:
1297
+ if settings.strategy != "consume-first" and not priority_mode:
1298
+ self._emit(
1299
+ NoSwitchEvent(
1300
+ reason="below-threshold",
1301
+ # Both sides through pct_label: .0f utilization could
1302
+ # display an impossible "100% < 99.9%".
1303
+ detail=_below_line_detail(
1304
+ active_binding,
1305
+ active_headroom,
1306
+ thresholds[current],
1307
+ ),
1308
+ )
1309
+ )
1310
+ return TickOutcome.NO_ACTION
1311
+ # consume-first: below the threshold we still proactively move to
1312
+ # whichever account's weekly window resets soonest, to burn the
1313
+ # most-perishable quota first. Candidate selection decides whether
1314
+ # a sooner-resetting account with room actually exists.
1315
+ trigger = "priority" if priority_mode else "consume-first"
1316
+ else:
1317
+ # Exhaustion is physical: at-limit reads the raw headroom.
1318
+ trigger = "at-limit" if active_headroom <= 0 else "proactive"
1319
+ else:
1320
+ if usage.get(current) == USAGE_TOKEN_EXPIRED:
1321
+ # Expired and the refresh could not complete this pass (lock
1322
+ # contention, unattributable lineage, failed persist, or the
1323
+ # row's failure backoff gating the fetch). The locked-refresh
1324
+ # path retries on later passes — no quota burn, nothing to
1325
+ # switch for yet; crawl slowly instead of burning failover
1326
+ # ticks (Finding 2 of the usage-lapse investigation).
1327
+ now = self.clock()
1328
+ if self._idle_hold_since is None:
1329
+ self._idle_hold_since = now
1330
+ if now - self._idle_hold_since <= IDLE_HOLD_MAX_S:
1331
+ self._unhealthy_ticks = 0
1332
+ self._idle_hold_slow = True
1333
+ self._emit(
1334
+ NoSwitchEvent(
1335
+ reason="active-idle",
1336
+ detail=(
1337
+ "token expired while Claude Code is idle; "
1338
+ "resumes on next use"
1339
+ ),
1340
+ )
1341
+ )
1342
+ return TickOutcome.NO_ACTION
1343
+ # Held far longer than any idle nap should need — likely a
1344
+ # dead refresh token with an *active* user. Fall through to
1345
+ # normal unhealthy counting so failover can still happen.
1346
+ _logger.warning(
1347
+ "Active token expired and owned for over %.0f minutes; "
1348
+ "resuming unhealthy counting (dead refresh token?)",
1349
+ IDLE_HOLD_MAX_S / 60,
1350
+ )
1351
+ else:
1352
+ self._idle_hold_since = None
1353
+ self._unhealthy_ticks += 1
1354
+ if self._unhealthy_ticks < settings.unhealthy_ticks:
1355
+ self._emit(
1356
+ NoSwitchEvent(
1357
+ reason="active-usage-unknown",
1358
+ detail=(
1359
+ f"{self._unhealthy_ticks}/{settings.unhealthy_ticks} "
1360
+ "before failover"
1361
+ ),
1362
+ )
1363
+ )
1364
+ return TickOutcome.NO_ACTION
1365
+ trigger = "failover"
1366
+
1367
+ if (
1368
+ trigger in ("proactive", "consume-first", "priority", "active-stale")
1369
+ and self._in_cooldown(state)
1370
+ ):
1371
+ self._emit(NoSwitchEvent(reason="cooldown"))
1372
+ return TickOutcome.NO_ACTION
1373
+
1374
+ # -- candidate selection ------------------------------------------
1375
+ switchable = self.switcher.switchable_account_numbers()
1376
+ candidates = [
1377
+ num
1378
+ for num in switchable
1379
+ if num != current and num not in quarantined
1380
+ ]
1381
+ oauth_candidates = [
1382
+ n for n in candidates if self.switcher.account_kind_for(n) != "api_key"
1383
+ ]
1384
+ # The no-return bar itself lives in `_rank` below: it is a statement
1385
+ # about the CHOICE, so it belongs where the choice is made rather than
1386
+ # in this census of what exists. See `_no_return_account` for the
1387
+ # incident, the scoping, and the release.
1388
+ api_key_candidates = (
1389
+ [n for n in candidates if self.switcher.account_kind_for(n) == "api_key"]
1390
+ if settings.include_api_key_accounts
1391
+ else []
1392
+ )
1393
+ if trigger == "active-stale" and not oauth_candidates:
1394
+ # No OAuth peer to measure: staying, as "nothing to do", whether
1395
+ # or not the store still serves the last reading, so the outcome
1396
+ # does not change when that reading's window resets. An API-key
1397
+ # account is the last resort for an account that must be left,
1398
+ # which this is not.
1399
+ return self._stay_blind(active_binding, active_entry)
1400
+ if (
1401
+ trigger in ("consume-first", "priority")
1402
+ and not oauth_candidates
1403
+ and active_headroom is not None
1404
+ ):
1405
+ # Healthy below-threshold account with no OAuth peer to compare
1406
+ # against — the same state `best` reports as below-threshold
1407
+ # NO_ACTION before ever reaching candidate selection. API-key
1408
+ # candidates don't change the outcome: they have no weekly window
1409
+ # to consume, so a consume-first nudge never targets them. Keep
1410
+ # the exit-code contract identical across strategies: cron
1411
+ # wrappers keying on BLOCKED must not see false "blocked" from
1412
+ # the flag alone.
1413
+ self._emit(
1414
+ NoSwitchEvent(
1415
+ reason="below-threshold",
1416
+ detail=_below_line_detail(
1417
+ active_binding, active_headroom, thresholds[current]
1418
+ ),
1419
+ )
1420
+ )
1421
+ return TickOutcome.NO_ACTION
1422
+ if not oauth_candidates and not api_key_candidates:
1423
+ # Won't change until the user adds/recovers an account — no point
1424
+ # re-polling at full cadence.
1425
+ self._blocked_wait_long = True
1426
+ self._emit(NoSwitchEvent(reason="no-candidates"))
1427
+ return TickOutcome.BLOCKED
1428
+
1429
+ consume_first = settings.strategy == "consume-first"
1430
+
1431
+ def _rank(**kw):
1432
+ """Rank with the no-return bar, and WITHOUT it if that empties AND
1433
+ the barred account is a different proposition from the one we left.
1434
+
1435
+ Emptiness alone cannot be the release. On two accounts there is
1436
+ exactly one candidate, so barring it ALWAYS empties the list —
1437
+ measured, sweeping active x barred headroom x both reset shapes,
1438
+ `n=2 barred-rank EMPTY=320 NONEMPTY=0`. An emptiness-only release
1439
+ therefore fires every tick and the bar is inert at the fleet size
1440
+ the flap was reported on: pcts 92/92, resets 500h/400h, 60 ticks
1441
+ gave `[1, 2, 1, 2]` with the bar on and the identical `[1, 2, 1, 2]`
1442
+ with `lastSwitchFrom` popped every tick.
1443
+
1444
+ "BARRING LEAVES NOTHING" AND "WE ARE FLAPPING" ARE DIFFERENT
1445
+ STATES, and at n=2 they are always the same state — which is how
1446
+ one swallowed the other. The ranking cannot separate them: it sees
1447
+ only the present, and both look like an empty list. What separates
1448
+ them is WHY the ranking flipped. Traced at each leg of that walk:
1449
+
1450
+ t8 1->2 left 1 holding 4.0 pts, 500h out
1451
+ t20 2->1 account 1 still 4.0 pts, still 500h out
1452
+ t22 1->2 account 2 still 2.0 pts, still 400h out
1453
+
1454
+ Every return won because the ACTIVE burned down, never because the
1455
+ target recovered. So the release asks the one question the ranking
1456
+ cannot: is the account we left better than when we left it?
1457
+
1458
+ ON BOTH AXES AN ACCOUNT CAN IMPROVE ON, each with its own margin —
1459
+ ``SPENT_HEADROOM_PCT`` of headroom (below that an edge is under two
1460
+ poll intervals of work) or a binding reset ``RECOVERY_HYSTERESIS_S``
1461
+ sooner. An account's headroom rises only when a window rolls over
1462
+ and its binding reset only moves nearer when a nearer window
1463
+ starts binding, so both are real events rather than the boundary
1464
+ crossings burn manufactures for free.
1465
+
1466
+ Emptiness still decides whether to ASK. Where the bar leaves a
1467
+ real alternative it simply applies, so a fleet with somewhere else
1468
+ to go is untouched by any of this.
1469
+
1470
+ Cheap: the retry runs only when the barred list came back empty,
1471
+ which is the tick that was about to do nothing anyway.
1472
+ """
1473
+ if trigger == "active-stale":
1474
+ # Its own landing rule, and no no-return bar: the account
1475
+ # this engine left qualifies again only once it has been
1476
+ # read anew, which is what the bar would otherwise ask.
1477
+ return (
1478
+ self._rank_verified_landings(
1479
+ oauth_candidates=kw["oauth_candidates"],
1480
+ entries=entries, usage=kw["usage"],
1481
+ headroom=kw["headroom"], settings=settings,
1482
+ now=kw["now"], thresholds=thresholds, policies=policies,
1483
+ ),
1484
+ True,
1485
+ None,
1486
+ )
1487
+ if priority_mode:
1488
+ # Strict landing and a stable priority/reset ordering make the
1489
+ # legacy escape/no-return heuristics unnecessary. A recovered
1490
+ # higher tier must be able to reclaim work immediately after
1491
+ # the configured cooldown, even when it is the account we left.
1492
+ return self._rank_priority_candidates(
1493
+ oauth_candidates=kw["oauth_candidates"],
1494
+ usage=kw["usage"], headroom=kw["headroom"],
1495
+ current=current, active_enabled=current in switchable,
1496
+ settings=settings, now=kw["now"], thresholds=thresholds,
1497
+ policies=policies,
1498
+ )
1499
+ # Recomputed per snapshot, never once per tick: the consume-first
1500
+ # two-phase commit replaces `headroom` and `active_headroom` and
1501
+ # re-ranks, and the ratio release consumes exactly those two
1502
+ # values. Computed once, the bar answered from a snapshot the
1503
+ # ranking had already thrown away — `left=20 active=30` bars,
1504
+ # `left=90 active=10` releases, and phase 2 is where that flips.
1505
+ recovered = self._left_account_recovered(
1506
+ state,
1507
+ kw["usage"],
1508
+ kw["headroom"],
1509
+ kw["active_headroom"],
1510
+ kw["settings"],
1511
+ kw["now"],
1512
+ kw["current"],
1513
+ thresholds=kw["thresholds"],
1514
+ entries=entries,
1515
+ )
1516
+ no_return = self._no_return_account(
1517
+ trigger,
1518
+ state,
1519
+ kw["headroom"],
1520
+ kw["active_headroom"],
1521
+ recovered,
1522
+ kw["settings"],
1523
+ kw["current"],
1524
+ thresholds=kw["thresholds"],
1525
+ usage=kw["usage"],
1526
+ )
1527
+ ranked = self._rank_candidates(no_return=no_return, **kw)
1528
+ if no_return is not None and not ranked[0] and recovered:
1529
+ unbarred = self._rank_candidates(no_return=None, **kw)
1530
+ if unbarred[0]:
1531
+ return unbarred
1532
+ return ranked
1533
+
1534
+ if trigger == "active-stale":
1535
+ # The landing must be measured in this pass, and an idle peer is
1536
+ # otherwise read every five to ten minutes. Asked for only now,
1537
+ # once the count and the cooldown allow a move, so the ticks
1538
+ # spent waiting keep every peer on its own poll plan. The active
1539
+ # row is left to its own backoff.
1540
+ entries = self.switcher.usage_entries_by_account(
1541
+ fetch=set(oauth_candidates)
1542
+ )
1543
+ if not _active_reading_blind(entries.get(current), self.clock()):
1544
+ # Another surface read the active account while this tick
1545
+ # ran. The reason to leave is gone; the next tick decides on
1546
+ # the new reading.
1547
+ self._unhealthy_ticks = 0
1548
+ self._emit(
1549
+ NoSwitchEvent(
1550
+ reason="active-usage-refreshed",
1551
+ detail="read again during this check",
1552
+ )
1553
+ )
1554
+ return TickOutcome.NO_ACTION
1555
+ usage = {num: entry.decision_value() for num, entry in entries.items()}
1556
+ headroom = _headroom_by_account(usage, self._models)
1557
+ active_headroom = headroom.get(current)
1558
+
1559
+ decided_now = self.clock()
1560
+ ordered, any_known, active_reset_ts = _rank(
1561
+ trigger=trigger,
1562
+ consume_first=consume_first,
1563
+ oauth_candidates=oauth_candidates,
1564
+ usage=usage,
1565
+ headroom=headroom,
1566
+ current=current,
1567
+ active_headroom=active_headroom,
1568
+ settings=settings,
1569
+ now=decided_now,
1570
+ thresholds=thresholds,
1571
+ )
1572
+
1573
+ if trigger == "active-stale" and not ordered:
1574
+ return self._stay_blind(active_binding, active_entry)
1575
+
1576
+ if (
1577
+ trigger != "active-stale"
1578
+ and (trigger == "consume-first" or priority_mode)
1579
+ and ordered
1580
+ ):
1581
+ # Two-phase commit: the provisional pick may have ridden a
1582
+ # snapshot up to CANDIDATE_MAX_INTERVAL_S stale — consume-first
1583
+ # decides below the threshold, where the collector only escalates
1584
+ # inside the ESCALATION_MARGIN_PCT band (flat-traffic invariant).
1585
+ # A switch is imminent, so spend the fetches now and re-decide on
1586
+ # fresh data.
1587
+ # reserve() serves just-fetched accounts from the store, so this
1588
+ # is cheap in-tick and plan-bounded across ticks. The trigger is
1589
+ # deliberately NOT re-classified if the fresh active crossed the
1590
+ # threshold: a still-qualifying sooner target switches anyway,
1591
+ # and otherwise the next tick escalates normally and escapes.
1592
+ entries = self.switcher.usage_entries_by_account(
1593
+ fetch={current, *candidates}
1594
+ )
1595
+ usage = {num: entry.decision_value() for num, entry in entries.items()}
1596
+ headroom = _headroom_by_account(usage, self._models)
1597
+ active_headroom = headroom.get(current)
1598
+ decided_now = self.clock()
1599
+ ordered, any_known, active_reset_ts = _rank(
1600
+ trigger=trigger,
1601
+ consume_first=consume_first,
1602
+ oauth_candidates=oauth_candidates,
1603
+ usage=usage,
1604
+ headroom=headroom,
1605
+ current=current,
1606
+ active_headroom=active_headroom,
1607
+ settings=settings,
1608
+ now=decided_now,
1609
+ thresholds=thresholds,
1610
+ )
1611
+
1612
+ priority_active_ready = priority_mode and current in switchable and self._priority_ready(
1613
+ usage.get(current), headroom.get(current), settings, thresholds[current]
1614
+ )
1615
+ if (
1616
+ not ordered and api_key_candidates
1617
+ and trigger not in ("consume-first", "priority")
1618
+ and not priority_active_ready
1619
+ ):
1620
+ # Last resort when we must move: metered API-key accounts
1621
+ # (unmeasurable headroom). Never for a below-threshold consume-first
1622
+ # nudge — those API-key accounts have no weekly window to consume.
1623
+ ordered = api_key_candidates
1624
+
1625
+ if not ordered:
1626
+ if priority_active_ready:
1627
+ self._emit(NoSwitchEvent(
1628
+ reason="already-consuming-priority",
1629
+ detail="no usable account has higher priority or an earlier weekly reset in this tier",
1630
+ ))
1631
+ return TickOutcome.NO_ACTION
1632
+ if priority_mode:
1633
+ self._emit(NoSwitchEvent(
1634
+ reason="no-qualifying-candidate",
1635
+ detail="no candidate is below every switch line with readable usage; waiting for recovery",
1636
+ ))
1637
+ return TickOutcome.BLOCKED
1638
+ if not any_known:
1639
+ # No candidate readable this tick — true for every strategy,
1640
+ # and must not be dressed up as a consume-first hold.
1641
+ self._emit(
1642
+ NoSwitchEvent(
1643
+ reason="no-comparison",
1644
+ detail="no candidate has readable usage",
1645
+ )
1646
+ )
1647
+ return TickOutcome.BLOCKED
1648
+ if trigger == "consume-first":
1649
+ # Below the threshold and healthy: staying put is a correct
1650
+ # outcome, never a block. Distinguish *why* nothing qualified
1651
+ # so an opted-in user can see the strategy working (or inert).
1652
+ if active_reset_ts is None:
1653
+ # The strictly-sooner filter skips every candidate when the
1654
+ # active account's weekly reset is unknown — without this
1655
+ # reason the strategy would look enabled while doing
1656
+ # nothing, with no way to tell.
1657
+ self._emit(
1658
+ NoSwitchEvent(
1659
+ reason="reset-unknown",
1660
+ detail=(
1661
+ "active account's weekly reset time is "
1662
+ "unknown; consume-first is idle until it "
1663
+ "is reported"
1664
+ ),
1665
+ )
1666
+ )
1667
+ return TickOutcome.NO_ACTION
1668
+ # Covers both "everyone resets later" and "sooner ones have no
1669
+ # room" — don't claim the active account resets first when the
1670
+ # real story may be exhausted candidates.
1671
+ self._emit(
1672
+ NoSwitchEvent(
1673
+ reason="already-consuming-soonest",
1674
+ detail="no sooner-resetting account with room to spare",
1675
+ )
1676
+ )
1677
+ return TickOutcome.NO_ACTION
1678
+ # "All exhausted" (and its bounded reset-aware sleep) only when it's
1679
+ # literally true: every candidate's usage is known and at its
1680
+ # limit. A candidate that merely failed the proactive hysteresis
1681
+ # gate, or one whose usage is unreadable this tick, can become
1682
+ # viable at any moment — and the active account can hit 100% and
1683
+ # need the at-limit escape — so those keep the normal cadence.
1684
+ candidate_headrooms = [headroom.get(n) for n in oauth_candidates]
1685
+ truly_exhausted = all(
1686
+ h is not None and h <= 0 for h in candidate_headrooms
1687
+ )
1688
+ if not truly_exhausted:
1689
+ self._emit(
1690
+ NoSwitchEvent(
1691
+ reason="no-qualifying-candidate",
1692
+ detail=(
1693
+ "no candidate is below its switch lines and better "
1694
+ "than the active account by the hysteresis "
1695
+ "margin, or usage is unreadable this tick"
1696
+ ),
1697
+ )
1698
+ )
1699
+ return TickOutcome.BLOCKED
1700
+ self._blocked_wait_long = True
1701
+ earliest = self._earliest_recovery(usage)
1702
+ if earliest is not None:
1703
+ self._sleep_until_ts = earliest.timestamp() + RESET_SLACK_S
1704
+ self._emit(
1705
+ AllExhaustedEvent(
1706
+ earliest_reset_at=(
1707
+ earliest.isoformat().replace("+00:00", "Z")
1708
+ if earliest
1709
+ else None
1710
+ )
1711
+ )
1712
+ )
1713
+ return TickOutcome.BLOCKED
1714
+
1715
+ # -- freshen + switch ----------------------------------------------
1716
+ # The departure snapshot of the account we are leaving, taken from the
1717
+ # SAME `usage`/`headroom` the ranking just decided on — for
1718
+ # consume-first that is the phase-2 refetch, not the stale one.
1719
+ left_snapshot = (
1720
+ active_headroom,
1721
+ _binding_recovery_ts(
1722
+ usage.get(current),
1723
+ self._models,
1724
+ decided_now,
1725
+ threshold=thresholds[current],
1726
+ weekly_threshold=settings.weekly_threshold,
1727
+ scale=settings.threshold,
1728
+ ),
1729
+ )
1730
+ transient_failure = False
1731
+ systemic = ""
1732
+ for num in ordered:
1733
+ email = self.switcher.account_email(num)
1734
+ if trigger == "consume-first" or (priority_mode and num in oauth_candidates):
1735
+ # The phase-2 refetch is best-effort: the collector refuses
1736
+ # accounts in failure backoff or claimed by a concurrent
1737
+ # poller, which then serve their stored entries. Consume-first
1738
+ # is opportunistic, not an escape — never act on stale data
1739
+ # or slide to a worse-ranked target; hold and retry next tick.
1740
+ # Priority rotation also requires fresh target data for escapes,
1741
+ # but an unusable active account must not be stranded by one
1742
+ # stale candidate when a lower-ranked fresh target can take over.
1743
+ entry = entries.get(num)
1744
+ if entry is None or not entry.fresh(self.clock()):
1745
+ self._emit(
1746
+ NoSwitchEvent(
1747
+ reason="stale-usage",
1748
+ detail=(
1749
+ f"account {num} usage could not be refreshed "
1750
+ "this tick (backoff or a concurrent poller); "
1751
+ "retrying"
1752
+ ),
1753
+ )
1754
+ )
1755
+ if priority_mode and not priority_active_ready:
1756
+ continue
1757
+ return TickOutcome.NO_ACTION
1758
+ if self.dry_run:
1759
+ # Dry-run stops at the decision: no token refresh, no
1760
+ # quarantine writes — freshening is a mutation.
1761
+ return self._perform(num, email, trigger, left_snapshot)
1762
+ status = self._freshen_target(num, email)
1763
+ if status == "identity-conflict":
1764
+ # The slot's credential is alive but belongs to a different
1765
+ # account — switching onto it would silently run the wrong
1766
+ # account. Quarantine (auto-released once a re-add replaces
1767
+ # the credential).
1768
+ self._quarantine(num, email, "identity-conflict")
1769
+ continue
1770
+ if status == "invalid_grant":
1771
+ self._quarantine(num, email, "invalid_grant")
1772
+ continue
1773
+ if status == "transient":
1774
+ transient_failure = True
1775
+ continue
1776
+ if status in _SYSTEMIC_STATUSES:
1777
+ # ONE cause is reported, so it must be the one worth acting
1778
+ # on. Assigning unconditionally made it the LAST candidate's,
1779
+ # and `consume-busy` clears itself on the next pass while the
1780
+ # other two need a human — unset an env var, chase a rejected
1781
+ # client_id. So a busy slot sorting after an unmirrored one
1782
+ # named the harmless cause and hid the real one: exactly the
1783
+ # "reads as intermittent, nothing names it" trap these kinds
1784
+ # were split out of "transient" to escape.
1785
+ if not systemic or _SYSTEMIC_STATUSES.index(
1786
+ status
1787
+ ) < _SYSTEMIC_STATUSES.index(systemic):
1788
+ systemic = status
1789
+ continue
1790
+ if status in ("skip-live-session", "skip-live-login"):
1791
+ continue
1792
+ return self._perform(num, email, trigger, left_snapshot)
1793
+
1794
+ if systemic or transient_failure:
1795
+ self._emit(
1796
+ ErrorEvent(
1797
+ message="could not freshen: " + _SYSTEMIC_MESSAGES[systemic]
1798
+ if systemic
1799
+ else "could not freshen any candidate (network?)",
1800
+ transient=True,
1801
+ )
1802
+ )
1803
+ return TickOutcome.ERROR
1804
+ self._emit(NoSwitchEvent(reason="no-viable-target"))
1805
+ return TickOutcome.BLOCKED
1806
+
1807
+ def _no_return_account(
1808
+ self,
1809
+ trigger: str,
1810
+ state: dict,
1811
+ headroom: dict[str, float | None],
1812
+ active_headroom: float | None,
1813
+ recovered: bool,
1814
+ settings: AutoSwitchSettings,
1815
+ current: str | None = None,
1816
+ *,
1817
+ usage: dict[str, dict | str | None],
1818
+ # Optional so a caller with no per-account context (and every
1819
+ # pre-existing test that exercises this helper directly) keeps
1820
+ # today's exact semantics: one global line for every account. The
1821
+ # engine's own tick always passes the resolved map explicitly.
1822
+ thresholds: Mapping[str, float] | None = None,
1823
+ ) -> str | None:
1824
+ """The account this engine most recently left, while it is still barred.
1825
+
1826
+ NEVER UNDO THE PREVIOUS MOVE. Each anti-flap margin is measured against
1827
+ the ACTIVE, and burn changes the active, so a burning pair can clear the
1828
+ margin in both directions. Measured, only the active burning:
1829
+ `[1, 2, 1, 2]` where one move was due.
1830
+
1831
+ SCOPED like every sibling gate — `at-limit` and `failover` skip the
1832
+ anti-flap gates by design. Unscoped this stranded a 2-account fleet on
1833
+ an exhausted active with the peer at 0%.
1834
+
1835
+ AND SCOPED TO THE ENGINE'S OWN LANDING (`lastSwitchTo == current`).
1836
+ The bar refuses to undo THIS ENGINE'S last move; once the user
1837
+ switches by hand the engine is no longer sitting where it put itself
1838
+ and that move is already undone, so the bar protects nothing and
1839
+ merely withholds the fleet's best account. Reproduced: engine 1 -> 2,
1840
+ user 2 -> 3 by hand, account 1 on 4 pts still barred against an
1841
+ active on 2, every reset far out, no release leg reachable — the
1842
+ `not recovered` return below fires before the ratio leg is read, and
1843
+ `recovered` is False because account 1 was 4 pts at departure too.
1844
+ The engine then holds the worse account until the at-limit escape.
1845
+ Both sides are `str`-normalised: `lastSwitchTo` is a `str` from
1846
+ `_perform` and `lastSwitchFrom` an `int` from `account_ref`. A state
1847
+ record written before `lastSwitchTo` existed has no such key and
1848
+ cannot prove the engine moved away, so it KEEPS the bar — the same
1849
+ conservative reading this module gives every other missing field, and
1850
+ the only one that does not silently drop the anti-flap bound for an
1851
+ upgrade cycle.
1852
+
1853
+ RELEASED when the account we left now beats us by the margin the
1854
+ all-above ranking uses (`_all_above_margin_met`): that is not the flip
1855
+ this bars, it is a move the outbound leg would have made on its own
1856
+ merits — BUT ONLY IF IT HAS ACTUALLY RECOVERED. The ratio compares
1857
+ against the ACTIVE, and the active burns, so ungated it comes true on
1858
+ a target that has done nothing. Measured on the cited walk, the barred
1859
+ account held 4.0 pts at departure and 4.0 pts at every return; the
1860
+ ratio fired purely because the active fell to 2.0, which is the flap
1861
+ arriving through the release instead of through the ranking.
1862
+ `recovered` is that gate, computed once per snapshot by
1863
+ `_left_account_recovered` and shared with the leaves-nothing retry in
1864
+ `_rank` so the two cannot disagree.
1865
+
1866
+ THE LEAVES-NOTHING RELEASE IS NOT HERE. It used to be, and it was
1867
+ rewritten twice for the same reason both times: this function cannot
1868
+ see the gates that decide. `lastSwitchFrom` is rewritten only by a
1869
+ successful switch — the one thing the bar prevents — so a bar that
1870
+ empties the ranking is permanent, and each attempt to predict emptiness
1871
+ landed one gate short of the ranking loop:
1872
+
1873
+ all(n == barred ...) "does another account EXIST"
1874
+ (headroom.get(n) or 0.0) > 0.0 "is another account not at its limit"
1875
+
1876
+ The loop also applies each candidate's own lines and the all-above
1877
+ margin (`_all_above_margin_met`). A third account on ONE point clears
1878
+ both predicates above and neither of those, so the n=2 stall came back
1879
+ at n>=3.
1880
+
1881
+ `_rank` now ASKS the ranking instead: it ranks with the bar, and
1882
+ re-ranks without it when the result is empty. That is exact by
1883
+ construction, and cannot be one gate behind because it is not a
1884
+ separate copy of the gates.
1885
+
1886
+ EMPTINESS ALONE IS NOT THE RELEASE, though — see `_rank`. At n=2 the
1887
+ barred ranking is always empty, so an emptiness-only retry is a no-op
1888
+ at exactly the fleet size the flap was reported on. Both the retry and
1889
+ the ratio above are gated on `recovered`, which is the one question the
1890
+ ranking cannot answer: is this a different account from the one we
1891
+ left, or only a different active?
1892
+ """
1893
+ if thresholds is None:
1894
+ thresholds = ThresholdMap({}, settings.threshold)
1895
+ came_from = state.get("lastSwitchFrom")
1896
+ if trigger not in ("proactive", "consume-first") or came_from is None:
1897
+ return None
1898
+ # Only while we are still standing where that switch put us. A manual
1899
+ # switch away already undid the move, so there is nothing left to
1900
+ # refuse to undo. `str` on both sides: `lastSwitchTo` is written from
1901
+ # `_perform`'s `number: str`, `lastSwitchFrom` from `account_ref`'s
1902
+ # `number: int`, and an int/str mismatch here would disarm the bar
1903
+ # everywhere rather than only after a hand switch.
1904
+ landed_on = state.get("lastSwitchTo")
1905
+ if landed_on is not None and current is not None:
1906
+ if str(landed_on) != str(current):
1907
+ return None
1908
+ # No membership check on `oauth_candidates`: the loop compares
1909
+ # `num == no_return` while iterating that same list, so naming an
1910
+ # account that is not in it bars nothing. The check was a no-op and
1911
+ # nothing killed it under mutation.
1912
+ barred = str(came_from)
1913
+ if not recovered:
1914
+ return barred # the ratio below burns true on its own; see above
1915
+ left_headroom = headroom.get(barred)
1916
+ if left_headroom is not None:
1917
+ if active_headroom is not None:
1918
+ if _all_above_margin_met(left_headroom, active_headroom):
1919
+ return None # beats us outright; not a flip
1920
+ elif settings is not None:
1921
+ # An unreadable active must not be silently scored as "the
1922
+ # peer does not beat it" -- same landing-eligible fallback
1923
+ # `_left_account_recovered` uses when it, too, has no active
1924
+ # to compare against: would the ranking accept the peer as a
1925
+ # landing spot, i.e. is it under every one of its own lines?
1926
+ left = self._binding(usage.get(barred), settings, thresholds[barred])
1927
+ if left is not None and not left.over:
1928
+ return None
1929
+ return barred
1930
+
1931
+ def _left_account_recovered(
1932
+ self,
1933
+ state: dict,
1934
+ usage: dict[str, dict | str | None],
1935
+ headroom: dict[str, float | None],
1936
+ active_headroom: float | None,
1937
+ settings: AutoSwitchSettings,
1938
+ now: float,
1939
+ current: str | None = None,
1940
+ *,
1941
+ # Optional so a caller with no per-account context (and every
1942
+ # pre-existing test that exercises this helper directly) keeps
1943
+ # today's exact semantics: one global line for every account. The
1944
+ # engine's own tick always passes the resolved map explicitly.
1945
+ thresholds: Mapping[str, float] | None = None,
1946
+ # The tick's entries, for the one departure that is judged on more
1947
+ # than a decision value (`active-stale`, below).
1948
+ entries: Mapping[str, UsageEntry] | None = None,
1949
+ ) -> bool:
1950
+ """Is the account we left a better proposition than when we left it?
1951
+
1952
+ This is the release the bar needs and the ranking cannot supply. A bar
1953
+ that leaves nothing is a stall, but "leaves nothing" is also what every
1954
+ flap looks like on two accounts, so lifting on emptiness alone lifts
1955
+ always. The distinction is not in the present state — it is between the
1956
+ present and the moment of departure, which is why `_perform` records
1957
+ that moment (`leftHeadroom` / `leftRecoveryAt`) alongside
1958
+ `lastSwitchFrom`.
1959
+
1960
+ Measured on the walk this guard exists for, the barred account was
1961
+ IDENTICAL at every return — same headroom, same reset — and only the
1962
+ active had changed. That is the flap: the ranking flipped underneath a
1963
+ target that did nothing.
1964
+
1965
+ FAILOVER FIRST, before any leg reads the active — checked ahead of
1966
+ dominance, because dominance-first starves this branch:
1967
+ `test_a_failover_departure_does_not_disarm_the_bar` broke on its
1968
+ FIRST tick the instant the active fell far enough for `4.0 > active
1969
+ x 2` to go true (measured at active=1.8, one fifth of a point past
1970
+ the boundary this branch's own sibling test already sits on).
1971
+ A `(None, None)` snapshot means severity was genuinely unmeasured at
1972
+ departure — there is no `leftHeadroom` to diff against and never was
1973
+ — so the two signals that do not depend on the active's LIVE state
1974
+ are (1) whether the peer, right now, would itself be a healthy place
1975
+ to land: under every one of its own switch lines (`not
1976
+ binding.over`), the same "would the ranking accept this as a landing
1977
+ spot" test the landing gate in `_rank_candidates` already runs on
1978
+ every candidate, reused rather than inventing a fresh
1979
+ constant; and (2), when the landing floor cannot answer, whether the
1980
+ peer's own binding reset is meaningfully sooner than the active's.
1981
+ The landing floor is the exact complement of
1982
+ `_every_account_above_threshold`, so it is UNSATISFIABLE whenever
1983
+ the
1984
+ fleet is all-spent — the recovery leg is what keeps the hold from
1985
+ becoming unconditional in exactly that regime. Neither leg can tell
1986
+ "genuinely recovered" from "was already this good" — there is
1987
+ nothing recorded to tell them apart. Measured which side the landing
1988
+ floor should land on: sweeping mutations of this same leg for the
1989
+ ordinary path showed an absolute floor is silently reintroducible
1990
+ with a green suite, so this is not free of that risk either — the
1991
+ difference is this constant is the user's own switch lines (the
1992
+ peer's effective threshold — its per-account override, else
1993
+ `settings.threshold` — and `settings.weekly_threshold`), not a
1994
+ hardcoded number, so a
1995
+ user's OWN policy decides how conservative the hold is, and it moves
1996
+ when they change it (pinned directly, below). Deliberately MORE
1997
+ conservative than the ordinary path below: a peer sitting at 4 points
1998
+ held through the whole walk that broke a bare dominance leg, with no
1999
+ upper bound short of the peer crossing the threshold itself OR its
2000
+ binding reset pulling meaningfully ahead of the active's. Bounded,
2001
+ not permanent — at-limit still escapes untouched
2002
+ (`_no_return_account` scopes this trigger out entirely), and the
2003
+ recovery leg means the bound is no longer just "the active reaches
2004
+ its own hard limit": a peer that resets first releases the hold on
2005
+ its own schedule, without the active ever needing to burn down to it.
2006
+
2007
+ THE ORDINARY PATH HAS A REAL BASELINE (`leftHeadroom` is a number,
2008
+ not null), so it gets three legs, checked in this order, each with
2009
+ the margin its axis already uses. Burn cannot manufacture any of
2010
+ them: headroom rises only when a window rolls over, the ratio needs
2011
+ the active to lose more than half its remaining headroom AND clear
2012
+ an extra `SPENT_HEADROOM_PCT` on top, and the binding reset moves
2013
+ nearer only when a nearer window starts binding.
2014
+
2015
+ dominance `> active x HORIZON_HEADROOM_RATIO + SPENT_HEADROOM_PCT`
2016
+ against the ACTIVE. A peer moved AWAY from for a reason
2017
+ other than headroom (e.g. consume-first's reset
2018
+ ordering) can dominate the active from the moment it
2019
+ was left, and self-improvement against its own
2020
+ departure baseline never fires for an account that had
2021
+ nothing to improve on. The `+SPENT_HEADROOM_PCT` on top
2022
+ of the bare ratio is what the bare ratio misses:
2023
+ measured on this branch's own flap fleet (peer frozen
2024
+ 4.0 pts, active burning 98.0% -> 98.4%), it flips
2025
+ true at active=1.8 pts purely because the active kept
2026
+ burning; the same walk with the margin added stays
2027
+ false through active=1.6 and only opens once the active
2028
+ is down to a genuine sliver (`x < 0.5`), which is the
2029
+ at-limit escape's territory, not a return worth calling
2030
+ anti-flap. `test_a_burn_walk_never_returns_to_what_it_
2031
+ left` still settles with the margin in place — it makes
2032
+ the boundary harder to cross, not impossible.
2033
+ headroom `+SPENT_HEADROOM_PCT` against the DEPARTURE baseline
2034
+ — below that an edge is under two poll intervals.
2035
+ recovery `-RECOVERY_HYSTERESIS_S` against the DEPARTURE
2036
+ baseline — longer than one poll cycle, so jitter on a
2037
+ reset timestamp is not a recovery.
2038
+
2039
+ NO SNAPSHOT MEANS RELEASE. State written before this field existed, or
2040
+ by a switch that never recorded one, carries no evidence either way —
2041
+ and of the two failure modes the permanent proactive lockout is the
2042
+ worse one, because it is persisted and survives a restart and a week of
2043
+ wall clock. Absence of evidence releases. This only gates the
2044
+ proactive/consume-first return; `_no_return_account` scopes at-limit
2045
+ and failover out of the bar by design, so either trigger still
2046
+ escapes the account untouched, and the next successful switch
2047
+ overwrites the snapshot outright.
2048
+ """
2049
+ if thresholds is None:
2050
+ thresholds = ThresholdMap({}, settings.threshold)
2051
+ came_from = state.get("lastSwitchFrom")
2052
+ if came_from is None:
2053
+ # Unreachable through `_no_return_account`, the only caller: it
2054
+ # returns `None` at its own `came_from is None` check before
2055
+ # `recovered` is ever read. Kept `True` (not load-bearing) so a
2056
+ # future direct caller gets "no evidence, release" rather than a
2057
+ # silent hold.
2058
+ return True
2059
+ barred = str(came_from)
2060
+ if "leftHeadroom" not in state:
2061
+ return True # pre-upgrade record: genuinely no evidence
2062
+ h = headroom.get(barred)
2063
+ left_headroom = state.get("leftHeadroom")
2064
+ left_recovery = state.get("leftRecoveryAt")
2065
+ # A `consume-first` departure can ALSO write (None, None) -- the
2066
+ # same shape a real failover writes -- whenever the phase-2 refetch's
2067
+ # active row is unmeasurable for headroom but still has a known
2068
+ # weekly reset (the split shape `oauth.
2069
+ # build_usage_result` emits for `utilization: null` plus a
2070
+ # `resets_at`). Inferring "failover" from the two nulls then ran the
2071
+ # more permissive failover legs (landing floor + recovery-only) on
2072
+ # what was really an ordinary departure -- reachable on 32%+ of
2073
+ # swept fleets, both directions. `leftTrigger` records the actual
2074
+ # trigger so this never has to guess again; a record written before
2075
+ # this field existed has no such key, so fall back to the old
2076
+ # two-null inference for it (unchanged behaviour for pre-upgrade
2077
+ # state).
2078
+ left_trigger = state.get("leftTrigger")
2079
+ if left_trigger == "active-stale" and entries is not None:
2080
+ # Left because a 429 kept it from being read. Until a refresh of
2081
+ # it succeeds, the number it shows is the one that was not
2082
+ # trusted, however good it looks beside the active's.
2083
+ left = entries.get(barred)
2084
+ if left is None or left.consecutive_failures > 0:
2085
+ return False
2086
+ is_failover_snapshot = (
2087
+ # `active-stale` left with no baseline it trusted, like failover.
2088
+ left_trigger in ("failover", "active-stale")
2089
+ if left_trigger is not None
2090
+ else (left_headroom is None and left_recovery is None)
2091
+ )
2092
+ if is_failover_snapshot:
2093
+ # Failover: real departure, severity unmeasured at the time --
2094
+ # not absence of evidence, and there is no baseline to diff
2095
+ # against (that is exactly what "unmeasured" means), so this
2096
+ # cannot use the active's HEADROOM at all -- see docstring for
2097
+ # why reading the active's headroom here is wrong, and the walk
2098
+ # that proved it. Two legs, both read-only against CURRENT state
2099
+ # (no departure baseline exists to diff against):
2100
+ #
2101
+ # landing `not peer.over` -- under every one of its own
2102
+ # lines: would the ranking accept this peer as a
2103
+ # landing spot right now (the landing gate in
2104
+ # `_rank_candidates`)?
2105
+ # recovery the peer's binding reset is meaningfully sooner
2106
+ # than the ACTIVE's binding reset. Needed because
2107
+ # `landing` is the exact complement of `_every_
2108
+ # account_above_threshold`: whenever the fleet is
2109
+ # all-spent, `landing` is unsatisfiable by
2110
+ # construction, so without this leg the bar would
2111
+ # hold until the active hit its limit. Releasing the
2112
+ # bar does not choose the peer; the room ranking and
2113
+ # its margin still decide.
2114
+ #
2115
+ # Burn cannot fake the recovery leg: a reset moves nearer only
2116
+ # when a nearer window starts binding, never as a side effect
2117
+ # of the active spending down -- the failure mode a bare
2118
+ # dominance leg has, guarded directly in the mutation table.
2119
+ peer = self._binding(usage.get(barred), settings, thresholds[barred])
2120
+ if peer is not None and not peer.over:
2121
+ return True
2122
+ peer_recovery_ts = _binding_recovery_ts(
2123
+ usage.get(barred),
2124
+ self._models,
2125
+ now,
2126
+ threshold=thresholds[barred],
2127
+ weekly_threshold=settings.weekly_threshold,
2128
+ scale=settings.threshold,
2129
+ )
2130
+ active_recovery_ts = _binding_recovery_ts(
2131
+ usage.get(current),
2132
+ self._models,
2133
+ now,
2134
+ threshold=thresholds[current],
2135
+ weekly_threshold=settings.weekly_threshold,
2136
+ scale=settings.threshold,
2137
+ )
2138
+ # The active's recovery must be a REAL measurement, not merely
2139
+ # "larger" -- `_binding_recovery_ts` returns `inf` for both
2140
+ # "never resets" and "we do not know" (no windows, no
2141
+ # `resets_at`, or a stale/past `resets_at`). Reading `inf` as
2142
+ # "never" here made `peer < inf - HYST` true for ANY finite
2143
+ # peer reset, releasing onto a peer arbitrarily far out on no
2144
+ # evidence. `math.isfinite` requires the active to have a
2145
+ # genuine, known reset before the comparison even runs --
2146
+ # unknown holds, exactly like unreadable already does on the
2147
+ # headroom axis.
2148
+ #
2149
+ # But two of the five `inf` states are ordinary shapes for an
2150
+ # active that is plainly alive and burning -- a `pct` reported
2151
+ # with no `resets_at`, or a `resets_at` already elapsed -- not
2152
+ # unknowns. Reading all five as "unknown, hold" pins the engine
2153
+ # on a near-spent active for up to a full window even when the
2154
+ # peer is back within `RECOVERY_HORIZON_S`. Requiring EITHER a known
2155
+ # active reset OR a peer inside that horizon keeps `isfinite`'s
2156
+ # intended release (a known active vs. an arbitrarily-far peer
2157
+ # still needs `isfinite`) while letting a near peer through
2158
+ # regardless of why the active's own reset reads `inf`.
2159
+ return (
2160
+ (
2161
+ math.isfinite(active_recovery_ts)
2162
+ or peer_recovery_ts - now <= RECOVERY_HORIZON_S
2163
+ )
2164
+ and peer_recovery_ts < active_recovery_ts - RECOVERY_HYSTERESIS_S
2165
+ )
2166
+ # Dominance over the ACTIVE, only reached once a real baseline is
2167
+ # confirmed to exist above -- a peer that was already miles ahead of
2168
+ # the active at departure (moved for a DIFFERENT reason -- e.g.
2169
+ # consume-first's reset ordering, not headroom) never "improves" on
2170
+ # its own baseline and would stall on self-improvement alone despite
2171
+ # dominating throughout.
2172
+ #
2173
+ # `active_headroom is None` means "we could not read the active this
2174
+ # tick" -- reachable through the consume-first two-phase commit,
2175
+ # which reassigns `active_headroom` from a fresh
2176
+ # refetch without re-classifying the trigger. That is a DIFFERENT
2177
+ # state from "readable, but does not dominate" and must not answer
2178
+ # the same way: fall back to the landing-eligible test the failover
2179
+ # branch above uses when IT has no baseline to compare against
2180
+ # either, rather than silently treating "unreadable" as "no
2181
+ # dominance".
2182
+ #
2183
+ # DEFENSIVE, not currently outcome-changing: measured exhaustively,
2184
+ # `active_headroom=None` on this path closes
2185
+ # BOTH of `_rank_candidates`'s gates before this leg is ever asked
2186
+ # (`_every_account_above_threshold` is False on a None active, and
2187
+ # the consume-first `active_reset_ts` gate is None too), so no
2188
+ # fleet shape has been found where this branch changes a `tick()`
2189
+ # outcome. Kept because the call IS reachable (confirmed via the
2190
+ # phase-2 refetch) and a future change to those gates could make it
2191
+ # live without anyone revisiting this function -- silently reading
2192
+ # None as "no dominance" would then be exactly the bug the
2193
+ # unreadable-active fallback was added for.
2194
+ if h is not None:
2195
+ if active_headroom is not None:
2196
+ if h > active_headroom * HORIZON_HEADROOM_RATIO + SPENT_HEADROOM_PCT:
2197
+ return True
2198
+ else:
2199
+ peer = self._binding(
2200
+ usage.get(barred), settings, thresholds[barred]
2201
+ )
2202
+ if peer is not None and not peer.over:
2203
+ return True
2204
+ if (
2205
+ isinstance(left_headroom, (int, float))
2206
+ and h is not None
2207
+ and h >= min(left_headroom + SPENT_HEADROOM_PCT, 100.0)
2208
+ ):
2209
+ return True
2210
+ # `None` is the JSON-safe spelling of "unknown or already past", which
2211
+ # `_binding_recovery_ts` returns as `inf`: an account nobody can
2212
+ # schedule around. Moving off it onto a real reset IS the improvement.
2213
+ was = left_recovery if isinstance(left_recovery, (int, float)) else float("inf")
2214
+ return (
2215
+ _binding_recovery_ts(
2216
+ usage.get(barred),
2217
+ self._models,
2218
+ now,
2219
+ threshold=thresholds[barred],
2220
+ weekly_threshold=settings.weekly_threshold,
2221
+ scale=settings.threshold,
2222
+ )
2223
+ < was - RECOVERY_HYSTERESIS_S
2224
+ )
2225
+
2226
+ def _priority_ready(
2227
+ self, value: dict | str | None, headroom: float | None,
2228
+ settings: AutoSwitchSettings, threshold: float,
2229
+ ) -> bool:
2230
+ """Priority rotation never lands at or above any configured line."""
2231
+ binding = self._binding(value, settings, threshold)
2232
+ return (
2233
+ headroom is not None and headroom > 0
2234
+ and binding is not None and not binding.over
2235
+ )
2236
+
2237
+ def _rank_priority_candidates(
2238
+ self, *, oauth_candidates: list[str],
2239
+ usage: dict[str, dict | str | None], headroom: dict[str, float | None],
2240
+ current: str, active_enabled: bool, settings: AutoSwitchSettings,
2241
+ now: float, thresholds: Mapping[str, float],
2242
+ policies: Mapping[str, AccountPolicy],
2243
+ ) -> tuple[list[str], bool, float | None]:
2244
+ """Highest usable tier, then earliest weekly reset, with stable ties.
2245
+
2246
+ Pure snapshot ranking, also used after the pre-switch refresh. Unknown
2247
+ reset times sort last within a tier; an eligible active account wins
2248
+ equal keys, so changing usage alone cannot cause ping-pong. Unlike the
2249
+ existing strategies, even at-limit/failover never selects an account
2250
+ at its switch line. Priorities do not bypass eligibility checks.
2251
+ """
2252
+ def key(num: str) -> tuple[int, float]:
2253
+ reset = _seven_day_reset_ts(usage.get(num), now)
2254
+ return (-policies.get(num, AccountPolicy()).priority,
2255
+ reset if reset is not None else float("inf"))
2256
+
2257
+ active_key = (
2258
+ key(current)
2259
+ if active_enabled and self._priority_ready(
2260
+ usage.get(current), headroom.get(current), settings, thresholds[current]
2261
+ ) else None
2262
+ )
2263
+ ordered = [
2264
+ num for num in oauth_candidates
2265
+ if self._priority_ready(usage.get(num), headroom.get(num), settings, thresholds[num])
2266
+ and (active_key is None or key(num) < active_key)
2267
+ ]
2268
+ ordered.sort(key=key) # Sequence order breaks candidate ties.
2269
+ return (
2270
+ ordered,
2271
+ any(headroom.get(num) is not None for num in oauth_candidates),
2272
+ _seven_day_reset_ts(usage.get(current), now),
2273
+ )
2274
+
2275
+ def _stay_blind(
2276
+ self, binding: BindingWindow | None, entry: UsageEntry | None
2277
+ ) -> TickOutcome:
2278
+ """Keep a blind active account for want of a measured landing.
2279
+ Staying is the decision, not a block: nothing measured is better."""
2280
+ self._emit(
2281
+ NoSwitchEvent(
2282
+ reason="no-verified-target",
2283
+ detail=(
2284
+ f"{_blind_detail(binding, entry)}; staying: no other "
2285
+ "account has a recent reading with room to spare"
2286
+ ),
2287
+ )
2288
+ )
2289
+ return TickOutcome.NO_ACTION
2290
+
2291
+ def _rank_verified_landings(
2292
+ self, *, oauth_candidates: list[str], entries: Mapping[str, UsageEntry],
2293
+ usage: dict[str, dict | str | None], headroom: dict[str, float | None],
2294
+ settings: AutoSwitchSettings, now: float,
2295
+ thresholds: Mapping[str, float], policies: Mapping[str, AccountPolicy],
2296
+ ) -> list[str]:
2297
+ """Where an ``active-stale`` move may land, best first.
2298
+
2299
+ The move is made because the active account cannot be measured, so
2300
+ the landing has to be: a reading that is ``_reading_verified``, below
2301
+ every one of its own lines, with the hysteresis margin of room under
2302
+ each (the room a ``consume-first`` landing needs, for the same
2303
+ reason: the cooldown this move starts must not hold the engine on an
2304
+ account about to cross). The active's stored number is not compared
2305
+ against, since it is the one figure here that is not a measurement.
2306
+
2307
+ Ordered as the strategy orders a forced move: by tier then soonest
2308
+ weekly reset under ``priority-consume-first``, soonest weekly reset
2309
+ under ``consume-first`` and ``weekly-first``, else most headroom
2310
+ against the account's own lines.
2311
+ """
2312
+ by_reset = settings.strategy in ("consume-first", "weekly-first")
2313
+ by_tier = settings.strategy == "priority-consume-first"
2314
+ ranked: list[tuple[tuple, str]] = []
2315
+ for num in oauth_candidates:
2316
+ h = headroom.get(num)
2317
+ if h is None or h <= 0 or not _reading_verified(entries.get(num), now):
2318
+ continue
2319
+ room = self._room(usage.get(num), settings, thresholds[num])
2320
+ if room is None:
2321
+ room = thresholds[num] - (100.0 - h)
2322
+ if room <= 0 or room < settings.hysteresis_pct:
2323
+ continue
2324
+ binding = self._binding(usage.get(num), settings, thresholds[num])
2325
+ lh = binding.line_headroom if binding is not None else h
2326
+ reset = _seven_day_reset_ts(usage.get(num), now)
2327
+ soonest = reset if reset is not None else float("inf")
2328
+ if by_tier:
2329
+ key: tuple = (-policies.get(num, AccountPolicy()).priority, soonest)
2330
+ elif by_reset:
2331
+ key = (soonest, -lh)
2332
+ else:
2333
+ key = (-lh,)
2334
+ ranked.append((key, num))
2335
+ # List order (sequence order) breaks ties.
2336
+ ranked.sort(key=lambda t: t[0])
2337
+ return [num for _, num in ranked]
2338
+
2339
+ def _rank_candidates(
2340
+ self,
2341
+ *,
2342
+ trigger: str,
2343
+ consume_first: bool,
2344
+ oauth_candidates: list[str],
2345
+ no_return: str | None,
2346
+ usage: dict[str, dict | str | None],
2347
+ headroom: dict[str, float | None],
2348
+ current: str,
2349
+ active_headroom: float | None,
2350
+ settings: AutoSwitchSettings,
2351
+ now: float,
2352
+ # See `_no_return_account`: optional, defaulting to the global line
2353
+ # for every account, so a caller without per-account context behaves
2354
+ # exactly as this function did before per-account thresholds existed.
2355
+ thresholds: Mapping[str, float] | None = None,
2356
+ ) -> tuple[list[str], bool, float | None]:
2357
+ """Filter and rank OAuth candidates for this tick's trigger.
2358
+
2359
+ Returns ``(ordered, any_known, active_reset_ts)``. Pure — no emits,
2360
+ no state writes — so the consume-first two-phase commit can run it
2361
+ twice per tick: on the stored snapshot to decide provisionally, then
2362
+ on the escalated refetch to re-verify before switching.
2363
+ """
2364
+ if thresholds is None:
2365
+ thresholds = ThresholdMap({}, settings.threshold)
2366
+ # weekly-first is `best` with consume-first's ranking: the same
2367
+ # departure line, landing gates, hysteresis and escapes as `best`, but
2368
+ # a proactive move picks the eligible account whose weekly window
2369
+ # resets soonest, since its unused weekly quota is lost first.
2370
+ weekly_first = settings.strategy == "weekly-first"
2371
+ # consume-first ranks by soonest weekly reset; a proactive (below-
2372
+ # threshold) target must reset strictly sooner than where we are.
2373
+ active_reset_ts = (
2374
+ _seven_day_reset_ts(usage.get(current), now) if consume_first else None
2375
+ )
2376
+ # One binding window per account under THIS snapshot's lines — the
2377
+ # consume-first phase-2 refetch hands in fresh `usage`, so nothing the
2378
+ # trigger computed is reused here.
2379
+ bindings = {
2380
+ num: self._binding(usage.get(num), settings, thresholds[num])
2381
+ for num in (*oauth_candidates, current)
2382
+ }
2383
+ active_binding = bindings[current]
2384
+ # Policy headroom against the active's own lines, for the hysteresis
2385
+ # gate and the sort keys below; raw when it reports no window.
2386
+ active_lh = (
2387
+ active_binding.line_headroom
2388
+ if active_binding is not None
2389
+ else active_headroom
2390
+ )
2391
+ # When NOTHING is under its lines — the active account and every
2392
+ # candidate each at or over its own switch lines — "land somewhere
2393
+ # healthy" has no answer, and holding out for one costs the user the
2394
+ # session. Sitting still means burning the active account to 100% and
2395
+ # taking a hard limit with a peer that still has room never tried. So
2396
+ # in that state the landing rule is dropped and every strategy ranks
2397
+ # by the most room left before a limit: RAW headroom, `100 - max pct`
2398
+ # over the 5h, 7d and configured per-model windows, whatever lines
2399
+ # they carry.
2400
+ #
2401
+ # Not by soonest reset. Ranking a nearly spent account ahead of one
2402
+ # with room because its window rolls over first lands on it at 98-99%,
2403
+ # where it hits its limit within a poll or two, and holds the active
2404
+ # there too while a peer that resets sooner is preferred to one with
2405
+ # real room. Measured over 32h of a 28-account fleet: every one of 18
2406
+ # switches onto a target already at 95% or more came through that
2407
+ # ranking. A reset only breaks an exact room tie. When every
2408
+ # candidate is exhausted nothing qualifies, and the all-exhausted
2409
+ # sleep wakes at the earliest reset, where that account has the most
2410
+ # room.
2411
+ #
2412
+ # Not by line headroom either. Past its lines an account's line
2413
+ # headroom is its room rescaled by how much room its line reserved,
2414
+ # so with per-account lines (global 90) a 96% account on a 95 line
2415
+ # scores 8 against an 85% account on an 80 line's 7.5, and the
2416
+ # ranking lands on the one four points from a hard limit: the failure
2417
+ # above, through a different door. Every account here has crossed the
2418
+ # lines that make line headroom meaningful, and the anti-flap margin
2419
+ # is raw (`_all_above_margin_met`), so the key is raw too, keeping
2420
+ # the filter and the sort on one axis. The cost is that a weekly point
2421
+ # counts the same as a five-hour one, though it is more work; the
2422
+ # engine has no exchange rate between windows, and a line is a policy
2423
+ # on when to leave, not a measure of capacity.
2424
+ #
2425
+ # Deliberately narrow. It engages only when every measured OAuth
2426
+ # candidate is at/over its own lines, so a single peer still under
2427
+ # them wins the normal way. A proactive move needs the active over
2428
+ # its lines too; the escapes leave whatever the active reads, and
2429
+ # failover cannot read it at all, so for them the candidates alone
2430
+ # decide.
2431
+ over_by_account = {
2432
+ num: (b.over if b is not None else None) for num, b in bindings.items()
2433
+ }
2434
+ if trigger in ("at-limit", "failover"):
2435
+ all_above = _every_candidate_above_threshold(
2436
+ oauth_candidates, over_by_account
2437
+ )
2438
+ else:
2439
+ all_above = _every_account_above_threshold(
2440
+ oauth_candidates,
2441
+ over_by_account,
2442
+ active_binding.over if active_binding is not None else None,
2443
+ )
2444
+
2445
+ def most_room(num: str, h: float) -> tuple:
2446
+ # Most raw headroom, the binding window's reset breaking an exact
2447
+ # tie: the all-above key, and a consume-first escape's below its
2448
+ # room bar.
2449
+ return (-h, _binding_recovery_ts(usage.get(num), self._models, now))
2450
+
2451
+ qualifying: list[tuple[tuple, str]] = []
2452
+ any_known = False
2453
+ for num in oauth_candidates:
2454
+ h = headroom.get(num)
2455
+ if h is None:
2456
+ continue
2457
+ any_known = True # it EXISTS and is readable either way
2458
+ if h <= 0:
2459
+ continue # itself at its limit — never a target
2460
+ if num == no_return:
2461
+ continue # the account we just left; see _no_return_account
2462
+ binding = bindings[num]
2463
+ # Policy headroom against the candidate's own lines, and whether
2464
+ # any of them is reached; raw `h` / the single line when it
2465
+ # reports no window (a readable headroom rules that out).
2466
+ lh = binding.line_headroom if binding is not None else h
2467
+ # Points left before the candidate reaches the nearest of its own
2468
+ # lines, each window in its own points (`lines.line_room`); the
2469
+ # single line against raw `h` when it reports no window.
2470
+ room = self._room(usage.get(num), settings, thresholds[num])
2471
+ if room is None:
2472
+ room = thresholds[num] - (100.0 - h)
2473
+ over = (
2474
+ binding.over
2475
+ if binding is not None
2476
+ else (100.0 - h) >= thresholds[num]
2477
+ )
2478
+ reset_ts = (
2479
+ _seven_day_reset_ts(usage.get(num), now)
2480
+ if consume_first or weekly_first
2481
+ else None
2482
+ )
2483
+ if trigger in ("proactive", "consume-first"):
2484
+ # Landing must be healthy: an account at/over any of its own
2485
+ # lines would re-trigger on the very next tick. At-limit and
2486
+ # failover are escapes that skip this whole block — any account
2487
+ # with real headroom beats a blocked or dead one.
2488
+ if over and not all_above:
2489
+ continue
2490
+ if all_above:
2491
+ # Checked before the strategies, because with nothing under
2492
+ # its lines the strategy question is moot: consume-first
2493
+ # exists to spend perishable WEEKLY quota, and every account
2494
+ # here is about to be blocked on a window. Both strategies
2495
+ # want the account with the most room, so both take this
2496
+ # gate and the matching key below. (Ordering matters: `if
2497
+ # consume_first` catching first filtered on weekly ordering
2498
+ # while the key sorted on room, two different axes, and
2499
+ # left consume-first users with no anti-flap guard at all.)
2500
+ if not _all_above_margin_met(h, active_headroom or 0.0):
2501
+ continue
2502
+ elif consume_first:
2503
+ # Purely proactive on reset ordering: below the threshold,
2504
+ # only move to accounts whose weekly window resets sooner
2505
+ # than the active one (above the threshold we must move, so
2506
+ # any healthy account qualifies and the sort picks soonest).
2507
+ if trigger == "consume-first" and (
2508
+ reset_ts is None
2509
+ or active_reset_ts is None
2510
+ or reset_ts >= active_reset_ts
2511
+ ):
2512
+ continue
2513
+ # ...and only with room to spend it: at least the hysteresis
2514
+ # margin under every one of its lines. The move is
2515
+ # opportunistic, and the cooldown it starts would hold auto on
2516
+ # a target a few points short of its line while it crosses it
2517
+ # and runs out (measured: 5h 85% under a 90 line, landed on,
2518
+ # 92/93/99% held by cooldown, the session limit hit at 100%).
2519
+ if trigger == "consume-first" and room < settings.hysteresis_pct:
2520
+ continue
2521
+ elif active_headroom is not None:
2522
+ # best: the candidate must beat the active account by the
2523
+ # full hysteresis margin (a one-way move like 99%→89%
2524
+ # qualifies; near-line pairs can't flap back). Measured in
2525
+ # policy headroom, so a 7d 93% candidate under a 97 line
2526
+ # beats a 5h 95% active under 85 — raw headroom (7 vs 5)
2527
+ # would park on the account about to hit its limit.
2528
+ if lh - active_lh < settings.hysteresis_pct:
2529
+ continue
2530
+ if all_above:
2531
+ # Every trigger, escapes included: at-limit and failover skip
2532
+ # the gate above, but an escape sorting by consume-first's
2533
+ # weekly key here lands on whichever spent account resets
2534
+ # first, and one sorting by line headroom on whichever sits on
2535
+ # the highest line. The reset breaks an exact room tie, where
2536
+ # sooner is plainly better than a lower slot number. It is the
2537
+ # reset of the window the room is measured on, the fullest one
2538
+ # (no lines passed), since its rollover is what gives the
2539
+ # account room again.
2540
+ key: tuple = most_room(num, h)
2541
+ elif consume_first or (weekly_first and trigger == "proactive"):
2542
+ # Soonest weekly reset first (unknown resets sort last), most
2543
+ # policy headroom breaks ties, then sequence order. weekly-first
2544
+ # keeps `best`'s headroom order for the at-limit and failover
2545
+ # escapes, which may land on accounts over their lines. A forced
2546
+ # (proactive) move first prefers targets with the hysteresis
2547
+ # margin of room: one a few points under its line would need
2548
+ # leaving again within the cooldown it is about to start.
2549
+ tight = trigger == "proactive" and room < settings.hysteresis_pct
2550
+ key = (tight, reset_ts if reset_ts is not None else float("inf"), -lh)
2551
+ else:
2552
+ key = (-lh,)
2553
+ if trigger in ("at-limit", "failover") and not all_above:
2554
+ # Escapes skip the landing gate on purpose (any account with
2555
+ # real headroom beats a dead one) but must still prefer a target
2556
+ # that can keep working, and one below its lines first: ranking
2557
+ # by weekly reset alone escaped onto an account at Fable 94% of
2558
+ # a 90 line while one at 1% / 3% was free (#305), and a target
2559
+ # over a line is left again at the next cooldown.
2560
+ if not consume_first:
2561
+ # best's key is already headroom; a room bar on top would
2562
+ # let a tenth of a point of room outrank points of headroom.
2563
+ key = (over, *key)
2564
+ elif not over and room >= settings.hysteresis_pct:
2565
+ # Room to spare, the hysteresis margin under every line:
2566
+ # safe to spend the soonest weekly reset first.
2567
+ key = (0, *key)
2568
+ else:
2569
+ # Without it the reset order would take 7d 97.9% under a 98 line
2570
+ # over 44%. Most raw headroom instead, as when nothing is
2571
+ # under its lines (all_above, above), under-line first.
2572
+ key = (1, over, *most_room(num, h))
2573
+ qualifying.append((key, num))
2574
+ # Ascending by the strategy's key; list order (sequence order) breaks ties.
2575
+ qualifying.sort(key=lambda t: t[0])
2576
+ return [num for _, num in qualifying], any_known, active_reset_ts
2577
+
2578
+ # -- adaptive usage scheduling ---------------------------------------------
2579
+
2580
+ def _collect_scheduled_usage(
2581
+ self,
2582
+ current: str,
2583
+ quarantined: set[str] = frozenset(),
2584
+ *,
2585
+ threshold: float | None = None,
2586
+ weekly_threshold: float | None = None,
2587
+ ) -> tuple[dict, dict[str, dict | str | None], dict[str, float | None]]:
2588
+ """Two-phase usage collection with an O(1) baseline.
2589
+
2590
+ Phase A fetches the active account (when its persisted poll plan says
2591
+ it is due — poll_policy's urgent mode is what tightens that cadence
2592
+ near the band) plus ONE due candidate (the one with the stalest data
2593
+ — never-fetched first, then oldest fetch); everyone else is served
2594
+ from the usage store. Phase B refetches ALL candidates and recomputes
2595
+ before any switch decision when a switch could be near: one of the
2596
+ active account's windows within ``ESCALATION_MARGIN_PCT`` of its own
2597
+ switch line, or active usage unknown (failover must not run on stale
2598
+ candidate data). Not while the active account is blind below its
2599
+ lines (``_active_reading_blind``): its reading cannot move, and the
2600
+ tick reads the landings itself once it may leave.
2601
+ At-limit, proactive, and ordinary unknown-usage failover selection
2602
+ never runs on the pre-escalation snapshot — those triggers imply the
2603
+ escalation condition (the deliberate exception: an owned-and-expired
2604
+ active is excluded above, so a post-idle-hold failover can run
2605
+ without escalating). The consume-first trigger can fire outside the
2606
+ escalation band, so it instead decides *provisionally* on the stored
2607
+ snapshot and, only when a switch would fire, re-runs an escalated
2608
+ collection and re-verifies the choice in ``_tick_inner`` (two-phase
2609
+ commit), plus a per-target ``UsageEntry.fresh`` gate before
2610
+ performing.
2611
+
2612
+ Stalest-first needs no rotation cursor: it reads the persisted store,
2613
+ so the loop and cron-driven ``--once`` runs schedule identically.
2614
+ Backoff (``backoffUntil``) is enforced by the collector even for the
2615
+ active account — a Retry-After must never be defeated — and during an
2616
+ idle-hold no candidate is polled at all (slow crawl for everything).
2617
+ Adapted cadences are persisted by the collector itself after each
2618
+ fetch (shared with every other surface), not by the engine.
2619
+
2620
+ Returns ``(entries, usage, headroom)`` where ``usage`` carries
2621
+ decision values and ``headroom`` the derived headroom per account.
2622
+ """
2623
+ now = self.clock()
2624
+ # Quarantined accounts can never be switch targets, so spending the
2625
+ # single alternate poll slot (or an escalation fetch) on one is wasted.
2626
+ candidates = [
2627
+ n
2628
+ for n in self.switcher.switchable_account_numbers()
2629
+ if n != current and n not in quarantined
2630
+ ]
2631
+
2632
+ pre = self.switcher.usage_entries_by_account(fetch=set())
2633
+ plan: set[str] = set()
2634
+ active_pre = pre.get(current)
2635
+ # The active account is nominated when never fetched, poll-due per its
2636
+ # persisted plan, or (no plan yet) past the normal cadence floor. The
2637
+ # collector's reserve() honors due-ness even inside the serve TTL, so
2638
+ # an urgent plan (60s while burning near the band) actually fetches.
2639
+ # A candidate-style plan (slower than any active plan can be) left
2640
+ # over from a role change the switcher never saw (e.g. a manual
2641
+ # login) is overridden past the active age cap. Exhausted accounts
2642
+ # carry their own bounded plan and become due normally.
2643
+ stale_candidate_plan = (
2644
+ active_pre is not None
2645
+ and active_pre.age_s is not None
2646
+ and active_pre.age_s >= poll_policy.ACTIVE_MAX_INTERVAL_S
2647
+ and (active_pre.poll_interval_s or 0.0)
2648
+ > poll_policy.ACTIVE_MAX_INTERVAL_S
2649
+ and (binding_pct(active_pre.last_good, self._models) or 0.0) < 100.0
2650
+ )
2651
+ overslept_plan = (
2652
+ active_pre is not None
2653
+ and plan_oversleeps_interval(active_pre, now)
2654
+ )
2655
+ if (
2656
+ active_pre is None
2657
+ or active_pre.age_s is None
2658
+ or stale_candidate_plan
2659
+ or overslept_plan
2660
+ or (
2661
+ active_pre.next_poll_at is not None
2662
+ and now >= active_pre.next_poll_at
2663
+ )
2664
+ or (
2665
+ active_pre.next_poll_at is None
2666
+ and active_pre.age_s >= poll_policy.MIN_INTERVAL_S
2667
+ )
2668
+ ):
2669
+ plan.add(current)
2670
+ if self._idle_hold_since is None:
2671
+ pick = due_candidate(candidates, pre, now)
2672
+ if pick is None:
2673
+ disabled = [
2674
+ n
2675
+ for n in self.switcher.disabled_account_numbers()
2676
+ if n != current and n not in quarantined
2677
+ ]
2678
+ pick = due_candidate(disabled, pre, now)
2679
+ if pick is not None:
2680
+ plan.add(pick)
2681
+ entries = self.switcher.usage_entries_by_account(
2682
+ fetch=plan,
2683
+ # A candidate-style plan on the active slot is deliberately
2684
+ # overridden after the active age cap; every other baseline
2685
+ # nomination preserves a valid future plan under the store lock.
2686
+ scheduled=not stale_candidate_plan,
2687
+ )
2688
+ usage = {num: entry.decision_value() for num, entry in entries.items()}
2689
+
2690
+ active_value = usage.get(current)
2691
+ active_headroom = oauth.account_headroom(
2692
+ active_value if isinstance(active_value, dict) else None, self._models
2693
+ )
2694
+ # The caller's tick-snapshotted lines, so one tick fetches and decides
2695
+ # on the same values even if apply_threshold() lands mid-tick. No
2696
+ # threshold means "the engine's own" for BOTH lines: None is a legal
2697
+ # weekly value, so it cannot mean "not passed".
2698
+ if threshold is None:
2699
+ threshold = self.settings.threshold
2700
+ weekly_threshold = self.settings.weekly_threshold
2701
+ # Any window of the active within the margin of ITS OWN line: a 5h
2702
+ # window closing on its line under a flat, higher weekly window is a
2703
+ # switch that is near, whatever the binding max says. With one line
2704
+ # this is exactly "binding utilization within the margin".
2705
+ active_windows = list(
2706
+ oauth.relevant_windows(
2707
+ active_value if isinstance(active_value, dict) else None, self._models
2708
+ )
2709
+ )
2710
+ near_a_line = any(
2711
+ pct >= window_line(label, threshold, weekly_threshold) - ESCALATION_MARGIN_PCT
2712
+ for label, pct, _ in active_windows
2713
+ )
2714
+ # A blind active below its lines is waiting out its count, on a
2715
+ # reading that cannot move. The tick reads the landings itself once
2716
+ # it may leave (`_tick_inner`), so refreshing every peer on each
2717
+ # waiting tick would only spend their request budgets.
2718
+ waiting_blind = _active_reading_blind(entries.get(current), now) and not any(
2719
+ pct >= window_line(label, threshold, weekly_threshold)
2720
+ for label, pct, _ in active_windows
2721
+ )
2722
+ escalate = bool(candidates) and not waiting_blind and (
2723
+ (active_headroom is None and active_value != USAGE_TOKEN_EXPIRED)
2724
+ or (active_headroom is not None and near_a_line)
2725
+ )
2726
+ if escalate:
2727
+ escalation_fetch = {current, *candidates}
2728
+ # Escalation may beat ordinary candidate plans to obtain a fresh
2729
+ # switch decision, but a decision-trusted exhausted row cannot be
2730
+ # a target. Preserve any wider post-429 plan instead of refetching
2731
+ # that token at the bounded all-exhausted wake cadence.
2732
+ for num in tuple(escalation_fetch):
2733
+ entry = entries.get(num)
2734
+ value = usage.get(num)
2735
+ planned_headroom = oauth.account_headroom(
2736
+ value if isinstance(value, dict) else None, self._models
2737
+ )
2738
+ if (
2739
+ entry is not None
2740
+ and entry.next_poll_at is not None
2741
+ and now < entry.next_poll_at
2742
+ and (entry.poll_interval_s or 0.0)
2743
+ > poll_policy.EXHAUSTED_INTERVAL_S
2744
+ and planned_headroom is not None
2745
+ and planned_headroom <= 0
2746
+ ):
2747
+ escalation_fetch.remove(num)
2748
+ entries = self.switcher.usage_entries_by_account(
2749
+ fetch=escalation_fetch
2750
+ )
2751
+ usage = {num: entry.decision_value() for num, entry in entries.items()}
2752
+
2753
+ headroom = _headroom_by_account(usage, self._models)
2754
+ return entries, usage, headroom
2755
+
2756
+ def _perform(
2757
+ self,
2758
+ number: str,
2759
+ email: str,
2760
+ trigger: str,
2761
+ left: tuple[float | None, float],
2762
+ ) -> TickOutcome:
2763
+ if self.dry_run:
2764
+ current = self.switcher.current_account_number()
2765
+ current_email = self.switcher.account_email(current) if current else ""
2766
+ self._emit(
2767
+ SwitchEvent(
2768
+ trigger=trigger,
2769
+ from_ref=_ref(current, current_email) if current else None,
2770
+ to_ref=_ref(number, email),
2771
+ dry_run=True,
2772
+ )
2773
+ )
2774
+ return TickOutcome.SWITCHED
2775
+
2776
+ # Hold the state lock across the whole recheck -> switch -> record
2777
+ # sequence so two concurrent engines (loop + cron --once) make one
2778
+ # serialized decision: the loser re-reads the winner's lastSwitchAt
2779
+ # and backs off instead of double-switching. No deadlock cycle: the
2780
+ # switch path (cswap FileLock + Claude Code locks) never takes the
2781
+ # state lock.
2782
+ with self._state_lock():
2783
+ state = self._read_state()
2784
+ if (
2785
+ trigger in ("proactive", "consume-first", "priority", "active-stale")
2786
+ and self._in_cooldown(state)
2787
+ ):
2788
+ self._emit(NoSwitchEvent(reason="cooldown"))
2789
+ return TickOutcome.NO_ACTION
2790
+
2791
+ result = self.switcher.switch_to(number, json_output=True)
2792
+ if not result or not result.get("switched"):
2793
+ self._emit(
2794
+ NoSwitchEvent(
2795
+ reason="already-active",
2796
+ detail=(result or {}).get("reason", ""),
2797
+ )
2798
+ )
2799
+ return TickOutcome.NO_ACTION
2800
+
2801
+ state["schemaVersion"] = STATE_SCHEMA_VERSION
2802
+ state["lastSwitchAt"] = self.clock()
2803
+ state["lastSwitchTo"] = number
2804
+ # WHERE we came from, so the next tick can refuse to undo this,
2805
+ # and WHAT IT LOOKED LIKE, so that refusal has a release that burn
2806
+ # cannot fake. See `_left_account_recovered` for why the present
2807
+ # state alone cannot supply one. `inf` is stored as null: it is not
2808
+ # portable JSON, and every other reader of this file would have to
2809
+ # learn about it.
2810
+ state["lastSwitchFrom"] = (result.get("from") or {}).get("number")
2811
+ state["leftHeadroom"], recovery = left
2812
+ state["leftRecoveryAt"] = None if recovery == float("inf") else recovery
2813
+ # A `consume-first` phase-2 refetch can write the SAME (None,
2814
+ # None) shape a `failover` departure writes, whenever the
2815
+ # refetched active row has a `pct` but is otherwise unmeasurable
2816
+ # in the same tick its weekly reset is known --
2817
+ # `account_headroom` needs a numeric `pct`, `_seven_day_reset_ts`
2818
+ # needs only `resets_at`. Inferring the trigger from the two
2819
+ # nulls then runs the wrong legs. Record it directly so the
2820
+ # reader never has to guess.
2821
+ state["leftTrigger"] = trigger
2822
+ atomic_write_json(self.state_path, state)
2823
+
2824
+ self._emit(
2825
+ SwitchEvent(
2826
+ trigger=trigger,
2827
+ from_ref=result.get("from"),
2828
+ to_ref=result.get("to"),
2829
+ warnings=result.get("warnings", []),
2830
+ )
2831
+ )
2832
+ return TickOutcome.SWITCHED
2833
+
2834
+ # -- helpers --------------------------------------------------------------
2835
+
2836
+ def _binding(
2837
+ self, value: dict | str | None, settings: AutoSwitchSettings, line: float
2838
+ ) -> BindingWindow | None:
2839
+ """The window binding this account under the tick's lines (see
2840
+ ``lines.binding_window``), or None when it reports no window. ``line``
2841
+ is the account's effective threshold from the tick's map. Reads
2842
+ only ``self._models`` and the ``settings`` it is handed, never
2843
+ ``self.settings``: a tick snapshots its settings once, and the ranking
2844
+ helpers are exercised directly on bare engines."""
2845
+ return binding_window(
2846
+ oauth.relevant_windows(
2847
+ value if isinstance(value, dict) else None, self._models
2848
+ ),
2849
+ line,
2850
+ settings.weekly_threshold,
2851
+ scale=settings.threshold,
2852
+ )
2853
+
2854
+ def _room(
2855
+ self, value: dict | str | None, settings: AutoSwitchSettings, line: float
2856
+ ) -> float | None:
2857
+ """Points left before this account's nearest line under the tick's
2858
+ lines (see ``lines.line_room``), or None when it reports no window.
2859
+ Same inputs as ``_binding``."""
2860
+ return line_room(
2861
+ oauth.relevant_windows(
2862
+ value if isinstance(value, dict) else None, self._models
2863
+ ),
2864
+ line,
2865
+ settings.weekly_threshold,
2866
+ )
2867
+
2868
+ def _in_cooldown(self, state: dict) -> bool:
2869
+ last = state.get("lastSwitchAt")
2870
+ if not isinstance(last, (int, float)):
2871
+ return False
2872
+ return (self.clock() - last) < self.settings.cooldown_seconds
2873
+
2874
+ def _check_model_names(
2875
+ self, quarantined: set[str], usage: dict[str, dict | str | None]
2876
+ ) -> None:
2877
+ """One-shot ``autoswitch.model`` typo guard.
2878
+
2879
+ A configured name that no account reports means the filter looks
2880
+ active while gating nothing. That's only provable once every
2881
+ relevant oauth account has readable usage this tick — adaptive
2882
+ polling legitimately leaves gaps before that — and never worth a
2883
+ forced refresh of its own.
2884
+ """
2885
+ wanted = {m.lower(): m for m in self._models if m.lower() != "all"}
2886
+ if not wanted:
2887
+ self._model_check_done = True # bare "all" needs no name match
2888
+ return
2889
+ relevant = [
2890
+ n
2891
+ for n in self.switcher.switchable_account_numbers()
2892
+ if n not in quarantined
2893
+ and self.switcher.account_kind_for(n) != "api_key"
2894
+ ]
2895
+ values = [usage.get(n) for n in relevant]
2896
+ readable = [v for v in values if isinstance(v, dict)]
2897
+ if not readable or len(readable) != len(values):
2898
+ return # not every account observed yet — re-check next tick
2899
+ seen = {
2900
+ s["name"].lower()
2901
+ for v in readable
2902
+ for s in (v.get("scoped") or [])
2903
+ if isinstance(s, dict) and isinstance(s.get("name"), str)
2904
+ }
2905
+ self._model_check_done = True
2906
+ missing = [name for low, name in wanted.items() if low not in seen]
2907
+ if missing:
2908
+ self._emit(
2909
+ ConfigWarningEvent(
2910
+ message=(
2911
+ f"autoswitch.model: {', '.join(missing)} matches no "
2912
+ "account's usage windows — only the 5h/7d limits are "
2913
+ "being watched for it (typo?)"
2914
+ )
2915
+ )
2916
+ )
2917
+
2918
+ def _earliest_recovery(
2919
+ self, usage: dict[str, dict | str | None]
2920
+ ) -> datetime | None:
2921
+ """Earliest moment any account becomes usable again (UTC), or None
2922
+ when that moment can't be proven.
2923
+
2924
+ Per account that's the *latest* reset among its ≥100% relevant
2925
+ windows — an account blocked on both 5h and a scoped weekly limit
2926
+ isn't usable when the 5h rolls over — then the minimum across
2927
+ accounts, the active one included (its recovery also ends the
2928
+ blocked state). A blocked account whose exhausted windows carry no
2929
+ reset time at all could recover at any moment, so it makes the whole
2930
+ answer unprovable: return None and let the bounded blocked-cadence
2931
+ fallback re-check, rather than sleeping toward another account's
2932
+ later known reset."""
2933
+ earliest: float | None = None
2934
+ now = self.clock()
2935
+ for value in usage.values():
2936
+ if not isinstance(value, dict):
2937
+ continue
2938
+ blocked = [
2939
+ resets_at
2940
+ for _, pct, resets_at in oauth.relevant_windows(value, self._models)
2941
+ if pct >= 100.0
2942
+ ]
2943
+ if not blocked:
2944
+ continue # not exhausted — doesn't gate the blocked state
2945
+ usable_at = _limiting_reset_ts(value, self._models)
2946
+ if usable_at is None or usable_at <= now:
2947
+ return None # blocked with unprovable recovery — don't oversleep
2948
+ if earliest is None or usable_at < earliest:
2949
+ earliest = usable_at
2950
+ if earliest is None:
2951
+ return None
2952
+ return datetime.fromtimestamp(earliest, tz=timezone.utc)
2953
+
2954
+ def _emit(self, event: AutoSwitchEvent) -> None:
2955
+ self.on_event(event)
2956
+
2957
+ # -- loop -------------------------------------------------------------------
2958
+
2959
+ def stop(self) -> None:
2960
+ """Ask ``run_loop`` to exit; wakes it from any sleep. Safe to call
2961
+ before the loop starts — the stop is never cleared, so the loop
2962
+ exits immediately (engines are single-use)."""
2963
+ self._stop.set()
2964
+ self._wake.set()
2965
+
2966
+ def wake(self) -> None:
2967
+ """Cut the current inter-tick sleep short and tick now."""
2968
+ self._wake.set()
2969
+
2970
+ def apply_threshold(self, threshold: float) -> None:
2971
+ """Session override from the TUI: retarget the trigger and poll
2972
+ cadence mid-run. Threshold only — the model axes (and their derived
2973
+ state) are fixed at construction. The frozen-settings swap is atomic
2974
+ and each tick snapshots ``self.settings`` once, so no locking."""
2975
+ self.settings = replace(self.settings, threshold=threshold)
2976
+ # Recomputed, not passed through: a per-account override may still be
2977
+ # lower than the new session global, and cadence follows the minimum.
2978
+ self.switcher.set_poll_policy_inputs(
2979
+ self._min_effective_threshold(),
2980
+ self.settings.weekly_threshold,
2981
+ self._models,
2982
+ )
2983
+
2984
+ def _next_delay(self, outcome: TickOutcome) -> float:
2985
+ interval = self.settings.interval_seconds
2986
+ if outcome is TickOutcome.BLOCKED:
2987
+ if self._sleep_until_ts is not None:
2988
+ delay = self._sleep_until_ts - self.clock()
2989
+ return min(max(delay, interval), MAX_SLEEP_S)
2990
+ if self._blocked_wait_long:
2991
+ # Truly exhausted with no reset time known / no candidates.
2992
+ return max(interval, NO_RESET_FALLBACK_S)
2993
+ # Blocked on something that can resolve any tick (hysteresis,
2994
+ # unreadable usage) — keep the normal cadence so the at-limit
2995
+ # escape isn't missed.
2996
+ elif outcome is TickOutcome.NO_ACTION and self._idle_hold_slow:
2997
+ # Idle-hold: Claude is idle on an expired token — nothing changes
2998
+ # until the user comes back, so crawl. Worst case protection
2999
+ # resumes one slow tick after they do.
3000
+ return max(interval, NO_RESET_FALLBACK_S)
3001
+ # ±10% jitter so multiple machines don't synchronize their API hits.
3002
+ return self._respect_poll_plan(interval * (0.9 + 0.2 * random.random()))
3003
+
3004
+ def _respect_poll_plan(self, delay: float) -> float:
3005
+ """Shorten a normal-cadence sleep to the store's own next-poll time.
3006
+
3007
+ The planner tightens the active row to URGENT_INTERVAL_S while it
3008
+ burns toward the threshold, but the loop always slept
3009
+ ``interval_seconds`` — so the plan ran late. Measured mid-episode: the
3010
+ row was due 112s ago while the engine still had minutes of sleep left.
3011
+
3012
+ Only ever shortens, never below the planner's floor: the 429 budget
3013
+ lives in the plan, and this makes the loop obey it rather than
3014
+ override it. Best-effort — the unshortened delay is always safe.
3015
+ """
3016
+ try:
3017
+ current = self.switcher.current_account_number()
3018
+ if current is None:
3019
+ return delay
3020
+ entry = self.switcher.usage_entries_by_account(fetch=set()).get(current)
3021
+ if entry is None or entry.next_poll_at is None:
3022
+ return delay
3023
+ due_in = entry.next_poll_at - self.clock()
3024
+ # Clamp the DEADLINE, not the result. max(min(delay, due_in), U)
3025
+ # raises a delay that was ALREADY below U: at the configurable
3026
+ # floor of 15s it turns a 13.5s jittered sleep into 60s, and at
3027
+ # the 60s default it flattens the entire lower jitter half.
3028
+ # Bounding due_in instead keeps "only ever shortens" true at every
3029
+ # configured interval, and still refuses to poll faster than the
3030
+ # planner's own floor when the row is overdue.
3031
+ return min(delay, max(due_in, poll_policy.URGENT_INTERVAL_S))
3032
+ except Exception:
3033
+ return delay
3034
+
3035
+ def run_loop(self) -> int:
3036
+ """Tick forever (until :meth:`stop`); a failing tick never kills it."""
3037
+ # Once per loop, not per tick: a settings key nothing reads would
3038
+ # otherwise leave the loop running on a default with no trace of why.
3039
+ log_unrecognized_keys(self.switcher.backup_dir)
3040
+ while True:
3041
+ # Clear at the top, not after the wait: a wake() racing a wait
3042
+ # timeout is then never lost — the tick right after this clear
3043
+ # already sees whatever settings that wake announced.
3044
+ self._wake.clear()
3045
+ if self._stop.is_set():
3046
+ return 0
3047
+ try:
3048
+ outcome = self.tick()
3049
+ except Exception as e: # pragma: no cover - tick() already guards
3050
+ self._emit(
3051
+ ErrorEvent(message=f"{type(e).__name__}: {e}", transient=True)
3052
+ )
3053
+ outcome = TickOutcome.ERROR
3054
+ delay = self._next_delay(outcome)
3055
+ if delay > self.settings.interval_seconds * 1.5:
3056
+ until = datetime.now(timezone.utc) + timedelta(seconds=delay)
3057
+ self._emit(
3058
+ SleepEvent(
3059
+ seconds=delay,
3060
+ until=until.isoformat(timespec="seconds").replace(
3061
+ "+00:00", "Z"
3062
+ ),
3063
+ )
3064
+ )
3065
+ self._wake.wait(delay)