sub-pool-client 0.8.2__tar.gz → 0.9.1__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 (23) hide show
  1. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/PKG-INFO +1 -1
  2. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/sub_pool_client/_cli_core.py +97 -29
  3. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/sub_pool_client/_health_watcher.py +36 -2
  4. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/sub_pool_client/_shared.py +220 -14
  5. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/sub_pool_client/_version.py +2 -2
  6. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/sub_pool_client/client.py +190 -108
  7. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/sub_pool_client/codex.py +111 -72
  8. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/.github/workflows/publish.yml +0 -0
  9. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/.gitignore +0 -0
  10. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/README.md +0 -0
  11. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/examples/codex_hello.py +0 -0
  12. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/examples/hello.py +0 -0
  13. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/meta/README.md +0 -0
  14. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/meta/pyproject.toml +0 -0
  15. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/pyproject.toml +0 -0
  16. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/sub_pool_client/__init__.py +0 -0
  17. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/sub_pool_client/_auth_watch.py +0 -0
  18. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/sub_pool_client/_cli_provider.py +0 -0
  19. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/sub_pool_client/_swap.py +0 -0
  20. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/sub_pool_client/cli_claude.py +0 -0
  21. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/sub_pool_client/cli_codex.py +0 -0
  22. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/sub_pool_client/cli_grok.py +0 -0
  23. {sub_pool_client-0.8.2 → sub_pool_client-0.9.1}/sub_pool_client/errors.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: sub-pool-client
3
- Version: 0.8.2
3
+ Version: 0.9.1
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
@@ -19,7 +19,7 @@ import tempfile
19
19
  import time
20
20
  from contextlib import suppress
21
21
  from pathlib import Path
22
- from typing import Any
22
+ from typing import Any, Callable
23
23
 
24
24
  import click
25
25
  import httpx
@@ -27,7 +27,13 @@ import httpx
27
27
  from sub_pool_client import _auth_watch
28
28
  from sub_pool_client._cli_provider import CliProvider
29
29
  from sub_pool_client._health_watcher import HealthWatcher
30
- from sub_pool_client._shared import next_refresh_sleep
30
+ from sub_pool_client._shared import (
31
+ LeaseRequestId,
32
+ check_pool_url,
33
+ next_refresh_sleep,
34
+ release_lease,
35
+ token_is_stale,
36
+ )
31
37
  from sub_pool_client._swap import NoSwapAvailable, swap_credentials
32
38
 
33
39
 
@@ -169,9 +175,15 @@ def run_setup(provider: CliProvider) -> int:
169
175
  "Pool URL", default=pool_default or "https://",
170
176
  show_default=bool(pool_default),
171
177
  ).strip()
172
- if pool_url.startswith(("http://", "https://")) and len(pool_url) > 8:
178
+ if not (pool_url.startswith(("http://", "https://"))
179
+ and len(pool_url) > 8):
180
+ click.echo(" → must start with http:// or https://", err=True)
181
+ continue
182
+ try:
183
+ check_pool_url(pool_url)
173
184
  break
174
- click.echo(" → must start with http:// or https://", err=True)
185
+ except ValueError as e:
186
+ click.echo(f" → {e}", err=True)
175
187
  api_key = click.prompt("API key (cp-...)", hide_input=True).strip()
176
188
  default_account = click.prompt(
177
189
  f"Default {provider.name} account (empty = strategy-based)",
@@ -318,38 +330,49 @@ class PoolHTTP:
318
330
  headers={"Authorization": f"Bearer {cfg.api_key}"},
319
331
  timeout=httpx.Timeout(30.0, connect=10.0),
320
332
  )
333
+ # Covers the initial lease and every swap; see LeaseRequestId.
334
+ self._lease_rid = LeaseRequestId()
335
+ # Called with the status whenever the pool answers 401/403.
336
+ self.on_key_rejected: Callable[[int], None] | None = None
321
337
 
322
338
  async def aclose(self) -> None:
323
339
  await self._client.aclose()
324
340
 
341
+ async def _send(self, method: str, url: str, **kw: Any) -> httpx.Response:
342
+ r = await self._client.request(method, url, **kw)
343
+ if r.status_code in (401, 403) and self.on_key_rejected is not None:
344
+ self.on_key_rejected(r.status_code)
345
+ return r
346
+
325
347
  async def lease(self, provider: CliProvider, *,
326
348
  account: str | None = None,
327
349
  user_id: str | None = None,
328
350
  required_model: str | None = None) -> dict:
329
351
  body: dict[str, Any] = dict(provider.lease_body_extras)
352
+ body["request_id"] = self._lease_rid.value
330
353
  if account:
331
354
  body["account"] = account
332
355
  if user_id:
333
356
  body["user_id"] = user_id
334
357
  if required_model:
335
358
  body["required_model"] = required_model
336
- r = await self._client.post("/credentials/lease", json=body)
359
+ r = await self._send("POST", "/credentials/lease", json=body)
337
360
  r.raise_for_status()
361
+ self._lease_rid.retire()
338
362
  return r.json()
339
363
 
340
364
  async def refresh_token(self, lease_id: str) -> dict:
341
- r = await self._client.post(f"/credentials/lease/{lease_id}/token")
365
+ r = await self._send("POST", f"/credentials/lease/{lease_id}/token")
342
366
  r.raise_for_status()
343
367
  return r.json()
344
368
 
345
369
  async def release(self, lease_id: str) -> None:
346
- with suppress(Exception):
347
- await self._client.request(
348
- "DELETE", f"/credentials/lease/{lease_id}", json={},
349
- )
370
+ await release_lease(lambda: self._send(
371
+ "DELETE", f"/credentials/lease/{lease_id}", json={},
372
+ ), lease_id)
350
373
 
351
374
  async def health(self, lease_id: str) -> dict:
352
- r = await self._client.get(f"/credentials/lease/{lease_id}/health")
375
+ r = await self._send("GET", f"/credentials/lease/{lease_id}/health")
353
376
  r.raise_for_status()
354
377
  return r.json()
355
378
 
@@ -367,8 +390,8 @@ class PoolHTTP:
367
390
  that follows.
368
391
  """
369
392
  with suppress(Exception):
370
- await self._client.post(
371
- f"/credentials/lease/{lease_id}/report-error",
393
+ await self._send(
394
+ "POST", f"/credentials/lease/{lease_id}/report-error",
372
395
  json={"code": code, "message": message},
373
396
  )
374
397
 
@@ -508,6 +531,11 @@ async def run_session(
508
531
  err=True,
509
532
  )
510
533
  return 2
534
+ try:
535
+ check_pool_url(cfg.pool_url)
536
+ except ValueError as e:
537
+ click.echo(f"[sp-{provider.name}] {e}", err=True)
538
+ return 2
511
539
 
512
540
  if verbose:
513
541
  logging.basicConfig(
@@ -524,6 +552,10 @@ async def run_session(
524
552
  required_model = model_from_args(prompt_args)
525
553
 
526
554
  pool = PoolHTTP(cfg)
555
+ # Set once we hold a lease. The outer finally releases whatever it points
556
+ # at by then (a swap may have advanced it), however the session ends —
557
+ # including a failure before the child ever starts (e.g. a missing binary).
558
+ current: dict | None = None
527
559
  try:
528
560
  try:
529
561
  lease = await pool.lease(
@@ -536,6 +568,7 @@ async def run_session(
536
568
  except httpx.HTTPError as e:
537
569
  click.echo(f"[sp-{provider.name}] pool unreachable: {e}", err=True)
538
570
  return 3
571
+ current = {"lease": lease}
539
572
  if verbose:
540
573
  log.info("leased %s (lease_id=%s)",
541
574
  lease.get("account"), lease.get("lease_id"))
@@ -560,7 +593,9 @@ async def run_session(
560
593
  # failure the pool cannot see (a revoked access token on a
561
594
  # still-valid grant — see _auth_watch). It requires piping, so it
562
595
  # is off whenever stdout is a real terminal: interactive `claude`
563
- # is a TUI that needs one. stdin is always inherited.
596
+ # is a TUI that needs one. stdin is always inherited. What covers
597
+ # an interactive session instead is `on_healthy` below, which
598
+ # catches a token the pool rotated out from under us.
564
599
  watch_output = _auth_watch.should_watch()
565
600
  _pipe = asyncio.subprocess.PIPE if watch_output else None
566
601
  proc = await asyncio.create_subprocess_exec(
@@ -583,7 +618,6 @@ async def run_session(
583
618
  installed_signals.append(sig)
584
619
 
585
620
  # Background tasks: token refresh + health-driven account swap.
586
- current = {"lease": lease}
587
621
  # Set by a successful swap so the expiry-anchored refresh loop
588
622
  # re-anchors to the NEW lease's token instead of sleeping out a
589
623
  # now-stale deadline — a swapped-in token may have far less life
@@ -636,6 +670,28 @@ async def run_session(
636
670
  if verbose:
637
671
  log.info("swap deferred: %s", e)
638
672
 
673
+ async def _refresh_now() -> bool:
674
+ ok = await _refresh_once(
675
+ pool, current, session_dir, provider, verbose,
676
+ )
677
+ if ok:
678
+ # Re-anchor the scheduled loop to the token we just
679
+ # installed, instead of leaving it asleep on the old
680
+ # deadline.
681
+ refresh_wake.set()
682
+ return ok
683
+
684
+ async def on_healthy(health: dict) -> None:
685
+ # The account is fine, but the pool may have rotated its token
686
+ # — every lease on it shares one — revoking the copy on our
687
+ # disk. For an interactive session this is the only recovery:
688
+ # its output can't be watched for 401s (see _auth_watch).
689
+ if token_is_stale(current["lease"], health):
690
+ if verbose:
691
+ log.info("pool rotated %s's token; pulling the "
692
+ "current one", current["lease"].get("account"))
693
+ await _refresh_now()
694
+
639
695
  refresher = asyncio.create_task(
640
696
  _token_refresh_loop(
641
697
  pool, current, session_dir, provider, verbose,
@@ -647,9 +703,13 @@ async def run_session(
647
703
  HealthWatcher(
648
704
  fetch=lambda: pool.health(current["lease"]["lease_id"]),
649
705
  on_unhealthy=on_swap_needed,
706
+ on_healthy=on_healthy,
650
707
  ).run(),
651
708
  name=f"sp-{provider.name}-health",
652
709
  )
710
+ # Everything that talks to the pool on our behalf, stopped as a
711
+ # unit if the pool rejects the key.
712
+ maintenance = [refresher, watcher]
653
713
 
654
714
  # Output-driven auth recovery. Detection runs in the pumps (sync,
655
715
  # non-blocking); the ACTION runs in one consumer task fed by a
@@ -659,17 +719,6 @@ async def run_session(
659
719
  aux: list[asyncio.Task] = []
660
720
  pumps: list[asyncio.Task] = []
661
721
  if watch_output:
662
- async def _auth_refresh() -> bool:
663
- ok = await _refresh_once(
664
- pool, current, session_dir, provider, verbose,
665
- )
666
- if ok:
667
- # Re-anchor the scheduled loop to the token we just
668
- # minted, instead of leaving it asleep on the old
669
- # deadline.
670
- refresh_wake.set()
671
- return ok
672
-
673
722
  async def _auth_report(code: str, message: str) -> None:
674
723
  await pool.report_error(
675
724
  current["lease"]["lease_id"], code, message,
@@ -679,7 +728,7 @@ async def run_session(
679
728
  await on_swap_needed({"reason": reason})
680
729
 
681
730
  recovery = _auth_watch.AuthRecovery(
682
- refresh=_auth_refresh,
731
+ refresh=_refresh_now,
683
732
  report_error=_auth_report,
684
733
  swap=_auth_swap,
685
734
  verbose=verbose,
@@ -696,9 +745,10 @@ async def run_session(
696
745
  sample = await signals.get()
697
746
  await recovery.on_signal(sample)
698
747
 
699
- aux.append(asyncio.create_task(
748
+ maintenance.append(asyncio.create_task(
700
749
  _consume_signals(), name=f"sp-{provider.name}-authrecover",
701
750
  ))
751
+ aux.append(maintenance[-1])
702
752
  for stream, sink in (
703
753
  (proc.stdout, _auth_watch.stdout_sink()),
704
754
  (proc.stderr, _auth_watch.stderr_sink()),
@@ -712,6 +762,22 @@ async def run_session(
712
762
  pumps.append(t)
713
763
  aux.append(t)
714
764
 
765
+ def _on_key_rejected(status: int) -> None:
766
+ # A revoked / expired key fails every call; retrying just
767
+ # polls a dead key forever. Report once and stop.
768
+ pool.on_key_rejected = None
769
+ click.echo(
770
+ f"[sp-{provider.name}] API key rejected by the pool "
771
+ f"({status}) — stopping lease maintenance. The session "
772
+ f"keeps its current credential until it expires; check "
773
+ f"the key with `sp-{provider.name} --setup`.",
774
+ err=True,
775
+ )
776
+ for t in maintenance:
777
+ t.cancel()
778
+
779
+ pool.on_key_rejected = _on_key_rejected
780
+
715
781
  try:
716
782
  exit_code = await proc.wait()
717
783
  # The child can exit with bytes still in the pipe buffers.
@@ -727,6 +793,7 @@ async def run_session(
727
793
  for sig in installed_signals:
728
794
  with suppress(NotImplementedError, RuntimeError):
729
795
  loop.remove_signal_handler(sig)
796
+ pool.on_key_rejected = None
730
797
  refresher.cancel()
731
798
  watcher.cancel()
732
799
  for t in aux:
@@ -734,13 +801,14 @@ async def run_session(
734
801
  for t in (refresher, watcher, *aux):
735
802
  with suppress(asyncio.CancelledError, Exception):
736
803
  await t
737
- await pool.release(current["lease"]["lease_id"])
738
804
  finally:
739
805
  with suppress(Exception):
740
806
  commit_session_to_home(session_dir, home_dir, provider)
741
807
  shutil.rmtree(session_dir, ignore_errors=True)
742
808
  return exit_code
743
809
  finally:
810
+ if current is not None:
811
+ await pool.release(current["lease"]["lease_id"])
744
812
  await pool.aclose()
745
813
 
746
814
 
@@ -7,7 +7,10 @@ window hit ≥95%). The handler is expected to perform an account swap
7
7
  (see `_swap.swap_credentials`).
8
8
 
9
9
  Transient failures (network blips, 5xx) are swallowed and retried on the
10
- next tick — the watcher's job is to be quietly reliable, not noisy.
10
+ next tick — the watcher's job is to be quietly reliable, not noisy. Two
11
+ answers end it instead: 401/403 (the API key is rejected; the owner's
12
+ HTTP layer stops the rest of lease maintenance), and a lease that stays
13
+ gone after `MAX_REACQUIRE_ATTEMPTS` re-leases.
11
14
  """
12
15
  from __future__ import annotations
13
16
 
@@ -17,15 +20,22 @@ from typing import Any, Awaitable, Callable
17
20
 
18
21
  import httpx
19
22
 
23
+ from sub_pool_client._shared import jittered
24
+
20
25
  log = logging.getLogger(__name__)
21
26
 
22
27
 
23
28
  class HealthWatcher:
29
+ # Consecutive re-lease attempts for a gone lease before giving up; the
30
+ # tick interval doubles after each one that didn't bring the lease back.
31
+ MAX_REACQUIRE_ATTEMPTS = 5
32
+
24
33
  def __init__(
25
34
  self,
26
35
  *,
27
36
  fetch: Callable[[], Awaitable[dict[str, Any]]],
28
37
  on_unhealthy: Callable[[dict[str, Any]], Awaitable[None]],
38
+ on_healthy: Callable[[dict[str, Any]], Awaitable[None]] | None = None,
29
39
  interval_s: float = 30.0,
30
40
  ):
31
41
  # `fetch` is a no-argument coroutine that returns the health dict
@@ -34,17 +44,25 @@ class HealthWatcher:
34
44
  # in place via a small mutable container).
35
45
  self._fetch = fetch
36
46
  self._on_unhealthy = on_unhealthy
47
+ # Sees every healthy answer, for fields beyond the verdict (the CLI
48
+ # uses `token_expires_at` to catch a token rotated out from under it).
49
+ self._on_healthy = on_healthy
37
50
  self._interval_s = interval_s
38
51
 
39
52
  async def run(self) -> None:
53
+ # Re-leases attempted since the lease was last seen alive. A tick that
54
+ # still finds it gone means the previous attempt failed.
55
+ reacquires = 0
40
56
  while True:
41
57
  try:
42
- await asyncio.sleep(self._interval_s)
58
+ await asyncio.sleep(jittered(self._interval_s * 2 ** reacquires))
43
59
  except asyncio.CancelledError:
44
60
  return
45
61
  try:
46
62
  data = await self._fetch()
47
63
  except httpx.HTTPStatusError as e:
64
+ if e.response.status_code in (401, 403):
65
+ return
48
66
  if e.response.status_code in (404, 410):
49
67
  # Our CURRENT lease died server-side while the session is
50
68
  # still live: reaped after a health-poll gap (e.g. the host
@@ -64,6 +82,14 @@ class HealthWatcher:
64
82
  # out from under a running session, DISABLE the account
65
83
  # (re-lease then 503s and the client quietly waits it out) or
66
84
  # revoke its api-key.
85
+ #
86
+ # Bounded: each failed attempt doubles the wait, and after
87
+ # MAX_REACQUIRE_ATTEMPTS we stop rather than keep leasing.
88
+ if reacquires >= self.MAX_REACQUIRE_ATTEMPTS:
89
+ log.error("lease still gone after %d re-lease attempts; "
90
+ "giving up on it", reacquires)
91
+ return
92
+ reacquires += 1
67
93
  try:
68
94
  await self._on_unhealthy({
69
95
  "healthy": False,
@@ -88,7 +114,15 @@ class HealthWatcher:
88
114
  log.debug("health probe unexpected: %s", e)
89
115
  continue
90
116
 
117
+ reacquires = 0
91
118
  if data.get("healthy"):
119
+ if self._on_healthy is not None:
120
+ try:
121
+ await self._on_healthy(data)
122
+ except asyncio.CancelledError:
123
+ return
124
+ except Exception as e: # noqa: BLE001
125
+ log.warning("on_healthy handler raised: %s", e)
92
126
  continue
93
127
 
94
128
  try:
@@ -20,6 +20,11 @@ Coordination rules:
20
20
  - When `holders` goes empty, the last holder reads `.credentials.json`
21
21
  (possibly rotated by the CLI mid-run) and posts it back to the pool as
22
22
  `updated_credentials` on DELETE, then removes the dir.
23
+
24
+ - Dirs are 0700 and every file in them 0600. A dir left behind by a crash
25
+ is removed by `sweep_stale_dirs` once it is old and all its holders are
26
+ dead; `locked_meta` retries on a fresh dir if one is removed while it
27
+ waits for the lock.
23
28
  """
24
29
  from __future__ import annotations
25
30
 
@@ -27,12 +32,21 @@ import asyncio
27
32
  import fcntl
28
33
  import hashlib
29
34
  import json
35
+ import logging
30
36
  import os
37
+ import random
31
38
  import shutil
39
+ import time
40
+ import uuid
32
41
  from contextlib import asynccontextmanager
33
42
  from dataclasses import dataclass
34
43
  from pathlib import Path
35
- from typing import AsyncIterator
44
+ from typing import AsyncIterator, Awaitable, Callable
45
+ from urllib.parse import urlsplit
46
+
47
+ import httpx
48
+
49
+ log = logging.getLogger(__name__)
36
50
 
37
51
 
38
52
  DEFAULT_ROOT = Path(
@@ -41,6 +55,93 @@ DEFAULT_ROOT = Path(
41
55
  )
42
56
 
43
57
 
58
+ # ---- pool URL -----------------------------------------------------------
59
+ _LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
60
+
61
+
62
+ def check_pool_url(url: str) -> None:
63
+ """Raise ValueError for a plain-http pool that isn't on this machine:
64
+ every request carries the API key, and lease responses carry OAuth
65
+ access tokens."""
66
+ parts = urlsplit(url)
67
+ if parts.scheme == "http" and parts.hostname not in _LOOPBACK_HOSTS:
68
+ raise ValueError(
69
+ f"refusing plain http:// pool URL {url!r}: the API key and leased "
70
+ f"credentials would travel unencrypted. Use https:// (http:// is "
71
+ f"only allowed for localhost / 127.0.0.1 / ::1)."
72
+ )
73
+
74
+
75
+ # ---- lease requests -----------------------------------------------------
76
+ class LeaseRequestId:
77
+ """Idempotency key for `POST /credentials/lease`.
78
+
79
+ The pool dedupes issuance on (request_id, api_key, provider): a POST that
80
+ repeats the id of a lease it already made returns that lease instead of
81
+ minting another. So one id covers one logical acquisition across all its
82
+ attempts, and is retired only once a 2xx proves we hold the lease. Any
83
+ other outcome keeps it: a timeout, a dropped connection or a proxy 5xx can
84
+ hide a lease the server did commit, and reusing the id after a genuine
85
+ rejection is harmless (the pool finds no active lease under it). Without
86
+ this, every timed-out attempt the server had committed became an orphan
87
+ held until the TTL reaper.
88
+ """
89
+
90
+ def __init__(self) -> None:
91
+ self.value = _new_request_id()
92
+
93
+ def retire(self) -> None:
94
+ self.value = _new_request_id()
95
+
96
+
97
+ def _new_request_id() -> str:
98
+ return "req-" + uuid.uuid4().hex
99
+
100
+
101
+ RELEASE_ATTEMPTS = 3
102
+ RELEASE_BACKOFF_S = 0.5
103
+
104
+
105
+ async def release_lease(
106
+ send: Callable[[], Awaitable[httpx.Response]], lease_id: str,
107
+ ) -> bool:
108
+ """DELETE a lease via `send`, retrying transient failures. True once the
109
+ pool confirms it (2xx, or 404/410: already gone).
110
+
111
+ Never raises — callers are cleanup paths. A lease we fail to release is
112
+ held until the pool's TTL reaper; that used to happen silently, which is
113
+ how leases piled up unnoticed, so the final failure is a WARNING.
114
+ """
115
+ problem = ""
116
+ for attempt in range(RELEASE_ATTEMPTS):
117
+ if attempt:
118
+ await asyncio.sleep(RELEASE_BACKOFF_S * 2 ** (attempt - 1))
119
+ try:
120
+ r = await send()
121
+ except Exception as e: # noqa: BLE001
122
+ problem = f"{type(e).__name__}: {e}"
123
+ continue
124
+ if r.is_success or r.status_code in (404, 410):
125
+ return True
126
+ problem = f"HTTP {r.status_code}"
127
+ if r.status_code < 500 and r.status_code not in (408, 429):
128
+ break # a definitive rejection (e.g. 401/403) won't change on retry
129
+ log.warning(
130
+ "failed to release lease %s (%s); the pool's TTL reaper will end it",
131
+ lease_id, problem,
132
+ )
133
+ return False
134
+
135
+
136
+ # ---- polling cadence ----------------------------------------------------
137
+ JITTER = 0.2
138
+
139
+
140
+ def jittered(seconds: float) -> float:
141
+ """`seconds` ±20%, so clients started together don't poll in lockstep."""
142
+ return seconds * random.uniform(1 - JITTER, 1 + JITTER)
143
+
144
+
44
145
  # ---- token-refresh scheduling -------------------------------------------
45
146
  # Shared by the sp-claude/sp-codex CLI refresh loop (_cli_core) AND both SDK
46
147
  # poll loops (PooledClient / PooledCodexClient). Kept in ONE place because the
@@ -65,10 +166,41 @@ def next_refresh_sleep(
65
166
  `min_sleep_s`. When `expires_at` carries no usable value (<=0), fall back to
66
167
  a fixed cadence instead of anchoring to a long-past deadline — that would
67
168
  refresh every `min_sleep_s` forever (a needless churn storm that hit codex
68
- api-key leases, whose token has no expiry)."""
169
+ api-key leases, whose token has no expiry).
170
+
171
+ The two fixed cadences are jittered so a fleet that failed together (pool
172
+ outage) doesn't retry together; the expiry-anchored one is exact, since
173
+ jitter there could overshoot the token's life."""
69
174
  if expires_at <= 0:
70
- return fallback_s
71
- return max(min_sleep_s, expires_at - now - slack_s)
175
+ return jittered(fallback_s)
176
+ anchored = expires_at - now - slack_s
177
+ return anchored if anchored > min_sleep_s else jittered(min_sleep_s)
178
+
179
+
180
+ def token_is_stale(lease: dict, health: dict) -> bool:
181
+ """Has the pool moved this lease's account onto a different token?
182
+
183
+ Reads `token_expires_at` off a `/health` answer — the expiry of the
184
+ account's CURRENT token. Every lease on an account shares that token, so
185
+ when anything pool-side rotates it (another lease's near-expiry poll, the
186
+ usage probe recovering from a 401) the copy this lease holds is revoked
187
+ while the account itself stays healthy. A rotation always moves the
188
+ expiry, which is how we notice.
189
+
190
+ False when the answer is about another lease (a swap raced the probe) or
191
+ carries no expiry: a pool that predates the field, or a provider the pool
192
+ deliberately leaves it out for because its /token rotates on every call.
193
+ """
194
+ if health.get("lease_id") != lease.get("lease_id"):
195
+ return False
196
+ pool_exp = health.get("token_expires_at")
197
+ if (isinstance(pool_exp, bool) or not isinstance(pool_exp, (int, float))
198
+ or pool_exp <= 0):
199
+ return False
200
+ ours = float(lease.get("token_expires_at") or 0.0)
201
+ # Slack for a float that has crossed JSON twice; two distinct tokens are
202
+ # minted seconds apart at the very least.
203
+ return abs(float(pool_exp) - ours) > 1.0
72
204
 
73
205
 
74
206
  def dir_key(
@@ -94,7 +226,9 @@ def dir_key(
94
226
 
95
227
  def shared_dir(key: str, root: Path | None = None) -> Path:
96
228
  d = (root or DEFAULT_ROOT) / key
97
- d.mkdir(parents=True, exist_ok=True)
229
+ d.mkdir(mode=0o700, parents=True, exist_ok=True)
230
+ # Also tightens a dir an older client created 0755.
231
+ os.chmod(d, 0o700)
98
232
  return d
99
233
 
100
234
 
@@ -184,14 +318,25 @@ async def locked_meta(dir_: Path) -> AsyncIterator[Meta]:
184
318
  meta_path = dir_ / "meta.json"
185
319
 
186
320
  async with _process_lock(str(dir_.resolve())):
187
- # Use O_CREAT so the first arriver creates the lockfile.
188
- fd = os.open(str(lock_path), os.O_RDWR | os.O_CREAT, 0o600)
321
+ while True:
322
+ dir_.mkdir(mode=0o700, parents=True, exist_ok=True)
323
+ # Use O_CREAT so the first arriver creates the lockfile.
324
+ fd = os.open(str(lock_path), os.O_RDWR | os.O_CREAT, 0o600)
325
+ try:
326
+ # flock is sync & blocking; release the loop while waiting so
327
+ # a second consumer in the same process isn't completely
328
+ # stuck if someone's running a long inter-process critical
329
+ # section next door.
330
+ await asyncio.to_thread(fcntl.flock, fd, fcntl.LOCK_EX)
331
+ except BaseException:
332
+ os.close(fd)
333
+ raise
334
+ if os.fstat(fd).st_nlink:
335
+ break
336
+ # The dir was removed (failed entry / stale sweep) while we waited
337
+ # for its lock: start over on a fresh one.
338
+ os.close(fd)
189
339
  try:
190
- # flock is sync & blocking; release the loop while waiting so
191
- # a second consumer in the same process isn't completely
192
- # stuck if someone's running a long inter-process critical
193
- # section next door.
194
- await asyncio.to_thread(fcntl.flock, fd, fcntl.LOCK_EX)
195
340
  try:
196
341
  raw = meta_path.read_text() if meta_path.exists() else "{}"
197
342
  data = json.loads(raw or "{}")
@@ -208,11 +353,22 @@ async def locked_meta(dir_: Path) -> AsyncIterator[Meta]:
208
353
  if meta.poll_leader is not None and not _pid_alive(meta.poll_leader):
209
354
  meta.poll_leader = None
210
355
 
211
- yield meta
356
+ try:
357
+ yield meta
358
+ except BaseException:
359
+ # A failed first entry (lease POST / credential write raised)
360
+ # leaves nothing worth keeping; remove the dir while we still
361
+ # hold its lock rather than leak an empty one per failure.
362
+ if not meta.lease_id and not meta.holders:
363
+ cleanup_dir(dir_)
364
+ raise
212
365
 
213
366
  payload = json.dumps(meta.to_json(), indent=2)
214
367
  tmp = meta_path.with_suffix(meta_path.suffix + ".tmp")
215
- tmp.write_text(payload)
368
+ tmp_fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
369
+ os.fchmod(tmp_fd, 0o600)
370
+ with os.fdopen(tmp_fd, "w") as f:
371
+ f.write(payload)
216
372
  os.replace(tmp, meta_path)
217
373
  finally:
218
374
  try:
@@ -339,6 +495,56 @@ def cleanup_dir(dir_: Path) -> None:
339
495
  pass
340
496
 
341
497
 
498
+ # A dir is only swept once it has also been untouched this long: pid liveness
499
+ # alone can be wrong (another container's pids look dead here, a reused pid
500
+ # looks alive).
501
+ STALE_DIR_AGE_S = 24 * 3600
502
+ _swept = False
503
+
504
+
505
+ async def sweep_stale_dirs_once() -> None:
506
+ """Run `sweep_stale_dirs` on DEFAULT_ROOT, at most once per process."""
507
+ global _swept
508
+ if _swept:
509
+ return
510
+ _swept = True
511
+ await asyncio.to_thread(sweep_stale_dirs, DEFAULT_ROOT)
512
+
513
+
514
+ def sweep_stale_dirs(root: Path, max_age_s: float = STALE_DIR_AGE_S) -> None:
515
+ """Best-effort removal of shared dirs a crashed process left behind —
516
+ each may still hold a credential file. Removes a dir only if its mtime is
517
+ older than `max_age_s` AND every holder in its meta.json is dead, checked
518
+ under the dir's lock (skipped if busy). Server-side leases are left to the
519
+ pool's TTL reaper."""
520
+ cutoff = time.time() - max_age_s
521
+ try:
522
+ dirs = [d for d in root.iterdir() if d.is_dir() and not d.is_symlink()]
523
+ except OSError:
524
+ return
525
+ for d in dirs:
526
+ try:
527
+ if d.stat().st_mtime > cutoff:
528
+ continue
529
+ fd = os.open(str(d / ".meta.lock"), os.O_RDWR | os.O_CREAT, 0o600)
530
+ try:
531
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
532
+ except BlockingIOError:
533
+ os.close(fd)
534
+ continue
535
+ try:
536
+ try:
537
+ holders = json.loads((d / "meta.json").read_text()).get("holders")
538
+ except (OSError, ValueError):
539
+ holders = None
540
+ if not any(_pid_alive(p) for p in holders or []):
541
+ cleanup_dir(d)
542
+ finally:
543
+ os.close(fd)
544
+ except Exception as e: # noqa: BLE001
545
+ log.debug("stale dir sweep skipped %s: %s", d, e)
546
+
547
+
342
548
  # The DEFAULT_ROOT constant pulls from $SUB_POOL_CLIENT_DIR at import
343
549
  # time; tests that want isolation should clear the env before import or
344
550
  # pass `root=` explicitly.