sub-pool-client 0.6.6__tar.gz → 0.6.8__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.6.6 → sub_pool_client-0.6.8}/PKG-INFO +1 -1
  2. {sub_pool_client-0.6.6 → sub_pool_client-0.6.8}/sub_pool_client/_cli_core.py +64 -5
  3. {sub_pool_client-0.6.6 → sub_pool_client-0.6.8}/sub_pool_client/_health_watcher.py +33 -7
  4. {sub_pool_client-0.6.6 → sub_pool_client-0.6.8}/sub_pool_client/_shared.py +30 -0
  5. {sub_pool_client-0.6.6 → sub_pool_client-0.6.8}/sub_pool_client/_version.py +2 -2
  6. {sub_pool_client-0.6.6 → sub_pool_client-0.6.8}/sub_pool_client/client.py +22 -13
  7. {sub_pool_client-0.6.6 → sub_pool_client-0.6.8}/sub_pool_client/codex.py +20 -9
  8. {sub_pool_client-0.6.6 → sub_pool_client-0.6.8}/.github/workflows/publish.yml +0 -0
  9. {sub_pool_client-0.6.6 → sub_pool_client-0.6.8}/.gitignore +0 -0
  10. {sub_pool_client-0.6.6 → sub_pool_client-0.6.8}/README.md +0 -0
  11. {sub_pool_client-0.6.6 → sub_pool_client-0.6.8}/examples/codex_hello.py +0 -0
  12. {sub_pool_client-0.6.6 → sub_pool_client-0.6.8}/examples/hello.py +0 -0
  13. {sub_pool_client-0.6.6 → sub_pool_client-0.6.8}/meta/README.md +0 -0
  14. {sub_pool_client-0.6.6 → sub_pool_client-0.6.8}/meta/pyproject.toml +0 -0
  15. {sub_pool_client-0.6.6 → sub_pool_client-0.6.8}/pyproject.toml +0 -0
  16. {sub_pool_client-0.6.6 → sub_pool_client-0.6.8}/sub_pool_client/__init__.py +0 -0
  17. {sub_pool_client-0.6.6 → sub_pool_client-0.6.8}/sub_pool_client/_cli_provider.py +0 -0
  18. {sub_pool_client-0.6.6 → sub_pool_client-0.6.8}/sub_pool_client/_swap.py +0 -0
  19. {sub_pool_client-0.6.6 → sub_pool_client-0.6.8}/sub_pool_client/cli_claude.py +0 -0
  20. {sub_pool_client-0.6.6 → sub_pool_client-0.6.8}/sub_pool_client/cli_codex.py +0 -0
  21. {sub_pool_client-0.6.6 → sub_pool_client-0.6.8}/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.6.6
3
+ Version: 0.6.8
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
@@ -25,6 +26,7 @@ import httpx
25
26
 
26
27
  from sub_pool_client._cli_provider import CliProvider
27
28
  from sub_pool_client._health_watcher import HealthWatcher
29
+ from sub_pool_client._shared import next_refresh_sleep
28
30
  from sub_pool_client._swap import NoSwapAvailable, swap_credentials
29
31
 
30
32
 
@@ -428,6 +430,11 @@ async def run_session(
428
430
 
429
431
  # Background tasks: token refresh + health-driven account swap.
430
432
  current = {"lease": lease}
433
+ # Set by a successful swap so the expiry-anchored refresh loop
434
+ # re-anchors to the NEW lease's token instead of sleeping out a
435
+ # now-stale deadline — a swapped-in token may have far less life
436
+ # left than the one it replaced.
437
+ refresh_wake = asyncio.Event()
431
438
 
432
439
  async def on_swap_needed(health: dict) -> None:
433
440
  # Read the from-account BEFORE swap_credentials runs —
@@ -439,6 +446,10 @@ async def run_session(
439
446
  pool, current, session_dir, provider,
440
447
  account=chosen_account,
441
448
  )
449
+ # swap_credentials already advanced current["lease"]
450
+ # (incl. token_expires_at) in its sync block; wake the
451
+ # refresh loop so it re-anchors to the new expiry.
452
+ refresh_wake.set()
442
453
  if verbose:
443
454
  log.info(
444
455
  "swapped %s → %s (reason: %s)",
@@ -450,7 +461,10 @@ async def run_session(
450
461
  log.info("swap deferred: %s", e)
451
462
 
452
463
  refresher = asyncio.create_task(
453
- _token_refresh_loop(pool, current, session_dir, provider, verbose),
464
+ _token_refresh_loop(
465
+ pool, current, session_dir, provider, verbose,
466
+ wake=refresh_wake,
467
+ ),
454
468
  name=f"sp-{provider.name}-refresh",
455
469
  )
456
470
  watcher = asyncio.create_task(
@@ -520,15 +534,60 @@ async def _refresh_once(
520
534
  async def _token_refresh_loop(
521
535
  pool: PoolHTTP, current: dict, session_dir: Path,
522
536
  provider: CliProvider, verbose: bool,
523
- *, interval_s: float = 50 * 60,
537
+ *, wake: "asyncio.Event | None" = None,
538
+ slack_s: float = 600.0, min_sleep_s: float = 60.0,
539
+ fallback_s: float = 50 * 60,
524
540
  ) -> None:
525
- """Periodically rotate access_token via the pool. Same cadence as
526
- PooledClient. See `_refresh_once` for the race-safety guard."""
541
+ """Rotate access_token via the pool BEFORE it expires.
542
+
543
+ Anthropic access tokens live only ~1h and the leased bundle is
544
+ sanitized (refreshToken=""), so the spawned CLI can't self-refresh —
545
+ the pool is the sole refresher, and the running `claude` re-reads the
546
+ rewritten .credentials.json across requests (see _swap.py).
547
+
548
+ The catch that broke this: a leased token is NOT freshly minted. The
549
+ pool only re-mints at seal time when under `slack_s` of life remains,
550
+ so a lease can hand out a token with as little as ~10min left. The old
551
+ fixed 50-min cadence therefore fired long AFTER such a token had
552
+ already died mid-session → an unrecoverable 401 (the exact failure
553
+ users hit). So anchor every sleep to the token's ACTUAL expiry
554
+ (mirrors PooledClient._poll_loop), and let a swap wake us to re-anchor
555
+ against the replacement token — which may itself be short-lived.
556
+
557
+ See `_refresh_once` for the concurrent-swap race-safety guard.
558
+ """
559
+ if wake is None:
560
+ wake = asyncio.Event() # never set → wait_for always times out
527
561
  while True:
562
+ exp = float(current["lease"].get("token_expires_at") or 0.0)
563
+ # Shared with both SDK poll loops (see _shared.next_refresh_sleep) so the
564
+ # three schedulers can't drift again. A refresh that FAILS leaves exp
565
+ # near-now, so the min_sleep_s floor makes us retry every min_sleep_s
566
+ # until it lands — or the token dies, at which point a genuinely-dead
567
+ # refresh_token has already flipped the account INVALID and the health
568
+ # watcher swaps us off it.
569
+ sleep_s = next_refresh_sleep(
570
+ exp, time.time(),
571
+ slack_s=slack_s, min_sleep_s=min_sleep_s, fallback_s=fallback_s,
572
+ )
528
573
  try:
529
- await asyncio.sleep(interval_s)
574
+ await asyncio.wait_for(wake.wait(), timeout=sleep_s)
575
+ except asyncio.TimeoutError:
576
+ # A swap can land in the same tick the deadline fires (set the
577
+ # wake just after wait_for times out); honor it so we re-anchor
578
+ # to the swapped-in token rather than refreshing a lease the swap
579
+ # already wrote fresh credentials for.
580
+ if wake.is_set():
581
+ wake.clear()
582
+ continue
530
583
  except asyncio.CancelledError:
531
584
  return
585
+ else:
586
+ # Woken by a swap: current["lease"] already points at the new
587
+ # token (written by swap_credentials); re-anchor without
588
+ # refreshing, since the swap installed fresh credentials.
589
+ wake.clear()
590
+ continue
532
591
  await _refresh_once(pool, current, session_dir, provider, verbose)
533
592
 
534
593
 
@@ -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
@@ -41,6 +41,36 @@ DEFAULT_ROOT = Path(
41
41
  )
42
42
 
43
43
 
44
+ # ---- token-refresh scheduling -------------------------------------------
45
+ # Shared by the sp-claude/sp-codex CLI refresh loop (_cli_core) AND both SDK
46
+ # poll loops (PooledClient / PooledCodexClient). Kept in ONE place because the
47
+ # three drifted apart twice: the CLI once regressed to a fixed cadence that
48
+ # outlived short-lived tokens (→ mid-session 401), and the exp<=0 fallback below
49
+ # once existed only in the CLI (→ codex api-key SDK leases polling every 60s).
50
+ POLL_SLACK_S = 600.0 # refresh this long BEFORE the token actually expires
51
+ POLL_MIN_SLEEP_S = 60.0 # floor so tiny-TTL tests / churn don't bash the pool
52
+ POLL_FALLBACK_S = 50 * 60.0 # no usable expiry (token_expires_at<=0, e.g. a codex
53
+ # api-key lease / an exp-less JWT) → fixed cadence
54
+
55
+
56
+ def next_refresh_sleep(
57
+ expires_at: float, now: float, *,
58
+ slack_s: float = POLL_SLACK_S,
59
+ min_sleep_s: float = POLL_MIN_SLEEP_S,
60
+ fallback_s: float = POLL_FALLBACK_S,
61
+ ) -> float:
62
+ """Seconds to sleep before the next pool token refresh.
63
+
64
+ Anchored to the token's ACTUAL expiry: wake `slack_s` before it, floored at
65
+ `min_sleep_s`. When `expires_at` carries no usable value (<=0), fall back to
66
+ a fixed cadence instead of anchoring to a long-past deadline — that would
67
+ refresh every `min_sleep_s` forever (a needless churn storm that hit codex
68
+ api-key leases, whose token has no expiry)."""
69
+ if expires_at <= 0:
70
+ return fallback_s
71
+ return max(min_sleep_s, expires_at - now - slack_s)
72
+
73
+
44
74
  def dir_key(
45
75
  *,
46
76
  pool_url: str,
@@ -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.6.6'
22
- __version_tuple__ = version_tuple = (0, 6, 6)
21
+ __version__ = version = '0.6.8'
22
+ __version_tuple__ = version_tuple = (0, 6, 8)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -55,6 +55,7 @@ from sub_pool_client._shared import (
55
55
  cleanup_dir,
56
56
  dir_key,
57
57
  locked_meta,
58
+ next_refresh_sleep,
58
59
  shared_dir,
59
60
  write_credentials,
60
61
  )
@@ -329,10 +330,10 @@ class PooledClient(ClaudeSDKClient):
329
330
  try:
330
331
  while True:
331
332
  self._poll_wake.clear()
332
- remaining = self._token_expires_at - time.time()
333
- # Wake up 10 min before expiry, minimum 60s sleep so we
334
- # don't bash the pool during tiny-TTL tests.
335
- sleep_s = max(60.0, remaining - 600.0)
333
+ # Wake ~10 min before expiry (min 60s), or a fixed cadence when
334
+ # the lease has no usable expiry — shared with the CLI + codex
335
+ # so the three schedulers can't drift (see next_refresh_sleep).
336
+ sleep_s = next_refresh_sleep(self._token_expires_at, time.time())
336
337
  # Interruptible sleep: a health swap sets _poll_wake so we
337
338
  # recompute the schedule against the NEW (possibly much shorter)
338
339
  # token expiry instead of oversleeping on the old account's.
@@ -438,15 +439,18 @@ class PooledClient(ClaudeSDKClient):
438
439
  f"{self._pool_url}/credentials/lease/{lease_id}/health",
439
440
  headers={"authorization": f"Bearer {self._api_key}"},
440
441
  )
441
- # 404 (unknown lease) / 410 (lease ended) → HealthWatcher stops. Other
442
- # non-2xx are logged + retried by the watcher.
442
+ # 404 (unknown lease) / 410 (lease ended) → HealthWatcher recovers by
443
+ # re-leasing (lease_gone). Other non-2xx are logged + retried.
443
444
  r.raise_for_status()
444
445
  return r.json()
445
446
 
446
447
  async def _on_unhealthy(self, health: dict) -> None:
447
- await self._swap_account(reason=str(health.get("reason") or "unhealthy"))
448
+ await self._swap_account(
449
+ reason=str(health.get("reason") or "unhealthy"),
450
+ lease_gone=bool(health.get("lease_gone")),
451
+ )
448
452
 
449
- async def _swap_account(self, *, reason: str) -> None:
453
+ async def _swap_account(self, *, reason: str, lease_gone: bool = False) -> None:
450
454
  """Lease a replacement account and rewrite the shared credential in
451
455
  place so the running CLI picks it up on its next request. Only the poll
452
456
  leader runs this. Best-effort: if the pool has no other healthy account
@@ -479,16 +483,21 @@ class PooledClient(ClaudeSDKClient):
479
483
  return
480
484
  # Same-account guard keys on the immutable server account_id, NOT the
481
485
  # name: a delete+recreate of the same name is a DIFFERENT account and
482
- # must be allowed to swap in. Only bail when the pool handed back the
483
- # very same account (its only healthy candidate) — nothing to swap to.
486
+ # must be allowed to swap in. For a cooled/unhealthy swap, the same
487
+ # account means "nothing to swap to" — keep the current, still-usable
488
+ # lease. But when the current lease is GONE (lease_gone, 410/404), the
489
+ # same account on a NEW lease_id IS the recovery: keeping the dead lease
490
+ # would strand the session 401ing. So only a byte-identical lease_id is
491
+ # truly nothing gained once the lease is gone.
492
+ same_lease = new_lease_id == old_lease_id
484
493
  same_account = (
485
- new_lease_id == old_lease_id
494
+ same_lease
486
495
  or (new_account_id is not None and old_account_id is not None
487
496
  and new_account_id == old_account_id)
488
497
  )
489
- if same_account:
498
+ if same_lease or (same_account and not lease_gone):
490
499
  await self._release_swap_dup(new_lease_id, old_lease_id)
491
- log.info("health swap: no other account available (still on %s)",
500
+ log.info("health swap: nothing to swap to (still on %s)",
492
501
  old_account)
493
502
  return
494
503
 
@@ -32,6 +32,7 @@ from sub_pool_client._shared import (
32
32
  cleanup_dir,
33
33
  dir_key,
34
34
  locked_meta,
35
+ next_refresh_sleep,
35
36
  shared_dir,
36
37
  write_codex_auth,
37
38
  )
@@ -338,9 +339,11 @@ class PooledCodexClient:
338
339
  try:
339
340
  while True:
340
341
  self._poll_wake.clear()
341
- remaining = self._token_expires_at - time.time()
342
- # Wake up 10 min before expiry, minimum 60s sleep.
343
- sleep_s = max(60.0, remaining - 600.0)
342
+ # Wake ~10 min before expiry (min 60s), or a fixed cadence when
343
+ # the lease has no usable expiry (codex api-key tokens have none)
344
+ # — shared with the CLI + claude SDK so the three schedulers
345
+ # can't drift (see next_refresh_sleep).
346
+ sleep_s = next_refresh_sleep(self._token_expires_at, time.time())
344
347
  # Interruptible: a health swap sets _poll_wake so we reschedule
345
348
  # against the NEW account's token expiry instead of oversleeping
346
349
  # on the old one (Codex tokens can be days out).
@@ -439,14 +442,18 @@ class PooledCodexClient:
439
442
  f"{self._pool_url}/credentials/lease/{lease_id}/health",
440
443
  headers={"authorization": f"Bearer {self._api_key}"},
441
444
  )
442
- # 404 (unknown lease) / 410 (lease ended) → HealthWatcher stops.
445
+ # 404 (unknown lease) / 410 (lease ended) → HealthWatcher recovers by
446
+ # re-leasing (lease_gone). Other non-2xx are logged + retried.
443
447
  r.raise_for_status()
444
448
  return r.json()
445
449
 
446
450
  async def _on_unhealthy(self, health: dict) -> None:
447
- await self._swap_account(reason=str(health.get("reason") or "unhealthy"))
451
+ await self._swap_account(
452
+ reason=str(health.get("reason") or "unhealthy"),
453
+ lease_gone=bool(health.get("lease_gone")),
454
+ )
448
455
 
449
- async def _swap_account(self, *, reason: str) -> None:
456
+ async def _swap_account(self, *, reason: str, lease_gone: bool = False) -> None:
450
457
  """Lease a replacement Codex account and rewrite the shared auth.json
451
458
  in place so the running CLI picks it up on its next call. Only the poll
452
459
  leader runs this. Best-effort: no other healthy account (503) → keep the
@@ -477,13 +484,17 @@ class PooledCodexClient:
477
484
  return
478
485
  # Same-account guard keys on the immutable server account_id, NOT the
479
486
  # name (a delete+recreate of the same name is a DIFFERENT account and
480
- # must swap in).
487
+ # must swap in). For a cooled swap the same account means "nothing to
488
+ # swap to" — keep the current lease. But when the lease is GONE
489
+ # (lease_gone, 410/404), the same account on a NEW lease_id IS the
490
+ # recovery; only a byte-identical lease_id is truly nothing gained.
491
+ same_lease = new_lease_id == old_lease_id
481
492
  same_account = (
482
- new_lease_id == old_lease_id
493
+ same_lease
483
494
  or (new_account_id is not None and old_account_id is not None
484
495
  and new_account_id == old_account_id)
485
496
  )
486
- if same_account:
497
+ if same_lease or (same_account and not lease_gone):
487
498
  await self._release_swap_dup(new_lease_id, old_lease_id)
488
499
  log.info("codex health swap: no other account available (still on %s)",
489
500
  old_account)