sub-pool-client 0.8.2__tar.gz → 0.9.0__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.0}/PKG-INFO +1 -1
  2. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/sub_pool_client/_cli_core.py +69 -16
  3. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/sub_pool_client/_health_watcher.py +25 -2
  4. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/sub_pool_client/_shared.py +194 -14
  5. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/sub_pool_client/_version.py +2 -2
  6. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/sub_pool_client/client.py +130 -81
  7. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/sub_pool_client/codex.py +111 -72
  8. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/.github/workflows/publish.yml +0 -0
  9. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/.gitignore +0 -0
  10. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/README.md +0 -0
  11. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/examples/codex_hello.py +0 -0
  12. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/examples/hello.py +0 -0
  13. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/meta/README.md +0 -0
  14. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/meta/pyproject.toml +0 -0
  15. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/pyproject.toml +0 -0
  16. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/sub_pool_client/__init__.py +0 -0
  17. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/sub_pool_client/_auth_watch.py +0 -0
  18. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/sub_pool_client/_cli_provider.py +0 -0
  19. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/sub_pool_client/_swap.py +0 -0
  20. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/sub_pool_client/cli_claude.py +0 -0
  21. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/sub_pool_client/cli_codex.py +0 -0
  22. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/sub_pool_client/cli_grok.py +0 -0
  23. {sub_pool_client-0.8.2 → sub_pool_client-0.9.0}/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.0
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,12 @@ 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
+ )
31
36
  from sub_pool_client._swap import NoSwapAvailable, swap_credentials
32
37
 
33
38
 
@@ -169,9 +174,15 @@ def run_setup(provider: CliProvider) -> int:
169
174
  "Pool URL", default=pool_default or "https://",
170
175
  show_default=bool(pool_default),
171
176
  ).strip()
172
- if pool_url.startswith(("http://", "https://")) and len(pool_url) > 8:
177
+ if not (pool_url.startswith(("http://", "https://"))
178
+ and len(pool_url) > 8):
179
+ click.echo(" → must start with http:// or https://", err=True)
180
+ continue
181
+ try:
182
+ check_pool_url(pool_url)
173
183
  break
174
- click.echo(" → must start with http:// or https://", err=True)
184
+ except ValueError as e:
185
+ click.echo(f" → {e}", err=True)
175
186
  api_key = click.prompt("API key (cp-...)", hide_input=True).strip()
176
187
  default_account = click.prompt(
177
188
  f"Default {provider.name} account (empty = strategy-based)",
@@ -318,38 +329,49 @@ class PoolHTTP:
318
329
  headers={"Authorization": f"Bearer {cfg.api_key}"},
319
330
  timeout=httpx.Timeout(30.0, connect=10.0),
320
331
  )
332
+ # Covers the initial lease and every swap; see LeaseRequestId.
333
+ self._lease_rid = LeaseRequestId()
334
+ # Called with the status whenever the pool answers 401/403.
335
+ self.on_key_rejected: Callable[[int], None] | None = None
321
336
 
322
337
  async def aclose(self) -> None:
323
338
  await self._client.aclose()
324
339
 
340
+ async def _send(self, method: str, url: str, **kw: Any) -> httpx.Response:
341
+ r = await self._client.request(method, url, **kw)
342
+ if r.status_code in (401, 403) and self.on_key_rejected is not None:
343
+ self.on_key_rejected(r.status_code)
344
+ return r
345
+
325
346
  async def lease(self, provider: CliProvider, *,
326
347
  account: str | None = None,
327
348
  user_id: str | None = None,
328
349
  required_model: str | None = None) -> dict:
329
350
  body: dict[str, Any] = dict(provider.lease_body_extras)
351
+ body["request_id"] = self._lease_rid.value
330
352
  if account:
331
353
  body["account"] = account
332
354
  if user_id:
333
355
  body["user_id"] = user_id
334
356
  if required_model:
335
357
  body["required_model"] = required_model
336
- r = await self._client.post("/credentials/lease", json=body)
358
+ r = await self._send("POST", "/credentials/lease", json=body)
337
359
  r.raise_for_status()
360
+ self._lease_rid.retire()
338
361
  return r.json()
339
362
 
340
363
  async def refresh_token(self, lease_id: str) -> dict:
341
- r = await self._client.post(f"/credentials/lease/{lease_id}/token")
364
+ r = await self._send("POST", f"/credentials/lease/{lease_id}/token")
342
365
  r.raise_for_status()
343
366
  return r.json()
344
367
 
345
368
  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
- )
369
+ await release_lease(lambda: self._send(
370
+ "DELETE", f"/credentials/lease/{lease_id}", json={},
371
+ ), lease_id)
350
372
 
351
373
  async def health(self, lease_id: str) -> dict:
352
- r = await self._client.get(f"/credentials/lease/{lease_id}/health")
374
+ r = await self._send("GET", f"/credentials/lease/{lease_id}/health")
353
375
  r.raise_for_status()
354
376
  return r.json()
355
377
 
@@ -367,8 +389,8 @@ class PoolHTTP:
367
389
  that follows.
368
390
  """
369
391
  with suppress(Exception):
370
- await self._client.post(
371
- f"/credentials/lease/{lease_id}/report-error",
392
+ await self._send(
393
+ "POST", f"/credentials/lease/{lease_id}/report-error",
372
394
  json={"code": code, "message": message},
373
395
  )
374
396
 
@@ -508,6 +530,11 @@ async def run_session(
508
530
  err=True,
509
531
  )
510
532
  return 2
533
+ try:
534
+ check_pool_url(cfg.pool_url)
535
+ except ValueError as e:
536
+ click.echo(f"[sp-{provider.name}] {e}", err=True)
537
+ return 2
511
538
 
512
539
  if verbose:
513
540
  logging.basicConfig(
@@ -524,6 +551,10 @@ async def run_session(
524
551
  required_model = model_from_args(prompt_args)
525
552
 
526
553
  pool = PoolHTTP(cfg)
554
+ # Set once we hold a lease. The outer finally releases whatever it points
555
+ # at by then (a swap may have advanced it), however the session ends —
556
+ # including a failure before the child ever starts (e.g. a missing binary).
557
+ current: dict | None = None
527
558
  try:
528
559
  try:
529
560
  lease = await pool.lease(
@@ -536,6 +567,7 @@ async def run_session(
536
567
  except httpx.HTTPError as e:
537
568
  click.echo(f"[sp-{provider.name}] pool unreachable: {e}", err=True)
538
569
  return 3
570
+ current = {"lease": lease}
539
571
  if verbose:
540
572
  log.info("leased %s (lease_id=%s)",
541
573
  lease.get("account"), lease.get("lease_id"))
@@ -583,7 +615,6 @@ async def run_session(
583
615
  installed_signals.append(sig)
584
616
 
585
617
  # Background tasks: token refresh + health-driven account swap.
586
- current = {"lease": lease}
587
618
  # Set by a successful swap so the expiry-anchored refresh loop
588
619
  # re-anchors to the NEW lease's token instead of sleeping out a
589
620
  # now-stale deadline — a swapped-in token may have far less life
@@ -650,6 +681,9 @@ async def run_session(
650
681
  ).run(),
651
682
  name=f"sp-{provider.name}-health",
652
683
  )
684
+ # Everything that talks to the pool on our behalf, stopped as a
685
+ # unit if the pool rejects the key.
686
+ maintenance = [refresher, watcher]
653
687
 
654
688
  # Output-driven auth recovery. Detection runs in the pumps (sync,
655
689
  # non-blocking); the ACTION runs in one consumer task fed by a
@@ -696,9 +730,10 @@ async def run_session(
696
730
  sample = await signals.get()
697
731
  await recovery.on_signal(sample)
698
732
 
699
- aux.append(asyncio.create_task(
733
+ maintenance.append(asyncio.create_task(
700
734
  _consume_signals(), name=f"sp-{provider.name}-authrecover",
701
735
  ))
736
+ aux.append(maintenance[-1])
702
737
  for stream, sink in (
703
738
  (proc.stdout, _auth_watch.stdout_sink()),
704
739
  (proc.stderr, _auth_watch.stderr_sink()),
@@ -712,6 +747,22 @@ async def run_session(
712
747
  pumps.append(t)
713
748
  aux.append(t)
714
749
 
750
+ def _on_key_rejected(status: int) -> None:
751
+ # A revoked / expired key fails every call; retrying just
752
+ # polls a dead key forever. Report once and stop.
753
+ pool.on_key_rejected = None
754
+ click.echo(
755
+ f"[sp-{provider.name}] API key rejected by the pool "
756
+ f"({status}) — stopping lease maintenance. The session "
757
+ f"keeps its current credential until it expires; check "
758
+ f"the key with `sp-{provider.name} --setup`.",
759
+ err=True,
760
+ )
761
+ for t in maintenance:
762
+ t.cancel()
763
+
764
+ pool.on_key_rejected = _on_key_rejected
765
+
715
766
  try:
716
767
  exit_code = await proc.wait()
717
768
  # The child can exit with bytes still in the pipe buffers.
@@ -727,6 +778,7 @@ async def run_session(
727
778
  for sig in installed_signals:
728
779
  with suppress(NotImplementedError, RuntimeError):
729
780
  loop.remove_signal_handler(sig)
781
+ pool.on_key_rejected = None
730
782
  refresher.cancel()
731
783
  watcher.cancel()
732
784
  for t in aux:
@@ -734,13 +786,14 @@ async def run_session(
734
786
  for t in (refresher, watcher, *aux):
735
787
  with suppress(asyncio.CancelledError, Exception):
736
788
  await t
737
- await pool.release(current["lease"]["lease_id"])
738
789
  finally:
739
790
  with suppress(Exception):
740
791
  commit_session_to_home(session_dir, home_dir, provider)
741
792
  shutil.rmtree(session_dir, ignore_errors=True)
742
793
  return exit_code
743
794
  finally:
795
+ if current is not None:
796
+ await pool.release(current["lease"]["lease_id"])
744
797
  await pool.aclose()
745
798
 
746
799
 
@@ -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,10 +20,16 @@ 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
  *,
@@ -37,14 +46,19 @@ class HealthWatcher:
37
46
  self._interval_s = interval_s
38
47
 
39
48
  async def run(self) -> None:
49
+ # Re-leases attempted since the lease was last seen alive. A tick that
50
+ # still finds it gone means the previous attempt failed.
51
+ reacquires = 0
40
52
  while True:
41
53
  try:
42
- await asyncio.sleep(self._interval_s)
54
+ await asyncio.sleep(jittered(self._interval_s * 2 ** reacquires))
43
55
  except asyncio.CancelledError:
44
56
  return
45
57
  try:
46
58
  data = await self._fetch()
47
59
  except httpx.HTTPStatusError as e:
60
+ if e.response.status_code in (401, 403):
61
+ return
48
62
  if e.response.status_code in (404, 410):
49
63
  # Our CURRENT lease died server-side while the session is
50
64
  # still live: reaped after a health-poll gap (e.g. the host
@@ -64,6 +78,14 @@ class HealthWatcher:
64
78
  # out from under a running session, DISABLE the account
65
79
  # (re-lease then 503s and the client quietly waits it out) or
66
80
  # revoke its api-key.
81
+ #
82
+ # Bounded: each failed attempt doubles the wait, and after
83
+ # MAX_REACQUIRE_ATTEMPTS we stop rather than keep leasing.
84
+ if reacquires >= self.MAX_REACQUIRE_ATTEMPTS:
85
+ log.error("lease still gone after %d re-lease attempts; "
86
+ "giving up on it", reacquires)
87
+ return
88
+ reacquires += 1
67
89
  try:
68
90
  await self._on_unhealthy({
69
91
  "healthy": False,
@@ -88,6 +110,7 @@ class HealthWatcher:
88
110
  log.debug("health probe unexpected: %s", e)
89
111
  continue
90
112
 
113
+ reacquires = 0
91
114
  if data.get("healthy"):
92
115
  continue
93
116
 
@@ -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,15 @@ 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)
72
178
 
73
179
 
74
180
  def dir_key(
@@ -94,7 +200,9 @@ def dir_key(
94
200
 
95
201
  def shared_dir(key: str, root: Path | None = None) -> Path:
96
202
  d = (root or DEFAULT_ROOT) / key
97
- d.mkdir(parents=True, exist_ok=True)
203
+ d.mkdir(mode=0o700, parents=True, exist_ok=True)
204
+ # Also tightens a dir an older client created 0755.
205
+ os.chmod(d, 0o700)
98
206
  return d
99
207
 
100
208
 
@@ -184,14 +292,25 @@ async def locked_meta(dir_: Path) -> AsyncIterator[Meta]:
184
292
  meta_path = dir_ / "meta.json"
185
293
 
186
294
  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)
295
+ while True:
296
+ dir_.mkdir(mode=0o700, parents=True, exist_ok=True)
297
+ # Use O_CREAT so the first arriver creates the lockfile.
298
+ fd = os.open(str(lock_path), os.O_RDWR | os.O_CREAT, 0o600)
299
+ try:
300
+ # flock is sync & blocking; release the loop while waiting so
301
+ # a second consumer in the same process isn't completely
302
+ # stuck if someone's running a long inter-process critical
303
+ # section next door.
304
+ await asyncio.to_thread(fcntl.flock, fd, fcntl.LOCK_EX)
305
+ except BaseException:
306
+ os.close(fd)
307
+ raise
308
+ if os.fstat(fd).st_nlink:
309
+ break
310
+ # The dir was removed (failed entry / stale sweep) while we waited
311
+ # for its lock: start over on a fresh one.
312
+ os.close(fd)
189
313
  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
314
  try:
196
315
  raw = meta_path.read_text() if meta_path.exists() else "{}"
197
316
  data = json.loads(raw or "{}")
@@ -208,11 +327,22 @@ async def locked_meta(dir_: Path) -> AsyncIterator[Meta]:
208
327
  if meta.poll_leader is not None and not _pid_alive(meta.poll_leader):
209
328
  meta.poll_leader = None
210
329
 
211
- yield meta
330
+ try:
331
+ yield meta
332
+ except BaseException:
333
+ # A failed first entry (lease POST / credential write raised)
334
+ # leaves nothing worth keeping; remove the dir while we still
335
+ # hold its lock rather than leak an empty one per failure.
336
+ if not meta.lease_id and not meta.holders:
337
+ cleanup_dir(dir_)
338
+ raise
212
339
 
213
340
  payload = json.dumps(meta.to_json(), indent=2)
214
341
  tmp = meta_path.with_suffix(meta_path.suffix + ".tmp")
215
- tmp.write_text(payload)
342
+ tmp_fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
343
+ os.fchmod(tmp_fd, 0o600)
344
+ with os.fdopen(tmp_fd, "w") as f:
345
+ f.write(payload)
216
346
  os.replace(tmp, meta_path)
217
347
  finally:
218
348
  try:
@@ -339,6 +469,56 @@ def cleanup_dir(dir_: Path) -> None:
339
469
  pass
340
470
 
341
471
 
472
+ # A dir is only swept once it has also been untouched this long: pid liveness
473
+ # alone can be wrong (another container's pids look dead here, a reused pid
474
+ # looks alive).
475
+ STALE_DIR_AGE_S = 24 * 3600
476
+ _swept = False
477
+
478
+
479
+ async def sweep_stale_dirs_once() -> None:
480
+ """Run `sweep_stale_dirs` on DEFAULT_ROOT, at most once per process."""
481
+ global _swept
482
+ if _swept:
483
+ return
484
+ _swept = True
485
+ await asyncio.to_thread(sweep_stale_dirs, DEFAULT_ROOT)
486
+
487
+
488
+ def sweep_stale_dirs(root: Path, max_age_s: float = STALE_DIR_AGE_S) -> None:
489
+ """Best-effort removal of shared dirs a crashed process left behind —
490
+ each may still hold a credential file. Removes a dir only if its mtime is
491
+ older than `max_age_s` AND every holder in its meta.json is dead, checked
492
+ under the dir's lock (skipped if busy). Server-side leases are left to the
493
+ pool's TTL reaper."""
494
+ cutoff = time.time() - max_age_s
495
+ try:
496
+ dirs = [d for d in root.iterdir() if d.is_dir() and not d.is_symlink()]
497
+ except OSError:
498
+ return
499
+ for d in dirs:
500
+ try:
501
+ if d.stat().st_mtime > cutoff:
502
+ continue
503
+ fd = os.open(str(d / ".meta.lock"), os.O_RDWR | os.O_CREAT, 0o600)
504
+ try:
505
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
506
+ except BlockingIOError:
507
+ os.close(fd)
508
+ continue
509
+ try:
510
+ try:
511
+ holders = json.loads((d / "meta.json").read_text()).get("holders")
512
+ except (OSError, ValueError):
513
+ holders = None
514
+ if not any(_pid_alive(p) for p in holders or []):
515
+ cleanup_dir(d)
516
+ finally:
517
+ os.close(fd)
518
+ except Exception as e: # noqa: BLE001
519
+ log.debug("stale dir sweep skipped %s: %s", d, e)
520
+
521
+
342
522
  # The DEFAULT_ROOT constant pulls from $SUB_POOL_CLIENT_DIR at import
343
523
  # time; tests that want isolation should clear the env before import or
344
524
  # pass `root=` explicitly.
@@ -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.8.2'
22
- __version_tuple__ = version_tuple = (0, 8, 2)
21
+ __version__ = version = '0.9.0'
22
+ __version_tuple__ = version_tuple = (0, 9, 0)
23
23
 
24
24
  __commit_id__ = commit_id = None