sub-pool-client 0.2.0__tar.gz → 0.6.6__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.
- {sub_pool_client-0.2.0 → sub_pool_client-0.6.6}/PKG-INFO +1 -1
- {sub_pool_client-0.2.0 → sub_pool_client-0.6.6}/sub_pool_client/_shared.py +13 -0
- {sub_pool_client-0.2.0 → sub_pool_client-0.6.6}/sub_pool_client/_version.py +2 -2
- {sub_pool_client-0.2.0 → sub_pool_client-0.6.6}/sub_pool_client/client.py +241 -14
- {sub_pool_client-0.2.0 → sub_pool_client-0.6.6}/sub_pool_client/codex.py +218 -18
- {sub_pool_client-0.2.0 → sub_pool_client-0.6.6}/.github/workflows/publish.yml +0 -0
- {sub_pool_client-0.2.0 → sub_pool_client-0.6.6}/.gitignore +0 -0
- {sub_pool_client-0.2.0 → sub_pool_client-0.6.6}/README.md +0 -0
- {sub_pool_client-0.2.0 → sub_pool_client-0.6.6}/examples/codex_hello.py +0 -0
- {sub_pool_client-0.2.0 → sub_pool_client-0.6.6}/examples/hello.py +0 -0
- {sub_pool_client-0.2.0 → sub_pool_client-0.6.6}/meta/README.md +0 -0
- {sub_pool_client-0.2.0 → sub_pool_client-0.6.6}/meta/pyproject.toml +0 -0
- {sub_pool_client-0.2.0 → sub_pool_client-0.6.6}/pyproject.toml +0 -0
- {sub_pool_client-0.2.0 → sub_pool_client-0.6.6}/sub_pool_client/__init__.py +0 -0
- {sub_pool_client-0.2.0 → sub_pool_client-0.6.6}/sub_pool_client/_cli_core.py +0 -0
- {sub_pool_client-0.2.0 → sub_pool_client-0.6.6}/sub_pool_client/_cli_provider.py +0 -0
- {sub_pool_client-0.2.0 → sub_pool_client-0.6.6}/sub_pool_client/_health_watcher.py +0 -0
- {sub_pool_client-0.2.0 → sub_pool_client-0.6.6}/sub_pool_client/_swap.py +0 -0
- {sub_pool_client-0.2.0 → sub_pool_client-0.6.6}/sub_pool_client/cli_claude.py +0 -0
- {sub_pool_client-0.2.0 → sub_pool_client-0.6.6}/sub_pool_client/cli_codex.py +0 -0
- {sub_pool_client-0.2.0 → sub_pool_client-0.6.6}/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.
|
|
3
|
+
Version: 0.6.6
|
|
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
|
|
@@ -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.
|
|
22
|
-
__version_tuple__ = version_tuple = (0,
|
|
21
|
+
__version__ = version = '0.6.6'
|
|
22
|
+
__version_tuple__ = version_tuple = (0, 6, 6)
|
|
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.
|
|
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
|
-
|
|
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
|
-
"""
|
|
248
|
-
|
|
249
|
-
|
|
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.
|
|
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
|
-
|
|
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,155 @@ 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 stops. Other
|
|
442
|
+
# non-2xx are logged + retried by the watcher.
|
|
443
|
+
r.raise_for_status()
|
|
444
|
+
return r.json()
|
|
445
|
+
|
|
446
|
+
async def _on_unhealthy(self, health: dict) -> None:
|
|
447
|
+
await self._swap_account(reason=str(health.get("reason") or "unhealthy"))
|
|
448
|
+
|
|
449
|
+
async def _swap_account(self, *, reason: str) -> None:
|
|
450
|
+
"""Lease a replacement account and rewrite the shared credential in
|
|
451
|
+
place so the running CLI picks it up on its next request. Only the poll
|
|
452
|
+
leader runs this. Best-effort: if the pool has no other healthy account
|
|
453
|
+
(503) we keep the current lease and let the next health tick retry.
|
|
454
|
+
"""
|
|
455
|
+
if self._dir is None or self._lease_id is None:
|
|
456
|
+
return
|
|
457
|
+
old_lease_id = self._lease_id
|
|
458
|
+
old_account = self._lease_account
|
|
459
|
+
old_account_id = self._lease_account_id
|
|
460
|
+
try:
|
|
461
|
+
# Do NOT reuse the caller's request_id here: the pool dedupes leases
|
|
462
|
+
# by request_id and would idempotently hand back the CURRENT
|
|
463
|
+
# (still-active, unhealthy) lease instead of a fresh account — the
|
|
464
|
+
# swap would silently no-op forever ("no other account" every tick).
|
|
465
|
+
lease = await self._post_lease(include_request_id=False)
|
|
466
|
+
except PoolError as e:
|
|
467
|
+
# 503 (all other accounts cooling/invalid) or a transient pool
|
|
468
|
+
# blip — don't tear down a working lease over it; retry next tick.
|
|
469
|
+
log.info("health swap deferred: new lease failed: %s", e)
|
|
470
|
+
return
|
|
471
|
+
|
|
472
|
+
bundle = lease.get("credentials") or {}
|
|
473
|
+
new_lease_id = lease.get("lease_id")
|
|
474
|
+
new_account = lease.get("account")
|
|
475
|
+
new_account_id = lease.get("pool_account_id")
|
|
476
|
+
if not bundle.get("access_token") or not new_lease_id:
|
|
477
|
+
log.warning("health swap: lease response missing bundle; keeping current")
|
|
478
|
+
await self._release_swap_dup(new_lease_id, old_lease_id)
|
|
479
|
+
return
|
|
480
|
+
# Same-account guard keys on the immutable server account_id, NOT the
|
|
481
|
+
# 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.
|
|
484
|
+
same_account = (
|
|
485
|
+
new_lease_id == old_lease_id
|
|
486
|
+
or (new_account_id is not None and old_account_id is not None
|
|
487
|
+
and new_account_id == old_account_id)
|
|
488
|
+
)
|
|
489
|
+
if same_account:
|
|
490
|
+
await self._release_swap_dup(new_lease_id, old_lease_id)
|
|
491
|
+
log.info("health swap: no other account available (still on %s)",
|
|
492
|
+
old_account)
|
|
493
|
+
return
|
|
494
|
+
|
|
495
|
+
new_exp = float(
|
|
496
|
+
bundle.get("expires_at") or lease.get("token_expires_at") or 0.0
|
|
497
|
+
)
|
|
498
|
+
# Commit under the meta lock so the poll loop's post-await lease_id
|
|
499
|
+
# re-check sees the rotation and drops any stale token patch. No await
|
|
500
|
+
# between the disk write and the meta / self advance.
|
|
501
|
+
#
|
|
502
|
+
# `committed` marks the point where the NEW lease becomes ours: the
|
|
503
|
+
# instant on-disk creds AND in-memory state point at it — set BEFORE the
|
|
504
|
+
# `async with` exit persists meta.json. If that persist fails (ENOSPC),
|
|
505
|
+
# committed is already True so the finally does NOT delete the new lease:
|
|
506
|
+
# self._lease_id / .credentials.json already use it, and deleting it
|
|
507
|
+
# would strand us on a dead lease (health 410 → no self-heal — the exact
|
|
508
|
+
# state this feature removes). meta.json just stays stale (old id) and
|
|
509
|
+
# self-corrects on the next locked_meta write; the now-unreferenced OLD
|
|
510
|
+
# lease is reaped by TTL.
|
|
511
|
+
committed = False
|
|
512
|
+
try:
|
|
513
|
+
async with locked_meta(self._dir) as meta:
|
|
514
|
+
write_credentials(self._dir, bundle)
|
|
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
|
+
# Wake the poll loop to reschedule against the new expiry, and
|
|
525
|
+
# take ownership — both inside the lock so a failed meta persist
|
|
526
|
+
# still leaves us pointing at a live lease.
|
|
527
|
+
self._poll_wake.set()
|
|
528
|
+
committed = True
|
|
529
|
+
finally:
|
|
530
|
+
if not committed:
|
|
531
|
+
# Never took ownership → release the orphaned new lease so it
|
|
532
|
+
# isn't leaked to the reaper. Shield so an in-flight cancel
|
|
533
|
+
# can't skip the cleanup.
|
|
534
|
+
with contextlib.suppress(Exception):
|
|
535
|
+
await asyncio.shield(self._delete_lease(new_lease_id, None))
|
|
536
|
+
|
|
537
|
+
# Release the cooled / dead lease. Shielded + best-effort so a
|
|
538
|
+
# concurrent __aexit__ cancel can't leak it. (Skipped if the meta
|
|
539
|
+
# persist above threw — the old lease then falls to the reaper.)
|
|
540
|
+
with contextlib.suppress(Exception):
|
|
541
|
+
await asyncio.shield(self._delete_lease(old_lease_id, None))
|
|
542
|
+
log.info("health-swapped account %s → %s (lease %s → %s; reason: %s)",
|
|
543
|
+
old_account, new_account, old_lease_id, new_lease_id, reason[:80])
|
|
544
|
+
|
|
545
|
+
async def _release_swap_dup(self, new_lease_id, old_lease_id) -> None:
|
|
546
|
+
"""Release a just-acquired lease we decided not to keep (missing bundle
|
|
547
|
+
or same-account), so a deferred swap never leaks it. Shielded so an
|
|
548
|
+
__aexit__ cancel landing on the DELETE can't skip the cleanup."""
|
|
549
|
+
if new_lease_id and new_lease_id != old_lease_id:
|
|
550
|
+
with contextlib.suppress(Exception):
|
|
551
|
+
await asyncio.shield(self._delete_lease(new_lease_id, None))
|
|
552
|
+
|
|
340
553
|
# ============================================================ HTTP
|
|
341
|
-
async def _post_lease(self) -> dict:
|
|
554
|
+
async def _post_lease(self, *, include_request_id: bool = True) -> dict:
|
|
342
555
|
body: dict[str, Any] = {"provider": "claude"}
|
|
343
556
|
if self._user_id:
|
|
344
557
|
body["user_id"] = self._user_id
|
|
345
|
-
if self._request_id_req:
|
|
558
|
+
if include_request_id and self._request_id_req:
|
|
346
559
|
body["request_id"] = self._request_id_req
|
|
347
560
|
if self._required_model:
|
|
348
561
|
body["required_model"] = self._required_model
|
|
@@ -396,11 +609,12 @@ class PooledClient(ClaudeSDKClient):
|
|
|
396
609
|
alive — caller decides whether to keep using it or tear down
|
|
397
610
|
and re-lease on a different account.
|
|
398
611
|
"""
|
|
399
|
-
|
|
612
|
+
lease_id = await self._current_lease_id()
|
|
613
|
+
if lease_id is None:
|
|
400
614
|
return {}
|
|
401
615
|
try:
|
|
402
616
|
r = await self._http.post(
|
|
403
|
-
f"{self._pool_url}/credentials/lease/{
|
|
617
|
+
f"{self._pool_url}/credentials/lease/{lease_id}/report-error",
|
|
404
618
|
headers={"authorization": f"Bearer {self._api_key}"},
|
|
405
619
|
json={"code": code, "message": message},
|
|
406
620
|
)
|
|
@@ -412,6 +626,19 @@ class PooledClient(ClaudeSDKClient):
|
|
|
412
626
|
return {}
|
|
413
627
|
return r.json()
|
|
414
628
|
|
|
629
|
+
async def _current_lease_id(self) -> str | None:
|
|
630
|
+
"""The lease id to act on right now. Prefers the shared meta over our
|
|
631
|
+
cached `self._lease_id`: a leader's health swap may have rotated the
|
|
632
|
+
lease past a non-leader holder's cache, and acting on the released old
|
|
633
|
+
lease would 410 (report_error) or misroute — so callers that reach the
|
|
634
|
+
pool by lease id resolve through here."""
|
|
635
|
+
if self._dir is not None:
|
|
636
|
+
with contextlib.suppress(Exception):
|
|
637
|
+
async with locked_meta(self._dir) as meta:
|
|
638
|
+
if meta.lease_id is not None:
|
|
639
|
+
return meta.lease_id
|
|
640
|
+
return self._lease_id
|
|
641
|
+
|
|
415
642
|
# ============================================================ introspection
|
|
416
643
|
@property
|
|
417
644
|
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.
|
|
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
|
-
|
|
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/{
|
|
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
|
-
|
|
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
|
-
"""
|
|
264
|
-
|
|
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.
|
|
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
|
-
|
|
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,135 @@ class PooledCodexClient:
|
|
|
340
411
|
)
|
|
341
412
|
return r.json()
|
|
342
413
|
|
|
343
|
-
|
|
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 stops.
|
|
443
|
+
r.raise_for_status()
|
|
444
|
+
return r.json()
|
|
445
|
+
|
|
446
|
+
async def _on_unhealthy(self, health: dict) -> None:
|
|
447
|
+
await self._swap_account(reason=str(health.get("reason") or "unhealthy"))
|
|
448
|
+
|
|
449
|
+
async def _swap_account(self, *, reason: str) -> None:
|
|
450
|
+
"""Lease a replacement Codex account and rewrite the shared auth.json
|
|
451
|
+
in place so the running CLI picks it up on its next call. Only the poll
|
|
452
|
+
leader runs this. Best-effort: no other healthy account (503) → keep the
|
|
453
|
+
current lease and let the next health tick retry.
|
|
454
|
+
"""
|
|
455
|
+
if self._dir is None or self._lease_id is None:
|
|
456
|
+
return
|
|
457
|
+
old_lease_id = self._lease_id
|
|
458
|
+
old_account = self._lease_account
|
|
459
|
+
old_account_id = self._lease_account_id
|
|
460
|
+
try:
|
|
461
|
+
# Do NOT reuse the caller's request_id: the pool dedupes by it and
|
|
462
|
+
# would hand back the current (unhealthy) lease, making the swap a
|
|
463
|
+
# silent no-op forever.
|
|
464
|
+
lease = await self._post_lease(include_request_id=False)
|
|
465
|
+
except PoolError as e:
|
|
466
|
+
log.info("codex health swap deferred: new lease failed: %s", e)
|
|
467
|
+
return
|
|
468
|
+
|
|
469
|
+
creds = lease.get("credentials") or {}
|
|
470
|
+
auth_json = creds.get("auth_json")
|
|
471
|
+
new_lease_id = lease.get("lease_id")
|
|
472
|
+
new_account = lease.get("account")
|
|
473
|
+
new_account_id = lease.get("pool_account_id")
|
|
474
|
+
if not isinstance(auth_json, dict) or not new_lease_id:
|
|
475
|
+
log.warning("codex health swap: lease response missing auth_json; keeping current")
|
|
476
|
+
await self._release_swap_dup(new_lease_id, old_lease_id)
|
|
477
|
+
return
|
|
478
|
+
# Same-account guard keys on the immutable server account_id, NOT the
|
|
479
|
+
# name (a delete+recreate of the same name is a DIFFERENT account and
|
|
480
|
+
# must swap in).
|
|
481
|
+
same_account = (
|
|
482
|
+
new_lease_id == old_lease_id
|
|
483
|
+
or (new_account_id is not None and old_account_id is not None
|
|
484
|
+
and new_account_id == old_account_id)
|
|
485
|
+
)
|
|
486
|
+
if same_account:
|
|
487
|
+
await self._release_swap_dup(new_lease_id, old_lease_id)
|
|
488
|
+
log.info("codex health swap: no other account available (still on %s)",
|
|
489
|
+
old_account)
|
|
490
|
+
return
|
|
491
|
+
|
|
492
|
+
new_exp = float(lease.get("token_expires_at") or 0.0)
|
|
493
|
+
# Commit under the meta lock so the poll loop's post-await lease_id
|
|
494
|
+
# re-check sees the rotation and drops any stale token write. No await
|
|
495
|
+
# between the disk write and the meta / self advance.
|
|
496
|
+
#
|
|
497
|
+
# `committed` marks ownership of the new lease — set BEFORE the block
|
|
498
|
+
# exit persists meta.json. If that persist fails (ENOSPC), committed is
|
|
499
|
+
# already True so the finally does NOT delete the new lease: self._
|
|
500
|
+
# lease_id / auth.json already use it and deleting it would strand us on
|
|
501
|
+
# a dead lease (health 410 → no self-heal). meta.json stays stale and
|
|
502
|
+
# self-corrects next write; the old lease is reaped by TTL.
|
|
503
|
+
committed = False
|
|
504
|
+
try:
|
|
505
|
+
async with locked_meta(self._dir) as meta:
|
|
506
|
+
write_codex_auth(self._dir, auth_json)
|
|
507
|
+
meta.lease_id = new_lease_id
|
|
508
|
+
meta.account = new_account
|
|
509
|
+
meta.account_id = new_account_id
|
|
510
|
+
meta.token_expires_at = new_exp
|
|
511
|
+
self._lease_id = new_lease_id
|
|
512
|
+
self._lease_account = new_account
|
|
513
|
+
self._lease_account_id = new_account_id
|
|
514
|
+
self._lease_request_id = lease.get("request_id")
|
|
515
|
+
self._token_expires_at = new_exp
|
|
516
|
+
self._poll_wake.set()
|
|
517
|
+
committed = True
|
|
518
|
+
finally:
|
|
519
|
+
if not committed:
|
|
520
|
+
with contextlib.suppress(Exception):
|
|
521
|
+
await asyncio.shield(self._delete_lease(new_lease_id, None))
|
|
522
|
+
|
|
523
|
+
# Release the cooled/dead old lease (skipped if the meta persist above
|
|
524
|
+
# threw — it then falls to the reaper).
|
|
525
|
+
with contextlib.suppress(Exception):
|
|
526
|
+
await asyncio.shield(self._delete_lease(old_lease_id, None))
|
|
527
|
+
log.info("codex health-swapped account %s → %s (lease %s → %s; reason: %s)",
|
|
528
|
+
old_account, new_account, old_lease_id, new_lease_id, reason[:80])
|
|
529
|
+
|
|
530
|
+
async def _release_swap_dup(self, new_lease_id, old_lease_id) -> None:
|
|
531
|
+
"""Release a just-acquired lease we decided not to keep (missing
|
|
532
|
+
auth_json or same-account) so a deferred swap never leaks it. Shielded
|
|
533
|
+
so an __aexit__ cancel on the DELETE can't skip the cleanup."""
|
|
534
|
+
if new_lease_id and new_lease_id != old_lease_id:
|
|
535
|
+
with contextlib.suppress(Exception):
|
|
536
|
+
await asyncio.shield(self._delete_lease(new_lease_id, None))
|
|
537
|
+
|
|
538
|
+
async def _post_lease(self, *, include_request_id: bool = True) -> dict:
|
|
344
539
|
body: dict[str, Any] = {"provider": "codex"}
|
|
345
540
|
if self._user_id:
|
|
346
541
|
body["user_id"] = self._user_id
|
|
347
|
-
if self._request_id_req:
|
|
542
|
+
if include_request_id and self._request_id_req:
|
|
348
543
|
body["request_id"] = self._request_id_req
|
|
349
544
|
if self._required_model:
|
|
350
545
|
body["required_model"] = self._required_model
|
|
@@ -380,12 +575,17 @@ class PooledCodexClient:
|
|
|
380
575
|
if exc is not None:
|
|
381
576
|
body["error_code"] = type(exc).__name__
|
|
382
577
|
body["error_message"] = str(exc)[:2000]
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
578
|
+
# Best-effort, like claude's _delete_lease: releasing a lease must never
|
|
579
|
+
# raise into a swap / release path (the reaper is the backstop).
|
|
580
|
+
try:
|
|
581
|
+
await self._http.request(
|
|
582
|
+
"DELETE",
|
|
583
|
+
f"{self._pool_url}/credentials/lease/{lease_id}",
|
|
584
|
+
headers={"authorization": f"Bearer {self._api_key}"},
|
|
585
|
+
json=body,
|
|
586
|
+
)
|
|
587
|
+
except Exception as e: # noqa: BLE001
|
|
588
|
+
log.warning("codex DELETE lease %s failed (best-effort): %s", lease_id, e)
|
|
389
589
|
|
|
390
590
|
|
|
391
591
|
def _detail_or_text(r: httpx.Response) -> dict[str, Any]:
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|