sub-pool-client 0.8.0__tar.gz → 0.8.2__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.8.0 → sub_pool_client-0.8.2}/PKG-INFO +1 -1
- {sub_pool_client-0.8.0 → sub_pool_client-0.8.2}/pyproject.toml +1 -0
- sub_pool_client-0.8.2/sub_pool_client/_auth_watch.py +374 -0
- {sub_pool_client-0.8.0 → sub_pool_client-0.8.2}/sub_pool_client/_cli_core.py +122 -1
- {sub_pool_client-0.8.0 → sub_pool_client-0.8.2}/sub_pool_client/_version.py +2 -2
- {sub_pool_client-0.8.0 → sub_pool_client-0.8.2}/.github/workflows/publish.yml +0 -0
- {sub_pool_client-0.8.0 → sub_pool_client-0.8.2}/.gitignore +0 -0
- {sub_pool_client-0.8.0 → sub_pool_client-0.8.2}/README.md +0 -0
- {sub_pool_client-0.8.0 → sub_pool_client-0.8.2}/examples/codex_hello.py +0 -0
- {sub_pool_client-0.8.0 → sub_pool_client-0.8.2}/examples/hello.py +0 -0
- {sub_pool_client-0.8.0 → sub_pool_client-0.8.2}/meta/README.md +0 -0
- {sub_pool_client-0.8.0 → sub_pool_client-0.8.2}/meta/pyproject.toml +0 -0
- {sub_pool_client-0.8.0 → sub_pool_client-0.8.2}/sub_pool_client/__init__.py +0 -0
- {sub_pool_client-0.8.0 → sub_pool_client-0.8.2}/sub_pool_client/_cli_provider.py +0 -0
- {sub_pool_client-0.8.0 → sub_pool_client-0.8.2}/sub_pool_client/_health_watcher.py +0 -0
- {sub_pool_client-0.8.0 → sub_pool_client-0.8.2}/sub_pool_client/_shared.py +0 -0
- {sub_pool_client-0.8.0 → sub_pool_client-0.8.2}/sub_pool_client/_swap.py +0 -0
- {sub_pool_client-0.8.0 → sub_pool_client-0.8.2}/sub_pool_client/cli_claude.py +0 -0
- {sub_pool_client-0.8.0 → sub_pool_client-0.8.2}/sub_pool_client/cli_codex.py +0 -0
- {sub_pool_client-0.8.0 → sub_pool_client-0.8.2}/sub_pool_client/cli_grok.py +0 -0
- {sub_pool_client-0.8.0 → sub_pool_client-0.8.2}/sub_pool_client/client.py +0 -0
- {sub_pool_client-0.8.0 → sub_pool_client-0.8.2}/sub_pool_client/codex.py +0 -0
- {sub_pool_client-0.8.0 → sub_pool_client-0.8.2}/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.
|
|
3
|
+
Version: 0.8.2
|
|
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
|
|
@@ -17,6 +17,7 @@ Repository = "https://github.com/subs-pool/sub-pool-client"
|
|
|
17
17
|
[project.scripts]
|
|
18
18
|
sp-claude = "sub_pool_client.cli_claude:main"
|
|
19
19
|
sp-codex = "sub_pool_client.cli_codex:main"
|
|
20
|
+
sp-grok = "sub_pool_client.cli_grok:main"
|
|
20
21
|
|
|
21
22
|
[build-system]
|
|
22
23
|
requires = ["hatchling", "hatch-vcs"]
|
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
"""Detect an upstream auth failure in the spawned CLI's output, and recover.
|
|
2
|
+
|
|
3
|
+
## The gap this closes
|
|
4
|
+
|
|
5
|
+
`run_session` had exactly one recovery trigger: the health watcher noticing
|
|
6
|
+
the pool had marked our account unhealthy. That covers a *pool-visible*
|
|
7
|
+
failure — quota COOLING, a dead refresh_token flipped INVALID, a reaped
|
|
8
|
+
lease. It does not cover the case where the **access token we already
|
|
9
|
+
handed the child is dead upstream while the pool still sees the account as
|
|
10
|
+
perfectly healthy**.
|
|
11
|
+
|
|
12
|
+
That happens because the pool's own probe authenticates through the refresh
|
|
13
|
+
chain: if the grant is alive, a refresh mints a working token and the
|
|
14
|
+
account reports AVAILABLE forever — even though the *specific* token sitting
|
|
15
|
+
in `.credentials.json` was revoked (a "log out other sessions", an
|
|
16
|
+
administrative token revocation, a rotation we lost the race on). The child
|
|
17
|
+
401s on every request, `/health` says `healthy: true` on every tick, and
|
|
18
|
+
nothing ever swaps. The session stays broken until its natural end.
|
|
19
|
+
|
|
20
|
+
## Why refresh-first is the whole trick
|
|
21
|
+
|
|
22
|
+
The obvious reaction to "the token is dead" is "swap accounts". That is the
|
|
23
|
+
wrong first move, and it is also the move that would make this module
|
|
24
|
+
dangerous: to swap on a detection you must be *sure* about the detection,
|
|
25
|
+
and we are reading a byte stream that also carries model output.
|
|
26
|
+
|
|
27
|
+
But an access-token revocation is precisely what a plain refresh fixes —
|
|
28
|
+
POST `/token`, the pool re-signs off the still-valid refresh_token, the new
|
|
29
|
+
token lands on disk, the child picks it up on its next request. So the
|
|
30
|
+
escalation ladder is:
|
|
31
|
+
|
|
32
|
+
refresh → (still failing?) → report-error + swap
|
|
33
|
+
|
|
34
|
+
and a **false positive costs one redundant `/token` call**, not a spurious
|
|
35
|
+
account rotation. That is what lets the detector below stay simple and
|
|
36
|
+
slightly over-eager instead of clever and brittle.
|
|
37
|
+
|
|
38
|
+
## Why the detector can be structural here
|
|
39
|
+
|
|
40
|
+
The consumer that motivated this runs `claude` with stream-json over a pipe,
|
|
41
|
+
so output is newline-delimited JSON and we can match on *shape* rather than
|
|
42
|
+
substring-scanning prose. That matters: `sub_pool.accounts.classify_error`
|
|
43
|
+
already documents that substring-matching free text for words like `oauth`
|
|
44
|
+
produces constant false positives, and raw CLI stdout is a far worse
|
|
45
|
+
haystack than an error field — it carries whatever the model just wrote.
|
|
46
|
+
|
|
47
|
+
So: JSON lines whose `type` is `assistant`/`user` are skipped outright (that
|
|
48
|
+
is model and caller content, never transport state), and everything else is
|
|
49
|
+
matched on the structured error keys first, with a deliberately narrow
|
|
50
|
+
literal list as the fallback for non-JSON output and stderr.
|
|
51
|
+
|
|
52
|
+
## One behavioural difference, worth knowing
|
|
53
|
+
|
|
54
|
+
Interposing is invisible to a child that was already writing to a pipe — it
|
|
55
|
+
sees a pipe either way. But stdout and stderr, which the caller may have
|
|
56
|
+
merged onto one fd (`sp-claude ... > log 2>&1`), are now carried by two
|
|
57
|
+
independent pumps. Relative ordering BETWEEN the two streams is no longer
|
|
58
|
+
the kernel's; within each stream it is unchanged. Consumers that read
|
|
59
|
+
stream-json off stdout are unaffected, which is the case this exists for.
|
|
60
|
+
|
|
61
|
+
## Why forwarding comes first
|
|
62
|
+
|
|
63
|
+
Piping the child's stdout puts this module on the critical path of the
|
|
64
|
+
caller's protocol. Every rule here follows from that: forward each chunk
|
|
65
|
+
before looking at it, never wait for a newline to forward, never let a
|
|
66
|
+
detector exception escape into the pump. A bug in detection must degrade to
|
|
67
|
+
"no recovery", never to "the session hangs".
|
|
68
|
+
"""
|
|
69
|
+
from __future__ import annotations
|
|
70
|
+
|
|
71
|
+
import asyncio
|
|
72
|
+
import json
|
|
73
|
+
import logging
|
|
74
|
+
import os
|
|
75
|
+
import sys
|
|
76
|
+
import time
|
|
77
|
+
from typing import Any, Awaitable, Callable, IO
|
|
78
|
+
|
|
79
|
+
log = logging.getLogger(__name__)
|
|
80
|
+
|
|
81
|
+
# Cap on how much unterminated output we hold while looking for a newline.
|
|
82
|
+
# A stream-json line can legitimately be large (a big tool result), so this
|
|
83
|
+
# is generous; past it we drop from the FRONT and keep the tail, because a
|
|
84
|
+
# trailing error object is what we are looking for.
|
|
85
|
+
MAX_LINE_BYTES = 1 << 20
|
|
86
|
+
|
|
87
|
+
# Structured keys. `error_status` is what the claude CLI emits alongside an
|
|
88
|
+
# upstream HTTP failure; `error` carries the code.
|
|
89
|
+
_AUTH_STATUSES = (401, 403)
|
|
90
|
+
_AUTH_CODES = frozenset({
|
|
91
|
+
"authentication_failed",
|
|
92
|
+
"invalid_grant",
|
|
93
|
+
"unauthorized",
|
|
94
|
+
"not_authenticated",
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
# Fallback for non-JSON output and stderr. Kept SHORT and specific on
|
|
98
|
+
# purpose — every entry here should be a string that a transport layer
|
|
99
|
+
# emits and prose essentially never does. Bare words like "oauth",
|
|
100
|
+
# "credential" or "token" are exactly the false-positive generators
|
|
101
|
+
# classify_error warns about, and must not be added.
|
|
102
|
+
_AUTH_LITERALS = (
|
|
103
|
+
"oauth access token has been revoked",
|
|
104
|
+
"authentication_failed",
|
|
105
|
+
"invalid_grant",
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
# stream-json message types that carry model / caller content rather than
|
|
109
|
+
# transport state. Their payloads routinely quote error JSON verbatim —
|
|
110
|
+
# never match inside them.
|
|
111
|
+
_CONTENT_TYPES = frozenset({"assistant", "user"})
|
|
112
|
+
|
|
113
|
+
_MAX_WALK_DEPTH = 6
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _walk_for_auth(node: Any, depth: int = 0) -> bool:
|
|
117
|
+
"""True if any nested object carries an auth-failure status or code."""
|
|
118
|
+
if depth > _MAX_WALK_DEPTH:
|
|
119
|
+
return False
|
|
120
|
+
if isinstance(node, dict):
|
|
121
|
+
status = node.get("error_status", node.get("status"))
|
|
122
|
+
if isinstance(status, (int, float)) and int(status) in _AUTH_STATUSES:
|
|
123
|
+
return True
|
|
124
|
+
for key in ("error", "error_code", "code", "type"):
|
|
125
|
+
v = node.get(key)
|
|
126
|
+
if isinstance(v, str) and v.strip().lower() in _AUTH_CODES:
|
|
127
|
+
return True
|
|
128
|
+
return any(_walk_for_auth(v, depth + 1) for v in node.values())
|
|
129
|
+
if isinstance(node, list):
|
|
130
|
+
return any(_walk_for_auth(v, depth + 1) for v in node[:64])
|
|
131
|
+
return False
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def looks_like_auth_failure(line: str) -> bool:
|
|
135
|
+
"""Does this one line of child output indicate an upstream auth failure?
|
|
136
|
+
|
|
137
|
+
Over-eagerness is survivable (one wasted refresh); a hang is not, so this
|
|
138
|
+
never raises — a malformed line is simply not a match.
|
|
139
|
+
"""
|
|
140
|
+
text = line.strip()
|
|
141
|
+
if not text:
|
|
142
|
+
return False
|
|
143
|
+
try:
|
|
144
|
+
if text[0] in "{[":
|
|
145
|
+
payload = json.loads(text)
|
|
146
|
+
if isinstance(payload, dict):
|
|
147
|
+
kind = payload.get("type")
|
|
148
|
+
if isinstance(kind, str) and kind.lower() in _CONTENT_TYPES:
|
|
149
|
+
# Model / caller content. An assistant message that
|
|
150
|
+
# happens to discuss a 401 is not a 401.
|
|
151
|
+
return False
|
|
152
|
+
return _walk_for_auth(payload)
|
|
153
|
+
except (ValueError, TypeError, RecursionError):
|
|
154
|
+
pass # not JSON — fall through to the literal scan
|
|
155
|
+
except Exception: # noqa: BLE001
|
|
156
|
+
return False
|
|
157
|
+
low = text.lower()
|
|
158
|
+
return any(lit in low for lit in _AUTH_LITERALS)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def should_watch() -> bool:
|
|
162
|
+
"""Whether to pipe the child's output so we can watch it.
|
|
163
|
+
|
|
164
|
+
Default: only when stdout is already NOT a tty. Interactive `claude` is a
|
|
165
|
+
full-screen TUI that needs a real terminal — handing it a pipe would
|
|
166
|
+
disable the UI it exists to draw. A piped stdout means the caller is
|
|
167
|
+
already consuming output programmatically (the stream-json case), where
|
|
168
|
+
interposing is invisible.
|
|
169
|
+
|
|
170
|
+
`SUB_POOL_AUTH_WATCH=0|1` forces the decision either way.
|
|
171
|
+
"""
|
|
172
|
+
raw = os.environ.get("SUB_POOL_AUTH_WATCH", "").strip().lower()
|
|
173
|
+
if raw in ("0", "false", "no", "off"):
|
|
174
|
+
return False
|
|
175
|
+
if raw in ("1", "true", "yes", "on"):
|
|
176
|
+
return True
|
|
177
|
+
try:
|
|
178
|
+
return not sys.stdout.isatty()
|
|
179
|
+
except Exception: # noqa: BLE001
|
|
180
|
+
# A stdout without isatty() (pytest capture, odd wrappers) is not a
|
|
181
|
+
# terminal we could break.
|
|
182
|
+
return True
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def stdout_sink() -> IO[bytes]:
|
|
186
|
+
"""Byte sink for forwarded child stdout.
|
|
187
|
+
|
|
188
|
+
Indirected through a function (rather than referencing `sys.stdout.buffer`
|
|
189
|
+
at the call site) so tests can substitute a buffer, and so a `sys.stdout`
|
|
190
|
+
without `.buffer` — pytest capture, some embedding wrappers — degrades to
|
|
191
|
+
the text stream instead of raising at wiring time.
|
|
192
|
+
"""
|
|
193
|
+
return getattr(sys.stdout, "buffer", sys.stdout)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def stderr_sink() -> IO[bytes]:
|
|
197
|
+
"""Byte sink for forwarded child stderr. See `stdout_sink`."""
|
|
198
|
+
return getattr(sys.stderr, "buffer", sys.stderr)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
async def pump(
|
|
202
|
+
reader: "asyncio.StreamReader",
|
|
203
|
+
sink: IO[bytes],
|
|
204
|
+
on_line: Callable[[str], None],
|
|
205
|
+
*,
|
|
206
|
+
chunk_size: int = 65536,
|
|
207
|
+
max_line_bytes: int = MAX_LINE_BYTES,
|
|
208
|
+
) -> None:
|
|
209
|
+
"""Copy `reader` to `sink` verbatim, feeding complete lines to `on_line`.
|
|
210
|
+
|
|
211
|
+
Forwarding happens BEFORE inspection and without waiting for a newline,
|
|
212
|
+
so interposing costs no latency and a partial line never stalls the
|
|
213
|
+
caller's stream. `on_line` exceptions are swallowed: detection is a
|
|
214
|
+
best-effort side channel and must never break the pipe.
|
|
215
|
+
"""
|
|
216
|
+
buf = bytearray()
|
|
217
|
+
while True:
|
|
218
|
+
try:
|
|
219
|
+
data = await reader.read(chunk_size)
|
|
220
|
+
except (asyncio.CancelledError, GeneratorExit):
|
|
221
|
+
raise
|
|
222
|
+
except Exception as e: # noqa: BLE001
|
|
223
|
+
log.debug("output pump read failed: %s", e)
|
|
224
|
+
return
|
|
225
|
+
if not data:
|
|
226
|
+
return
|
|
227
|
+
try:
|
|
228
|
+
sink.write(data)
|
|
229
|
+
sink.flush()
|
|
230
|
+
except Exception as e: # noqa: BLE001
|
|
231
|
+
# The caller closed our stdout. Nothing useful left to do, but
|
|
232
|
+
# keep draining so the child never blocks on a full pipe.
|
|
233
|
+
log.debug("output pump write failed: %s", e)
|
|
234
|
+
sink = _NULL_SINK
|
|
235
|
+
buf += data
|
|
236
|
+
while True:
|
|
237
|
+
nl = buf.find(b"\n")
|
|
238
|
+
if nl < 0:
|
|
239
|
+
break
|
|
240
|
+
line = bytes(buf[:nl])
|
|
241
|
+
del buf[:nl + 1]
|
|
242
|
+
try:
|
|
243
|
+
on_line(line.decode("utf-8", "replace"))
|
|
244
|
+
except Exception as e: # noqa: BLE001
|
|
245
|
+
log.debug("auth detector raised (ignored): %s", e)
|
|
246
|
+
if len(buf) > max_line_bytes:
|
|
247
|
+
# Keep the tail: a truncated giant line's END is where a
|
|
248
|
+
# trailing error object would be.
|
|
249
|
+
del buf[:len(buf) - max_line_bytes]
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
class _NullSink:
|
|
253
|
+
def write(self, data: bytes) -> int: # noqa: D102
|
|
254
|
+
return len(data)
|
|
255
|
+
|
|
256
|
+
def flush(self) -> None: # noqa: D102
|
|
257
|
+
return None
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
_NULL_SINK: Any = _NullSink()
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
class AuthRecovery:
|
|
264
|
+
"""Escalating response to auth-failure signals from the child.
|
|
265
|
+
|
|
266
|
+
Ladder, per incident:
|
|
267
|
+
|
|
268
|
+
1. `refresh()` — POST /token. Fixes the common case (the access token
|
|
269
|
+
was revoked but the grant is alive) and is cheap enough that a
|
|
270
|
+
false-positive detection is a non-event.
|
|
271
|
+
2. If the refresh itself fails, or a second signal arrives within
|
|
272
|
+
`escalate_after_s` of a refresh that was supposed to have fixed
|
|
273
|
+
things, the credential is not merely stale: `report_error()` so the
|
|
274
|
+
pool cools the account and routes OTHER leases away, then `swap()`
|
|
275
|
+
onto a different one.
|
|
276
|
+
|
|
277
|
+
Order matters in step 2. `report_error` must land before `swap`, because
|
|
278
|
+
the pool's strategy is what decides which account the replacement lease
|
|
279
|
+
gets — cooling the bad one first is the only thing stopping it from
|
|
280
|
+
handing the same account straight back (`swap_credentials` only rejects
|
|
281
|
+
an identical *lease_id*, not an identical account).
|
|
282
|
+
|
|
283
|
+
`cooldown_s` absorbs the burst: one dead token produces an auth error on
|
|
284
|
+
every in-flight request, and each retry after a fix produces more before
|
|
285
|
+
the new credential is picked up. Acting once per burst is the point.
|
|
286
|
+
"""
|
|
287
|
+
|
|
288
|
+
def __init__(
|
|
289
|
+
self,
|
|
290
|
+
*,
|
|
291
|
+
refresh: Callable[[], Awaitable[bool]],
|
|
292
|
+
report_error: Callable[[str, str], Awaitable[None]],
|
|
293
|
+
swap: Callable[[str], Awaitable[None]],
|
|
294
|
+
verbose: bool = False,
|
|
295
|
+
cooldown_s: float = 20.0,
|
|
296
|
+
escalate_after_s: float = 120.0,
|
|
297
|
+
max_actions: int = 6,
|
|
298
|
+
now: Callable[[], float] = time.monotonic,
|
|
299
|
+
):
|
|
300
|
+
self._refresh = refresh
|
|
301
|
+
self._report_error = report_error
|
|
302
|
+
self._swap = swap
|
|
303
|
+
self._verbose = verbose
|
|
304
|
+
self._cooldown_s = cooldown_s
|
|
305
|
+
self._escalate_after_s = escalate_after_s
|
|
306
|
+
self._max_actions = max_actions
|
|
307
|
+
self._now = now
|
|
308
|
+
self._lock = asyncio.Lock()
|
|
309
|
+
self._last_at = float("-inf")
|
|
310
|
+
self._refreshed = False
|
|
311
|
+
self._actions = 0
|
|
312
|
+
self._exhausted_logged = False
|
|
313
|
+
# Test/diagnostic visibility into what the ladder actually did.
|
|
314
|
+
self.history: list[str] = []
|
|
315
|
+
|
|
316
|
+
@property
|
|
317
|
+
def actions(self) -> int:
|
|
318
|
+
return self._actions
|
|
319
|
+
|
|
320
|
+
async def on_signal(self, sample: str) -> None:
|
|
321
|
+
"""Handle one detected auth failure. Safe to call on every match."""
|
|
322
|
+
async with self._lock:
|
|
323
|
+
now = self._now()
|
|
324
|
+
if self._actions >= self._max_actions:
|
|
325
|
+
if not self._exhausted_logged:
|
|
326
|
+
self._exhausted_logged = True
|
|
327
|
+
log.warning(
|
|
328
|
+
"auth recovery gave up after %d attempts; the session "
|
|
329
|
+
"will keep failing. Last signal: %s",
|
|
330
|
+
self._actions, sample[:200],
|
|
331
|
+
)
|
|
332
|
+
return
|
|
333
|
+
if now - self._last_at < self._cooldown_s:
|
|
334
|
+
# Same burst, or the previous fix has not been picked up yet.
|
|
335
|
+
return
|
|
336
|
+
|
|
337
|
+
escalate = (
|
|
338
|
+
self._refreshed
|
|
339
|
+
and (now - self._last_at) <= self._escalate_after_s
|
|
340
|
+
)
|
|
341
|
+
self._last_at = now
|
|
342
|
+
self._actions += 1
|
|
343
|
+
|
|
344
|
+
if not escalate:
|
|
345
|
+
if self._verbose:
|
|
346
|
+
log.info("upstream auth failure; refreshing token (%s)",
|
|
347
|
+
sample[:120])
|
|
348
|
+
ok = False
|
|
349
|
+
try:
|
|
350
|
+
ok = await self._refresh()
|
|
351
|
+
except Exception as e: # noqa: BLE001
|
|
352
|
+
log.warning("auth-triggered refresh raised: %s", e)
|
|
353
|
+
if ok:
|
|
354
|
+
self._refreshed = True
|
|
355
|
+
self.history.append("refresh")
|
|
356
|
+
return
|
|
357
|
+
# Refresh could not produce a working credential — go
|
|
358
|
+
# straight to the swap rather than burning the cooldown.
|
|
359
|
+
self.history.append("refresh-failed")
|
|
360
|
+
|
|
361
|
+
self._refreshed = False
|
|
362
|
+
if self._verbose:
|
|
363
|
+
log.info("auth failure persists after refresh; cooling "
|
|
364
|
+
"account and swapping")
|
|
365
|
+
try:
|
|
366
|
+
await self._report_error("401", "upstream rejected the leased "
|
|
367
|
+
"credential (auth failure)")
|
|
368
|
+
except Exception as e: # noqa: BLE001
|
|
369
|
+
log.warning("report_error raised: %s", e)
|
|
370
|
+
try:
|
|
371
|
+
await self._swap("upstream auth failure")
|
|
372
|
+
except Exception as e: # noqa: BLE001
|
|
373
|
+
log.warning("auth-triggered swap raised: %s", e)
|
|
374
|
+
self.history.append("swap")
|
|
@@ -24,6 +24,7 @@ from typing import Any
|
|
|
24
24
|
import click
|
|
25
25
|
import httpx
|
|
26
26
|
|
|
27
|
+
from sub_pool_client import _auth_watch
|
|
27
28
|
from sub_pool_client._cli_provider import CliProvider
|
|
28
29
|
from sub_pool_client._health_watcher import HealthWatcher
|
|
29
30
|
from sub_pool_client._shared import next_refresh_sleep
|
|
@@ -352,6 +353,25 @@ class PoolHTTP:
|
|
|
352
353
|
r.raise_for_status()
|
|
353
354
|
return r.json()
|
|
354
355
|
|
|
356
|
+
async def report_error(self, lease_id: str, code: str, message: str) -> None:
|
|
357
|
+
"""Tell the pool the leased credential was rejected upstream.
|
|
358
|
+
|
|
359
|
+
The pool cools the account (never INVALID — see
|
|
360
|
+
`AccountRegistry.classify_error`, which refuses to let a consumer
|
|
361
|
+
report sticky-park a shared account), so parallel leases route
|
|
362
|
+
elsewhere and, critically, so OUR next lease request does not get
|
|
363
|
+
handed the same account straight back.
|
|
364
|
+
|
|
365
|
+
Best-effort by construction: this is an advisory signal on a
|
|
366
|
+
recovery path, and failing to deliver it must not stop the swap
|
|
367
|
+
that follows.
|
|
368
|
+
"""
|
|
369
|
+
with suppress(Exception):
|
|
370
|
+
await self._client.post(
|
|
371
|
+
f"/credentials/lease/{lease_id}/report-error",
|
|
372
|
+
json={"code": code, "message": message},
|
|
373
|
+
)
|
|
374
|
+
|
|
355
375
|
|
|
356
376
|
# ============================================================ session main
|
|
357
377
|
|
|
@@ -536,8 +556,16 @@ async def run_session(
|
|
|
536
556
|
for k in provider.bypass_env_vars:
|
|
537
557
|
env.pop(k, None)
|
|
538
558
|
|
|
559
|
+
# Watching the child's output is what catches an upstream auth
|
|
560
|
+
# failure the pool cannot see (a revoked access token on a
|
|
561
|
+
# still-valid grant — see _auth_watch). It requires piping, so it
|
|
562
|
+
# is off whenever stdout is a real terminal: interactive `claude`
|
|
563
|
+
# is a TUI that needs one. stdin is always inherited.
|
|
564
|
+
watch_output = _auth_watch.should_watch()
|
|
565
|
+
_pipe = asyncio.subprocess.PIPE if watch_output else None
|
|
539
566
|
proc = await asyncio.create_subprocess_exec(
|
|
540
567
|
bin_path, *prompt_args, env=env,
|
|
568
|
+
stdout=_pipe, stderr=_pipe,
|
|
541
569
|
)
|
|
542
570
|
|
|
543
571
|
# Forward common signals so Ctrl-C reaches the child. Record
|
|
@@ -562,10 +590,31 @@ async def run_session(
|
|
|
562
590
|
# left than the one it replaced.
|
|
563
591
|
refresh_wake = asyncio.Event()
|
|
564
592
|
|
|
593
|
+
# Serializes the two swap callers. The health watcher used to be
|
|
594
|
+
# the only one, so a plain await was enough; the auth ladder is a
|
|
595
|
+
# second, and its escalation path *causes* a health-visible
|
|
596
|
+
# failure (report-error cools the account), so the two can fire
|
|
597
|
+
# on the same incident. Concurrently, both would read the same
|
|
598
|
+
# `old_lease_id`, lease a replacement each, and the loser's lease
|
|
599
|
+
# would leak — held by the pool with nothing left pointing at it.
|
|
600
|
+
swap_lock = asyncio.Lock()
|
|
601
|
+
|
|
565
602
|
async def on_swap_needed(health: dict) -> None:
|
|
566
603
|
# Read the from-account BEFORE swap_credentials runs —
|
|
567
604
|
# the call mutates `current["lease"]` in place (that's
|
|
568
605
|
# what closes the refresh/swap race; see _swap.py).
|
|
606
|
+
seen_lease_id = current["lease"]["lease_id"]
|
|
607
|
+
async with swap_lock:
|
|
608
|
+
if current["lease"]["lease_id"] != seen_lease_id:
|
|
609
|
+
# Someone swapped while we waited: whatever we were
|
|
610
|
+
# reacting to is about a lease we are no longer on.
|
|
611
|
+
if verbose:
|
|
612
|
+
log.info("swap skipped: already moved off %s",
|
|
613
|
+
seen_lease_id)
|
|
614
|
+
return
|
|
615
|
+
await _do_swap(health)
|
|
616
|
+
|
|
617
|
+
async def _do_swap(health: dict) -> None:
|
|
569
618
|
old_account = current["lease"].get("account")
|
|
570
619
|
try:
|
|
571
620
|
new = await swap_credentials(
|
|
@@ -602,15 +651,87 @@ async def run_session(
|
|
|
602
651
|
name=f"sp-{provider.name}-health",
|
|
603
652
|
)
|
|
604
653
|
|
|
654
|
+
# Output-driven auth recovery. Detection runs in the pumps (sync,
|
|
655
|
+
# non-blocking); the ACTION runs in one consumer task fed by a
|
|
656
|
+
# size-1 queue, so a burst of auth errors — which is what a dead
|
|
657
|
+
# token actually produces — collapses into a single ladder step
|
|
658
|
+
# instead of spawning a task per line.
|
|
659
|
+
aux: list[asyncio.Task] = []
|
|
660
|
+
pumps: list[asyncio.Task] = []
|
|
661
|
+
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
|
+
async def _auth_report(code: str, message: str) -> None:
|
|
674
|
+
await pool.report_error(
|
|
675
|
+
current["lease"]["lease_id"], code, message,
|
|
676
|
+
)
|
|
677
|
+
|
|
678
|
+
async def _auth_swap(reason: str) -> None:
|
|
679
|
+
await on_swap_needed({"reason": reason})
|
|
680
|
+
|
|
681
|
+
recovery = _auth_watch.AuthRecovery(
|
|
682
|
+
refresh=_auth_refresh,
|
|
683
|
+
report_error=_auth_report,
|
|
684
|
+
swap=_auth_swap,
|
|
685
|
+
verbose=verbose,
|
|
686
|
+
)
|
|
687
|
+
signals: asyncio.Queue[str] = asyncio.Queue(maxsize=1)
|
|
688
|
+
|
|
689
|
+
def _on_line(line: str) -> None:
|
|
690
|
+
if _auth_watch.looks_like_auth_failure(line):
|
|
691
|
+
with suppress(asyncio.QueueFull):
|
|
692
|
+
signals.put_nowait(line)
|
|
693
|
+
|
|
694
|
+
async def _consume_signals() -> None:
|
|
695
|
+
while True:
|
|
696
|
+
sample = await signals.get()
|
|
697
|
+
await recovery.on_signal(sample)
|
|
698
|
+
|
|
699
|
+
aux.append(asyncio.create_task(
|
|
700
|
+
_consume_signals(), name=f"sp-{provider.name}-authrecover",
|
|
701
|
+
))
|
|
702
|
+
for stream, sink in (
|
|
703
|
+
(proc.stdout, _auth_watch.stdout_sink()),
|
|
704
|
+
(proc.stderr, _auth_watch.stderr_sink()),
|
|
705
|
+
):
|
|
706
|
+
if stream is None:
|
|
707
|
+
continue
|
|
708
|
+
t = asyncio.create_task(
|
|
709
|
+
_auth_watch.pump(stream, sink, _on_line),
|
|
710
|
+
name=f"sp-{provider.name}-pump",
|
|
711
|
+
)
|
|
712
|
+
pumps.append(t)
|
|
713
|
+
aux.append(t)
|
|
714
|
+
|
|
605
715
|
try:
|
|
606
716
|
exit_code = await proc.wait()
|
|
717
|
+
# The child can exit with bytes still in the pipe buffers.
|
|
718
|
+
# Let the pumps run to EOF so the caller sees every byte,
|
|
719
|
+
# but never hang the exit on a stuck reader.
|
|
720
|
+
if pumps:
|
|
721
|
+
with suppress(Exception):
|
|
722
|
+
await asyncio.wait_for(
|
|
723
|
+
asyncio.gather(*pumps, return_exceptions=True),
|
|
724
|
+
timeout=5.0,
|
|
725
|
+
)
|
|
607
726
|
finally:
|
|
608
727
|
for sig in installed_signals:
|
|
609
728
|
with suppress(NotImplementedError, RuntimeError):
|
|
610
729
|
loop.remove_signal_handler(sig)
|
|
611
730
|
refresher.cancel()
|
|
612
731
|
watcher.cancel()
|
|
613
|
-
for t in
|
|
732
|
+
for t in aux:
|
|
733
|
+
t.cancel()
|
|
734
|
+
for t in (refresher, watcher, *aux):
|
|
614
735
|
with suppress(asyncio.CancelledError, Exception):
|
|
615
736
|
await t
|
|
616
737
|
await pool.release(current["lease"]["lease_id"])
|
|
@@ -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.
|
|
22
|
-
__version_tuple__ = version_tuple = (0, 8,
|
|
21
|
+
__version__ = version = '0.8.2'
|
|
22
|
+
__version_tuple__ = version_tuple = (0, 8, 2)
|
|
23
23
|
|
|
24
24
|
__commit_id__ = commit_id = None
|
|
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
|
|
File without changes
|
|
File without changes
|