sub-pool-client 0.2.0__tar.gz → 0.6.7__tar.gz

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 (21) hide show
  1. {sub_pool_client-0.2.0 → sub_pool_client-0.6.7}/PKG-INFO +1 -1
  2. {sub_pool_client-0.2.0 → sub_pool_client-0.6.7}/sub_pool_client/_cli_core.py +66 -5
  3. {sub_pool_client-0.2.0 → sub_pool_client-0.6.7}/sub_pool_client/_health_watcher.py +33 -7
  4. {sub_pool_client-0.2.0 → sub_pool_client-0.6.7}/sub_pool_client/_shared.py +13 -0
  5. {sub_pool_client-0.2.0 → sub_pool_client-0.6.7}/sub_pool_client/_version.py +2 -2
  6. {sub_pool_client-0.2.0 → sub_pool_client-0.6.7}/sub_pool_client/client.py +249 -14
  7. {sub_pool_client-0.2.0 → sub_pool_client-0.6.7}/sub_pool_client/codex.py +226 -18
  8. {sub_pool_client-0.2.0 → sub_pool_client-0.6.7}/.github/workflows/publish.yml +0 -0
  9. {sub_pool_client-0.2.0 → sub_pool_client-0.6.7}/.gitignore +0 -0
  10. {sub_pool_client-0.2.0 → sub_pool_client-0.6.7}/README.md +0 -0
  11. {sub_pool_client-0.2.0 → sub_pool_client-0.6.7}/examples/codex_hello.py +0 -0
  12. {sub_pool_client-0.2.0 → sub_pool_client-0.6.7}/examples/hello.py +0 -0
  13. {sub_pool_client-0.2.0 → sub_pool_client-0.6.7}/meta/README.md +0 -0
  14. {sub_pool_client-0.2.0 → sub_pool_client-0.6.7}/meta/pyproject.toml +0 -0
  15. {sub_pool_client-0.2.0 → sub_pool_client-0.6.7}/pyproject.toml +0 -0
  16. {sub_pool_client-0.2.0 → sub_pool_client-0.6.7}/sub_pool_client/__init__.py +0 -0
  17. {sub_pool_client-0.2.0 → sub_pool_client-0.6.7}/sub_pool_client/_cli_provider.py +0 -0
  18. {sub_pool_client-0.2.0 → sub_pool_client-0.6.7}/sub_pool_client/_swap.py +0 -0
  19. {sub_pool_client-0.2.0 → sub_pool_client-0.6.7}/sub_pool_client/cli_claude.py +0 -0
  20. {sub_pool_client-0.2.0 → sub_pool_client-0.6.7}/sub_pool_client/cli_codex.py +0 -0
  21. {sub_pool_client-0.2.0 → sub_pool_client-0.6.7}/sub_pool_client/errors.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sub-pool-client
3
- Version: 0.2.0
3
+ Version: 0.6.7
4
4
  Summary: Python client + `sp-claude` / `sp-codex` CLIs for a sub-pool credential broker.
5
5
  Project-URL: Homepage, https://github.com/subs-pool/sub-pool-client
6
6
  Project-URL: Repository, https://github.com/subs-pool/sub-pool-client
@@ -16,6 +16,7 @@ import shutil
16
16
  import signal
17
17
  import sys
18
18
  import tempfile
19
+ import time
19
20
  from contextlib import suppress
20
21
  from pathlib import Path
21
22
  from typing import Any
@@ -428,6 +429,11 @@ async def run_session(
428
429
 
429
430
  # Background tasks: token refresh + health-driven account swap.
430
431
  current = {"lease": lease}
432
+ # Set by a successful swap so the expiry-anchored refresh loop
433
+ # re-anchors to the NEW lease's token instead of sleeping out a
434
+ # now-stale deadline — a swapped-in token may have far less life
435
+ # left than the one it replaced.
436
+ refresh_wake = asyncio.Event()
431
437
 
432
438
  async def on_swap_needed(health: dict) -> None:
433
439
  # Read the from-account BEFORE swap_credentials runs —
@@ -439,6 +445,10 @@ async def run_session(
439
445
  pool, current, session_dir, provider,
440
446
  account=chosen_account,
441
447
  )
448
+ # swap_credentials already advanced current["lease"]
449
+ # (incl. token_expires_at) in its sync block; wake the
450
+ # refresh loop so it re-anchors to the new expiry.
451
+ refresh_wake.set()
442
452
  if verbose:
443
453
  log.info(
444
454
  "swapped %s → %s (reason: %s)",
@@ -450,7 +460,10 @@ async def run_session(
450
460
  log.info("swap deferred: %s", e)
451
461
 
452
462
  refresher = asyncio.create_task(
453
- _token_refresh_loop(pool, current, session_dir, provider, verbose),
463
+ _token_refresh_loop(
464
+ pool, current, session_dir, provider, verbose,
465
+ wake=refresh_wake,
466
+ ),
454
467
  name=f"sp-{provider.name}-refresh",
455
468
  )
456
469
  watcher = asyncio.create_task(
@@ -520,15 +533,63 @@ async def _refresh_once(
520
533
  async def _token_refresh_loop(
521
534
  pool: PoolHTTP, current: dict, session_dir: Path,
522
535
  provider: CliProvider, verbose: bool,
523
- *, interval_s: float = 50 * 60,
536
+ *, wake: "asyncio.Event | None" = None,
537
+ slack_s: float = 600.0, min_sleep_s: float = 60.0,
538
+ fallback_s: float = 50 * 60,
524
539
  ) -> None:
525
- """Periodically rotate access_token via the pool. Same cadence as
526
- PooledClient. See `_refresh_once` for the race-safety guard."""
540
+ """Rotate access_token via the pool BEFORE it expires.
541
+
542
+ Anthropic access tokens live only ~1h and the leased bundle is
543
+ sanitized (refreshToken=""), so the spawned CLI can't self-refresh —
544
+ the pool is the sole refresher, and the running `claude` re-reads the
545
+ rewritten .credentials.json across requests (see _swap.py).
546
+
547
+ The catch that broke this: a leased token is NOT freshly minted. The
548
+ pool only re-mints at seal time when under `slack_s` of life remains,
549
+ so a lease can hand out a token with as little as ~10min left. The old
550
+ fixed 50-min cadence therefore fired long AFTER such a token had
551
+ already died mid-session → an unrecoverable 401 (the exact failure
552
+ users hit). So anchor every sleep to the token's ACTUAL expiry
553
+ (mirrors PooledClient._poll_loop), and let a swap wake us to re-anchor
554
+ against the replacement token — which may itself be short-lived.
555
+
556
+ See `_refresh_once` for the concurrent-swap race-safety guard.
557
+ """
558
+ if wake is None:
559
+ wake = asyncio.Event() # never set → wait_for always times out
527
560
  while True:
561
+ exp = float(current["lease"].get("token_expires_at") or 0.0)
562
+ if exp <= 0:
563
+ # No usable expiry (e.g. a codex api-key lease / an exp-less JWT
564
+ # → the pool reports token_expires_at=0). We can't anchor, so
565
+ # fall back to the old fixed cadence instead of hammering /token
566
+ # every min_sleep_s (which anchoring-to-a-past-deadline would do).
567
+ sleep_s = fallback_s
568
+ else:
569
+ # A refresh that FAILS leaves exp near-now, so max()-clamping to
570
+ # min_sleep_s makes us retry every min_sleep_s until it lands —
571
+ # or the token dies, at which point a genuinely-dead refresh_token
572
+ # has already flipped the account INVALID and the health watcher
573
+ # swaps us off it.
574
+ sleep_s = max(min_sleep_s, exp - time.time() - slack_s)
528
575
  try:
529
- await asyncio.sleep(interval_s)
576
+ await asyncio.wait_for(wake.wait(), timeout=sleep_s)
577
+ except asyncio.TimeoutError:
578
+ # A swap can land in the same tick the deadline fires (set the
579
+ # wake just after wait_for times out); honor it so we re-anchor
580
+ # to the swapped-in token rather than refreshing a lease the swap
581
+ # already wrote fresh credentials for.
582
+ if wake.is_set():
583
+ wake.clear()
584
+ continue
530
585
  except asyncio.CancelledError:
531
586
  return
587
+ else:
588
+ # Woken by a swap: current["lease"] already points at the new
589
+ # token (written by swap_credentials); re-anchor without
590
+ # refreshing, since the swap installed fresh credentials.
591
+ wake.clear()
592
+ continue
532
593
  await _refresh_once(pool, current, session_dir, provider, verbose)
533
594
 
534
595
 
@@ -45,13 +45,39 @@ class HealthWatcher:
45
45
  try:
46
46
  data = await self._fetch()
47
47
  except httpx.HTTPStatusError as e:
48
- if e.response.status_code == 410:
49
- # Lease ended out from under us (someone called
50
- # DELETE, or a prior swap obsoleted us). Stop.
51
- return
52
- if e.response.status_code == 404:
53
- # Wrong key / unknown lease — same disposition.
54
- return
48
+ if e.response.status_code in (404, 410):
49
+ # Our CURRENT lease died server-side while the session is
50
+ # still live: reaped after a health-poll gap (e.g. the host
51
+ # slept past LEASE_TTL_S), externally released, or the
52
+ # account deleted. Giving up here is what left a long
53
+ # session 401ing forever with no recovery. Instead recover
54
+ # through the same swap handler — it re-leases a fresh
55
+ # account (releasing the dead one is best-effort) — then
56
+ # keep watching the new lease. `lease_gone` tells the
57
+ # handler this is a re-lease, so a same-account replacement
58
+ # (new lease_id) is still adopted rather than discarded as
59
+ # "nothing to swap to".
60
+ #
61
+ # Operator note: because of this, a bare DELETE of the lease
62
+ # no longer evicts a live client — it re-leases within one
63
+ # tick (possibly onto the same account). To take an account
64
+ # out from under a running session, DISABLE the account
65
+ # (re-lease then 503s and the client quietly waits it out) or
66
+ # revoke its api-key.
67
+ try:
68
+ await self._on_unhealthy({
69
+ "healthy": False,
70
+ "state": "gone",
71
+ "lease_gone": True,
72
+ "reason": f"lease gone ({e.response.status_code}); "
73
+ f"re-leasing",
74
+ })
75
+ except asyncio.CancelledError:
76
+ return
77
+ except Exception as ex: # noqa: BLE001
78
+ log.warning("re-lease after %s raised: %s",
79
+ e.response.status_code, ex)
80
+ continue
55
81
  # Other 4xx/5xx — log and keep going.
56
82
  log.debug("health probe http error: %s", e)
57
83
  continue
@@ -82,6 +82,15 @@ class Meta:
82
82
  # right account through `client.account` — they never saw the
83
83
  # original `POST /credentials/lease` response themselves.
84
84
  account: str | None = None
85
+ # Immutable server-side account id for this lease (surrogate PK). Persisted
86
+ # alongside `account` so a same-account check survives a rename, and so a
87
+ # holder promoted to leader after a health swap can re-sync to the CURRENT
88
+ # lease's identity from here rather than trusting its own stale cache.
89
+ account_id: int | None = None
90
+ # Current access_token expiry (epoch seconds) for the shared lease.
91
+ # Persisted so a promoted leader schedules its token poll off the CURRENT
92
+ # lease, not the one it originally joined (a health swap advances this).
93
+ token_expires_at: float = 0.0
85
94
 
86
95
  @classmethod
87
96
  def from_json(cls, d: dict) -> "Meta":
@@ -90,6 +99,8 @@ class Meta:
90
99
  holders=list(d.get("holders") or []),
91
100
  poll_leader=d.get("poll_leader"),
92
101
  account=d.get("account"),
102
+ account_id=d.get("account_id"),
103
+ token_expires_at=float(d.get("token_expires_at") or 0.0),
93
104
  )
94
105
 
95
106
  def to_json(self) -> dict:
@@ -98,6 +109,8 @@ class Meta:
98
109
  "holders": self.holders or [],
99
110
  "poll_leader": self.poll_leader,
100
111
  "account": self.account,
112
+ "account_id": self.account_id,
113
+ "token_expires_at": self.token_expires_at,
101
114
  }
102
115
 
103
116
 
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '0.2.0'
22
- __version_tuple__ = version_tuple = (0, 2, 0)
21
+ __version__ = version = '0.6.7'
22
+ __version_tuple__ = version_tuple = (0, 6, 7)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -38,6 +38,7 @@ Scale by adding accounts, not by cross-host sharing.
38
38
  from __future__ import annotations
39
39
 
40
40
  import asyncio
41
+ import contextlib
41
42
  import copy
42
43
  import json
43
44
  import logging
@@ -49,6 +50,7 @@ from typing import Any
49
50
  import httpx
50
51
  from claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient # type: ignore
51
52
 
53
+ from sub_pool_client._health_watcher import HealthWatcher
52
54
  from sub_pool_client._shared import (
53
55
  cleanup_dir,
54
56
  dir_key,
@@ -59,6 +61,7 @@ from sub_pool_client._shared import (
59
61
  from sub_pool_client.errors import (
60
62
  PoolAuthError,
61
63
  PoolConnectionError,
64
+ PoolError,
62
65
  PoolUpstreamError,
63
66
  )
64
67
 
@@ -80,6 +83,7 @@ class PooledClient(ClaudeSDKClient):
80
83
  required_model: str | None = None,
81
84
  required_features: list[str] | None = None,
82
85
  http_client: httpx.AsyncClient | None = None,
86
+ health_interval_s: float = 30.0,
83
87
  ):
84
88
  self._pool_url = (pool_url or os.environ.get("SUB_POOL_URL", "")).rstrip("/")
85
89
  self._api_key = api_key or os.environ.get("SUB_POOL_KEY", "")
@@ -92,6 +96,7 @@ class PooledClient(ClaudeSDKClient):
92
96
  self._request_id_req = request_id
93
97
  self._required_model = required_model
94
98
  self._required_features = list(required_features or [])
99
+ self._health_interval_s = health_interval_s
95
100
 
96
101
  # Caller-supplied options are never mutated; we copy to attach env.
97
102
  self._base_options = copy.copy(options) if options else ClaudeAgentOptions()
@@ -107,11 +112,18 @@ class PooledClient(ClaudeSDKClient):
107
112
  self._is_poll_leader = False # we run the token poll task
108
113
  self._lease_id: str | None = None
109
114
  self._lease_account: str | None = None
115
+ self._lease_account_id: int | None = None
110
116
  self._lease_request_id: str | None = None
111
117
  self._token_expires_at: float = 0.0
112
118
  self._sdk_inited = False
113
119
  self._poll_task: asyncio.Task | None = None
120
+ self._health_task: asyncio.Task | None = None
114
121
  self._heartbeat_task: asyncio.Task | None = None
122
+ # Set by a health swap to interrupt the poll loop's (possibly
123
+ # multi-hour) sleep so it reschedules against the NEW account's token
124
+ # expiry — otherwise a swap to a shorter-lived token could expire
125
+ # unnoticed mid-sleep.
126
+ self._poll_wake = asyncio.Event()
115
127
 
116
128
  # ============================================================ lifecycle
117
129
  async def __aenter__(self) -> "PooledClient":
@@ -137,15 +149,24 @@ class PooledClient(ClaudeSDKClient):
137
149
  await ClaudeSDKClient.__aenter__(self)
138
150
 
139
151
  if self._is_poll_leader:
140
- self._poll_task = asyncio.create_task(self._poll_loop())
152
+ self._start_leader_tasks()
141
153
  # Every holder runs the heartbeat — cheap, and takes over
142
154
  # leadership if the current leader crashed.
143
155
  self._heartbeat_task = asyncio.create_task(self._heartbeat_loop())
144
156
 
145
157
  return self
146
158
 
159
+ def _start_leader_tasks(self) -> None:
160
+ """The poll leader owns two background tasks: token rotation
161
+ (`_poll_loop`) and health-driven account swap (`_health_loop`).
162
+ Idempotent — a heartbeat promotion or re-entry won't double-spawn."""
163
+ if self._poll_task is None:
164
+ self._poll_task = asyncio.create_task(self._poll_loop())
165
+ if self._health_task is None:
166
+ self._health_task = asyncio.create_task(self._health_loop())
167
+
147
168
  async def __aexit__(self, exc_type, exc, tb) -> None:
148
- for attr in ("_poll_task", "_heartbeat_task"):
169
+ for attr in ("_poll_task", "_health_task", "_heartbeat_task"):
149
170
  t = getattr(self, attr, None)
150
171
  if t is not None:
151
172
  t.cancel()
@@ -173,9 +194,14 @@ class PooledClient(ClaudeSDKClient):
173
194
 
174
195
  async with locked_meta(self._dir) as meta:
175
196
  if meta.lease_id and meta.holders:
176
- # Active lease already present — reuse it.
197
+ # Active lease already present — reuse it. Read identity +
198
+ # expiry from meta (the shared source of truth): a prior
199
+ # health swap may have advanced them past what any earlier
200
+ # holder saw, and we may be promoted to leader later.
177
201
  self._lease_id = meta.lease_id
178
202
  self._lease_account = meta.account
203
+ self._lease_account_id = meta.account_id
204
+ self._token_expires_at = meta.token_expires_at
179
205
  # Always append (one entry per __aenter__, not per pid)
180
206
  # so N `async with` in the same pid are refcounted by
181
207
  # N removes on exit.
@@ -199,12 +225,15 @@ class PooledClient(ClaudeSDKClient):
199
225
  write_credentials(self._dir, bundle)
200
226
  self._lease_id = lease["lease_id"]
201
227
  self._lease_account = lease.get("account")
228
+ self._lease_account_id = lease.get("pool_account_id")
202
229
  self._lease_request_id = lease.get("request_id")
203
230
  self._token_expires_at = float(
204
231
  bundle.get("expires_at") or lease.get("token_expires_at") or 0.0
205
232
  )
206
233
  meta.lease_id = self._lease_id
207
234
  meta.account = self._lease_account
235
+ meta.account_id = self._lease_account_id
236
+ meta.token_expires_at = self._token_expires_at
208
237
  meta.holders = [my_pid]
209
238
  meta.poll_leader = my_pid
210
239
  self._is_first_holder = True
@@ -228,8 +257,12 @@ class PooledClient(ClaudeSDKClient):
228
257
  pass
229
258
  # If we were the poll leader, hand leadership off. The next
230
259
  # heartbeat in a surviving holder will elect itself and start
231
- # its own poll_loop.
232
- if meta.poll_leader == my_pid:
260
+ # its own poll_loop. Guard on self._is_poll_leader: with two
261
+ # instances in the SAME process (identical pid), a departing
262
+ # NON-leader must not clear the live leader's seat — that would
263
+ # trigger a spurious promotion and leave two leaders both running
264
+ # _swap_account.
265
+ if meta.poll_leader == my_pid and self._is_poll_leader:
233
266
  meta.poll_leader = None
234
267
  if not meta.holders:
235
268
  lease_id_to_release = meta.lease_id
@@ -244,9 +277,13 @@ class PooledClient(ClaudeSDKClient):
244
277
 
245
278
  # ============================================================ heartbeat
246
279
  async def _heartbeat_loop(self, interval_s: float = 30.0) -> None:
247
- """Periodically re-checks meta.json for liveness of the current
248
- poll leader. If the leader is gone (crashed / exited) this
249
- holder promotes itself and starts its own poll_loop.
280
+ """Every tick a non-leader holder (a) re-syncs its cached lease state
281
+ from meta and (b) promotes itself if the poll leader is gone.
282
+
283
+ The re-sync is what keeps a non-leader honest after the leader
284
+ health-swaps the shared lease: without it `self._lease_id` (hence
285
+ `.account`, `report_error`, and a future promotion) would stay pinned to
286
+ a released old lease.
250
287
  """
251
288
  try:
252
289
  while True:
@@ -257,13 +294,21 @@ class PooledClient(ClaudeSDKClient):
257
294
  my_pid = os.getpid()
258
295
  promoted = False
259
296
  async with locked_meta(self._dir) as meta:
297
+ # Track the shared lease (a leader's health swap advances it
298
+ # past our cache). Guard on non-None so we never clobber a
299
+ # live cache with a torn/empty meta.
300
+ if meta.lease_id is not None:
301
+ self._lease_id = meta.lease_id
302
+ self._lease_account = meta.account
303
+ self._lease_account_id = meta.account_id
304
+ self._token_expires_at = meta.token_expires_at
260
305
  # locked_meta already cleared dead-leader pids.
261
306
  if meta.poll_leader is None and my_pid in (meta.holders or []):
262
307
  meta.poll_leader = my_pid
263
308
  promoted = True
264
309
  if promoted:
265
310
  self._is_poll_leader = True
266
- self._poll_task = asyncio.create_task(self._poll_loop())
311
+ self._start_leader_tasks()
267
312
  log.info("heartbeat: promoted self to poll leader")
268
313
  return # heartbeat's job done
269
314
  except asyncio.CancelledError:
@@ -283,24 +328,49 @@ class PooledClient(ClaudeSDKClient):
283
328
  """
284
329
  try:
285
330
  while True:
331
+ self._poll_wake.clear()
286
332
  remaining = self._token_expires_at - time.time()
287
333
  # Wake up 10 min before expiry, minimum 60s sleep so we
288
334
  # don't bash the pool during tiny-TTL tests.
289
335
  sleep_s = max(60.0, remaining - 600.0)
290
- await asyncio.sleep(sleep_s)
336
+ # Interruptible sleep: a health swap sets _poll_wake so we
337
+ # recompute the schedule against the NEW (possibly much shorter)
338
+ # token expiry instead of oversleeping on the old account's.
339
+ woke_early = True
340
+ try:
341
+ await asyncio.wait_for(self._poll_wake.wait(), timeout=sleep_s)
342
+ except asyncio.TimeoutError:
343
+ woke_early = False
344
+ if woke_early:
345
+ # Swap advanced self._token_expires_at; reschedule, don't
346
+ # burn a poll on the freshly-written token.
347
+ continue
291
348
 
292
349
  if self._dir is None or self._lease_id is None:
293
350
  return
294
351
 
352
+ lease_id_before = self._lease_id
295
353
  try:
296
354
  new = await self._post_poll_token()
297
355
  except Exception as e: # noqa: BLE001
356
+ # If a swap rotated us mid-poll, this failure is just the
357
+ # OLD lease's 410 — don't clobber the new expiry the swap
358
+ # already set (that would force a pointless refresh 60s on).
359
+ if self._lease_id != lease_id_before:
360
+ continue
298
361
  log.warning("lease token poll failed: %s", e)
299
362
  # Try again in 30s; a transient 5xx / network blip
300
363
  # shouldn't tear down the agent.
301
364
  self._token_expires_at = time.time() + 60.0
302
365
  continue
303
366
 
367
+ # A health-driven swap may have rotated us onto a different
368
+ # lease/account while this poll was in flight. The token we
369
+ # just fetched belongs to the OLD lease; writing it onto the
370
+ # NEW account's shared credentials file would clobber the swap.
371
+ if self._lease_id != lease_id_before:
372
+ continue
373
+
304
374
  new_access = new.get("access_token")
305
375
  new_exp = float(new.get("token_expires_at") or 0.0)
306
376
  if not new_access or not new_exp:
@@ -337,12 +407,163 @@ class PooledClient(ClaudeSDKClient):
337
407
  )
338
408
  return r.json()
339
409
 
410
+ # ============================================================ health swap
411
+ async def _health_loop(self) -> None:
412
+ """Leader-only: watch the lease's account health and swap to a fresh
413
+ account when the pool marks the current one unhealthy — quota COOLING,
414
+ or INVALID after a revoked / auth-expired credential (see the server's
415
+ usage-probe recovery). Reuses the same `HealthWatcher` the `sp-claude`
416
+ CLI uses; the running `claude` subprocess re-reads `.credentials.json`
417
+ on its next request, so the swap is transparent to the caller.
418
+
419
+ This is what closes the "healthy-looking lease but its token is dead
420
+ upstream" gap: without it a PooledClient would 401 for the rest of the
421
+ session with no way to recover.
422
+ """
423
+ watcher = HealthWatcher(
424
+ fetch=self._fetch_health,
425
+ on_unhealthy=self._on_unhealthy,
426
+ interval_s=self._health_interval_s,
427
+ )
428
+ try:
429
+ await watcher.run()
430
+ except asyncio.CancelledError:
431
+ return
432
+
433
+ async def _fetch_health(self) -> dict:
434
+ lease_id = self._lease_id
435
+ if self._dir is None or lease_id is None:
436
+ return {"healthy": True}
437
+ r = await self._http.get(
438
+ f"{self._pool_url}/credentials/lease/{lease_id}/health",
439
+ headers={"authorization": f"Bearer {self._api_key}"},
440
+ )
441
+ # 404 (unknown lease) / 410 (lease ended) → HealthWatcher recovers by
442
+ # re-leasing (lease_gone). Other non-2xx are logged + retried.
443
+ r.raise_for_status()
444
+ return r.json()
445
+
446
+ async def _on_unhealthy(self, health: dict) -> None:
447
+ await self._swap_account(
448
+ reason=str(health.get("reason") or "unhealthy"),
449
+ lease_gone=bool(health.get("lease_gone")),
450
+ )
451
+
452
+ async def _swap_account(self, *, reason: str, lease_gone: bool = False) -> None:
453
+ """Lease a replacement account and rewrite the shared credential in
454
+ place so the running CLI picks it up on its next request. Only the poll
455
+ leader runs this. Best-effort: if the pool has no other healthy account
456
+ (503) we keep the current lease and let the next health tick retry.
457
+ """
458
+ if self._dir is None or self._lease_id is None:
459
+ return
460
+ old_lease_id = self._lease_id
461
+ old_account = self._lease_account
462
+ old_account_id = self._lease_account_id
463
+ try:
464
+ # Do NOT reuse the caller's request_id here: the pool dedupes leases
465
+ # by request_id and would idempotently hand back the CURRENT
466
+ # (still-active, unhealthy) lease instead of a fresh account — the
467
+ # swap would silently no-op forever ("no other account" every tick).
468
+ lease = await self._post_lease(include_request_id=False)
469
+ except PoolError as e:
470
+ # 503 (all other accounts cooling/invalid) or a transient pool
471
+ # blip — don't tear down a working lease over it; retry next tick.
472
+ log.info("health swap deferred: new lease failed: %s", e)
473
+ return
474
+
475
+ bundle = lease.get("credentials") or {}
476
+ new_lease_id = lease.get("lease_id")
477
+ new_account = lease.get("account")
478
+ new_account_id = lease.get("pool_account_id")
479
+ if not bundle.get("access_token") or not new_lease_id:
480
+ log.warning("health swap: lease response missing bundle; keeping current")
481
+ await self._release_swap_dup(new_lease_id, old_lease_id)
482
+ return
483
+ # Same-account guard keys on the immutable server account_id, NOT the
484
+ # name: a delete+recreate of the same name is a DIFFERENT account and
485
+ # must be allowed to swap in. For a cooled/unhealthy swap, the same
486
+ # account means "nothing to swap to" — keep the current, still-usable
487
+ # lease. But when the current lease is GONE (lease_gone, 410/404), the
488
+ # same account on a NEW lease_id IS the recovery: keeping the dead lease
489
+ # would strand the session 401ing. So only a byte-identical lease_id is
490
+ # truly nothing gained once the lease is gone.
491
+ same_lease = new_lease_id == old_lease_id
492
+ same_account = (
493
+ same_lease
494
+ or (new_account_id is not None and old_account_id is not None
495
+ and new_account_id == old_account_id)
496
+ )
497
+ if same_lease or (same_account and not lease_gone):
498
+ await self._release_swap_dup(new_lease_id, old_lease_id)
499
+ log.info("health swap: nothing to swap to (still on %s)",
500
+ old_account)
501
+ return
502
+
503
+ new_exp = float(
504
+ bundle.get("expires_at") or lease.get("token_expires_at") or 0.0
505
+ )
506
+ # Commit under the meta lock so the poll loop's post-await lease_id
507
+ # re-check sees the rotation and drops any stale token patch. No await
508
+ # between the disk write and the meta / self advance.
509
+ #
510
+ # `committed` marks the point where the NEW lease becomes ours: the
511
+ # instant on-disk creds AND in-memory state point at it — set BEFORE the
512
+ # `async with` exit persists meta.json. If that persist fails (ENOSPC),
513
+ # committed is already True so the finally does NOT delete the new lease:
514
+ # self._lease_id / .credentials.json already use it, and deleting it
515
+ # would strand us on a dead lease (health 410 → no self-heal — the exact
516
+ # state this feature removes). meta.json just stays stale (old id) and
517
+ # self-corrects on the next locked_meta write; the now-unreferenced OLD
518
+ # lease is reaped by TTL.
519
+ committed = False
520
+ try:
521
+ async with locked_meta(self._dir) as meta:
522
+ write_credentials(self._dir, bundle)
523
+ meta.lease_id = new_lease_id
524
+ meta.account = new_account
525
+ meta.account_id = new_account_id
526
+ meta.token_expires_at = new_exp
527
+ self._lease_id = new_lease_id
528
+ self._lease_account = new_account
529
+ self._lease_account_id = new_account_id
530
+ self._lease_request_id = lease.get("request_id")
531
+ self._token_expires_at = new_exp
532
+ # Wake the poll loop to reschedule against the new expiry, and
533
+ # take ownership — both inside the lock so a failed meta persist
534
+ # still leaves us pointing at a live lease.
535
+ self._poll_wake.set()
536
+ committed = True
537
+ finally:
538
+ if not committed:
539
+ # Never took ownership → release the orphaned new lease so it
540
+ # isn't leaked to the reaper. Shield so an in-flight cancel
541
+ # can't skip the cleanup.
542
+ with contextlib.suppress(Exception):
543
+ await asyncio.shield(self._delete_lease(new_lease_id, None))
544
+
545
+ # Release the cooled / dead lease. Shielded + best-effort so a
546
+ # concurrent __aexit__ cancel can't leak it. (Skipped if the meta
547
+ # persist above threw — the old lease then falls to the reaper.)
548
+ with contextlib.suppress(Exception):
549
+ await asyncio.shield(self._delete_lease(old_lease_id, None))
550
+ log.info("health-swapped account %s → %s (lease %s → %s; reason: %s)",
551
+ old_account, new_account, old_lease_id, new_lease_id, reason[:80])
552
+
553
+ async def _release_swap_dup(self, new_lease_id, old_lease_id) -> None:
554
+ """Release a just-acquired lease we decided not to keep (missing bundle
555
+ or same-account), so a deferred swap never leaks it. Shielded so an
556
+ __aexit__ cancel landing on the DELETE can't skip the cleanup."""
557
+ if new_lease_id and new_lease_id != old_lease_id:
558
+ with contextlib.suppress(Exception):
559
+ await asyncio.shield(self._delete_lease(new_lease_id, None))
560
+
340
561
  # ============================================================ HTTP
341
- async def _post_lease(self) -> dict:
562
+ async def _post_lease(self, *, include_request_id: bool = True) -> dict:
342
563
  body: dict[str, Any] = {"provider": "claude"}
343
564
  if self._user_id:
344
565
  body["user_id"] = self._user_id
345
- if self._request_id_req:
566
+ if include_request_id and self._request_id_req:
346
567
  body["request_id"] = self._request_id_req
347
568
  if self._required_model:
348
569
  body["required_model"] = self._required_model
@@ -396,11 +617,12 @@ class PooledClient(ClaudeSDKClient):
396
617
  alive — caller decides whether to keep using it or tear down
397
618
  and re-lease on a different account.
398
619
  """
399
- if self._lease_id is None:
620
+ lease_id = await self._current_lease_id()
621
+ if lease_id is None:
400
622
  return {}
401
623
  try:
402
624
  r = await self._http.post(
403
- f"{self._pool_url}/credentials/lease/{self._lease_id}/report-error",
625
+ f"{self._pool_url}/credentials/lease/{lease_id}/report-error",
404
626
  headers={"authorization": f"Bearer {self._api_key}"},
405
627
  json={"code": code, "message": message},
406
628
  )
@@ -412,6 +634,19 @@ class PooledClient(ClaudeSDKClient):
412
634
  return {}
413
635
  return r.json()
414
636
 
637
+ async def _current_lease_id(self) -> str | None:
638
+ """The lease id to act on right now. Prefers the shared meta over our
639
+ cached `self._lease_id`: a leader's health swap may have rotated the
640
+ lease past a non-leader holder's cache, and acting on the released old
641
+ lease would 410 (report_error) or misroute — so callers that reach the
642
+ pool by lease id resolve through here."""
643
+ if self._dir is not None:
644
+ with contextlib.suppress(Exception):
645
+ async with locked_meta(self._dir) as meta:
646
+ if meta.lease_id is not None:
647
+ return meta.lease_id
648
+ return self._lease_id
649
+
415
650
  # ============================================================ introspection
416
651
  @property
417
652
  def account(self) -> str | None:
@@ -18,6 +18,7 @@ Symmetric to `PooledClient` for claude:
18
18
  from __future__ import annotations
19
19
 
20
20
  import asyncio
21
+ import contextlib
21
22
  import logging
22
23
  import os
23
24
  import time
@@ -26,6 +27,7 @@ from typing import Any
26
27
 
27
28
  import httpx
28
29
 
30
+ from sub_pool_client._health_watcher import HealthWatcher
29
31
  from sub_pool_client._shared import (
30
32
  cleanup_dir,
31
33
  dir_key,
@@ -36,6 +38,7 @@ from sub_pool_client._shared import (
36
38
  from sub_pool_client.errors import (
37
39
  PoolAuthError,
38
40
  PoolConnectionError,
41
+ PoolError,
39
42
  PoolUpstreamError,
40
43
  )
41
44
 
@@ -62,6 +65,7 @@ class PooledCodexClient:
62
65
  required_features: list[str] | None = None,
63
66
  codex_bin: str = "codex",
64
67
  http_client: httpx.AsyncClient | None = None,
68
+ health_interval_s: float = 30.0,
65
69
  ):
66
70
  self._pool_url = (pool_url or os.environ.get("SUB_POOL_URL", "")).rstrip("/")
67
71
  self._api_key = api_key or os.environ.get("SUB_POOL_KEY", "")
@@ -75,18 +79,25 @@ class PooledCodexClient:
75
79
  self._required_model = required_model
76
80
  self._required_features = list(required_features or [])
77
81
  self._codex_bin = codex_bin
82
+ self._health_interval_s = health_interval_s
78
83
  self._owned_http = http_client is None
79
84
  self._http = http_client or httpx.AsyncClient(timeout=10.0)
80
85
 
81
86
  self._dir: Path | None = None
82
87
  self._lease_id: str | None = None
83
88
  self._lease_account: str | None = None
89
+ self._lease_account_id: int | None = None
84
90
  self._lease_request_id: str | None = None
85
91
  self._token_expires_at: float = 0.0
86
92
 
87
93
  self._poll_task: asyncio.Task | None = None
94
+ self._health_task: asyncio.Task | None = None
88
95
  self._heartbeat_task: asyncio.Task | None = None
89
96
  self._is_poll_leader: bool = False
97
+ # Set by a health swap to interrupt the poll loop's (possibly very long,
98
+ # Codex tokens run ~10 days) sleep so it reschedules against the NEW
99
+ # account's token expiry.
100
+ self._poll_wake = asyncio.Event()
90
101
 
91
102
  async def __aenter__(self) -> "PooledCodexClient":
92
103
  key = dir_key(
@@ -99,14 +110,23 @@ class PooledCodexClient:
99
110
  self._dir = shared_dir(key)
100
111
  await self._join_or_acquire_lease()
101
112
  if self._is_poll_leader:
102
- self._poll_task = asyncio.create_task(self._poll_loop())
113
+ self._start_leader_tasks()
103
114
  # Every holder runs the heartbeat — cheap, and takes over
104
115
  # leadership if the current leader exits.
105
116
  self._heartbeat_task = asyncio.create_task(self._heartbeat_loop())
106
117
  return self
107
118
 
119
+ def _start_leader_tasks(self) -> None:
120
+ """The poll leader owns two background tasks: token rotation
121
+ (`_poll_loop`) and health-driven account swap (`_health_loop`).
122
+ Idempotent — a heartbeat promotion or re-entry won't double-spawn."""
123
+ if self._poll_task is None:
124
+ self._poll_task = asyncio.create_task(self._poll_loop())
125
+ if self._health_task is None:
126
+ self._health_task = asyncio.create_task(self._health_loop())
127
+
108
128
  async def __aexit__(self, exc_type, exc, tb) -> None:
109
- for attr in ("_poll_task", "_heartbeat_task"):
129
+ for attr in ("_poll_task", "_health_task", "_heartbeat_task"):
110
130
  t = getattr(self, attr, None)
111
131
  if t is not None:
112
132
  t.cancel()
@@ -152,11 +172,12 @@ class PooledCodexClient:
152
172
  leases elsewhere. The lease itself stays alive — caller decides
153
173
  whether to keep using it or tear down and re-lease.
154
174
  """
155
- if self._lease_id is None:
175
+ lease_id = await self._current_lease_id()
176
+ if lease_id is None:
156
177
  return {}
157
178
  try:
158
179
  r = await self._http.post(
159
- f"{self._pool_url}/credentials/lease/{self._lease_id}/report-error",
180
+ f"{self._pool_url}/credentials/lease/{lease_id}/report-error",
160
181
  headers={"authorization": f"Bearer {self._api_key}"},
161
182
  json={"code": code, "message": message},
162
183
  )
@@ -168,6 +189,17 @@ class PooledCodexClient:
168
189
  return {}
169
190
  return r.json()
170
191
 
192
+ async def _current_lease_id(self) -> str | None:
193
+ """The lease id to act on now — prefers shared meta over our cached
194
+ self._lease_id so a non-leader holder acts on the leader's swapped lease
195
+ rather than a released old one."""
196
+ if self._dir is not None:
197
+ with contextlib.suppress(Exception):
198
+ async with locked_meta(self._dir) as meta:
199
+ if meta.lease_id is not None:
200
+ return meta.lease_id
201
+ return self._lease_id
202
+
171
203
  async def exec(
172
204
  self,
173
205
  prompt: str,
@@ -202,9 +234,13 @@ class PooledCodexClient:
202
234
  my_pid = os.getpid()
203
235
  async with locked_meta(self._dir) as meta:
204
236
  if meta.lease_id and meta.holders:
205
- # Active lease already present — reuse it.
237
+ # Active lease already present — reuse it. Read identity +
238
+ # expiry from meta (shared source of truth): a prior health
239
+ # swap may have advanced them, and we may be promoted later.
206
240
  self._lease_id = meta.lease_id
207
241
  self._lease_account = meta.account
242
+ self._lease_account_id = meta.account_id
243
+ self._token_expires_at = meta.token_expires_at
208
244
  meta.holders.append(my_pid)
209
245
  # locked_meta cleared dead-pid leaders, so poll_leader is
210
246
  # either a live pid or None. Claim leadership right away
@@ -226,10 +262,13 @@ class PooledCodexClient:
226
262
  write_codex_auth(self._dir, auth_json)
227
263
  self._lease_id = lease["lease_id"]
228
264
  self._lease_account = lease.get("account")
265
+ self._lease_account_id = lease.get("pool_account_id")
229
266
  self._lease_request_id = lease.get("request_id")
230
267
  self._token_expires_at = float(lease.get("token_expires_at") or 0.0)
231
268
  meta.lease_id = self._lease_id
232
269
  meta.account = self._lease_account
270
+ meta.account_id = self._lease_account_id
271
+ meta.token_expires_at = self._token_expires_at
233
272
  meta.holders = [my_pid]
234
273
  meta.poll_leader = my_pid
235
274
  self._is_poll_leader = True
@@ -246,7 +285,10 @@ class PooledCodexClient:
246
285
  meta.holders.remove(my_pid)
247
286
  except ValueError:
248
287
  pass
249
- if meta.poll_leader == my_pid:
288
+ # Guard on self._is_poll_leader so a departing NON-leader in the
289
+ # same process (identical pid) can't clear the live leader's seat
290
+ # and trigger a spurious double-leader.
291
+ if meta.poll_leader == my_pid and self._is_poll_leader:
250
292
  meta.poll_leader = None
251
293
  if not meta.holders:
252
294
  lease_id_to_release = meta.lease_id
@@ -260,8 +302,10 @@ class PooledCodexClient:
260
302
  cleanup_dir(self._dir)
261
303
 
262
304
  async def _heartbeat_loop(self, interval_s: float = 30.0) -> None:
263
- """If the original poll leader exits, the next-in-line holder
264
- promotes itself and takes over the rotation."""
305
+ """Every tick a non-leader holder (a) re-syncs its cached lease state
306
+ from meta — so its `.account` / `report_error` / a future promotion
307
+ track a leader's health swap instead of a released old lease — and
308
+ (b) promotes itself if the poll leader is gone."""
265
309
  try:
266
310
  while True:
267
311
  await asyncio.sleep(interval_s)
@@ -270,12 +314,17 @@ class PooledCodexClient:
270
314
  my_pid = os.getpid()
271
315
  promoted = False
272
316
  async with locked_meta(self._dir) as meta:
317
+ if meta.lease_id is not None:
318
+ self._lease_id = meta.lease_id
319
+ self._lease_account = meta.account
320
+ self._lease_account_id = meta.account_id
321
+ self._token_expires_at = meta.token_expires_at
273
322
  if meta.poll_leader is None and my_pid in (meta.holders or []):
274
323
  meta.poll_leader = my_pid
275
324
  promoted = True
276
325
  if promoted:
277
326
  self._is_poll_leader = True
278
- self._poll_task = asyncio.create_task(self._poll_loop())
327
+ self._start_leader_tasks()
279
328
  log.info("codex heartbeat: promoted self to poll leader")
280
329
  return
281
330
  except asyncio.CancelledError:
@@ -288,21 +337,43 @@ class PooledCodexClient:
288
337
  """
289
338
  try:
290
339
  while True:
340
+ self._poll_wake.clear()
291
341
  remaining = self._token_expires_at - time.time()
292
342
  # Wake up 10 min before expiry, minimum 60s sleep.
293
343
  sleep_s = max(60.0, remaining - 600.0)
294
- await asyncio.sleep(sleep_s)
344
+ # Interruptible: a health swap sets _poll_wake so we reschedule
345
+ # against the NEW account's token expiry instead of oversleeping
346
+ # on the old one (Codex tokens can be days out).
347
+ woke_early = True
348
+ try:
349
+ await asyncio.wait_for(self._poll_wake.wait(), timeout=sleep_s)
350
+ except asyncio.TimeoutError:
351
+ woke_early = False
352
+ if woke_early:
353
+ continue
295
354
 
296
355
  if self._dir is None or self._lease_id is None:
297
356
  return
298
357
 
358
+ lease_id_before = self._lease_id
299
359
  try:
300
360
  new = await self._post_poll_token()
301
361
  except Exception as e: # noqa: BLE001
362
+ # If a swap rotated us mid-poll, this is just the OLD lease's
363
+ # 410 — don't clobber the new expiry the swap already set.
364
+ if self._lease_id != lease_id_before:
365
+ continue
302
366
  log.warning("codex lease token poll failed: %s", e)
303
367
  self._token_expires_at = time.time() + 60.0
304
368
  continue
305
369
 
370
+ # A health-driven swap may have rotated us onto a different
371
+ # lease/account while this poll was in flight — the fetched
372
+ # auth.json belongs to the OLD lease; writing it onto the NEW
373
+ # account's shared file would clobber the swap.
374
+ if self._lease_id != lease_id_before:
375
+ continue
376
+
306
377
  creds = new.get("credentials") or {}
307
378
  new_auth = creds.get("auth_json")
308
379
  new_exp = float(new.get("token_expires_at") or 0.0)
@@ -340,11 +411,143 @@ class PooledCodexClient:
340
411
  )
341
412
  return r.json()
342
413
 
343
- async def _post_lease(self) -> dict:
414
+ # ============================================================ health swap
415
+ async def _health_loop(self) -> None:
416
+ """Leader-only: watch the lease's account health and swap to a fresh
417
+ account when the pool marks the current one unhealthy — quota COOLING
418
+ or INVALID after a revoked / auth-expired credential. Reuses the same
419
+ `HealthWatcher` the `sp-codex` CLI uses; the running `codex` subprocess
420
+ re-reads `auth.json` on its next call, so the swap is transparent.
421
+ Without it a PooledCodexClient handed a dead account would 401 for the
422
+ rest of the session with no way to recover.
423
+ """
424
+ watcher = HealthWatcher(
425
+ fetch=self._fetch_health,
426
+ on_unhealthy=self._on_unhealthy,
427
+ interval_s=self._health_interval_s,
428
+ )
429
+ try:
430
+ await watcher.run()
431
+ except asyncio.CancelledError:
432
+ return
433
+
434
+ async def _fetch_health(self) -> dict:
435
+ lease_id = self._lease_id
436
+ if self._dir is None or lease_id is None:
437
+ return {"healthy": True}
438
+ r = await self._http.get(
439
+ f"{self._pool_url}/credentials/lease/{lease_id}/health",
440
+ headers={"authorization": f"Bearer {self._api_key}"},
441
+ )
442
+ # 404 (unknown lease) / 410 (lease ended) → HealthWatcher recovers by
443
+ # re-leasing (lease_gone). Other non-2xx are logged + retried.
444
+ r.raise_for_status()
445
+ return r.json()
446
+
447
+ async def _on_unhealthy(self, health: dict) -> None:
448
+ await self._swap_account(
449
+ reason=str(health.get("reason") or "unhealthy"),
450
+ lease_gone=bool(health.get("lease_gone")),
451
+ )
452
+
453
+ async def _swap_account(self, *, reason: str, lease_gone: bool = False) -> None:
454
+ """Lease a replacement Codex account and rewrite the shared auth.json
455
+ in place so the running CLI picks it up on its next call. Only the poll
456
+ leader runs this. Best-effort: no other healthy account (503) → keep the
457
+ current lease and let the next health tick retry.
458
+ """
459
+ if self._dir is None or self._lease_id is None:
460
+ return
461
+ old_lease_id = self._lease_id
462
+ old_account = self._lease_account
463
+ old_account_id = self._lease_account_id
464
+ try:
465
+ # Do NOT reuse the caller's request_id: the pool dedupes by it and
466
+ # would hand back the current (unhealthy) lease, making the swap a
467
+ # silent no-op forever.
468
+ lease = await self._post_lease(include_request_id=False)
469
+ except PoolError as e:
470
+ log.info("codex health swap deferred: new lease failed: %s", e)
471
+ return
472
+
473
+ creds = lease.get("credentials") or {}
474
+ auth_json = creds.get("auth_json")
475
+ new_lease_id = lease.get("lease_id")
476
+ new_account = lease.get("account")
477
+ new_account_id = lease.get("pool_account_id")
478
+ if not isinstance(auth_json, dict) or not new_lease_id:
479
+ log.warning("codex health swap: lease response missing auth_json; keeping current")
480
+ await self._release_swap_dup(new_lease_id, old_lease_id)
481
+ return
482
+ # Same-account guard keys on the immutable server account_id, NOT the
483
+ # name (a delete+recreate of the same name is a DIFFERENT account and
484
+ # must swap in). For a cooled swap the same account means "nothing to
485
+ # swap to" — keep the current lease. But when the lease is GONE
486
+ # (lease_gone, 410/404), the same account on a NEW lease_id IS the
487
+ # recovery; only a byte-identical lease_id is truly nothing gained.
488
+ same_lease = new_lease_id == old_lease_id
489
+ same_account = (
490
+ same_lease
491
+ or (new_account_id is not None and old_account_id is not None
492
+ and new_account_id == old_account_id)
493
+ )
494
+ if same_lease or (same_account and not lease_gone):
495
+ await self._release_swap_dup(new_lease_id, old_lease_id)
496
+ log.info("codex health swap: no other account available (still on %s)",
497
+ old_account)
498
+ return
499
+
500
+ new_exp = float(lease.get("token_expires_at") or 0.0)
501
+ # Commit under the meta lock so the poll loop's post-await lease_id
502
+ # re-check sees the rotation and drops any stale token write. No await
503
+ # between the disk write and the meta / self advance.
504
+ #
505
+ # `committed` marks ownership of the new lease — set BEFORE the block
506
+ # exit persists meta.json. If that persist fails (ENOSPC), committed is
507
+ # already True so the finally does NOT delete the new lease: self._
508
+ # lease_id / auth.json already use it and deleting it would strand us on
509
+ # a dead lease (health 410 → no self-heal). meta.json stays stale and
510
+ # self-corrects next write; the old lease is reaped by TTL.
511
+ committed = False
512
+ try:
513
+ async with locked_meta(self._dir) as meta:
514
+ write_codex_auth(self._dir, auth_json)
515
+ meta.lease_id = new_lease_id
516
+ meta.account = new_account
517
+ meta.account_id = new_account_id
518
+ meta.token_expires_at = new_exp
519
+ self._lease_id = new_lease_id
520
+ self._lease_account = new_account
521
+ self._lease_account_id = new_account_id
522
+ self._lease_request_id = lease.get("request_id")
523
+ self._token_expires_at = new_exp
524
+ self._poll_wake.set()
525
+ committed = True
526
+ finally:
527
+ if not committed:
528
+ with contextlib.suppress(Exception):
529
+ await asyncio.shield(self._delete_lease(new_lease_id, None))
530
+
531
+ # Release the cooled/dead old lease (skipped if the meta persist above
532
+ # threw — it then falls to the reaper).
533
+ with contextlib.suppress(Exception):
534
+ await asyncio.shield(self._delete_lease(old_lease_id, None))
535
+ log.info("codex health-swapped account %s → %s (lease %s → %s; reason: %s)",
536
+ old_account, new_account, old_lease_id, new_lease_id, reason[:80])
537
+
538
+ async def _release_swap_dup(self, new_lease_id, old_lease_id) -> None:
539
+ """Release a just-acquired lease we decided not to keep (missing
540
+ auth_json or same-account) so a deferred swap never leaks it. Shielded
541
+ so an __aexit__ cancel on the DELETE can't skip the cleanup."""
542
+ if new_lease_id and new_lease_id != old_lease_id:
543
+ with contextlib.suppress(Exception):
544
+ await asyncio.shield(self._delete_lease(new_lease_id, None))
545
+
546
+ async def _post_lease(self, *, include_request_id: bool = True) -> dict:
344
547
  body: dict[str, Any] = {"provider": "codex"}
345
548
  if self._user_id:
346
549
  body["user_id"] = self._user_id
347
- if self._request_id_req:
550
+ if include_request_id and self._request_id_req:
348
551
  body["request_id"] = self._request_id_req
349
552
  if self._required_model:
350
553
  body["required_model"] = self._required_model
@@ -380,12 +583,17 @@ class PooledCodexClient:
380
583
  if exc is not None:
381
584
  body["error_code"] = type(exc).__name__
382
585
  body["error_message"] = str(exc)[:2000]
383
- await self._http.request(
384
- "DELETE",
385
- f"{self._pool_url}/credentials/lease/{lease_id}",
386
- headers={"authorization": f"Bearer {self._api_key}"},
387
- json=body,
388
- )
586
+ # Best-effort, like claude's _delete_lease: releasing a lease must never
587
+ # raise into a swap / release path (the reaper is the backstop).
588
+ try:
589
+ await self._http.request(
590
+ "DELETE",
591
+ f"{self._pool_url}/credentials/lease/{lease_id}",
592
+ headers={"authorization": f"Bearer {self._api_key}"},
593
+ json=body,
594
+ )
595
+ except Exception as e: # noqa: BLE001
596
+ log.warning("codex DELETE lease %s failed (best-effort): %s", lease_id, e)
389
597
 
390
598
 
391
599
  def _detail_or_text(r: httpx.Response) -> dict[str, Any]: