From 114288f9218e271251a46af0698069ca163d00e7 Mon Sep 17 00:00:00 2001 From: B3hnamR Date: Sat, 21 Nov 2026 05:46:04 +0330 Subject: [PATCH 1/7] Handle ZCode concurrency limits as retryable 3008/3009/3010 are per-user/per-model capacity errors, not quota or account failures. Normalize them to HTTP 429, retry with a short exponential backoff, and stop cooling accounts or parking models. Map 200 JSON envelopes and SSE error frames the same way, so clients see 429 with the business code after the bounded retries. The new retry budget is concurrency_max_attempts (5) with 1s base and 10s cap, configurable in config.example.yaml. Existing configs keep the defaults. Also make the overload rotation test use a deterministic pool clock; its strict account alternation depended on Windows timer resolution. --- config.example.yaml | 3 + tests/test_model_retry.py | 30 ++++++++- tests/test_zcode_core.py | 122 +++++++++++++++++++++++++++++++++++ zcode_gateway/config.py | 6 ++ zcode_gateway/model_retry.py | 13 ++++ zcode_gateway/service.py | 69 +++++++++++++++----- zcode_gateway/upstream.py | 14 ++++ 7 files changed, 239 insertions(+), 18 deletions(-) diff --git a/config.example.yaml b/config.example.yaml index 444f3f7..efcbecb 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -16,6 +16,9 @@ upstream: overload_max_attempts: 11 overload_base_delay_seconds: 2 overload_max_delay_seconds: 60 + concurrency_max_attempts: 5 + concurrency_base_delay_seconds: 1 + concurrency_max_delay_seconds: 10 pool: strategy: drain_first cooldown_seconds: 30 diff --git a/tests/test_model_retry.py b/tests/test_model_retry.py index e1f5e2e..7d098dc 100644 --- a/tests/test_model_retry.py +++ b/tests/test_model_retry.py @@ -5,7 +5,32 @@ import pytest from zcode_gateway.config import UpstreamConfig -from zcode_gateway.model_retry import overload_delay, retry_after_seconds +from zcode_gateway.model_retry import concurrency_delay, overload_delay, retry_after_seconds +from zcode_gateway.upstream import ErrorKind, classify, is_concurrency_code + + +@pytest.mark.parametrize('code', [3008, '3008', ' 3008 ', '3009', '3010']) +def test_concurrency_codes(code): + assert is_concurrency_code(code) + + +@pytest.mark.parametrize('code', [None, '', 3007, '3011', 'rate_limit_error']) +def test_non_concurrency_codes(code): + assert not is_concurrency_code(code) + + +@pytest.mark.parametrize('status', [200, 429, 502]) +def test_concurrency_classifies_as_rate_limited(status): + assert classify(status, '{"error":{"code":3008,"message":"user concurrency limit exceeded"}}') is ErrorKind.RATE_LIMITED + + +def test_concurrency_backoff_bounds(): + cfg = UpstreamConfig() + for attempt in range(1, 6): + ceiling = min(2 ** (attempt - 1), 10) + assert ceiling / 2 <= concurrency_delay(cfg, attempt) <= ceiling + assert concurrency_delay(cfg, 1, 600) == 10 + assert concurrency_delay(cfg, 1, 0) == 0 @pytest.mark.parametrize('headers,expected', [ @@ -37,6 +62,9 @@ def test_backoff_jitter_and_server_delay_bounds(): ('overload_max_attempts',0), ('overload_max_attempts',31), ('overload_base_delay_seconds',-1), ('overload_base_delay_seconds',math.nan), ('overload_max_delay_seconds',math.inf), ('overload_max_delay_seconds',61), + ('concurrency_max_attempts',0), ('concurrency_max_attempts',31), + ('concurrency_base_delay_seconds',-1), ('concurrency_base_delay_seconds',math.nan), + ('concurrency_max_delay_seconds',math.inf), ('concurrency_max_delay_seconds',61), ]) def test_invalid_retry_configuration(field, value): with pytest.raises(ValueError): diff --git a/tests/test_zcode_core.py b/tests/test_zcode_core.py index 8595bc0..9100b47 100644 --- a/tests/test_zcode_core.py +++ b/tests/test_zcode_core.py @@ -2,6 +2,7 @@ import json import time from pathlib import Path +from types import SimpleNamespace import httpx import pytest @@ -452,6 +453,13 @@ async def wait(delay, disconnected=None): async def test_overload_rotates_accounts_after_wait_without_cooling(service, monkeypatch): service.cfg.pool.strategy = 'least_in_flight' await service.pool.upsert(Account(id='two', access_token='token-two')) + # least_in_flight breaks ties on last_used. Back-to-back mocked retries can + # land in the same Windows clock tick, which made the expected alternation + # a coin flip; give the pool its own strictly increasing clock. + ticks = iter(range(1000, 100000)) + monkeypatch.setattr('zcode_gateway.pool.time', + SimpleNamespace(time=lambda: next(ticks), + monotonic=lambda: next(ticks))) waits = [] async def wait(delay, disconnected=None): waits.append(delay) monkeypatch.setattr('zcode_gateway.service.wait_for_retry', wait) @@ -525,6 +533,89 @@ async def wait(delay, ignored=None): await wait_for_retry(delay, disconnected) assert all(a.in_flight == 0 and a.state is AccountState.READY for a in await service.pool.all()) +def concurrency_response(code=3008, status=429): + return FakeResponse(json.dumps({'error':{'code':str(code),'message':'user concurrency limit exceeded'}}).encode(), status) + + +def concurrency_envelope(code=3008): + response=FakeResponse(json.dumps({'code':str(code),'msg':'user concurrency limit exceeded'}).encode(),200) + response.headers['content-type']='application/json' + return response + + +@pytest.mark.asyncio +@pytest.mark.parametrize('code', [3008, 3009, 3010]) +async def test_concurrency_codes_retry_without_parking_or_cooling(service, monkeypatch, code): + waits=[] + async def wait(delay, disconnected=None): + waits.append(delay) + account=(await service.pool.all())[0] + assert account.in_flight==0 and service.client.responses[-1].closed + monkeypatch.setattr('zcode_gateway.service.wait_for_retry', wait) + service.client=FakeClient(responses=[concurrency_response(code),FakeResponse(sample_sse())]) + result=await service.complete({'messages':[{'role':'user','content':'hi'}]}, model='GLM-5.3') + assert result.status==200 and len(service.client.calls)==2 and len(waits)==1 + account=(await service.pool.all())[0] + assert account.state is AccountState.READY and account.in_flight==0 + assert not account.model_caps and not account.error_history + assert all(r.closed for r in service.client.responses) + + +@pytest.mark.asyncio +async def test_http200_concurrency_envelope_retries_as_429(service, monkeypatch): + waits=[] + async def wait(delay, disconnected=None): waits.append(delay) + monkeypatch.setattr('zcode_gateway.service.wait_for_retry', wait) + service.client=FakeClient(responses=[concurrency_envelope(3008),FakeResponse(sample_sse())]) + result=await service.complete({'messages':[{'role':'user','content':'hi'}]}, model='GLM-5.3') + assert result.status==200 and len(service.client.calls)==2 and len(waits)==1 + account=(await service.pool.all())[0] + assert account.state is AccountState.READY and account.in_flight==0 + assert not account.model_caps and not account.error_history + + +@pytest.mark.asyncio +async def test_persistent_concurrency_is_bounded_429_without_parking(service, monkeypatch): + monkeypatch.setattr(service.cfg.upstream, 'concurrency_max_attempts', 3) + waits=[] + async def wait(delay, disconnected=None): waits.append(delay) + monkeypatch.setattr('zcode_gateway.service.wait_for_retry', wait) + service.client=FakeClient(responses=[concurrency_response() for _ in range(3)]) + with pytest.raises(UpstreamFailure) as err: + await service.open_stream({'messages':[{'role':'user','content':'hi'}]}, model='GLM-5.3') + assert err.value.status==429 and err.value.code=='3008' + assert len(service.client.calls)==3 and len(waits)==2 + account=(await service.pool.all())[0] + assert account.state is AccountState.READY and account.in_flight==0 + assert not account.model_caps + assert all(r.closed for r in service.client.responses) + + +@pytest.mark.asyncio +async def test_midstream_concurrency_error_is_429_without_cooling(service): + events=sample_events() + events.insert(1, {'type':'error','error':{'code':3008,'message':'user concurrency limit exceeded'}}) + service.client=FakeClient(b''.join(frame(e) for e in events)) + with pytest.raises(UpstreamFailure) as err: + await service.complete({'messages':[{'role':'user','content':'hi'}]}, model='GLM-5.3') + assert err.value.status==429 and err.value.code=='3008' + account=(await service.pool.all())[0] + assert account.state is AccountState.READY and account.in_flight==0 + assert not account.model_caps + + +@pytest.mark.asyncio +async def test_stream_concurrency_error_does_not_park_model(service): + events=sample_events() + events.insert(1, {'type':'error','error':{'code':3009,'message':'model concurrency limit exceeded'}}) + service.client=FakeClient(b''.join(frame(e) for e in events)) + handle=await service.open_stream({'messages':[{'role':'user','content':'hi'}]}, model='GLM-5.3') + out=b''.join([part async for part in service.stream_from(handle, model='GLM-5.3')]) + assert b'model concurrency limit exceeded' in out and len(service.client.calls)==1 + assert handle.account.state is AccountState.READY and handle.account.in_flight==0 + assert not handle.account.model_caps + + @pytest.mark.parametrize('path', ['/v1/chat/completions', '/v1/messages']) @pytest.mark.parametrize('stream', [False, True]) def test_api_retries_busy_model_in_both_dialects(cfg, path, stream): @@ -538,3 +629,34 @@ def test_api_retries_busy_model_in_both_dialects(cfg, path, stream): assert response.status_code == 200 assert len(state.service.client.calls) == 2 assert state.pool._accounts['one'].in_flight == 0 + + +@pytest.mark.parametrize('path', ['/v1/chat/completions', '/v1/messages']) +@pytest.mark.parametrize('stream', [False, True]) +def test_api_retries_concurrency_in_both_dialects(cfg, path, stream): + cfg.upstream.concurrency_base_delay_seconds = 0 + with TestClient(create_app(cfg)) as client: + state = client.app.state.app_state + state.pool._accounts['one'] = Account(id='one', access_token='fake') + state.service.client = FakeClient(responses=[concurrency_response(), FakeResponse(sample_sse())]) + response = client.post(path, headers={'Authorization':'Bearer test-client'}, + json={'model':'GLM-5.3','messages':[{'role':'user','content':'hi'}],'stream':stream}) + assert response.status_code == 200 + assert len(state.service.client.calls) == 2 + account = state.pool._accounts['one'] + assert account.in_flight == 0 and not account.model_caps + + +def test_api_surfaces_concurrency_as_429(cfg): + cfg.upstream.concurrency_max_attempts = 2 + cfg.upstream.concurrency_base_delay_seconds = 0 + with TestClient(create_app(cfg)) as client: + state = client.app.state.app_state + state.pool._accounts['one'] = Account(id='one', access_token='fake') + state.service.client = FakeClient(responses=[concurrency_response(), concurrency_response()]) + response = client.post('/v1/chat/completions', headers={'Authorization':'Bearer test-client'}, + json={'model':'GLM-5.3','messages':[{'role':'user','content':'hi'}],'stream':False}) + assert response.status_code == 429 + assert response.json()['error']['code'] == '3008' + account = state.pool._accounts['one'] + assert account.in_flight == 0 and not account.model_caps diff --git a/zcode_gateway/config.py b/zcode_gateway/config.py index 0df9ed5..194f2a4 100644 --- a/zcode_gateway/config.py +++ b/zcode_gateway/config.py @@ -214,6 +214,12 @@ class UpstreamConfig(BaseModel): overload_max_attempts: int = Field(default=11, ge=1, le=30) overload_base_delay_seconds: float = Field(default=2, ge=0, le=60, allow_inf_nan=False) overload_max_delay_seconds: float = Field(default=60, ge=0, le=60, allow_inf_nan=False) + # 3008 (user concurrency) / 3009 (model concurrency) / 3010 (busy) are + # capacity rejections, not quota: retry briefly without parking the + # account or model. The wait stays short because a slot frees quickly. + concurrency_max_attempts: int = Field(default=5, ge=1, le=30) + concurrency_base_delay_seconds: float = Field(default=1, ge=0, le=60, allow_inf_nan=False) + concurrency_max_delay_seconds: float = Field(default=10, ge=0, le=60, allow_inf_nan=False) # Whether the anthropic body variant carries `cache_control`. The capture # always included it; flip to false to test whether it is optional. anthropic_cache_control: bool = True diff --git a/zcode_gateway/model_retry.py b/zcode_gateway/model_retry.py index 67ebdfd..c4c3ddb 100644 --- a/zcode_gateway/model_retry.py +++ b/zcode_gateway/model_retry.py @@ -40,6 +40,19 @@ def overload_delay(cfg, retry_number, retry_after=None): return delay * random.uniform(.5, 1) +def concurrency_delay(cfg, retry_number, retry_after=None): + """Short exponential backoff for 3008/3009/3010 capacity rejections. + + These clear as soon as an in-flight request finishes, so the wait is much + shorter than an overload backoff and never parks the account. + """ + base = cfg.concurrency_base_delay_seconds * 2 ** (retry_number - 1) + if retry_after is not None: + return min(retry_after, cfg.concurrency_max_delay_seconds) + delay = min(base, cfg.concurrency_max_delay_seconds) + return delay * random.uniform(.5, 1) + + async def wait_for_retry(delay, is_disconnected=None): if is_disconnected is None: await asyncio.sleep(delay) diff --git a/zcode_gateway/service.py b/zcode_gateway/service.py index 84b217a..431ca85 100644 --- a/zcode_gateway/service.py +++ b/zcode_gateway/service.py @@ -16,11 +16,12 @@ from .affinity import affinity_key_from_payload from .pool import Account from .breaker import EdgeBlockBreaker -from .model_retry import is_model_overload, overload_delay, retry_after_seconds, wait_for_retry +from .model_retry import concurrency_delay, is_model_overload, overload_delay, retry_after_seconds, wait_for_retry from .zcode_protocol import MessageAccumulator, OpenAITranslator, usage_openai from .upstream import (build_headers, build_upstream_body, iter_sse_events, sse_frame, parse_upstream_error, anthropic_error, openai_error, TransportError, - is_block_code, client_not_supported, CLIENT_NOT_SUPPORTED_PARK_S) + is_block_code, is_concurrency_code, client_not_supported, + CLIENT_NOT_SUPPORTED_PARK_S) from .registry import model_caps log = logging.getLogger('zcode_gateway.service') @@ -85,6 +86,27 @@ def _sse_event(name, data): return (f'event: {name}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n').encode() +def _normalize_error_status(status, code): + """Concurrency business codes are 429 capacity rejections even when the + HTTP envelope says 200 or a 5xx.""" + if is_concurrency_code(code): + return 429 + if status == 200: + return 429 if code in ('11113', '1005') else 502 + return status + + +def _stream_error_status(code): + """Status for an error delivered inside an SSE frame.""" + if is_model_overload(502, code): + return 529 + if is_concurrency_code(code) or code in ('11113', 'rate_limit_error'): + return 429 + if is_block_code(code): + return 405 + return 502 + + async def upstream_events(resp): pending = b'' try: @@ -159,9 +181,10 @@ async def _close(self, handle): async def _apply_error(self, account, model, status, code, message, headers=None, *, expected_credentials=None): if expected_credentials is not None and account.credential_key() != expected_credentials: return - if is_model_overload(status, code): - # A busy model is not evidence of a bad account or spent quota. - # Keep this account available for other models and delayed retries. + if is_model_overload(status, code) or is_concurrency_code(code): + # A busy model or a concurrency cap is not evidence of a bad + # account or spent quota. Keep this account available for other + # models and the retry loop. return # autopsy trail: keep the last errors for the dashboard "why" view try: @@ -376,22 +399,35 @@ async def _open_stream(self, payload, *, model, variant='anthropic', dialect='op async def _open_model_stream(self, payload, *, model, variant='anthropic', dialect='openai', client_key='anonymous', is_disconnected=None): # Only retry before a StreamHandle is returned. Never replay output or tools. - attempts = self.cfg.upstream.overload_max_attempts - for attempt in range(attempts): + overloads = concurrency = 0 + while True: if is_disconnected is not None and await is_disconnected(): raise asyncio.CancelledError() try: return await self._open_model_stream_once(payload, model=model, variant=variant, dialect=dialect, client_key=client_key) except UpstreamFailure as exc: + if is_concurrency_code(exc.code): + concurrency += 1 + delay = concurrency_delay(self.cfg.upstream, concurrency, exc.retry_after) + if concurrency >= self.cfg.upstream.concurrency_max_attempts: + exc.release_in_s = max(1, int(delay + .999)) + raise + log.info('ZCode concurrency limit (%s) for %s; retry %s/%s in %.2fs', + exc.code, model, concurrency, + self.cfg.upstream.concurrency_max_attempts - 1, delay) + await wait_for_retry(delay, is_disconnected) + continue if not is_model_overload(exc.status, exc.code): raise - delay = overload_delay(self.cfg.upstream, attempt + 1, exc.retry_after) - if attempt + 1 == attempts: + overloads += 1 + delay = overload_delay(self.cfg.upstream, overloads, exc.retry_after) + if overloads >= self.cfg.upstream.overload_max_attempts: exc.release_in_s = max(1, int(delay + .999)) raise log.info('ZCode model %s overloaded (%s); retry %s/%s in %.2fs', - model, exc.code, attempt + 1, attempts - 1, delay) + model, exc.code, overloads, + self.cfg.upstream.overload_max_attempts - 1, delay) await wait_for_retry(delay, is_disconnected) async def _open_model_stream_once(self, payload, *, model, variant='anthropic', dialect='openai', client_key='anonymous'): @@ -462,8 +498,7 @@ async def _open_model_stream_once(self, payload, *, model, variant='anthropic', raw = await resp.aread() info = parse_upstream_error(resp.status_code, raw) status, code, message = resp.status_code, str(info['code']), info['message'] - if status == 200: - status = 429 if code in ('11113', '1005') else 502 + status = _normalize_error_status(status, code) if status == 401 and await self.tokens.refresh( account, force=True, expected_credentials=credentials): # Retry a newly imported token once, without a second pool reservation. @@ -479,8 +514,7 @@ async def _open_model_stream_once(self, payload, *, model, variant='anthropic', raw = await resp.aread() info = parse_upstream_error(resp.status_code, raw) status, code, message = resp.status_code, str(info['code']), info['message'] - if status == 200: - status = 429 if code in ('11113', '1005') else 502 + status = _normalize_error_status(status, code) if status != 200: # IP-wide CDN edge block (HTML body, not API JSON)? # Detect BEFORE _apply_error — this is not an account @@ -528,7 +562,7 @@ async def _open_model_stream_once(self, payload, *, model, variant='anthropic', if first.get('type') == 'error' or (first.get('type') is None and 'error' in first): info = first.get('error') or first code, message = str(info.get('code') or info.get('type') or 'api_error'), info.get('message', 'ZCode stream failed') - status = 529 if is_model_overload(502, code) else (429 if code in ('11113', 'rate_limit_error') else (405 if is_block_code(code) else 502)) + status = _stream_error_status(code) await self._apply_error(account, model, status, code, message, expected_credentials=credentials) last = UpstreamFailure(status, code, message) @@ -640,7 +674,8 @@ async def events(): if kind == 'error' or (kind is None and 'error' in event): info = event.get('error') or event code, message = str(info.get('code') or info.get('type') or 'api_error'), info.get('message', 'ZCode stream failed') - status = 529 if is_model_overload(502, code) else (429 if code in ('11113', 'rate_limit_error') else 502) + status = 529 if is_model_overload(502, code) else ( + 429 if code in ('11113', 'rate_limit_error') or is_concurrency_code(code) else 502) await self._apply_error(handle.account, model, status, code, message, expected_credentials=handle.credentials) self._log_stream_failure(handle, UpstreamFailure(status, code, message), @@ -707,7 +742,7 @@ async def complete(self, payload, *, model, variant='anthropic', dialect='openai if event.get('type') == 'error' or (event.get('type') is None and 'error' in event): info = event.get('error') or event code = str(info.get('code') or info.get('type') or 'api_error') - status = 529 if is_model_overload(502, code) else (429 if code in ('11113', 'rate_limit_error') else (405 if is_block_code(code) else 502)) + status = _stream_error_status(code) message = info.get('message', 'ZCode stream failed') await self._apply_error(handle.account, model, status, code, message, expected_credentials=handle.credentials) diff --git a/zcode_gateway/upstream.py b/zcode_gateway/upstream.py index 765a47f..c62d0a4 100644 --- a/zcode_gateway/upstream.py +++ b/zcode_gateway/upstream.py @@ -144,6 +144,18 @@ def is_block_code(code: str, status: int = 0) -> bool: return c in BLOCKED_CODES or "3012" in c or "405" in c +# Capacity codes, not quota codes: the request is valid and the account is +# healthy — the upstream just refuses more parallel work right now. +# 3008 = user-level concurrency (all models on this account share the limit) +# 3009 = model-level concurrency +# 3010 = concurrency family (upstream busy) +CONCURRENCY_CODES = frozenset({"3008", "3009", "3010"}) + + +def is_concurrency_code(code) -> bool: + return str(code or "").strip() in CONCURRENCY_CODES + + # The bootstrap system text (identity line + harness body) is fingerprinted # byte-for-byte upstream: one wrong space answers 405/3012 "This client is not # supported. Please use the official ZCode client." with the SAME outcome on @@ -195,6 +207,8 @@ def classify(status: int, body: str | bytes | None = None) -> ErrorKind: info = parse_upstream_error(status, body) if info["code"] == "11113": return ErrorKind.INSUFFICIENT_CREDITS + if is_concurrency_code(info["code"]): + return ErrorKind.RATE_LIMITED if status == 200: return ErrorKind.OK if status == 401: From 9623cea23a512a79f6424d7dd95a4f7588e2d809 Mon Sep 17 00:00:00 2001 From: B3hnamR Date: Sat, 21 Nov 2026 07:56:58 +0330 Subject: [PATCH 2/7] Queue requests instead of over-admitting ZCode answers a second concurrent request on one account with 3008/3009/3010. The pool admitted four per account and retried at once, so a burst failed whole sessions. Cap each account at one in-flight request and let acquire() wait for a slot. After a refusal, hold the account with exponential backoff (cleared on success) so retries rotate instead of re-hitting the same busy slot. The account stays READY: no cooldown, park, or error history, because the refusal is capacity, not a bad account. Expose the strike count and hold deadline so the dashboard can show why an account is skipped. --- config.example.yaml | 8 +++- tests/test_acquire_wait.py | 59 +++++++++++++++++++++++++++++- tests/test_affinity.py | 16 ++++++++ tests/test_zcode_core.py | 75 ++++++++++++++++++++++++++++++++++++++ zcode_gateway/config.py | 15 ++++++-- zcode_gateway/pool.py | 57 +++++++++++++++++++++++++++-- zcode_gateway/service.py | 14 +++++-- 7 files changed, 231 insertions(+), 13 deletions(-) diff --git a/config.example.yaml b/config.example.yaml index efcbecb..90a07ba 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -22,8 +22,12 @@ upstream: pool: strategy: drain_first cooldown_seconds: 30 - max_in_flight_per_account: 4 - acquire_wait_seconds: 5 + # ZCode admits one concurrent request per account for GLM-5.3 (3008/3009 + # above it). Keep this at 1 and let acquire_wait_seconds queue the rest. + max_in_flight_per_account: 1 + acquire_wait_seconds: 120 + concurrency_hold_seconds: 10 + concurrency_hold_max_seconds: 60 balance_poll_seconds: 60 blocked_model_cooldown_seconds: 900 accounts: diff --git a/tests/test_acquire_wait.py b/tests/test_acquire_wait.py index 223db07..e70b989 100644 --- a/tests/test_acquire_wait.py +++ b/tests/test_acquire_wait.py @@ -3,11 +3,12 @@ from __future__ import annotations import asyncio +import time import pytest from zcode_gateway.config import PoolConfig -from zcode_gateway.pool import Account, PoolManager +from zcode_gateway.pool import Account, AccountState, PoolManager @pytest.mark.asyncio @@ -39,3 +40,59 @@ async def test_acquire_times_out_when_no_slot_frees(): # nothing releases -> must give up after the wait, not hang forever result = await pool.acquire(wait_seconds=0.2) assert result is None + + +@pytest.mark.asyncio +async def test_concurrency_refusal_routes_to_another_account(): + pool = PoolManager( + PoolConfig(max_in_flight_per_account=1, concurrency_hold_seconds=30), + [Account(id="a1", access_token="t"), Account(id="a2", access_token="t")]) + first = await pool.acquire(wait_seconds=0.0) + assert first is not None and first.id == "a1" + await pool.release(first) + await pool.on_concurrency_refusal(first) + + second = await pool.acquire(wait_seconds=0.0) + assert second is not None and second.id == "a2" + + +@pytest.mark.asyncio +async def test_concurrency_hold_queues_instead_of_failing(): + pool = PoolManager( + PoolConfig(max_in_flight_per_account=1, concurrency_hold_seconds=30), + [Account(id="a1", access_token="t")]) + account = (await pool.all())[0] + await pool.on_concurrency_refusal(account) + assert account.state is AccountState.READY + + waiter = asyncio.create_task(pool.acquire(wait_seconds=2.0)) + await asyncio.sleep(0.05) + assert not waiter.done() # held, so acquire must wait, not return None + + account.concurrency_hold_until = 0.0 + picked = await waiter + assert picked is account and picked.in_flight == 1 + + +@pytest.mark.asyncio +async def test_concurrency_hold_escalates_then_success_clears(): + pool = PoolManager( + PoolConfig(max_in_flight_per_account=1, + concurrency_hold_seconds=10, + concurrency_hold_max_seconds=60), + [Account(id="a1", access_token="t")]) + account = (await pool.all())[0] + + await pool.on_concurrency_refusal(account) + first_hold = account.concurrency_hold_until - time.time() + assert account.concurrency_strikes == 1 + assert 9.0 < first_hold <= 10.0 + + await pool.on_concurrency_refusal(account) + second_hold = account.concurrency_hold_until - time.time() + assert account.concurrency_strikes == 2 + assert 19.0 < second_hold <= 20.0 + + await pool.on_success(account) + assert account.concurrency_strikes == 0 + assert account.concurrency_hold_until == 0.0 diff --git a/tests/test_affinity.py b/tests/test_affinity.py index 5c559e8..6389095 100644 --- a/tests/test_affinity.py +++ b/tests/test_affinity.py @@ -81,6 +81,22 @@ async def test_acquire_binds_on_first_pick_then_sticks(): await pool.release(second) +@pytest.mark.asyncio +async def test_affinity_skips_concurrency_held_account(): + pool = PoolManager(PoolConfig(strategy="round_robin", conversation_affinity_seconds=600, + max_in_flight_per_account=1, concurrency_hold_seconds=30), + [Account(id="a1", access_token="t1"), + Account(id="a2", access_token="t2")]) + key = affinity_key_from_payload({"session_id": "conv-held"}) + pool._affinity.bind(key, "a1") + held = pool._accounts["a1"] + await pool.on_concurrency_refusal(held) + + picked = await pool.acquire(affinity_key=key) + assert picked is not None and picked.id == "a2" + await pool.release(picked) + + @pytest.mark.asyncio async def test_stale_binding_falls_back_to_a_candidate(): pool = PoolManager(PoolConfig(strategy="round_robin", conversation_affinity_seconds=600), diff --git a/tests/test_zcode_core.py b/tests/test_zcode_core.py index 9100b47..dc9dec5 100644 --- a/tests/test_zcode_core.py +++ b/tests/test_zcode_core.py @@ -31,6 +31,7 @@ def cfg(tmp_path): config.logging.capture=False config.pool.balance_poll_seconds=0 config.pool.acquire_wait_seconds=0 + config.pool.concurrency_hold_seconds=0 config.server.admin_key='test-admin' config.server.client_keys=[ClientKey(key='test-client')] return config @@ -331,6 +332,7 @@ def test_quota_aware_uses_requested_model(cfg): def test_drain_first_reuses_one_account_until_it_is_capped(cfg): cfg.pool.strategy='drain_first' + cfg.pool.max_in_flight_per_account=4 one=Account(id='one',access_token='a',notes={'quotas':{'GLM-5.3':{'remaining':5}}}) two=Account(id='two',access_token='b',notes={'quotas':{'GLM-5.3':{'remaining':100}}}) router=Router(cfg.pool) @@ -591,6 +593,79 @@ async def wait(delay, disconnected=None): waits.append(delay) assert all(r.closed for r in service.client.responses) +@pytest.mark.asyncio +async def test_concurrency_refusals_do_not_kill_burst_of_sessions(cfg): + cfg.pool.concurrency_hold_seconds=30 + cfg.pool.acquire_wait_seconds=2 + cfg.upstream.concurrency_base_delay_seconds=0 + cfg.upstream.max_attempts=3 + accounts=[Account(id=f'a{i}',access_token=f't{i}') for i in range(5)] + pool=PoolManager(cfg.pool,accounts) + store=Store(cfg.store.sqlite_path) + class FakeTokens: + async def refresh(self, account, force=False, *, expected_credentials=None): return False + svc=ChatService(cfg,pool,FakeTokens(),FakeClient(),Registry(),store,JsonlCapture(cfg.logging.capture_dir,False)) + class AccountAwareClient: + def __init__(self): self.calls=[] + async def send(self, headers, body, stream): + token=headers['authorization'].rsplit(' ',1)[-1] + self.calls.append(token) + if token in ('t0','t1','t2'): return concurrency_response(3008) + return FakeResponse(sample_sse()) + try: + svc.client=AccountAwareClient() + results=await asyncio.gather(*( + svc.complete({'messages':[{'role':'user','content':'hi'}]}, model='GLM-5.3') + for _ in range(6))) + assert [r.status for r in results]==[200]*6 + assert all(a.in_flight==0 for a in accounts) + assert all(a.state is AccountState.READY for a in accounts) + assert all(a.concurrency_strikes>=1 and a.is_concurrency_held() for a in accounts[:3]) + assert all(a.concurrency_strikes==0 and not a.is_concurrency_held() for a in accounts[3:]) + assert not any(a.model_caps for a in accounts) + finally: + store.close() + + +@pytest.mark.asyncio +async def test_concurrency_refusal_benches_account_and_routes_elsewhere(cfg): + cfg.pool.concurrency_hold_seconds=30 + one=Account(id='one',access_token='t-one') + two=Account(id='two',access_token='t-two') + pool=PoolManager(cfg.pool,[one,two]) + store=Store(cfg.store.sqlite_path) + class FakeTokens: + async def refresh(self, account, force=False, *, expected_credentials=None): return False + svc=ChatService(cfg,pool,FakeTokens(),FakeClient(),Registry(),store,JsonlCapture(cfg.logging.capture_dir,False)) + try: + svc.client=FakeClient(responses=[concurrency_response(3008),FakeResponse(sample_sse())]) + result=await svc.complete({'messages':[{'role':'user','content':'hi'}]}, model='GLM-5.3') + assert result.status==200 and len(svc.client.calls)==2 + assert [call[0]['authorization'] for call in svc.client.calls]==['Bearer t-one','Bearer t-two'] + assert one.state is AccountState.READY and one.in_flight==0 + assert one.concurrency_strikes==1 and one.is_concurrency_held() + assert two.concurrency_strikes==0 and not two.is_concurrency_held() + assert two.in_flight==0 and not one.model_caps and not one.error_history + assert all(r.closed for r in svc.client.responses) + finally: + store.close() + + +@pytest.mark.asyncio +async def test_midstream_concurrency_error_benches_account(service): + events=sample_events() + events.insert(1, {'type':'error','error':{'code':3008,'message':'user concurrency limit exceeded'}}) + service.cfg.pool.concurrency_hold_seconds=30 + service.client=FakeClient(b''.join(frame(e) for e in events)) + with pytest.raises(UpstreamFailure) as err: + await service.complete({'messages':[{'role':'user','content':'hi'}]}, model='GLM-5.3') + assert err.value.status==429 and err.value.code=='3008' + account=(await service.pool.all())[0] + assert account.state is AccountState.READY and account.in_flight==0 + assert account.concurrency_strikes==1 and account.is_concurrency_held() + assert not account.model_caps + + @pytest.mark.asyncio async def test_midstream_concurrency_error_is_429_without_cooling(service): events=sample_events() diff --git a/zcode_gateway/config.py b/zcode_gateway/config.py index 194f2a4..afd2bb9 100644 --- a/zcode_gateway/config.py +++ b/zcode_gateway/config.py @@ -241,11 +241,20 @@ class PoolConfig(BaseModel): min_balance_micro: int = 0 refresh_lead_seconds: int = Field(default=600, ge=0) cooldown_seconds: int = Field(default=30, ge=0) + # Measured ZCode limit: one concurrent request per account for GLM-5.3 + # (3008/3009 above it). Queueing beats over-admitting and getting 429s. # 0 would make every account permanently busy — all requests 503 forever - max_in_flight_per_account: int = Field(default=4, ge=1) + max_in_flight_per_account: int = Field(default=1, ge=1) # how long acquire() waits for an in-flight slot when every eligible - # account is at max_in_flight_per_account (0 = fail immediately) - acquire_wait_seconds: float = Field(default=5.0, ge=0) + # account is at max_in_flight_per_account or briefly held (0 = fail + # immediately). This is the request queue: wait, do not oversubscribe. + acquire_wait_seconds: float = Field(default=120.0, ge=0) + # After a 3008/3009/3010 refusal, skip this account for this long (doubling + # per consecutive refusal up to the max, cleared by the next success), so + # retries rotate to another account or wait instead of re-hitting the same + # saturated slot. Not a cooldown: state stays READY. + concurrency_hold_seconds: float = Field(default=10.0, ge=0) + concurrency_hold_max_seconds: float = Field(default=60.0, ge=0) balance_poll_seconds: int = Field(default=300, ge=10) # 405/code 3012 "unusual activity": park this model on the offending # account for this long, then rotate. Per model, so other models on the diff --git a/zcode_gateway/pool.py b/zcode_gateway/pool.py index e16a5dc..d0f4959 100644 --- a/zcode_gateway/pool.py +++ b/zcode_gateway/pool.py @@ -70,6 +70,13 @@ class Account: # dashboard "why did this account die" view and the health sparkline error_history: deque = field(default_factory=lambda: deque(maxlen=50)) + # Upstream concurrency refusals (3008/3009/3010). This is not a cooldown: + # state stays READY and no quota/model park is applied, but pick() skips the + # account until the hold expires so retries stop hammering a slot upstream + # still counts as busy. Doubles per consecutive refusal, cleared by success. + concurrency_hold_until: float = 0.0 + concurrency_strikes: int = 0 + # Credit exhaustion is per model-class, not per account: a paid model can 402 # (insufficient_credits) while zcode-free/* models keep working on the same # account, because free models do not consume Zcode Credits. @@ -119,6 +126,9 @@ def is_model_capped(self, model: str, now: float | None = None) -> bool: until = self.model_caps.get(model) return bool(until and until > now) + def is_concurrency_held(self, now: float | None = None) -> bool: + return self.concurrency_hold_until > (time.time() if now is None else now) + @property def is_free_tier(self) -> bool: return False # credential-level; free/paid is per-model, kept for future use @@ -180,16 +190,22 @@ def needs_refresh(self, lead_seconds: int) -> bool: def to_public(self) -> dict: tok = self.access_token or "" + now = time.time() return { "id": self.id, "email": self.email, "state": self.state.value, + "death_reason": self.death_reason, + "cooldown_in_s": int(max(self.cooldown_until - now, 0)), "paid_exhausted": self.paid_exhausted, "expires_at": self.expires_at, "expires_in_s": round(self.expires_in(), 1), "needs_refresh": self.needs_refresh(600), "in_flight": self.in_flight, "error_count": self.error_count, + "concurrency_strikes": self.concurrency_strikes, + "concurrency_hold_until": self.concurrency_hold_until, + "concurrency_hold_in_s": int(max(self.concurrency_hold_until - now, 0)), "balance_micro": self.balance_micro, "balance_checked_at": self.balance_checked_at, "quota_check_attempted_at": self.notes.get("quota_check_attempted_at"), @@ -320,7 +336,8 @@ def candidates(self, accounts: Iterable[Account], exclude: set[str], and not (a.state is AccountState.COOLING and now < a.cooldown_until) and a.access_token] if self.cfg.strategy == "quota_aware" and model and pool: - available = [a for a in pool if a.in_flight < self.cfg.max_in_flight_per_account] + available = [a for a in pool if a.in_flight < self.cfg.max_in_flight_per_account + and not a.is_concurrency_held(now)] # Keep saturated candidates only when there is no free slot, so # acquire() can still distinguish saturation from ineligibility. if available: @@ -354,7 +371,12 @@ def pick(self, accounts: list[Account]) -> Account | None: if not accounts: return None cap = self.cfg.max_in_flight_per_account - under_cap = [a for a in accounts if a.in_flight < cap] + now = time.time() + # Held accounts stay in candidates() so acquire() knows the pool is + # saturated (and waits) rather than absent — but they are not pickable + # until the hold expires. + under_cap = [a for a in accounts + if a.in_flight < cap and not a.is_concurrency_held(now)] if not under_cap: # The configured cap must be a cap, not a preference: when every # candidate is saturated, report no candidate. The manager waits @@ -810,9 +832,37 @@ async def on_success(self, account: Account, *, expected_credentials: tuple | No account.error_count = 0 account.last_error = "" account.auth_strikes = 0 + account.concurrency_strikes = 0 + account.concurrency_hold_until = 0.0 if account.state is AccountState.COOLING: account.state = AccountState.READY + async def on_concurrency_refusal(self, account: Account, *, + expected_credentials: tuple | None = None) -> None: + """Bench an account briefly after upstream refuses for concurrency. + + The refusal means a slot upstream still counts as busy, not that the + account is bad, so state stays READY and nothing is cooled or parked. + Holding the account out of pick() makes the retry go to another account + (or queue) instead of immediately hitting the same saturated slot. + Repeated refusals double the hold; a successful stream clears it. + """ + async with self._lock: + if expected_credentials is not None and (self._accounts.get(account.id) is not account + or account.credential_key() != expected_credentials): + return + account.concurrency_strikes += 1 + base = self.cfg.concurrency_hold_seconds + if base <= 0: + return + cap = max(base, self.cfg.concurrency_hold_max_seconds) + exponent = min(account.concurrency_strikes - 1, 16) + hold = min(cap, base * (2 ** exponent)) + account.concurrency_hold_until = max(account.concurrency_hold_until, + time.time() + hold) + log.info('concurrency refusal on %s; holding %.1fs (strike %s)', + account.id, hold, account.concurrency_strikes) + async def restore(self, account: Account, *, plan_recovered: bool = False, expected_credentials: tuple | None = None) -> bool: """A retired account's balance recovered: back into rotation.""" @@ -1024,7 +1074,8 @@ def _affine_candidate(self, candidates: list[Account], affinity_key: str) -> Acc return None cap = self.cfg.max_in_flight_per_account for account in candidates: - if account.id == bound and (cap <= 0 or account.in_flight < cap): + if (account.id == bound and (cap <= 0 or account.in_flight < cap) + and not account.is_concurrency_held()): return account return None diff --git a/zcode_gateway/service.py b/zcode_gateway/service.py index 431ca85..ce561f2 100644 --- a/zcode_gateway/service.py +++ b/zcode_gateway/service.py @@ -181,10 +181,16 @@ async def _close(self, handle): async def _apply_error(self, account, model, status, code, message, headers=None, *, expected_credentials=None): if expected_credentials is not None and account.credential_key() != expected_credentials: return - if is_model_overload(status, code) or is_concurrency_code(code): - # A busy model or a concurrency cap is not evidence of a bad - # account or spent quota. Keep this account available for other - # models and the retry loop. + if is_concurrency_code(code): + # Upstream still counts a slot as busy for this account: bench it + # briefly so the retry rotates instead of immediately re-hitting + # the same saturated slot. No error history, no cooling/parking. + await self.pool.on_concurrency_refusal( + account, expected_credentials=expected_credentials) + return + if is_model_overload(status, code): + # A busy model is not evidence of a bad account or spent quota. + # Keep this account available for other models and the retry loop. return # autopsy trail: keep the last errors for the dashboard "why" view try: From 15b03797e2012a60be673e198d1802f5bfeb211a Mon Sep 17 00:00:00 2001 From: B3hnamR Date: Sat, 21 Nov 2026 07:57:36 +0330 Subject: [PATCH 3/7] Remove suspended accounts from rotation ZCode answers a suspended account with 405/3012 and a message saying the account was suspended for proxying. The 405 handler parked only the requested model, so the banned account stayed in rotation and produced a 405 on every request. Recognise the suspension text and mark the account DEAD with death_reason=suspended. It stops serving until an operator re-enables it. An "unusual activity" block and the client-not-supported case keep their existing model-only park. --- tests/test_inference_audit.py | 16 ++++++++++++++++ zcode_gateway/service.py | 10 +++++++++- zcode_gateway/upstream.py | 13 +++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/tests/test_inference_audit.py b/tests/test_inference_audit.py index 70df83d..63e8d0f 100644 --- a/tests/test_inference_audit.py +++ b/tests/test_inference_audit.py @@ -507,3 +507,19 @@ async def test_genuine_unusual_activity_still_parks_for_the_full_window(): await service._apply_error(account, MODEL, 405, "3012", "request has been blocked due to unusual activity.") assert account.model_cap_info[MODEL]["code"] == "UNUSUAL_ACTIVITY" + + +@pytest.mark.asyncio +async def test_suspended_account_leaves_rotation_instead_of_parking_one_model(): + """The suspension message is account-wide and permanent. Parking only the + requested model kept a banned account in rotation for the next request.""" + service, _ = service_for([]) + account = await service.pool.find("one") + await service._apply_error( + account, MODEL, 405, "3012", + "Your account has been suspended for misusing the Start Plan, " + "such as proxying it to non-ZCode clients.") + assert account.state is AccountState.DEAD + assert account.death_reason == "suspended" + assert MODEL not in account.model_caps + assert await service.pool.acquire() is None diff --git a/zcode_gateway/service.py b/zcode_gateway/service.py index ce561f2..ce88270 100644 --- a/zcode_gateway/service.py +++ b/zcode_gateway/service.py @@ -21,7 +21,7 @@ from .upstream import (build_headers, build_upstream_body, iter_sse_events, sse_frame, parse_upstream_error, anthropic_error, openai_error, TransportError, is_block_code, is_concurrency_code, client_not_supported, - CLIENT_NOT_SUPPORTED_PARK_S) + is_account_suspended, CLIENT_NOT_SUPPORTED_PARK_S) from .registry import model_caps log = logging.getLogger('zcode_gateway.service') @@ -213,6 +213,14 @@ async def _apply_error(self, account, model, status, code, message, headers=None # not match. Every account then fails identically, so a 900s park # per account only spreads a pool-wide outage over 15 minutes of # misleading state. Park briefly and name the real cause instead. + if is_account_suspended(message): + # The account itself is banned upstream for proxying: no model + # on it can serve, and retrying only produces a 405 per request. + # Take it out of rotation until an operator re-enables it. + await self.pool.kill(account, reason=str(message)[:200], + cause='suspended', + expected_credentials=expected_credentials) + return if client_not_supported(message): await self.pool.cap_model(account, model, CLIENT_NOT_SUPPORTED_PARK_S, diff --git a/zcode_gateway/upstream.py b/zcode_gateway/upstream.py index c62d0a4..601a845 100644 --- a/zcode_gateway/upstream.py +++ b/zcode_gateway/upstream.py @@ -169,6 +169,19 @@ def client_not_supported(message: str | None) -> bool: return any(marker in text for marker in CLIENT_NOT_SUPPORTED_MARKERS) +# Account-level suspension ("Your account has been suspended for misusing the +# Start Plan, such as proxying it to non-ZCode clients"). Unlike an "unusual +# activity" block, this is not scoped to one model and does not lift on its +# own: every request on the account fails until support restores it, so the +# account must leave the pool instead of being retried. +SUSPENSION_MARKERS = ("has been suspended", "account suspended") + + +def is_account_suspended(message: str | None) -> bool: + text = (message or "").lower() + return any(marker in text for marker in SUSPENSION_MARKERS) + + def _error_code(body: str | bytes | None) -> str: """Best-effort extraction of error.code from a JSON error body.""" text = body.decode("utf-8", "replace") if isinstance(body, bytes) else (body or "") From ae034636703efacd638c922f896c1f0140ef47ac Mon Sep 17 00:00:00 2001 From: B3hnamR Date: Sat, 21 Nov 2026 07:57:36 +0330 Subject: [PATCH 4/7] Surface account problems on the accounts page A failing account was only visible as "N err" in a tooltip. Add an Issues metric and a Needs attention panel naming each blocked account, the reason, and an Enable action for dead ones. Show the last error inline with its age and full message on hover, and show concurrency holds and cooldowns under the state badge so a throttled account is distinguishable from a healthy one. --- .../dashboard/assets/js/views/accounts.js | 161 +++++++++++++++++- 1 file changed, 152 insertions(+), 9 deletions(-) diff --git a/zcode_gateway/dashboard/assets/js/views/accounts.js b/zcode_gateway/dashboard/assets/js/views/accounts.js index 260d0a1..7e1cb47 100644 --- a/zcode_gateway/dashboard/assets/js/views/accounts.js +++ b/zcode_gateway/dashboard/assets/js/views/accounts.js @@ -112,18 +112,156 @@ function tokenCell(a) { }); } +function stateCell(a) { + const parts = [stateBadge(a.state)]; + const hold = Number(a.concurrency_hold_in_s) || 0; + const cooldown = Number(a.cooldown_in_s) || 0; + if (hold > 0) { + parts.push(el("div", { + class: "faint text-xs", text: "throttled " + duration(hold), + title: "Upstream refused a parallel request on this account (3008). " + + "It is benched briefly and returns automatically.", + })); + } else if (a.state === "cooling" && cooldown > 0) { + parts.push(el("div", { + class: "faint text-xs", text: "retry in " + duration(cooldown), + title: a.last_error || "Transient upstream error", + })); + } else if (a.last_error && (a.state === "dead" || a.state === "exhausted")) { + parts.push(el("div", { + class: "text-err text-xs", text: a.last_error, title: a.last_error, + style: { maxWidth: "220px", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, + })); + } + return el("div", { style: { display: "flex", flexDirection: "column", gap: "3px" } }, parts); +} + +const SUSPENDED = /suspended/i; + +function errorLabel(e) { + const code = String(e.code || ""); + if (SUSPENDED.test(e.message || "") || SUSPENDED.test(code)) return "suspended"; + if (code === "UNUSUAL_ACTIVITY") return "unusual activity"; + if (code === "CLIENT_NOT_SUPPORTED") return "client not supported"; + return [e.status, code].filter((v) => v !== null && v !== undefined && v !== "").join(" · ") || "error"; +} + function errorCell(a) { const errs = (a.error_history || []).slice(-12); - if (!errs.length) return el("span", { class: "faint", text: "—" }); - const detail = errs.map((e) => (e.ago_s ?? "?") + "s ago · " + (e.status || "") + " " + (e.code || "")).join("\n"); - return el("span", { - class: "mono text-xs " + (a.state === "dead" ? "text-err" : "text-warn"), - text: errs.length + " err", - title: detail, - style: { cursor: "help" }, + if (!errs.length) { + return a.last_error + ? el("div", { class: "text-warn text-xs", text: a.last_error, title: a.last_error }) + : el("span", { class: "faint", text: "—" }); + } + const last = errs[errs.length - 1]; + const detail = errs.slice().reverse().map((e) => { + const when = Number.isFinite(Number(e.ago_s)) ? duration(e.ago_s) + " ago" : "?"; + const model = e.model ? " · " + String(e.model).split("/").pop() : ""; + return when + " · " + errorLabel(e) + model + + (e.message ? "\n " + e.message : ""); + }).join("\n"); + return el("div", { title: detail, style: { cursor: "help" } }, [ + el("div", { + class: "text-xs " + (a.state === "dead" ? "text-err" : "text-warn"), + text: errorLabel(last), + }), + el("div", { + class: "faint text-xs", + text: (Number.isFinite(Number(last.ago_s)) ? duration(last.ago_s) + " ago" : "?") + + (errs.length > 1 ? " · " + errs.length + " recent" : ""), + }), + ]); +} + +/** One dominant, human-readable problem per account, or null when healthy. + Order matters: the first match is what the operator needs to act on. */ +function accountIssue(a) { + const suspended = SUSPENDED.test(a.last_error || "") || a.death_reason === "suspended"; + if (suspended) { + return { + tone: "err", label: "Suspended by upstream", + detail: a.last_error || "ZCode suspended this account for proxying; support must restore it.", + dead: a.state === "dead", + }; + } + if (a.state === "dead") { + const why = a.death_reason === "plan_lost" + ? "The ZCode plan expired or was removed." + : a.death_reason === "authentication_error" + ? "The token was revoked; sign in again or reimport the account." + : ""; + return { + tone: "err", label: "Out of rotation", + detail: why || a.last_error || a.death_reason || "Account is dead; re-enable it to retry.", + dead: true, + }; + } + if (a.state === "exhausted") { + return { + tone: "err", label: "Exhausted", + detail: a.last_error || "Repeated quota rejections with no visible quota buckets.", + }; + } + const hold = Number(a.concurrency_hold_in_s) || 0; + if (hold > 0) { + return { + tone: "warn", label: "Throttled " + duration(hold), + detail: "Upstream reported a concurrency limit (3008); retries resume on their own.", + }; + } + if (a.state === "cooling") { + return { + tone: "warn", label: "Cooling " + duration(a.cooldown_in_s), + detail: a.last_error || "Transient upstream error; the account returns automatically.", + }; + } + if (Number(a.expires_at) > 0 && Number(a.expires_at) <= Date.now()) { + return { + tone: "err", label: "Token expired", + detail: "Sign in again or reimport the account to restore service.", + }; + } + if (a.quota_check_error) { + return { + tone: "warn", label: "Quota check failed", + detail: a.quota_check_error, + }; + } + return null; +} + +/** Accounts with a real blocker, kept visible above the table so a bad + account never hides behind a tooltip in the Errors column. */ +function attentionCard(accounts, reload) { + const rows = accounts + .map((a) => ({ account: a, issue: accountIssue(a) })) + .filter((r) => r.issue); + if (!rows.length) return null; + return card({ + title: "Needs attention", + desc: rows.length + (rows.length === 1 ? " account is" : " accounts are") + + " not serving (or about to stop). Hover a reason for the full upstream message.", + body: el("div", { class: "stack stack--tight" }, rows.map(({ account: a, issue }) => + el("div", { + class: "row row--tight", + style: { alignItems: "center", padding: "6px 0", borderBottom: "1px solid var(--border)" }, + }, [ + badge(issue.label, issue.tone), + el("div", { style: { flex: "1", minWidth: "0" } }, [ + el("div", { text: a.email || a.id, style: { fontWeight: "500" } }), + el("div", { + class: "faint text-xs", text: issue.detail, title: issue.detail, + style: { overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: "760px" }, + }), + ]), + issue.dead + ? button({ label: "Enable", icon: "check", onClick: () => accountAction("enable", a.id, reload) }) + : el("span", { class: "faint text-xs", text: "automatic" }), + ]))), }); } + /* ----------------------------------------------------------- actions ---- */ async function accountAction(action, id, reload) { @@ -324,9 +462,12 @@ function render(root, accounts, pool, reload, batch, signal, campaign = {}) { : "Locked until the Weekend Build window opens"; const counts = pool.by_state || {}; + const issueCount = accounts.filter((a) => accountIssue(a)).length; const summary = el("div", { class: "grid grid--metrics" }, [ metric({ label: "Accounts", value: num(pool.accounts ?? rows.length) }), metric({ label: "Ready", value: num(pool.ready ?? 0), tone: (pool.ready ?? 0) > 0 ? "ok" : "warn" }), + metric({ label: "Issues", value: num(issueCount), tone: issueCount ? "warn" : "ok", + hint: issueCount ? "See Needs attention below" : "Every account can serve" }), metric({ label: "Cooling", value: num(counts.cooling ?? 0), tone: counts.cooling ? "warn" : null }), metric({ label: "Dead", value: num(counts.dead ?? 0), tone: counts.dead ? "err" : null }), metric({ label: "Strategy", value: pool.strategy || "—" }), @@ -402,7 +543,7 @@ function render(root, accounts, pool, reload, batch, signal, campaign = {}) { ]), el("div", { class: "mono faint text-xs", text: a.id }), ]), - stateBadge(a.state), + stateCell(a), planCell(a), tokenCell(a), quotaCell(a), @@ -436,7 +577,9 @@ function render(root, accounts, pool, reload, batch, signal, campaign = {}) { flush: true, }); - fill(root, el("div", { class: "stack" }, [summary, quotaTotals, bar, batch.node, tableCard])); + fill(root, el("div", { class: "stack" }, + [summary, quotaTotals, attentionCard(accounts, reload), bar, batch.node, tableCard] + .filter(Boolean))); applyFilter(root); paintSocks(); } From d3d8a9dc72e16b4cb92442ed99f3ed7681a9fdf1 Mon Sep 17 00:00:00 2001 From: B3hnamR Date: Sun, 22 Nov 2026 05:44:19 +0330 Subject: [PATCH 5/7] Keep accounts distinct and ban-safe Every account shared the install's device_mid and timezone, so upstream saw one machine cycling credentials - the pattern it suspends for. Each account now keeps its own stable id (uuid4 for new logins, uuid5 of the account id for imports) and timezone, and the generator derives the same id. DEAD, EXHAUSTED and active COOLING states are written back to the live account source, so a restart no longer resurrects a suspended account as READY. A released account waits concurrency_settle_seconds before re-admission, because upstream still counts the finished request; refusal strikes also decay after a quiet gap instead of stacking to the maximum hold forever. A 405/3012 suspension now kills the account, logs the upstream text and aborts the request instead of rotating the ban onto the next account. scripts/accounts/backfill_device_mids.py migrates existing snapshots (dry run by default). --- config.example.yaml | 5 + generator/invite_claim.py | 17 +- generator/plan_check.py | 18 +- scripts/accounts/backfill_device_mids.py | 71 +++++++ scripts/accounts/import_account.py | 18 +- tests/test_accounts_dir.py | 66 ++++++ tests/test_acquire_wait.py | 120 ++++++++++- tests/test_affinity.py | 26 ++- tests/test_core_review_fixes.py | 6 + tests/test_credential_quota_fixes.py | 1 + tests/test_inference_audit.py | 1 + tests/test_jwt_import.py | 19 ++ tests/test_model_caps_persist.py | 22 +- tests/test_pr2_regressions.py | 11 + tests/test_stream_retry.py | 1 + tests/test_zcode_core.py | 151 ++++++++++++++ tests/test_zcode_device.py | 12 ++ zcode_gateway/accounts_dir.py | 37 +++- zcode_gateway/accounts_dir_bridge.py | 8 +- zcode_gateway/api_admin.py | 29 ++- zcode_gateway/api_dash.py | 7 +- zcode_gateway/app.py | 10 + zcode_gateway/config.py | 5 + .../dashboard/assets/js/views/accounts.js | 21 +- zcode_gateway/device_auth.py | 17 +- zcode_gateway/pool.py | 194 +++++++++++++++++- zcode_gateway/service.py | 30 ++- zcode_gateway/token_utils.py | 32 +++ zcode_gateway/tokens.py | 7 +- zcode_gateway/upstream.py | 4 +- zcode_gateway/zcode_accounts.py | 20 +- zcode_gateway/zcode_device.py | 16 ++ 32 files changed, 921 insertions(+), 81 deletions(-) create mode 100644 scripts/accounts/backfill_device_mids.py diff --git a/config.example.yaml b/config.example.yaml index 90a07ba..30bef65 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -28,6 +28,11 @@ pool: acquire_wait_seconds: 120 concurrency_hold_seconds: 10 concurrency_hold_max_seconds: 60 + # Upstream keeps a just-finished request in its per-user concurrency count + # for a few seconds, so handing a released account out again immediately + # answers 3008 even though the slot is free locally. Wait this long after + # release() before re-admitting the account. + concurrency_settle_seconds: 5 balance_poll_seconds: 60 blocked_model_cooldown_seconds: 900 accounts: diff --git a/generator/invite_claim.py b/generator/invite_claim.py index 5b67cf8..0a0c75a 100644 --- a/generator/invite_claim.py +++ b/generator/invite_claim.py @@ -25,7 +25,13 @@ sys.stderr.reconfigure(encoding='utf-8', errors='replace') from utils import BROWSER_ARGS -from plan_check import APP_VERSION, _request, client_timezone, direct_requests +from plan_check import ( + APP_VERSION, + _request, + client_timezone, + direct_requests, + per_account_device_mid, +) # NOTE: playwright is imported lazily inside claim_invite(). The referral # helpers below (referral_summary / send_one_message) are imported by the @@ -557,20 +563,11 @@ def wrapper(*args, **kwargs): return wrapper -def per_account_device_mid(token: str) -> str: - """Stable per-account device id (uuid5 of the chat token) instead of the - hardcoded shared one — every account reporting the SAME x-device-mid in - telemetry is a direct cross-account correlation signal.""" - import uuid as _u - return str(_u.uuid5(_u.NAMESPACE_URL, 'zcode-device:' + (token or ''))) - - APP_HEADERS = { # exact cli/init header set captured from the desktop app 'content-type': 'application/json', 'http-referer': 'https://zcode.z.ai', 'user-agent': 'ZCode/' + APP_VERSION, 'x-client-language': 'en-US', - 'x-device-mid': '58aca3b3-3239-4cb7-9c70-df3e5488fb99', 'x-os-category': 'windows', 'x-os-version': '10.0.26200', 'x-platform': 'win32-x64', diff --git a/generator/plan_check.py b/generator/plan_check.py index 3574891..36ef9df 100644 --- a/generator/plan_check.py +++ b/generator/plan_check.py @@ -246,16 +246,22 @@ def is_campaign_plan_name(name) -> bool: } # Stable PER-ACCOUNT device id: every account using one shared hardcoded # x-device-mid is a direct cross-account correlation signal for risk control. -# uuid5 of the chat token keeps the id deterministic per account (the gateway -# plan-checker and the message flow then report a consistent device). DEVICE_MID = "58aca3b3-3239-4cb7-9c70-df3e5488fb99" # legacy fallback only +def account_device_mid(account_id: str) -> str: + """Same derivation as zcode_gateway.zcode_device.account_device_mid. + + The generator runs under its own interpreter, where the gateway package is + not importable, so the formula is duplicated; tests pin the two together. + """ + return str(uuid.uuid5(uuid.NAMESPACE_URL, 'zcode-device:' + (account_id or ''))) + + def per_account_device_mid(token: str) -> str: - import uuid as _u - if not token: - return DEVICE_MID - return str(_u.uuid5(_u.NAMESPACE_URL, 'zcode-device:' + token)) + """The device of the account a chat token or zjwt belongs to.""" + ident = jwt_user_id(token) + return account_device_mid(ident) if ident else DEVICE_MID _TZ_CACHE = None diff --git a/scripts/accounts/backfill_device_mids.py b/scripts/accounts/backfill_device_mids.py new file mode 100644 index 0000000..2974653 --- /dev/null +++ b/scripts/accounts/backfill_device_mids.py @@ -0,0 +1,71 @@ +"""Give every account snapshot its own stable device_mid. + +Dry run by default. Only accounts that share a mid with another account (or +have none) are touched; an account whose mid is already unique is left alone. +The new mid is `account_device_mid(account_id)`, the same derivation the +generator uses, so both sides agree after migration. +""" +import argparse +import sys +from collections import Counter +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from gui_main import _bootstrap_config +from zcode_gateway.accounts_dir import parse_snapshot, snapshot_transaction, write_snapshot +from zcode_gateway.config import load_config +from zcode_gateway.zcode_device import account_device_mid + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument('directory', nargs='?', + help='accounts folder (default: the configured accounts.dir)') + parser.add_argument('--config') + parser.add_argument('--apply', action='store_true', + help='rewrite the files (default: dry run)') + args = parser.parse_args() + if args.directory: + directory = Path(args.directory) + else: + directory = Path(load_config(args.config or _bootstrap_config()).accounts.dir) + if not directory.is_dir(): + print(f"accounts folder not found: {directory}") + return 1 + + with snapshot_transaction(directory) as folder: + rows = [] + for path in sorted(folder.iterdir()): + if path.suffix.casefold() != '.txt' or not path.is_file() or path.is_symlink(): + continue + try: + fields = parse_snapshot(path) + except Exception: + print(f"skipping unreadable snapshot: {path.name}") + continue + ident = fields.get('account_id') or fields.get('zcode_user_id') or path.stem + rows.append((path, fields, ident, fields.get('device_mid', '').strip())) + + shared = Counter(mid for *_, mid in rows if mid) + targets = [row for row in rows if not row[3] or shared[row[3]] > 1] + if not targets: + print(f"every account in {directory} already has a unique device_mid") + return 0 + print(f"{'Rewriting' if args.apply else 'Would rewrite'} " + f"{len(targets)} of {len(rows)} account(s) in {directory}") + for path, fields, ident, old in targets: + new = account_device_mid(ident) + print(f"{fields.get('email') or ident} -> {old or '(none)'} -> {new}") + if not args.apply or new == old: + continue + fields['device_mid'] = new + write_snapshot(path, fields) + + if not args.apply: + print("Dry run: nothing written. Back up the accounts folder, " + "then re-run with --apply.") + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/scripts/accounts/import_account.py b/scripts/accounts/import_account.py index 3244954..e5d304e 100644 --- a/scripts/accounts/import_account.py +++ b/scripts/accounts/import_account.py @@ -1,12 +1,10 @@ """Import a ZCode credentials file or the user's MITM dataset into this install.""" import argparse -import json import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[2])) from gui_main import _bootstrap_config -from zcode_gateway.accounts_dir import parse_snapshot, write_snapshot from zcode_gateway.config import load_config from zcode_gateway.zcode_accounts import import_credentials @@ -18,21 +16,9 @@ def main(): args = parser.parse_args() cfg = load_config(args.config or _bootstrap_config()) source = Path(args.source) - dataset = source if source.is_dir() else None - if dataset: - source = dataset / 'data' / 'tokens.json' + if source.is_dir(): + source = source / 'data' / 'tokens.json' result = import_credentials(source, cfg.accounts.dir) - if dataset: - flows = sorted((dataset / 'captures' / 'model-api').glob('*.json')) - if flows: - flow = json.loads(flows[-1].read_text(encoding='utf-8')) - mid = flow.get('request', {}).get('headers', {}).get('x-device-mid') - if mid: - for name in result['files']: - path = Path(cfg.accounts.dir) / name - fields = parse_snapshot(path) - fields['device_mid'] = mid - write_snapshot(path, fields) print(f"Imported {result['written']} account(s) into {cfg.accounts.dir}. Reload pool to activate.") return 0 if result['written'] else 1 diff --git a/tests/test_accounts_dir.py b/tests/test_accounts_dir.py index cb69834..3d354ec 100644 --- a/tests/test_accounts_dir.py +++ b/tests/test_accounts_dir.py @@ -2,13 +2,21 @@ from __future__ import annotations +import base64 +import json +import time from pathlib import Path +import pytest + from zcode_gateway.accounts_dir import ( load_from_accounts_dir, parse_snapshot, + persist_account_states, write_snapshot, ) +from zcode_gateway.pool import AccountState, PoolConfig, PoolManager +from zcode_gateway.zcode_accounts import read_credentials SNAPSHOT = """\ # Zcode account snapshot @@ -134,3 +142,61 @@ def parse_snapshot_file(tmp_path) -> dict: f = tmp_path / "src.txt" f.write_text(SNAPSHOT, encoding="utf-8") return parse_snapshot(f) + + +def test_shared_telemetry_mid_does_not_reach_two_records(tmp_path): + def token(ident): + claims = base64.urlsafe_b64encode( + json.dumps({"user_id": ident, "iat": 1}).encode()).decode().rstrip("=") + return f"header.{claims}.signature" + + (tmp_path / "telemetry-state.json").write_text( + json.dumps({"deviceMid": "desktop-mid"}), encoding="utf-8") + (tmp_path / "credentials.json").write_text(json.dumps({ + "account-provider:coding-plan:account:a:api-key": token("acct-a"), + "account-provider:coding-plan:account:b:api-key": token("acct-b"), + }), encoding="utf-8") + mids = {row["account_id"]: row["device_mid"] + for row in read_credentials(tmp_path / "credentials.json")} + assert len(mids) == 2 + assert len(set(mids.values())) == 2 + assert "desktop-mid" not in mids.values() + # a second import (or a providers_json restart) keeps the same identity + again = {row["account_id"]: row["device_mid"] + for row in read_credentials(tmp_path / "credentials.json")} + assert again == mids + + +def test_state_and_death_reason_round_trip(tmp_path): + fields = parse_snapshot_file(tmp_path) + fields.update(state="dead", death_reason="suspended", + paid_exhausted="true", cooldown_until="0") + write_snapshot(tmp_path / "src.txt", fields) + account = load_from_accounts_dir(tmp_path)[0] + assert account.state is AccountState.DEAD + assert account.death_reason == "suspended" + assert account.paid_exhausted is True + + +def test_expired_cooldown_restores_ready(tmp_path): + fields = parse_snapshot_file(tmp_path) + fields.update(state="cooling", cooldown_until=str(time.time() - 5)) + write_snapshot(tmp_path / "src.txt", fields) + assert load_from_accounts_dir(tmp_path)[0].state is AccountState.READY + + +@pytest.mark.asyncio +async def test_killed_account_reloads_dead_with_its_reason(tmp_path): + write_snapshot(tmp_path / "one.txt", { + "account_id": "acct-one", "email": "one@example.test", + "access_token": "offline", "expires_at_ms": "0", "device_mid": "device-one", + }) + accounts = load_from_accounts_dir(tmp_path) + pool = PoolManager(PoolConfig(), accounts) + pool._STATE_SAVE_DEBOUNCE_S = 0.01 + pool.set_state_saver(lambda rows: persist_account_states(tmp_path, rows)) + await pool.kill(accounts[0], "banned for proxying", cause="suspended") + await pool.aclose() + reloaded = load_from_accounts_dir(tmp_path)[0] + assert reloaded.state is AccountState.DEAD + assert reloaded.death_reason == "suspended" diff --git a/tests/test_acquire_wait.py b/tests/test_acquire_wait.py index e70b989..c9aefbf 100644 --- a/tests/test_acquire_wait.py +++ b/tests/test_acquire_wait.py @@ -13,7 +13,8 @@ @pytest.mark.asyncio async def test_acquire_waits_for_a_freed_slot(): - pool = PoolManager(PoolConfig(max_in_flight_per_account=1), + pool = PoolManager(PoolConfig(max_in_flight_per_account=1, + concurrency_settle_seconds=0), [Account(id="a1", access_token="t")]) first = await pool.acquire(wait_seconds=0.0) assert first is not None @@ -34,7 +35,8 @@ async def release_soon(): @pytest.mark.asyncio async def test_acquire_times_out_when_no_slot_frees(): - pool = PoolManager(PoolConfig(max_in_flight_per_account=1), + pool = PoolManager(PoolConfig(max_in_flight_per_account=1, + concurrency_settle_seconds=0), [Account(id="a1", access_token="t")]) await pool.acquire(wait_seconds=0.0) # nothing releases -> must give up after the wait, not hang forever @@ -96,3 +98,117 @@ async def test_concurrency_hold_escalates_then_success_clears(): await pool.on_success(account) assert account.concurrency_strikes == 0 assert account.concurrency_hold_until == 0.0 + + +@pytest.mark.asyncio +async def test_settling_account_is_not_pickable_until_window_passes(): + pool = PoolManager( + PoolConfig(max_in_flight_per_account=1, + concurrency_settle_seconds=30), + [Account(id="a1", access_token="t")]) + account = (await pool.all())[0] + account.in_flight = 1 + await pool.release(account) # marks the settle window + + # released but still settling: pick() must refuse, acquire() reports no + # candidate (the pool is briefly saturated, not absent) + assert pool._router.pick([account]) is None + got = await pool.acquire(wait_seconds=0.0) + assert got is None + assert account.state is AccountState.READY + assert account.in_flight == 0 + + # after the window the account serves again + account.settled_until = 0.0 + assert pool._router.pick([account]) is account + + +@pytest.mark.asyncio +async def test_settle_window_queues_instead_of_failing(): + pool = PoolManager( + PoolConfig(max_in_flight_per_account=1, + concurrency_settle_seconds=30), + [Account(id="a1", access_token="t")]) + first = await pool.acquire(wait_seconds=0.0) + await pool.release(first) + + waiter = asyncio.create_task(pool.acquire(wait_seconds=2.0)) + await asyncio.sleep(0.05) + assert not waiter.done() # settling, so acquire must wait, not fail + + first.settled_until = 0.0 + picked = await waiter + assert picked is first and picked.in_flight == 1 + + +@pytest.mark.asyncio +async def test_zero_settle_keeps_current_behavior(): + pool = PoolManager( + PoolConfig(max_in_flight_per_account=1, + concurrency_settle_seconds=0), + [Account(id="a1", access_token="t")]) + first = await pool.acquire(wait_seconds=0.0) + await pool.release(first) + assert pool._router.pick([first]) is first + + +@pytest.mark.asyncio +async def test_new_concurrency_refusal_fails_pick_but_readmission_waits(): + """A fresh refusal must exclude the account from selection even though the + readmission queue would let it back in — the hold wins.""" + pool = PoolManager( + PoolConfig(max_in_flight_per_account=1, + concurrency_hold_seconds=60, + concurrency_settle_seconds=0), + [Account(id="a1", access_token="t")]) + account = (await pool.all())[0] + await pool.on_concurrency_refusal(account) + # hold active, so the account is not pickable now... + assert pool._router.pick([account]) is None + # ...and it stays not pickable regardless of any settle window state, + # proving the hold outlives readmission + account.settled_until = 0.0 + assert pool._router.pick([account]) is None + account.concurrency_hold_until = 0.0 + assert pool._router.pick([account]) is account + + +@pytest.mark.asyncio +async def test_concurrency_strikes_decay_after_quiet_gap(): + pool = PoolManager( + PoolConfig(max_in_flight_per_account=1, + concurrency_hold_seconds=10, + concurrency_hold_max_seconds=60), + [Account(id="a1", access_token="t")]) + account = (await pool.all())[0] + await pool.on_concurrency_refusal(account) + await pool.on_concurrency_refusal(account) + assert account.concurrency_strikes == 2 + + # a served request clears the counter, but holds can also expire with no + # success in between: a quiet gap LONGER than the max hold decays the + # escalation, so the next refusal starts near the base again + account.concurrency_hold_until = time.time() - 61 + await pool.on_concurrency_refusal(account) + # strike 3 on 10s base would be 40s; decayed to 2 it is 20s + hold = account.concurrency_hold_until - time.time() + assert account.concurrency_strikes == 2 + assert 9.0 < hold <= 20.0 + + +@pytest.mark.asyncio +async def test_consecutive_refusals_inside_the_hold_still_escalate(): + pool = PoolManager( + PoolConfig(max_in_flight_per_account=1, + concurrency_hold_seconds=10, + concurrency_hold_max_seconds=60), + [Account(id="a1", access_token="t")]) + account = (await pool.all())[0] + await pool.on_concurrency_refusal(account) + await pool.on_concurrency_refusal(account) # hold still ~10s out + assert account.concurrency_strikes == 2 + account.concurrency_hold_until = time.time() + 5 # not expired: still chaining + await pool.on_concurrency_refusal(account) + assert account.concurrency_strikes == 3 + hold = account.concurrency_hold_until - time.time() + assert 19.0 < hold <= 40.0 diff --git a/tests/test_affinity.py b/tests/test_affinity.py index 6389095..143d9ed 100644 --- a/tests/test_affinity.py +++ b/tests/test_affinity.py @@ -53,7 +53,8 @@ def test_map_expires_and_drops(): @pytest.mark.asyncio async def test_acquire_reuses_bound_account(): - pool = PoolManager(PoolConfig(strategy="round_robin", conversation_affinity_seconds=600), + pool = PoolManager(PoolConfig(strategy="round_robin", conversation_affinity_seconds=600, + concurrency_settle_seconds=0), [Account(id="a1", access_token="t1"), Account(id="a2", access_token="t2")]) key = affinity_key_from_payload({"session_id": "conv-1"}) @@ -66,7 +67,8 @@ async def test_acquire_reuses_bound_account(): @pytest.mark.asyncio async def test_acquire_binds_on_first_pick_then_sticks(): - pool = PoolManager(PoolConfig(strategy="round_robin", conversation_affinity_seconds=600), + pool = PoolManager(PoolConfig(strategy="round_robin", conversation_affinity_seconds=600, + concurrency_settle_seconds=0), [Account(id="a1", access_token="t1"), Account(id="a2", access_token="t2")]) key = affinity_key_from_payload({"session_id": "conv-2"}) @@ -97,9 +99,27 @@ async def test_affinity_skips_concurrency_held_account(): await pool.release(picked) +@pytest.mark.asyncio +async def test_affinity_skips_settling_account(): + pool = PoolManager(PoolConfig(strategy="round_robin", conversation_affinity_seconds=600, + max_in_flight_per_account=1, concurrency_settle_seconds=30), + [Account(id="a1", access_token="t1"), + Account(id="a2", access_token="t2")]) + key = affinity_key_from_payload({"session_id": "conv-settle"}) + first = await pool.acquire(affinity_key=key) + assert first.id == "a1" + await pool.release(first) # arms the settle window on a1 + assert pool._accounts["a1"].is_settling() + + picked = await pool.acquire(affinity_key=key) + assert picked is not None and picked.id == "a2" + await pool.release(picked) + + @pytest.mark.asyncio async def test_stale_binding_falls_back_to_a_candidate(): - pool = PoolManager(PoolConfig(strategy="round_robin", conversation_affinity_seconds=600), + pool = PoolManager(PoolConfig(strategy="round_robin", conversation_affinity_seconds=600, + concurrency_settle_seconds=0), [Account(id="a1", access_token="t1")]) key = affinity_key_from_payload({"session_id": "conv-3"}) pool._affinity.bind(key, "gone") diff --git a/tests/test_core_review_fixes.py b/tests/test_core_review_fixes.py index 1bdada0..1817a97 100644 --- a/tests/test_core_review_fixes.py +++ b/tests/test_core_review_fixes.py @@ -292,6 +292,9 @@ async def test_retried_http_401_uses_credentials_of_second_send(): service, _ = service_for([]) service.cfg.upstream.max_attempts = 1 account = await service.pool.find('one') + # a bare account is assigned a mid on its first request, and the mid is + # part of the credential key; pin one so `before` is the key actually sent + account.notes['device_mid'] = 'test-device' calls, refresh_keys = [], [] async def refresh(account, force=False, *, expected_credentials=None): @@ -399,6 +402,9 @@ async def test_rotation_during_open_does_not_penalize_new_credentials(failure): account = await service.pool.find('one') if failure == 'expired': account.expires_at = 1 + # a bare account is assigned a mid on its first request, and the mid is + # part of the credential key; pin one so `before` is the key actually sent + account.notes['device_mid'] = 'test-device' before = account.credential_key() def rotate(): diff --git a/tests/test_credential_quota_fixes.py b/tests/test_credential_quota_fixes.py index e773dc4..c4e5650 100644 --- a/tests/test_credential_quota_fixes.py +++ b/tests/test_credential_quota_fixes.py @@ -401,6 +401,7 @@ def test_quota_aware_skips_saturated_highest_quota_before_ranking(): async def test_quota_aware_waits_only_when_all_eligible_accounts_are_saturated(): cfg = Config().pool cfg.strategy, cfg.max_in_flight_per_account = 'quota_aware', 1 + cfg.concurrency_settle_seconds = 0 accounts = [Account(id='best', access_token='dummy-best', in_flight=1, notes={'quotas': {MODEL: {'remaining': 100}}}), Account(id='next', access_token='dummy-next', in_flight=1, diff --git a/tests/test_inference_audit.py b/tests/test_inference_audit.py index 63e8d0f..a0adac3 100644 --- a/tests/test_inference_audit.py +++ b/tests/test_inference_audit.py @@ -49,6 +49,7 @@ async def send(self, headers, body, stream): def service_for(responses, accounts=None): cfg = Config() cfg.pool.acquire_wait_seconds = 0 + cfg.pool.concurrency_settle_seconds = 0 cfg.upstream.max_attempts = 2 cfg.upstream.overload_max_attempts = 2 pool = PoolManager(cfg.pool, accounts or [Account(id='one', access_token='dummy-one')]) diff --git a/tests/test_jwt_import.py b/tests/test_jwt_import.py index 96b088e..2c68456 100644 --- a/tests/test_jwt_import.py +++ b/tests/test_jwt_import.py @@ -78,6 +78,25 @@ def handler(request): assert client.get(f"/admin/accounts/{IDENT}/token").status_code in (401, 403) +def test_import_without_export_device_mid_assigns_a_valid_one(tmp_path, monkeypatch): + import uuid + seen = [] + + def handler(request): + seen.append(request.headers.get("x-device-mid")) + return httpx.Response(200, json={"code": 0, "data": {"plans": [], "balances": []}}) + + cfg = config(tmp_path) + with TestClient(create_app(cfg)) as client: + provider(monkeypatch, handler) + response = client.post("/admin/accounts/import-jwt", headers=HEADERS, json={"token": jwt()}) + assert response.status_code == 200, response.text + row = load_from_accounts_dir(cfg.accounts.dir)[0] + assert str(uuid.UUID(row.notes["device_mid"])) == row.notes["device_mid"] + assert row.notes["device_mid"] == seen[0] + assert row.notes["device_mid"] != cfg.upstream.fingerprint.device_mid + + @pytest.mark.parametrize("token", [None, "junk", jwt(exp=1), jwt(exp=True), jwt(sub="invalid"), jwt(exp="NaN")]) def test_import_rejects_malformed_before_provider_or_persistence(tmp_path, monkeypatch, token): with TestClient(create_app(config(tmp_path))) as client: diff --git a/tests/test_model_caps_persist.py b/tests/test_model_caps_persist.py index 970a2ef..2975b5b 100644 --- a/tests/test_model_caps_persist.py +++ b/tests/test_model_caps_persist.py @@ -1,11 +1,13 @@ """Model-cap parks (UNUSUAL_ACTIVITY / GEO_BLOCKED) survive restarts.""" import asyncio +import json import time import pytest from zcode_gateway.config import PoolConfig -from zcode_gateway.pool import Account, PoolManager +from zcode_gateway.pool import Account, AccountState, PoolManager, load_from_pool_file +from zcode_gateway.token_utils import persist_pool_states def _mgr(tmp_path, accounts): @@ -85,3 +87,21 @@ async def test_removed_account_pruned(tmp_path): import json data = json.loads((tmp_path / "model-caps.json").read_text()) assert "gone" not in data + + +@pytest.mark.asyncio +async def test_killed_account_stays_dead_in_pool_file(tmp_path): + pool_file = tmp_path / "pool.json" + pool_file.write_text(json.dumps([{"id": "acc-1", "email": "a@x.io", + "access_token": "t"}]), encoding="utf-8") + acc = load_from_pool_file(pool_file)[0] + m = _mgr(tmp_path, [acc]) + m.set_state_saver(lambda rows: persist_pool_states(pool_file, rows)) + await m.kill(acc, "banned for proxying", cause="suspended") + await _flush(m) + + # a flat file keeps its shape; a restart reads the hard state back + assert isinstance(json.loads(pool_file.read_text(encoding="utf-8")), list) + reloaded = load_from_pool_file(pool_file)[0] + assert reloaded.state is AccountState.DEAD + assert reloaded.death_reason == "suspended" diff --git a/tests/test_pr2_regressions.py b/tests/test_pr2_regressions.py index 35e7910..ff3d7a5 100644 --- a/tests/test_pr2_regressions.py +++ b/tests/test_pr2_regressions.py @@ -417,6 +417,17 @@ def request(method, url, **kwargs): assert claim._headers('token')['x-client-timezone'] == 'UTC' +def test_generator_and_gateway_derive_the_same_device_mid(monkeypatch): + import base64 + from zcode_gateway.zcode_device import account_device_mid + monkeypatch.syspath_prepend(str(ROOT / 'generator')) + pc = _load_script('plan_check') + claims = base64.urlsafe_b64encode( + json.dumps({'user_id': 'usr-123'}).encode()).decode().rstrip('=') + assert pc.account_device_mid('usr-123') == account_device_mid('usr-123') + assert pc.per_account_device_mid('header.' + claims + '.signature') == account_device_mid('usr-123') + + @pytest.mark.parametrize('script', ['export_starter', 'recheck_plans']) def test_generator_batch_continues_after_failure(tmp_path, monkeypatch, script): monkeypatch.syspath_prepend(str(ROOT / 'generator')) diff --git a/tests/test_stream_retry.py b/tests/test_stream_retry.py index 2bb753e..ff90717 100644 --- a/tests/test_stream_retry.py +++ b/tests/test_stream_retry.py @@ -43,6 +43,7 @@ def cfg(tmp_path): config.logging.capture = False config.pool.balance_poll_seconds = 0 config.pool.acquire_wait_seconds = 0 + config.pool.concurrency_settle_seconds = 0 config.server.admin_key = 'test-admin' config.server.client_keys = [ClientKey(key='test-client')] return config diff --git a/tests/test_zcode_core.py b/tests/test_zcode_core.py index dc9dec5..805414d 100644 --- a/tests/test_zcode_core.py +++ b/tests/test_zcode_core.py @@ -32,6 +32,7 @@ def cfg(tmp_path): config.pool.balance_poll_seconds=0 config.pool.acquire_wait_seconds=0 config.pool.concurrency_hold_seconds=0 + config.pool.concurrency_settle_seconds=0 config.server.admin_key='test-admin' config.server.client_keys=[ClientKey(key='test-client')] return config @@ -207,6 +208,17 @@ def unusual_activity_response(): return response +SUSPENDED_MESSAGE=('Your account has been suspended for misusing the Start Plan, ' + 'such as proxying it to non-ZCode clients.') + + +def suspended_response(): + body=json.dumps({'error':{'message':SUSPENDED_MESSAGE,'type':'api_error','code':'3012'}}).encode() + response=FakeResponse(body,405) + response.headers['content-type']='application/json' + return response + + @pytest.mark.asyncio async def test_unusual_activity_parks_model_and_rotates_accounts(service): await service.pool.upsert(Account(id='two',access_token='second-token')) @@ -245,6 +257,60 @@ async def test_unusual_activity_drives_model_fallback(service): assert service.client.calls[0][1]['model']=='GLM-5.3' assert service.client.calls[1][1]['model']=='GLM-5.3-Flash' + +@pytest.mark.asyncio +async def test_suspended_account_aborts_request_without_rotation(service): + await service.pool.upsert(Account(id='two',access_token='second-token')) + service.client=FakeClient(responses=[suspended_response(),FakeResponse(sample_sse())]) + with pytest.raises(UpstreamFailure) as err: + await service.complete({'model':'GLM-5.3','messages':[{'role':'user','content':'hi'}]},model='GLM-5.3') + assert err.value.status==405 + assert len(service.client.calls)==1 + killed=await service.pool.find('one') + spare=await service.pool.find('two') + assert killed.state is AccountState.DEAD and killed.death_reason=='suspended' + assert spare.state is AccountState.READY and spare.in_flight==0 + + +@pytest.mark.asyncio +async def test_suspension_logs_upstream_text(service, caplog): + service.client=FakeClient(responses=[suspended_response()]) + with caplog.at_level('WARNING', logger='zcode_gateway.service'): + with pytest.raises(UpstreamFailure): + await service.complete({'model':'GLM-5.3','messages':[{'role':'user','content':'hi'}]},model='GLM-5.3') + text='\n'.join(record.getMessage() for record in caplog.records) + assert 'SUSPENDED' in text and 'misusing the Start Plan' in text and 'one' in text + + +@pytest.mark.asyncio +async def test_accounts_without_device_mid_get_distinct_mids(service): + import uuid + await service.pool.upsert(Account(id='two',access_token='second-token')) + service.client=FakeClient(responses=[FakeResponse(sample_sse()),FakeResponse(sample_sse())]) + for ident in ('one','two'): + result=await service.complete({'model':'GLM-5.3','messages':[{'role':'user','content':'hi'}], + 'account':ident},model='GLM-5.3') + assert result.status==200 + mids=[json.loads(body['metadata']['user_id'])['device_id'] for _,body in service.client.calls] + assert len(mids)==2 and mids[0]!=mids[1] + assert all(str(uuid.UUID(mid))==mid for mid in mids) + assert service.cfg.upstream.fingerprint.device_mid not in mids + + +@pytest.mark.asyncio +async def test_account_timezone_overrides_config_default(service): + account=await service.pool.find('one') + account.notes['timezone']='Asia/Tehran' + service.client=FakeClient() + assert (await service.complete({'model':'GLM-5.3','messages':[{'role':'user','content':'hi'}]}, + model='GLM-5.3')).status==200 + assert service.client.calls[0][0]['x-client-timezone']=='Asia/Tehran' + account.notes.pop('timezone') + service.client=FakeClient() + assert (await service.complete({'model':'GLM-5.3','messages':[{'role':'user','content':'hi'}]}, + model='GLM-5.3')).status==200 + assert service.client.calls[0][0]['x-client-timezone']==service.cfg.upstream.fingerprint.timezone + def test_import_all_coding_plan_jwts_excludes_api_keys(tmp_path): import base64 from zcode_gateway.zcode_accounts import read_credentials, import_credentials @@ -596,6 +662,7 @@ async def wait(delay, disconnected=None): waits.append(delay) @pytest.mark.asyncio async def test_concurrency_refusals_do_not_kill_burst_of_sessions(cfg): cfg.pool.concurrency_hold_seconds=30 + cfg.pool.concurrency_settle_seconds=0 cfg.pool.acquire_wait_seconds=2 cfg.upstream.concurrency_base_delay_seconds=0 cfg.upstream.max_attempts=3 @@ -666,6 +733,90 @@ async def test_midstream_concurrency_error_benches_account(service): assert not account.model_caps +@pytest.mark.asyncio +async def test_settle_window_blocks_instant_reacquire_but_queue_serves(cfg, monkeypatch): + """The core regression the settle window fixes: a released account must + not be handed out again immediately, but a queued waiter gets it the + moment the settle window passes — no 3008, no failure.""" + cfg.pool.concurrency_settle_seconds=0.2 + cfg.pool.acquire_wait_seconds=5 + pool=PoolManager(cfg.pool,[Account(id='one',access_token='test-token')]) + store=Store(cfg.store.sqlite_path) + class FakeTokens: + async def refresh(self, account, force=False, *, expected_credentials=None): return False + svc=ChatService(cfg,pool,FakeTokens(),FakeClient(),Registry(),store,JsonlCapture(cfg.logging.capture_dir,False)) + try: + # first call succeeds, releasing with the settle window armed; + # second call must wait out the window and still succeed + svc.client=FakeClient(responses=[FakeResponse(sample_sse()),FakeResponse(sample_sse())]) + first=await svc.complete({'messages':[{'role':'user','content':'hi'}]}, model='GLM-5.3') + assert first.status==200 + assert pool._accounts['one'].is_settling() + second=await svc.complete({'messages':[{'role':'user','content':'hi'}]}, model='GLM-5.3') + assert second.status==200 and len(svc.client.calls)==2 + assert pool._accounts['one'].in_flight==0 + finally: + store.close() + + +@pytest.mark.asyncio +async def test_settle_window_with_two_accounts_avoids_the_bench_entirely(cfg, monkeypatch): + """With a second account available, a just-released account is skipped in + favor of the idle one — the refusal-prone pattern never happens.""" + cfg.pool.concurrency_settle_seconds=30 + cfg.pool.strategy='least_recently_used' + pool=PoolManager(cfg.pool,[Account(id='one',access_token='t-one'), + Account(id='two',access_token='t-two')]) + store=Store(cfg.store.sqlite_path) + class FakeTokens: + async def refresh(self, account, force=False, *, expected_credentials=None): return False + svc=ChatService(cfg,pool,FakeTokens(),FakeClient(),Registry(),store,JsonlCapture(cfg.logging.capture_dir,False)) + try: + svc.client=FakeClient(responses=[FakeResponse(sample_sse()),FakeResponse(sample_sse())]) + first=await svc.complete({'messages':[{'role':'user','content':'hi'}]}, model='GLM-5.3') + assert first.status==200 + # 'one' just served and is settling; the next request must go to 'two' + # WITHOUT any 3008 round-trip + second=await svc.complete({'messages':[{'role':'user','content':'hi'}]}, model='GLM-5.3') + assert second.status==200 + assert [call[0]['authorization'] for call in svc.client.calls]==['Bearer t-one','Bearer t-two'] + assert pool._accounts['one'].concurrency_strikes==0 + assert pool._accounts['two'].concurrency_strikes==0 + finally: + store.close() + + +@pytest.mark.asyncio +async def test_refusal_strikes_decay_so_idle_accounts_recover(cfg): + """End-to-end decay through the real request path: a 3008 refusal banks a + strike (mirrors the production hold config); the decay math itself is + covered pool-level in test_acquire_wait.""" + cfg.pool.concurrency_hold_seconds=10 + cfg.pool.concurrency_hold_max_seconds=60 + cfg.pool.acquire_wait_seconds=0.5 + pool=PoolManager(cfg.pool,[Account(id='one',access_token='test-token')]) + store=Store(cfg.store.sqlite_path) + class FakeTokens: + async def refresh(self, account, force=False, *, expected_credentials=None): return False + svc=ChatService(cfg,pool,FakeTokens(),FakeClient(),Registry(),store,JsonlCapture(cfg.logging.capture_dir,False)) + try: + svc.client=FakeClient(responses=[concurrency_response()]) + # real request path banks the strike: the 3008 benches the account + # (with a single account the retry then fails fast on the hold — + # multi-account rotation is covered by the burst test above) + with pytest.raises((UpstreamFailure, NoAccountsAvailable)): + await svc.open_stream({'messages':[{'role':'user','content':'hi'}]}, model='GLM-5.3') + one=pool._accounts['one'] + assert one.concurrency_strikes==1 and one.is_concurrency_held() + # quiet gap longer than the max hold decays the escalation + one.concurrency_hold_until=time.time()-61 + await pool.on_concurrency_refusal(one) + hold=one.concurrency_hold_until-time.time() + assert one.concurrency_strikes==2 and hold<=20.0 + finally: + store.close() + + @pytest.mark.asyncio async def test_midstream_concurrency_error_is_429_without_cooling(service): events=sample_events() diff --git a/tests/test_zcode_device.py b/tests/test_zcode_device.py index 6314e4a..f98f8f7 100644 --- a/tests/test_zcode_device.py +++ b/tests/test_zcode_device.py @@ -28,3 +28,15 @@ def test_default_device_uses_saved_identity_or_uuid(monkeypatch): assert zcode_device.default_device_mid()=='saved-device' monkeypatch.setattr(zcode_device,'read_device_mid',lambda:None) assert str(uuid.UUID(zcode_device.default_device_mid())) + + +def test_new_account_device_mid_is_a_distinct_uuid(): + first, second = zcode_device.new_account_device_mid(), zcode_device.new_account_device_mid() + assert str(uuid.UUID(first)) == first + assert str(uuid.UUID(second)) == second + assert first != second + + +def test_account_device_mid_is_stable_per_account(): + assert zcode_device.account_device_mid('usr-one') == zcode_device.account_device_mid('usr-one') + assert zcode_device.account_device_mid('usr-one') != zcode_device.account_device_mid('usr-two') diff --git a/zcode_gateway/accounts_dir.py b/zcode_gateway/accounts_dir.py index 0b5438c..73d0045 100644 --- a/zcode_gateway/accounts_dir.py +++ b/zcode_gateway/accounts_dir.py @@ -27,7 +27,7 @@ from datetime import datetime, timezone from pathlib import Path -from .pool import Account +from .pool import Account, _restore_hard_state log = logging.getLogger("zcode_gateway.accounts_dir") @@ -224,10 +224,12 @@ def _to_account(fields: dict[str, str], path: Path) -> Account | None: "workos_user_id": fields.get("workos_user_id", ""), "file": path.name, "device_mid": fields.get("device_mid", ""), + "timezone": fields.get("timezone", ""), "auto_run_id": fields.get("auto_run_id", ""), "auto_attempt_id": fields.get("auto_attempt_id", ""), "imported_jwt": fields.get("imported_jwt") == "true" or fields.get("source") == "Manual JWT import", } + _restore_hard_state(account, fields) return account @@ -279,6 +281,7 @@ def write_snapshot(path: Path, fields: dict[str, str]) -> None: "issuer", "client_id", "", "balance_micro", "balance_usd", "plan", "", "access_token", "refresh_token", + "", "state", "death_reason", "paid_exhausted", "cooldown_until", "timezone", ] lines = ["# Zcode account snapshot"] for key in order: @@ -304,3 +307,35 @@ def write_snapshot(path: Path, fields: dict[str, str]) -> None: os.replace(tmp, path) finally: tmp.unlink(missing_ok=True) + + +def persist_account_states(directory: str | Path, rows: list[dict]) -> None: + """Write hard-state fields into the matching snapshots. + + The LIVE source is a folder of files, not pool.json: without this a + restart re-reads a banned account as READY. Files whose fields already + match are left untouched. + """ + by_id = {str(row["id"]): row for row in rows} + with snapshot_transaction(directory) as folder: + for path in sorted(folder.iterdir()): + if path.suffix.casefold() != ".txt" or not path.is_file() or path.is_symlink(): + continue + try: + fields = parse_snapshot(path) + except Exception: + continue + ident = fields.get("account_id") or fields.get("zcode_user_id") or path.stem + row = by_id.get(str(ident)) + if row is None: + continue + update = { + "state": str(row["state"]), + "death_reason": str(row["death_reason"] or ""), + "paid_exhausted": "true" if row["paid_exhausted"] else "false", + "cooldown_until": f"{float(row['cooldown_until']):.6f}", + } + if all(fields.get(key, "") == value for key, value in update.items()): + continue + fields.update(update) + write_snapshot(path, fields) diff --git a/zcode_gateway/accounts_dir_bridge.py b/zcode_gateway/accounts_dir_bridge.py index 16cac4d..2694695 100644 --- a/zcode_gateway/accounts_dir_bridge.py +++ b/zcode_gateway/accounts_dir_bridge.py @@ -17,6 +17,7 @@ snapshot_filename, write_snapshot, ) +from .zcode_device import account_device_mid log = logging.getLogger("zcode_gateway.accounts_dir_bridge") @@ -61,6 +62,9 @@ def mint_and_register(accounts_dir: str | Path, email: str, zcode_jwt: str, saved: dict[str, str] = {} def write_saved(path, fields): + # a re-registration keeps the mid the account already had; a new + # account gets the derived one, never the global fingerprint + fields["device_mid"] = fields.get("device_mid") or account_device_mid(account_id) _write_snapshot(path, fields) saved.update(fields) @@ -70,8 +74,10 @@ def write_saved(path, fields): "account_id": account_id, "access_token": zcode_jwt, "expires_at_ms": str(expires_ms), - "email": email, "device_mid": device_mid, "plan": plan, + "email": email, "plan": plan, } + if device_mid: + fields["device_mid"] = device_mid if claims.get("exp"): fields["expires_at"] = str(claims["exp"]) if receipt: diff --git a/zcode_gateway/api_admin.py b/zcode_gateway/api_admin.py index 1505ab1..271f010 100644 --- a/zcode_gateway/api_admin.py +++ b/zcode_gateway/api_admin.py @@ -6,6 +6,7 @@ import logging import json import math +import re import time import uuid @@ -19,6 +20,7 @@ from .deps import admin_key, get_state from .pool import Account, load_accounts from .tokens import _parse_expiry, persist_pool_snapshot +from .zcode_device import new_account_device_mid log = logging.getLogger("zcode_gateway.admin") @@ -197,9 +199,14 @@ async def import_jwt_account(request: Request, body: dict[str, Any] = Body(...), raise HTTPException(400, "Invalid email label") name = bundle.get("name", "") if bundle else "" device = bundle.get("device_mid", "") if bundle else "" + timezone = bundle.get("timezone", "") if bundle else "" if any(not isinstance(v, str) or len(v) > 254 or any(ord(c) < 32 or ord(c) == 127 for c in v) - for v in (name, device)): + for v in (name, device, timezone)): raise HTTPException(400, "Invalid account export metadata") + if timezone and not re.fullmatch(r"[\w/+_-]{1,64}", timezone): + raise HTTPException(400, "Invalid account export metadata") + bundle_device = device + device = device or new_account_device_mid() if state.cfg.accounts.source not in ("accounts_dir", "pool_file"): raise HTTPException(409, "Account import requires Accounts source: Accounts folder or Pool file") # Decoding a JWT is not signature validation. Require the configured Zcode @@ -211,7 +218,7 @@ async def import_jwt_account(request: Request, body: dict[str, Any] = Body(...), response = await client.get( state.cfg.upstream.base_url.rstrip("/") + "/zcode-plan/billing/balance", params={"app_version": state.cfg.upstream.fingerprint.client_version}, - headers=build_headers(token, state.cfg.upstream.fingerprint, device_mid=device or None)) + headers=build_headers(token, state.cfg.upstream.fingerprint, device_mid=device)) if response.status_code in (401, 403): raise HTTPException(400, "Zcode rejected this token") response.raise_for_status() @@ -231,12 +238,17 @@ async def import_jwt_account(request: Request, body: dict[str, Any] = Body(...), async with state.account_persist_lock, state.tokens._lock_for(ident): existing = await state.pool.find(ident) email = email or (existing.email if existing else "") + if not bundle_device and existing is not None: + device = existing.notes.get("device_mid") or device + if not timezone and existing is not None: + timezone = existing.notes.get("timezone", "") account = Account(id=ident, email=email, access_token=token, refresh_token=existing.refresh_token if existing else "", expires_at=int(expiry * 1000), source="jwt-import", notes={"name": name or (existing.notes.get("name", "") if existing else ""), "imported_jwt": True}) - if device: - account.notes["device_mid"] = device + account.notes["device_mid"] = device + if timezone: + account.notes["timezone"] = timezone account.notes.update(plans=plans, quotas=quotas, quota_check_attempted_at=time.time()) account.balance_checked_at = time.time() account.plan_checked_at = account.balance_checked_at @@ -246,9 +258,10 @@ async def import_jwt_account(request: Request, body: dict[str, Any] = Body(...), folder = Path(state.cfg.accounts.dir) fields = dict(account_id=ident, email=email, name=account.notes["name"], access_token=token, expires_at_ms=str(account.expires_at), - source="Manual JWT import", imported_jwt="true") - if device: - fields["device_mid"] = device + source="Manual JWT import", imported_jwt="true", + device_mid=device) + if timezone: + fields["timezone"] = timezone path = await asyncio.to_thread(save_account_snapshot, folder, fields) account.notes["file"] = path.name else: @@ -295,6 +308,8 @@ async def export_account(request: Request, account_id: str, "name": account.notes.get("name", ""), "device_mid": account.notes.get("device_mid", ""), "access_token": account.access_token, "expires_at_ms": account.expires_at} + if account.notes.get("timezone"): + bundle["timezone"] = account.notes["timezone"] return JSONResponse(bundle, headers={"Cache-Control": "no-store, private", "Pragma": "no-cache"}) diff --git a/zcode_gateway/api_dash.py b/zcode_gateway/api_dash.py index 7ed8113..2181faf 100644 --- a/zcode_gateway/api_dash.py +++ b/zcode_gateway/api_dash.py @@ -26,6 +26,8 @@ from .deps import admin_key, get_state, internal_or_admin from .logbuffer import LogBuffer +from .zcode_detect import jwt_claims +from .zcode_device import account_device_mid log = logging.getLogger("zcode_gateway.dash") @@ -1117,14 +1119,13 @@ def cancelled_result(): log.info("generator: %s has no plan after retries — leaving " "it for the catch-up scan", email) return + identity = jwt_claims(zjwt) if auto: from plan_check import is_start_plan if not plan_info or plan_info.get("code") != 0 or not any(is_start_plan(p) for p in plans): return {"qualified": False, "category": "no_plan", "error": "No active Starter/Start Plan verified"} # The run must count a NEW provider identity, not a duplicate # token for an account already loaded before registration. - from .zcode_detect import jwt_claims - identity = jwt_claims(zjwt) ident = identity.get("user_id") or identity.get("sub") if not ident: return {"qualified": False, "category": "registration_error", "error": "Account identity missing"} @@ -1147,7 +1148,7 @@ def cancelled_result(): receipt = {"auto_run_id": run_id, "auto_attempt_id": attempt_id, "auto_qualified": "true"} account = mint_and_register( state.cfg.accounts.dir, email, zjwt, - state.cfg.upstream.fingerprint.device_mid, + account_device_mid(identity.get("user_id") or identity.get("sub") or email), plan=chosen_plan, **({"receipt": receipt} if auto else {})) if account: log.info("generator: %s joined the pool (plan=%s)", email, chosen_plan) diff --git a/zcode_gateway/app.py b/zcode_gateway/app.py index d2ad4d0..0818355 100644 --- a/zcode_gateway/app.py +++ b/zcode_gateway/app.py @@ -83,6 +83,16 @@ async def lifespan(app: FastAPI): pool.load_caps() except Exception: log.warning("model-cap persistence unavailable", exc_info=True) + # hard state (DEAD / EXHAUSTED) must reach the live source, or a restart + # resurrects a banned account as READY + if cfg.accounts.source == "accounts_dir": + from .accounts_dir import persist_account_states + pool.set_state_saver( + lambda rows: persist_account_states(cfg.accounts.dir, rows)) + elif cfg.accounts.source == "pool_file": + from .token_utils import persist_pool_states + pool.set_state_saver( + lambda rows: persist_pool_states(cfg.accounts.pool_file, rows)) tokens = TokenManager(cfg, pool) client = UpstreamClient(cfg.upstream, relay_manager=relay_manager, pacing=cfg.models.pacing) diff --git a/zcode_gateway/config.py b/zcode_gateway/config.py index afd2bb9..14e41a0 100644 --- a/zcode_gateway/config.py +++ b/zcode_gateway/config.py @@ -255,6 +255,11 @@ class PoolConfig(BaseModel): # saturated slot. Not a cooldown: state stays READY. concurrency_hold_seconds: float = Field(default=10.0, ge=0) concurrency_hold_max_seconds: float = Field(default=60.0, ge=0) + # The upstream keeps a just-finished request in its per-user concurrency + # count for a few seconds, so re-admitting a released account immediately + # answers 3008 even though in_flight is 0. After release(), wait this long + # before pick() hands the account out again. 0 disables it. + concurrency_settle_seconds: float = Field(default=5.0, ge=0) balance_poll_seconds: int = Field(default=300, ge=10) # 405/code 3012 "unusual activity": park this model on the offending # account for this long, then rotate. Per model, so other models on the diff --git a/zcode_gateway/dashboard/assets/js/views/accounts.js b/zcode_gateway/dashboard/assets/js/views/accounts.js index 7e1cb47..43304f7 100644 --- a/zcode_gateway/dashboard/assets/js/views/accounts.js +++ b/zcode_gateway/dashboard/assets/js/views/accounts.js @@ -116,12 +116,19 @@ function stateCell(a) { const parts = [stateBadge(a.state)]; const hold = Number(a.concurrency_hold_in_s) || 0; const cooldown = Number(a.cooldown_in_s) || 0; + const settling = Number(a.settling_in_s) || 0; if (hold > 0) { parts.push(el("div", { class: "faint text-xs", text: "throttled " + duration(hold), title: "Upstream refused a parallel request on this account (3008). " + "It is benched briefly and returns automatically.", })); + } else if (settling > 0 && a.in_flight === 0) { + parts.push(el("div", { + class: "faint text-xs", text: "settling " + duration(settling), + title: "Just served a request; briefly held out so upstream's concurrency " + + "count clears before the next one. Not an error.", + })); } else if (a.state === "cooling" && cooldown > 0) { parts.push(el("div", { class: "faint text-xs", text: "retry in " + duration(cooldown), @@ -209,6 +216,14 @@ function accountIssue(a) { detail: "Upstream reported a concurrency limit (3008); retries resume on their own.", }; } + const settling = Number(a.settling_in_s) || 0; + if (settling > 0 && a.in_flight === 0) { + return { + tone: "info", label: "Settling " + duration(settling), + detail: "Just served a request; held out briefly so upstream's concurrency " + + "count clears before the next one. Not an error.", + }; + } if (a.state === "cooling") { return { tone: "warn", label: "Cooling " + duration(a.cooldown_in_s), @@ -462,7 +477,11 @@ function render(root, accounts, pool, reload, batch, signal, campaign = {}) { : "Locked until the Weekend Build window opens"; const counts = pool.by_state || {}; - const issueCount = accounts.filter((a) => accountIssue(a)).length; + // settling is a planned pause, not a problem: keep it out of the Issues count + const issueCount = accounts.filter((a) => { + const issue = accountIssue(a); + return issue && !(issue.tone === "info"); + }).length; const summary = el("div", { class: "grid grid--metrics" }, [ metric({ label: "Accounts", value: num(pool.accounts ?? rows.length) }), metric({ label: "Ready", value: num(pool.ready ?? 0), tone: (pool.ready ?? 0) > 0 ? "ok" : "warn" }), diff --git a/zcode_gateway/device_auth.py b/zcode_gateway/device_auth.py index 59a044a..5e17187 100644 --- a/zcode_gateway/device_auth.py +++ b/zcode_gateway/device_auth.py @@ -10,6 +10,7 @@ from .pool import Account from .upstream import build_headers from .zcode_detect import jwt_claims +from .zcode_device import new_account_device_mid class DeviceLogin: def __init__(self, accounts_dir: Path, client=None, on_account=None, base_url='https://zcode.z.ai/api/v1', fingerprint=None): @@ -22,6 +23,9 @@ def __init__(self, accounts_dir: Path, client=None, on_account=None, base_url='h self._ready, self._cancel = asyncio.Event(), asyncio.Event() self._poll_token, self._flow_id = None, None self._expires_at, self._interval = 0, 2 + # one stable identity for this login: OAuth init/poll and the account + # this login registers must present the same device + self._device_mid = new_account_device_mid() def status(self): return {'state': self.state, 'user_code': self.user_code, 'verification_url': self.verification_url, @@ -31,7 +35,8 @@ def cancel(self): self._cancel.set() async def _authorize(self): self._poll_token = secrets.token_hex(32) - headers = build_headers(self._poll_token, self.fingerprint) + headers = build_headers(self._poll_token, self.fingerprint, + device_mid=self._device_mid) headers.pop('x-api-key', None) resp = await self.client.post(self.base_url+'/oauth/cli/init', json={'provider': 'zai'}, headers=headers) @@ -60,7 +65,8 @@ async def _poll(self): if self._cancel.is_set(): self.state = 'cancelled' return None - headers = build_headers(self._poll_token, self.fingerprint) + headers = build_headers(self._poll_token, self.fingerprint, + device_mid=self._device_mid) headers.pop('x-api-key', None) resp = await self.client.get(self.base_url+'/oauth/cli/poll/'+quote(self._flow_id, safe=''), headers=headers) resp.raise_for_status() @@ -86,18 +92,21 @@ async def _register(self, data): if not ident: raise ValueError('ZCode login returned no account identity') account = Account(id=ident, email=user.get('email', ''), access_token=token, expires_at=int(claims.get('exp') or 0)*1000, source='device-login', - notes={'name': user.get('name', ''), 'device_mid': self.fingerprint.device_mid}) + notes={'name': user.get('name', ''), 'device_mid': self._device_mid}) fields = {} def write_saved(path, merged): + # a re-login keeps the mid its account already had + merged['device_mid'] = merged.get('device_mid') or self._device_mid write_snapshot(path, merged) fields.update(merged) self.snapshot_path = await asyncio.to_thread(save_account_snapshot, self.accounts_dir, {'account_id': ident, 'email': account.email, 'name': user.get('name', ''), 'access_token': token, 'expires_at_ms': str(account.expires_at), - 'device_mid': self.fingerprint.device_mid, 'source': 'ZCode CLI OAuth'}, + 'source': 'ZCode CLI OAuth'}, writer=write_saved) + self._device_mid = fields.get('device_mid') or self._device_mid account.email = fields.get('email', account.email) account.refresh_token = fields.get('refresh_token', '') account.notes.update({key: fields.get(key, '') for key in ( diff --git a/zcode_gateway/pool.py b/zcode_gateway/pool.py index d0f4959..c3189f2 100644 --- a/zcode_gateway/pool.py +++ b/zcode_gateway/pool.py @@ -74,8 +74,19 @@ class Account: # state stays READY and no quota/model park is applied, but pick() skips the # account until the hold expires so retries stop hammering a slot upstream # still counts as busy. Doubles per consecutive refusal, cleared by success. + # Strikes decay: a refusal that arrives after the previous hold has already + # expired counts the escalation from near the base again, so a burst of + # refusals spread over minutes cannot bench an account for the max hold + # forever (live: one account reached strike 13 / 120s holds on 3008s that + # each cleared seconds later). concurrency_hold_until: float = 0.0 concurrency_strikes: int = 0 + # Settle window: upstream keeps a just-finished request in its per-user + # concurrency count briefly after the stream ends, so a released account + # re-admitted at once answers 3008 with in_flight already 0 (observed live: + # refusals landing on idle accounts seconds after their last request). + # release() marks settled_until; pick() skips the account until it passes. + settled_until: float = 0.0 # Credit exhaustion is per model-class, not per account: a paid model can 402 # (insufficient_credits) while zcode-free/* models keep working on the same @@ -129,6 +140,9 @@ def is_model_capped(self, model: str, now: float | None = None) -> bool: def is_concurrency_held(self, now: float | None = None) -> bool: return self.concurrency_hold_until > (time.time() if now is None else now) + def is_settling(self, now: float | None = None) -> bool: + return self.settled_until > (time.time() if now is None else now) + @property def is_free_tier(self) -> bool: return False # credential-level; free/paid is per-model, kept for future use @@ -206,6 +220,8 @@ def to_public(self) -> dict: "concurrency_strikes": self.concurrency_strikes, "concurrency_hold_until": self.concurrency_hold_until, "concurrency_hold_in_s": int(max(self.concurrency_hold_until - now, 0)), + "settled_until": self.settled_until, + "settling_in_s": int(max(self.settled_until - now, 0)), "balance_micro": self.balance_micro, "balance_checked_at": self.balance_checked_at, "quota_check_attempted_at": self.notes.get("quota_check_attempted_at"), @@ -244,7 +260,7 @@ def to_public(self) -> dict: def _account_from_auth(auth: dict, ident: str, source: str) -> Account: meta = (auth.get("metadata") or {}).get("userInfo") or {} - return Account( + account = Account( id=auth.get("accountId") or ident, email=meta.get("email", ""), access_token=auth.get("accessToken", ""), @@ -252,6 +268,8 @@ def _account_from_auth(auth: dict, ident: str, source: str) -> Account: expires_at=_expiry_ms(auth.get("expiresAt")), source=source, ) + _restore_hard_state(account, auth) + return account def _expiry_ms(value) -> int: @@ -264,6 +282,40 @@ def _expiry_ms(value) -> int: return _parse_expiry(value) +def _as_bool(value) -> bool: + if isinstance(value, bool): + return value + return str(value or "").strip().lower() in ("1", "true", "yes") + + +def _restore_hard_state(account: Account, item: dict, now: float | None = None) -> None: + """Re-apply only the states a restart must not forget. + + DEAD and EXHAUSTED are account-level and last until an operator acts; + COOLING is transient and survives only while its window is still running. + Anything else — including a corrupt value — falls back to READY: a bad + file must never strand an account in a state no request can leave. + """ + now = time.time() if now is None else now + try: + state = AccountState(str(item.get("state") or "").strip().lower()) + except ValueError: + state = AccountState.READY + if state in (AccountState.DEAD, AccountState.EXHAUSTED): + account.state = state + account.death_reason = str(item.get("death_reason") or "")[:200] + elif state is AccountState.COOLING: + try: + until = float(item.get("cooldown_until") or 0) + except (TypeError, ValueError): + until = 0.0 + if until > now: + account.state = AccountState.COOLING + account.cooldown_until = until + if "paid_exhausted" in item: + account.paid_exhausted = _as_bool(item.get("paid_exhausted")) + + def load_from_providers_json(path: str) -> list[Account]: """Read ZCode's credentials.json or the supplied tokens.json extract.""" from .zcode_accounts import read_credentials @@ -283,10 +335,12 @@ def load_from_pool_file(path: str) -> list[Account]: out: list[Account] = [] for i, item in enumerate(raw or []): if "auth" in item: - out.append(_account_from_auth(item["auth"], item.get("id", f"pool-{i}"), - "pool.json")) + account = _account_from_auth(item["auth"], item.get("id", f"pool-{i}"), + "pool.json") + _restore_hard_state(account, item) + out.append(account) else: - out.append(Account( + account = Account( id=item.get("id") or f"pool-{i}", email=item.get("email", ""), access_token=item.get("access_token") or item.get("accessToken", ""), @@ -294,8 +348,11 @@ def load_from_pool_file(path: str) -> list[Account]: expires_at=_expiry_ms(item.get("expires_at") or item.get("expiresAt")), source="pool.json", notes={"imported_jwt": bool(item.get("imported_jwt") or item.get("source") == "jwt-import"), - "name": item.get("name", ""), "device_mid": item.get("device_mid", "")}, - )) + "name": item.get("name", ""), "device_mid": item.get("device_mid", ""), + "timezone": item.get("timezone", "")}, + ) + _restore_hard_state(account, item) + out.append(account) return out @@ -374,9 +431,11 @@ def pick(self, accounts: list[Account]) -> Account | None: now = time.time() # Held accounts stay in candidates() so acquire() knows the pool is # saturated (and waits) rather than absent — but they are not pickable - # until the hold expires. + # until the hold expires. Settling accounts likewise: released seconds + # ago, upstream still counts the finished request as busy. under_cap = [a for a in accounts - if a.in_flight < cap and not a.is_concurrency_held(now)] + if a.in_flight < cap and not a.is_concurrency_held(now) + and not a.is_settling(now)] if not under_cap: # The configured cap must be a cap, not a preference: when every # candidate is saturated, report no candidate. The manager waits @@ -434,6 +493,15 @@ def __init__(self, cfg: PoolConfig, accounts: list[Account]) -> None: self._caps_io_lock = threading.Lock() self._caps_close_lock = asyncio.Lock() self._caps_closing = False + # debounced hard-state persistence (see _schedule_state_save): DEAD / + # EXHAUSTED must reach the live account source or a restart resurrects + # a banned account as READY + self._state_saver = None + self._state_dirty = False + self._state_save_task: asyncio.Task | None = None + self._state_write_task: asyncio.Task | None = None + self._state_io_lock = threading.Lock() + self._state_closing = False # notification center (attached in app setup); pool events worth a # human's attention go through here, safe from any thread self._notify = None @@ -445,6 +513,7 @@ async def aclose(self) -> None: """Join the actual disk writer before flushing the latest snapshot.""" async with self._caps_close_lock: self._caps_closing = True + self._state_closing = True task = self._caps_save_task if task is not None and not task.done(): task.cancel() @@ -458,6 +527,19 @@ async def aclose(self) -> None: while self._caps_dirty and self.caps_path: if not await self._flush_caps(): break + task = self._state_save_task + if task is not None and not task.done(): + task.cancel() + try: + await task + except asyncio.CancelledError: + pass + if self._state_write_task is not None: + if not await asyncio.shield(self._state_write_task): + self._state_dirty = True + while self._state_dirty and self._state_saver: + if not await self._flush_state(): + break def notify(self, category: str, message: str, level: str = "info") -> None: """Emit a dashboard notification if a center is attached. Never raises.""" @@ -597,6 +679,78 @@ def _save_caps(self) -> None: out = self._caps_snapshot() self._write_caps_snapshot(out) + _STATE_SAVE_DEBOUNCE_S = 5.0 + + def set_state_saver(self, saver) -> None: + """Point hard-state persistence at the configured account source.""" + self._state_saver = saver + + def _schedule_state_save(self) -> None: + """Debounced, off-loop write of DEAD/EXHAUSTED to the live source.""" + self._state_dirty = True + if self._state_closing: + return + task = self._state_save_task + if task is not None and not task.done(): + return + self._state_save_task = asyncio.get_running_loop().create_task( + self._state_save_later()) + + async def _state_save_later(self) -> None: + try: + while True: + await asyncio.sleep(self._STATE_SAVE_DEBOUNCE_S) + if not self._state_dirty or self._state_saver is None: + return + if not await self._flush_state(): + return + except asyncio.CancelledError: + raise + except Exception: + self._state_dirty = True + log.debug("debounced account-state save failed", exc_info=True) + + async def _flush_state(self) -> bool: + if self._state_write_task is not None: + if not await asyncio.shield(self._state_write_task): + self._state_dirty = True + async with self._lock: + self._state_dirty = False + out = self._state_snapshot() + self._state_write_task = asyncio.create_task( + asyncio.to_thread(self._write_state_snapshot, out)) + ok = await asyncio.shield(self._state_write_task) + if not ok: + self._state_dirty = True + return ok + + def _state_snapshot(self) -> list[dict]: + """Hard-state rows for every account. Caller holds the lock.""" + now = time.time() + out = [] + for acc in self._accounts.values(): + state = acc.state.value + if acc.state is AccountState.COOLING and acc.cooldown_until <= now: + state = AccountState.READY.value + out.append({"id": acc.id, "state": state, + "death_reason": acc.death_reason, + "paid_exhausted": bool(acc.paid_exhausted), + "cooldown_until": float(acc.cooldown_until)}) + return out + + def _write_state_snapshot(self, rows: list[dict]) -> bool: + """Returns False when the write failed so the debounced saver retries.""" + saver = self._state_saver + if saver is None: + return True + try: + with self._state_io_lock: + saver(rows) + return True + except Exception: + log.debug("could not persist account state", exc_info=True) + return False + # -- access ---------------------------------------------------------- # async def all(self) -> list[Account]: @@ -820,6 +974,10 @@ async def parked_reason(self, model: str) -> dict | None: async def release(self, account: Account) -> None: async with self._lock: account.in_flight = max(0, account.in_flight - 1) + settle = self.cfg.concurrency_settle_seconds + if settle > 0: + account.settled_until = max(account.settled_until, + time.time() + settle) self._slot_gen += 1 # wake acquire() waiters # -- state transitions ----------------------------------------------- # @@ -851,6 +1009,13 @@ async def on_concurrency_refusal(self, account: Account, *, if expected_credentials is not None and (self._accounts.get(account.id) is not account or account.credential_key() != expected_credentials): return + # Strike decay: escalation only makes sense while failures chain. + # If the previous hold already expired (minutes of quiet, no + # success to clear the counter), the next refusal starts from + # near the base again instead of stacking on banked strikes. + quiet_s = time.time() - account.concurrency_hold_until + if account.concurrency_strikes > 1 and quiet_s > self.cfg.concurrency_hold_max_seconds: + account.concurrency_strikes = 1 account.concurrency_strikes += 1 base = self.cfg.concurrency_hold_seconds if base <= 0: @@ -920,6 +1085,7 @@ async def retire(self, account: Account, reason: str = "insufficient_credits", account.state = AccountState.READY else: account.state = AccountState.EXHAUSTED + self._schedule_state_save() async def kill(self, account: Account, reason: str = "", *, cause: str = "", expected_credentials: tuple | None = None) -> bool: @@ -936,6 +1102,7 @@ async def kill(self, account: Account, reason: str = "", *, cause: str = "", account.error_history.append( {'ts': time.time(), 'status': None, 'code': cause, 'message': reason, 'state': 'dead'}) + self._schedule_state_save() self.notify('account_dead', f"account {account.id} marked DEAD — {reason}", level='error') @@ -963,7 +1130,8 @@ async def kill_after_strikes(self, account: Account, reason: str = "", account.last_error = reason return account.auth_strikes = n - if n >= strikes: + killed = n >= strikes + if killed: account.state = AccountState.DEAD account.death_reason = reason or 'authentication_error' account.last_error = reason @@ -981,6 +1149,8 @@ async def kill_after_strikes(self, account: Account, reason: str = "", account.error_history.append( {"ts": time.time(), "status": 401, "code": f"auth_strike_{n}", "message": reason, "state": "cooling"}) + if killed: + self._schedule_state_save() async def auth_failed(self, account: Account, reason: str = "", *, expected_credentials: tuple | None = None) -> None: @@ -1000,7 +1170,8 @@ async def enable(self, account_id: str) -> bool: acc.last_error = "" acc.auth_strikes = 0 acc.quota_strikes = 0 - return True + self._schedule_state_save() + return True async def upsert(self, account: Account) -> None: """Insert or UPDATE-IN-PLACE. @@ -1075,7 +1246,8 @@ def _affine_candidate(self, candidates: list[Account], affinity_key: str) -> Acc cap = self.cfg.max_in_flight_per_account for account in candidates: if (account.id == bound and (cap <= 0 or account.in_flight < cap) - and not account.is_concurrency_held()): + and not account.is_concurrency_held() + and not account.is_settling()): return account return None diff --git a/zcode_gateway/service.py b/zcode_gateway/service.py index ce88270..efb3165 100644 --- a/zcode_gateway/service.py +++ b/zcode_gateway/service.py @@ -14,7 +14,7 @@ import anyio from .aggregate import aggregate_openai_stream from .affinity import affinity_key_from_payload -from .pool import Account +from .pool import Account, AccountState from .breaker import EdgeBlockBreaker from .model_retry import concurrency_delay, is_model_overload, overload_delay, retry_after_seconds, wait_for_retry from .zcode_protocol import MessageAccumulator, OpenAITranslator, usage_openai @@ -23,6 +23,7 @@ is_block_code, is_concurrency_code, client_not_supported, is_account_suspended, CLIENT_NOT_SUPPORTED_PARK_S) from .registry import model_caps +from .zcode_device import new_account_device_mid log = logging.getLogger('zcode_gateway.service') @@ -217,10 +218,14 @@ async def _apply_error(self, account, model, status, code, message, headers=None # The account itself is banned upstream for proxying: no model # on it can serve, and retrying only produces a 405 per request. # Take it out of rotation until an operator re-enables it. + log.warning('ZCode account %s (%s) SUSPENDED by upstream (status=%s code=%s): %s', + account.id, account.email, status, code, message) await self.pool.kill(account, reason=str(message)[:200], cause='suspended', expected_credentials=expected_credentials) return + if status == 405: + log.warning('ZCode 405/3012 on account %s model %s: %s', account.id, model, message) if client_not_supported(message): await self.pool.cap_model(account, model, CLIENT_NOT_SUPPORTED_PARK_S, @@ -480,11 +485,16 @@ async def _open_model_stream_once(self, payload, *, model, variant='anthropic', raise UpstreamFailure(reason['status'], reason['code'], reason['message'], reason.get('release_at'), reason.get('release_in_s')) raise NoAccountsAvailable() + device_mid = account.notes.get('device_mid') + if not device_mid: + device_mid = account.notes['device_mid'] = new_account_device_mid() + log.warning('account %s had no device_mid; assigned a fresh one', account.id) credentials = account.credential_key() + timezone = account.notes.get('timezone') or None headers = build_headers(account.access_token, self.cfg.upstream.fingerprint, - device_mid=account.notes.get('device_mid'), include_device_mid=False) + device_mid=device_mid, include_device_mid=False, + timezone=timezone) if generated_identity: - device_mid = account.notes.get('device_mid') or self.cfg.upstream.fingerprint.device_mid body['metadata'] = {**(original_metadata or {}), 'user_id': json.dumps({'device_id': device_mid, 'account_uuid': '', 'session_id': headers['x-session-id']}, separators=(',', ':'))} @@ -505,8 +515,8 @@ async def _open_model_stream_once(self, payload, *, model, variant='anthropic', # credentials actually sent, not the mutable account later. credentials = account.credential_key() headers = build_headers(account.access_token, self.cfg.upstream.fingerprint, - task_id=headers['x-session-id'], device_mid=account.notes.get('device_mid'), - include_device_mid=False) + task_id=headers['x-session-id'], device_mid=device_mid, + include_device_mid=False, timezone=timezone) resp = await self.client.send(headers, body, stream=True) if resp.status_code != 200 or 'application/json' in resp.headers.get('content-type', ''): raw = await resp.aread() @@ -519,8 +529,8 @@ async def _open_model_stream_once(self, payload, *, model, variant='anthropic', await resp.aclose() credentials = account.credential_key() headers = build_headers(account.access_token, self.cfg.upstream.fingerprint, - task_id=headers['x-session-id'], device_mid=account.notes.get('device_mid'), - include_device_mid=False) + task_id=headers['x-session-id'], device_mid=device_mid, + include_device_mid=False, timezone=timezone) resp = await self.client.send(headers, body, stream=True) if resp.status_code == 200 and 'application/json' not in resp.headers.get('content-type', ''): status = 200 @@ -552,6 +562,10 @@ async def _open_model_stream_once(self, payload, *, model, variant='anthropic', if (status < 500 and status not in (401, 402, 403, 405, 429, 451) and code != '11113' and not is_block_code(code, status)): raise last + # a killed account cannot serve this request; rotating + # now only burns the next account on the same ban + if account.state is AccountState.DEAD: + raise last tried.add(account.id) continue handle = StreamHandle(account, headers, body, resp, variant, time.time(), @@ -581,6 +595,8 @@ async def _open_model_stream_once(self, payload, *, model, variant='anthropic', expected_credentials=credentials) last = UpstreamFailure(status, code, message) if is_model_overload(status, code): raise last + if account.state is AccountState.DEAD: + raise last tried.add(account.id) break if first.get('type') != 'message_start': diff --git a/zcode_gateway/token_utils.py b/zcode_gateway/token_utils.py index d77cf83..0e6eb36 100644 --- a/zcode_gateway/token_utils.py +++ b/zcode_gateway/token_utils.py @@ -71,8 +71,40 @@ def persist_pool_snapshot(cfg: Config, accounts: list[Account]) -> None: "imported_jwt": bool(a.notes.get("imported_jwt") or a.source == "jwt-import"), "name": a.notes.get("name", ""), "device_mid": a.notes.get("device_mid", ""), + "timezone": a.notes.get("timezone", ""), + "state": a.state.value, + "death_reason": a.death_reason, + "paid_exhausted": a.paid_exhausted, + "cooldown_until": a.cooldown_until, } for a in accounts ] } _atomic_write(path, json.dumps(payload, indent=2)) + + +def persist_pool_states(path: str | Path, rows: list[dict]) -> None: + """Write hard-state fields into an existing pool file, leaving the rest. + + Only the rows that actually changed are rewritten, so the debounced saver + does not touch every credential record on every account event. + """ + p = Path(path) + data = json.loads(p.read_text(encoding="utf-8")) + items = (data.get("accounts") or []) if isinstance(data, dict) else data + by_id = {str(row["id"]): row for row in rows} + changed = False + for i, item in enumerate(items or []): + if not isinstance(item, dict): + continue + auth = item.get("auth") or {} + ident = str(auth.get("accountId") or item.get("id") or f"pool-{i}") + row = by_id.get(ident) + if row is None: + continue + for key in ("state", "death_reason", "paid_exhausted", "cooldown_until"): + if item.get(key) != row[key]: + item[key] = row[key] + changed = True + if changed: + _atomic_write(p, json.dumps(data, indent=2)) diff --git a/zcode_gateway/tokens.py b/zcode_gateway/tokens.py index f67a8b4..98556d9 100644 --- a/zcode_gateway/tokens.py +++ b/zcode_gateway/tokens.py @@ -14,6 +14,7 @@ from .accounts_dir import (parse_snapshot, snapshot_path, snapshot_transaction, write_snapshot) from .upstream import build_headers +from .zcode_device import new_account_device_mid log = logging.getLogger('zcode_gateway.tokens') @@ -215,10 +216,14 @@ async def check_account(self, account): return None account.quota_check_generation += 1 revision = account.quota_check_generation + device_mid = account.notes.get('device_mid') + if not device_mid: + device_mid = account.notes['device_mid'] = new_account_device_mid() + log.warning('account %s had no device_mid; assigned a fresh one', account.id) credentials = account.credential_key() account.notes['quota_check_attempted_at'] = time.time() headers = build_headers(account.access_token, self.cfg.upstream.fingerprint, - device_mid=account.notes.get('device_mid')) + device_mid=device_mid) url = self.cfg.upstream.base_url.rstrip('/') + '/zcode-plan/billing/balance' try: for attempt in range(2): diff --git a/zcode_gateway/upstream.py b/zcode_gateway/upstream.py index 601a845..25f2e63 100644 --- a/zcode_gateway/upstream.py +++ b/zcode_gateway/upstream.py @@ -56,7 +56,7 @@ def merge_anthropic_beta(base: str, extra: str | None) -> str: def build_headers(access_token, fp, task_id=None, *, device_mid=None, include_device_mid=True, - anthropic_beta: str | None = None): + anthropic_beta: str | None = None, timezone: str | None = None): token = access_token.removeprefix("Bearer ").strip() h = dict(STATIC_HEADERS) if anthropic_beta: @@ -64,7 +64,7 @@ def build_headers(access_token, fp, task_id=None, *, device_mid=None, include_de STATIC_HEADERS.get("anthropic-beta", ""), anthropic_beta) h.update({"authorization": "Bearer " + token, "x-api-key": token, "user-agent": fp.user_agent, "x-device-mid": device_mid or fp.device_mid, - "x-client-language": fp.language, "x-client-timezone": fp.timezone, + "x-client-language": fp.language, "x-client-timezone": timezone or fp.timezone, "x-os-category": fp.os_category, "x-os-version": fp.os_version, "x-platform": fp.platform, "x-release-channel": "production", "x-title": "Z Code@electron", "x-zcode-agent": "glm", diff --git a/zcode_gateway/zcode_accounts.py b/zcode_gateway/zcode_accounts.py index cc777c2..13b664f 100644 --- a/zcode_gateway/zcode_accounts.py +++ b/zcode_gateway/zcode_accounts.py @@ -10,7 +10,7 @@ from .accounts_dir import parse_snapshot, save_account_snapshot, snapshot_transaction from .zcode_detect import jwt_claims -from .zcode_device import read_device_mid +from .zcode_device import account_device_mid, read_device_mid def decrypt_credential(value): @@ -33,7 +33,12 @@ def decrypt_credential(value): def read_credentials(path): data = json.loads(Path(path).read_text(encoding='utf-8-sig')) - device_mid = read_device_mid(Path(path).parent / 'telemetry-state.json') + # The desktop install's mid belongs to the ONE account it is signed into. + # Stamping it on every record made the whole pool share one device; with + # several records there is no telling which one the desktop owns. + shared_mid = read_device_mid(Path(path).parent / 'telemetry-state.json') + record_mid = data.get('device_mid') + record_mid = record_mid.strip() if isinstance(record_mid, str) else '' token = decrypt_credential(data.get('zcodejwttoken') or data.get('zcodeJWT')) user = decrypt_credential(data.get('oauth:zai:user_info')) or data.get('user') or {} if isinstance(user, str): @@ -58,11 +63,16 @@ def read_credentials(path): account_user = user if ident == current_id else {} fields = {'account_id': ident, 'email': account_user.get('email', ''), 'name': account_user.get('name', ''), 'access_token': candidate, 'expires_at_ms': str(int(claims.get('exp') or 0) * 1000), - 'source': str(path), 'captured_at': datetime.now(timezone.utc).isoformat()} - if device_mid: - fields['device_mid'] = device_mid + 'source': str(path), 'captured_at': datetime.now(timezone.utc).isoformat(), + 'device_mid': account_device_mid(ident)} if ident not in accounts or int(claims.get('iat') or 0) > int(jwt_claims(accounts[ident]['access_token']).get('iat') or 0): accounts[ident] = fields + if len(accounts) == 1: + # the file's own mid belongs to the ONE account it holds; with more + # than one there is no telling which record it came from + hint = record_mid or shared_mid + if hint: + next(iter(accounts.values()))['device_mid'] = hint return list(accounts.values()) diff --git a/zcode_gateway/zcode_device.py b/zcode_gateway/zcode_device.py index 5d1b662..0d404c9 100644 --- a/zcode_gateway/zcode_device.py +++ b/zcode_gateway/zcode_device.py @@ -17,3 +17,19 @@ def read_device_mid(path=None): def default_device_mid(): return read_device_mid() or str(uuid.uuid4()) + + +def account_device_mid(account_id: str) -> str: + """Stable per-account device id, derivable from the account identity. + + The account id is identical in the chat token (id/sub) and the zjwt + (sub/user_id), so generator and gateway derive the SAME id without any + cross-process coordination. A real install's mid is a uuid4, not a uuid5, + but this is the smaller diff and removes the three-identity problem. + """ + return str(uuid.uuid5(uuid.NAMESPACE_URL, "zcode-device:" + account_id)) + + +def new_account_device_mid() -> str: + """A fresh, stable device identity for one account (a real install has one).""" + return str(uuid.uuid4()) From 47084608da5c08d0d27c1461c81910a4a44b0ce8 Mon Sep 17 00:00:00 2001 From: B3hnamR Date: Sun, 22 Nov 2026 05:44:31 +0330 Subject: [PATCH 6/7] Keep the gateway running in the tray Closing the window now hides it to a notification-area icon instead of quitting, so the gateway keeps serving. The icon is drawn with ctypes (Shell_NotifyIcon) rather than a GUI toolkit, because the onefile exe is already 60 MB and pystray/Pillow would add about 15 MB more. The menu offers the dashboard, the address, the log, the data folder and Quit; the icon re-registers on TaskbarCreated so an Explorer restart does not lose it. --no-tray restores close-to-quit and --tray starts hidden. Tray failure is non-fatal: the app falls back to its old behaviour, and a dead tray thread makes closing the window quit rather than strand the process with no window and no icon. --- gui_main.py | 130 +++++++++- scripts/build/windows.ps1 | 2 + tests/test_tray.py | 114 +++++++++ zcode_gateway/tray.py | 484 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 728 insertions(+), 2 deletions(-) create mode 100644 tests/test_tray.py create mode 100644 zcode_gateway/tray.py diff --git a/gui_main.py b/gui_main.py index 8d417ff..56d9bd9 100644 --- a/gui_main.py +++ b/gui_main.py @@ -3,6 +3,9 @@ Replaces the Tkinter GUI. The gateway runs on a background thread; the window is the served dashboard (/dash) in a native WebView2 shell via pywebview. A single-instance mutex prevents a second exe from fighting over the port. + +A notification-area icon keeps the gateway reachable with the window closed: +closing hides the window, the tray menu reopens it or quits for real. """ from __future__ import annotations @@ -23,6 +26,17 @@ MUTEX_NAME = "ZcodeGatewayByB3hnamR-SingleInstance" DASH_PATH = "/dash" +CMD_OPEN, CMD_COPY, CMD_LOG, CMD_FOLDER, CMD_QUIT = 1, 2, 3, 4, 9 +TRAY_MENU = ( + (CMD_OPEN, "Open dashboard"), + (CMD_COPY, "Copy address"), + (None, ""), + (CMD_LOG, "Open log"), + (CMD_FOLDER, "Open data folder"), + (None, ""), + (CMD_QUIT, "Quit"), +) + _mutex_handle = None @@ -244,6 +258,86 @@ def _offer_webview2_or_browser(url: str) -> bool: return True +def _log_file() -> Path: + return Path(os.environ.get("LOCALAPPDATA", ".")) / "ZcodeGateway" / "zcode-gateway.log" + + +def _open_path(path: Path) -> None: + try: + os.startfile(str(path)) + except OSError: + pass + + +def _quit_from_tray(window_ref: list, quitting: threading.Event) -> None: + """Destroy the window from the tray thread; main() finishes the shutdown.""" + quitting.set() + + def finish() -> None: + window = window_ref[0] + try: + if window is not None: + window.destroy() + except Exception: + pass + # main() runs the normal shutdown once webview.start() returns. If the + # UI thread is wedged, quit anyway rather than leave a dead tray icon. + time.sleep(8) + _shutdown_generator() + os._exit(0) + + threading.Thread(target=finish, daemon=True, name="tray-quit").start() + + +def _start_tray(url: str, quitting: threading.Event, window_ref: list): + """Notification-area icon, or None when the shell will not give us one.""" + from zcode_gateway import tray as tray_icon + + def open_dashboard() -> None: + window = window_ref[0] + if window is None: + return + try: + window.show() + window.restore() + except Exception: + pass + + def run_command(command: int) -> None: + if command == CMD_OPEN: + open_dashboard() + elif command == CMD_COPY: + tray_icon.copy_text(url) + elif command == CMD_LOG: + _open_path(_log_file()) + elif command == CMD_FOLDER: + _open_path(_exe_dir()) + elif command == CMD_QUIT: + _quit_from_tray(window_ref, quitting) + + icon = tray_icon.TrayIcon( + tooltip=f"Zcode Gateway - {url}", + menu=TRAY_MENU, + on_activate=open_dashboard, + on_command=run_command, + icon_path=tray_icon.asset_path("assets", "zcode.ico")) + if not icon.start(): + print("[tray] notification-area icon unavailable", file=sys.stderr, flush=True) + return None + return icon + + +def _watch_gateway(icon, quitting: threading.Event) -> None: + """Turn the icon into an alarm when the gateway thread dies.""" + _server_failed.wait() + if quitting.is_set() or not icon.alive: + return + icon.set_tooltip("Zcode Gateway - gateway stopped") + icon.notify("Gateway stopped", + "The gateway exited. Open the log, then restart Zcode Gateway.", + warning=True) + + def main() -> None: global _server, _server_error _server = None @@ -253,6 +347,10 @@ def main() -> None: import argparse parser = argparse.ArgumentParser(description='Zcode Gateway desktop or headless server') parser.add_argument('--headless', action='store_true') + parser.add_argument('--tray', action='store_true', + help='start hidden in the notification area') + parser.add_argument('--no-tray', action='store_true', + help='no notification-area icon; closing the window quits') parser.add_argument('--config') args = parser.parse_args() if args.config: @@ -315,10 +413,36 @@ def main() -> None: raise SystemExit(1) from _server_error import webview - webview.create_window( + quitting = threading.Event() + window_ref: list = [None] + tray_icon = None if args.no_tray else _start_tray(url, quitting, window_ref) + window = webview.create_window( "Zcode Gateway", url, width=1280, height=800, min_size=(980, 620), - background_color="#0f1115", text_select=True) + background_color="#0f1115", text_select=True, + hidden=bool(args.tray and tray_icon is not None)) + window_ref[0] = window + + if tray_icon is not None: + def on_closing(): + # if the tray thread died there is no icon to restore from, so + # hiding here would strand an invisible, unclosable app + if quitting.is_set() or not tray_icon.alive: + return True + window.hide() + tray_icon.notify( + "Zcode Gateway is still running", + "The dashboard is in the notification area. Right-click the " + "icon to reopen it or quit.") + return False + + window.events.closing += on_closing + threading.Thread(target=_watch_gateway, args=(tray_icon, quitting), + name="tray-watchdog", daemon=True).start() + if args.tray: + tray_icon.notify("Zcode Gateway is running", + f"The dashboard is in the notification area ({url}).") + webview.start(gui="edgechromium") # The window closed. edgechromium/pythonnet leave non-daemon threads that @@ -328,6 +452,8 @@ def main() -> None: # Before the hard exit, stop the generator's workers — os._exit skips # atexit and the FastAPI lifespan, and spawned Chromium children would # otherwise be orphaned on the machine. + if tray_icon is not None: + tray_icon.stop() _shutdown_generator() os._exit(0) diff --git a/scripts/build/windows.ps1 b/scripts/build/windows.ps1 index 5c55a04..ef35b3f 100644 --- a/scripts/build/windows.ps1 +++ b/scripts/build/windows.ps1 @@ -163,6 +163,8 @@ $buildArgs = @( # so PyInstaller cannot see them "--hidden-import", "zcode_gateway.generator", "--hidden-import", "zcode_gateway.accounts_dir_bridge", + # the desktop shell imports the notification-area module inside main() + "--hidden-import", "zcode_gateway.tray", # ship the example config, the app icon assets, the dashboard page, the # Cloudflare mail-worker template, and the bundled generator scripts "--add-data", "$(Join-Path $Here 'config.example.yaml');.", diff --git a/tests/test_tray.py b/tests/test_tray.py new file mode 100644 index 0000000..ad9378e --- /dev/null +++ b/tests/test_tray.py @@ -0,0 +1,114 @@ +import ctypes +import os +import sys +from ctypes import wintypes + +import pytest + +from zcode_gateway import tray + + +def _read_clipboard_text(): + user32 = ctypes.WinDLL("user32") + kernel32 = ctypes.WinDLL("kernel32") + user32.GetClipboardData.argtypes = [wintypes.UINT] + user32.GetClipboardData.restype = wintypes.HANDLE + kernel32.GlobalLock.argtypes = [wintypes.HGLOBAL] + kernel32.GlobalLock.restype = wintypes.LPVOID + kernel32.GlobalUnlock.argtypes = [wintypes.HGLOBAL] + if not user32.OpenClipboard(None): + return None + try: + handle = user32.GetClipboardData(tray.CF_UNICODETEXT) + if not handle: + return None + pointer = kernel32.GlobalLock(handle) + if not pointer: + return None + try: + return ctypes.wstring_at(pointer) + finally: + kernel32.GlobalUnlock(handle) + finally: + user32.CloseClipboard() + + +def test_tooltip_is_truncated_to_the_shell_limit(): + assert len(tray.TrayIcon(tooltip="x" * 300, menu=[]).tooltip) == 127 + + +def test_notify_and_tooltip_before_start_do_not_raise(): + icon = tray.TrayIcon(tooltip="Zcode Gateway", menu=[]) + icon.set_tooltip("still not started") + icon.notify("title", "message") + assert icon.alive is False + + +def test_unsupported_platform_is_a_noop(monkeypatch): + monkeypatch.setattr(tray, "SUPPORTED", False) + icon = tray.TrayIcon(tooltip="Zcode Gateway", menu=[]) + assert icon.start() is False + assert icon.alive is False + icon.stop() + icon.notify("title", "message") + assert tray.copy_text("hello") is False + assert tray.find_window() is None + + +def test_asset_path_follows_the_pyinstaller_bundle(monkeypatch, tmp_path): + monkeypatch.setattr(sys, "_MEIPASS", str(tmp_path), raising=False) + assert tray.asset_path("assets", "zcode.ico") == tmp_path / "assets" / "zcode.ico" + + +@pytest.mark.skipif(sys.platform != "win32", reason="Shell_NotifyIcon is Windows-only") +def test_icon_starts_stops_and_restarts(): + # unique class: a real gateway may be running on this machine and its tray + # window would be the one find_window() returns + class_name = f"ZcodeGatewayTrayTest{os.getpid()}" + icon = tray.TrayIcon(tooltip="Zcode Gateway test", + menu=[(1, "Open dashboard"), (None, ""), (9, "Quit")], + class_name=class_name) + if not icon.start(): + pytest.skip("no interactive shell (no notification area)") + try: + assert icon.alive is True + assert tray.find_window(class_name) == icon._hwnd + assert tray.wait_until_ready(icon, timeout=2) is True + finally: + icon.stop() + assert icon.alive is False + assert tray.find_window(class_name) is None + if not icon.start(): + pytest.skip("shell refused a second icon") + icon.stop() + assert icon.alive is False + + +@pytest.mark.skipif(sys.platform != "win32", reason="clipboard APIs are Windows-only") +def test_copy_text_puts_text_on_the_clipboard(): + previous = _read_clipboard_text() + try: + if not tray.copy_text("zcode-tray-test"): + pytest.skip("no clipboard in this session") + assert _read_clipboard_text() == "zcode-tray-test" + finally: + if previous is not None: + tray.copy_text(previous) + + +def test_registration_flags_the_icon_message_and_tooltip(): + icon = tray.TrayIcon(tooltip="Zcode Gateway", menu=[]) + icon._hwnd = 1234 + data = icon._nid() + assert data.uFlags == tray.NIF_MESSAGE | tray.NIF_ICON | tray.NIF_TIP + assert data.uCallbackMessage == tray.WM_TRAY + assert data.hWnd == 1234 + + +def test_desktop_menu_opens_the_dashboard_and_can_quit(): + import gui_main + commands = [command for command, _ in gui_main.TRAY_MENU if command is not None] + assert commands[0] == gui_main.CMD_OPEN + assert commands[-1] == gui_main.CMD_QUIT + assert len(commands) == len(set(commands)) + assert all(label for command, label in gui_main.TRAY_MENU if command is not None) diff --git a/zcode_gateway/tray.py b/zcode_gateway/tray.py new file mode 100644 index 0000000..fa5c57c --- /dev/null +++ b/zcode_gateway/tray.py @@ -0,0 +1,484 @@ +"""Notification-area icon for the desktop shell (Windows). + +Pure ctypes: pystray + Pillow would add ~15 MB to the onefile exe for one +16x16 icon, and the app already ships assets/zcode.ico. Shell_NotifyIcon on a +hidden top-level window is the same API Explorer itself drives. + +The tray is optional infrastructure. start() returns False when the shell is +unavailable (a service session, a stripped Windows install) and the caller +keeps its previous behaviour; nothing here may raise into the gateway. +""" +from __future__ import annotations + +import ctypes +import sys +import threading +import time +from ctypes import wintypes +from pathlib import Path + +SUPPORTED = sys.platform == "win32" + +# Window class is fixed, not per-PID: the single-instance mutex already +# guarantees one tray per session, and a stable name makes the icon's window +# findable from outside (FindWindowW) when diagnosing a missing icon. +TRAY_WINDOW_CLASS = "ZcodeGatewayTrayWindow" + +WM_APP = 0x8000 +WM_NULL = 0x0000 +WM_DESTROY = 0x0002 +WM_CLOSE = 0x0010 +WM_LBUTTONUP = 0x0202 +WM_LBUTTONDBLCLK = 0x0203 +WM_RBUTTONUP = 0x0205 +WM_CONTEXTMENU = 0x007B +WM_TRAY = WM_APP + 20 + +NIM_ADD, NIM_MODIFY, NIM_DELETE = 0, 1, 2 +NIF_MESSAGE, NIF_ICON, NIF_TIP, NIF_INFO = 0x1, 0x2, 0x4, 0x10 +NIIF_INFO, NIIF_WARNING = 0x1, 0x2 +MF_STRING, MF_SEPARATOR = 0x0, 0x800 +TPM_RIGHTBUTTON, TPM_RETURNCMD, TPM_NONOTIFY = 0x2, 0x100, 0x80 +IMAGE_ICON = 1 +LR_LOADFROMFILE, LR_DEFAULTSIZE = 0x10, 0x40 +SM_CXSMICON = 49 +IDI_APPLICATION = 32512 +CF_UNICODETEXT = 13 +GMEM_MOVEABLE = 0x0002 + +WPARAM = ctypes.c_size_t +LPARAM = ctypes.c_ssize_t +LRESULT = ctypes.c_ssize_t +# WINFUNCTYPE is Windows-only; the struct is never used elsewhere, but the +# module still has to import on the Linux target (CI runs the suite there). +_FUNCTYPE = getattr(ctypes, "WINFUNCTYPE", ctypes.CFUNCTYPE) +WNDPROC = _FUNCTYPE(LRESULT, wintypes.HWND, wintypes.UINT, WPARAM, LPARAM) + + +class WNDCLASSW(ctypes.Structure): + _fields_ = [ + ("style", wintypes.UINT), + ("lpfnWndProc", WNDPROC), + ("cbClsExtra", ctypes.c_int), + ("cbWndExtra", ctypes.c_int), + ("hInstance", wintypes.HINSTANCE), + ("hIcon", wintypes.HICON), + ("hCursor", wintypes.HANDLE), + ("hbrBackground", wintypes.HBRUSH), + ("lpszMenuName", wintypes.LPCWSTR), + ("lpszClassName", wintypes.LPCWSTR), + ] + + +class GUID(ctypes.Structure): + _fields_ = [("Data1", wintypes.DWORD), ("Data2", wintypes.WORD), + ("Data3", wintypes.WORD), ("Data4", ctypes.c_ubyte * 8)] + + +class NOTIFYICONDATAW(ctypes.Structure): + _fields_ = [ + ("cbSize", wintypes.DWORD), + ("hWnd", wintypes.HWND), + ("uID", wintypes.UINT), + ("uFlags", wintypes.UINT), + ("uCallbackMessage", wintypes.UINT), + ("hIcon", wintypes.HICON), + ("szTip", ctypes.c_wchar * 128), + ("dwState", wintypes.DWORD), + ("dwStateMask", wintypes.DWORD), + ("szInfo", ctypes.c_wchar * 256), + ("uVersion", wintypes.UINT), + ("szInfoTitle", ctypes.c_wchar * 64), + ("dwInfoFlags", wintypes.DWORD), + ("guidItem", GUID), + ("hBalloonIcon", wintypes.HICON), + ] + + +class MSG(ctypes.Structure): + _fields_ = [ + ("hWnd", wintypes.HWND), + ("message", wintypes.UINT), + ("wParam", WPARAM), + ("lParam", LPARAM), + ("time", wintypes.DWORD), + ("pt", wintypes.POINT), + ] + + +if SUPPORTED: + _user32 = ctypes.WinDLL("user32", use_last_error=True) + _shell32 = ctypes.WinDLL("shell32", use_last_error=True) + _kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + + _user32.RegisterClassW.argtypes = [ctypes.POINTER(WNDCLASSW)] + _user32.RegisterClassW.restype = ctypes.c_ushort + _user32.UnregisterClassW.argtypes = [wintypes.LPCWSTR, wintypes.HINSTANCE] + _user32.CreateWindowExW.argtypes = [ + wintypes.DWORD, wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.DWORD, + ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, + wintypes.HWND, wintypes.HMENU, wintypes.HINSTANCE, wintypes.LPVOID] + _user32.CreateWindowExW.restype = wintypes.HWND + _user32.DefWindowProcW.argtypes = [wintypes.HWND, wintypes.UINT, WPARAM, LPARAM] + _user32.DefWindowProcW.restype = LRESULT + _user32.DestroyWindow.argtypes = [wintypes.HWND] + _user32.PostMessageW.argtypes = [wintypes.HWND, wintypes.UINT, WPARAM, LPARAM] + _user32.PostQuitMessage.argtypes = [ctypes.c_int] + _user32.GetMessageW.argtypes = [ctypes.POINTER(MSG), wintypes.HWND, + wintypes.UINT, wintypes.UINT] + _user32.GetMessageW.restype = ctypes.c_int + _user32.TranslateMessage.argtypes = [ctypes.POINTER(MSG)] + _user32.DispatchMessageW.argtypes = [ctypes.POINTER(MSG)] + _user32.DispatchMessageW.restype = LRESULT + _user32.RegisterWindowMessageW.argtypes = [wintypes.LPCWSTR] + _user32.RegisterWindowMessageW.restype = wintypes.UINT + _user32.CreatePopupMenu.restype = wintypes.HMENU + _user32.AppendMenuW.argtypes = [wintypes.HMENU, wintypes.UINT, WPARAM, + wintypes.LPCWSTR] + _user32.TrackPopupMenu.argtypes = [wintypes.HMENU, wintypes.UINT, + ctypes.c_int, ctypes.c_int, ctypes.c_int, + wintypes.HWND, wintypes.LPVOID] + _user32.TrackPopupMenu.restype = ctypes.c_int + _user32.DestroyMenu.argtypes = [wintypes.HMENU] + _user32.SetForegroundWindow.argtypes = [wintypes.HWND] + _user32.GetCursorPos.argtypes = [ctypes.POINTER(wintypes.POINT)] + # resource ids arrive as MAKEINTRESOURCE pointers, not strings + _user32.LoadIconW.argtypes = [wintypes.HINSTANCE, ctypes.c_void_p] + _user32.LoadIconW.restype = wintypes.HICON + _user32.LoadImageW.argtypes = [wintypes.HINSTANCE, wintypes.LPCWSTR, + wintypes.UINT, ctypes.c_int, ctypes.c_int, + wintypes.UINT] + _user32.LoadImageW.restype = wintypes.HANDLE + _user32.DestroyIcon.argtypes = [wintypes.HICON] + _user32.GetSystemMetrics.argtypes = [ctypes.c_int] + _user32.GetSystemMetrics.restype = ctypes.c_int + _user32.FindWindowW.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR] + _user32.FindWindowW.restype = wintypes.HWND + _user32.OpenClipboard.argtypes = [wintypes.HWND] + _user32.OpenClipboard.restype = wintypes.BOOL + _user32.EmptyClipboard.restype = wintypes.BOOL + _user32.CloseClipboard.restype = wintypes.BOOL + _user32.SetClipboardData.argtypes = [wintypes.UINT, wintypes.HANDLE] + _user32.SetClipboardData.restype = wintypes.HANDLE + + _shell32.Shell_NotifyIconW.argtypes = [wintypes.DWORD, + ctypes.POINTER(NOTIFYICONDATAW)] + _shell32.Shell_NotifyIconW.restype = wintypes.BOOL + _shell32.ExtractIconExW.argtypes = [wintypes.LPCWSTR, ctypes.c_int, + ctypes.POINTER(wintypes.HICON), + ctypes.POINTER(wintypes.HICON), + wintypes.UINT] + _shell32.ExtractIconExW.restype = wintypes.UINT + + _kernel32.GetModuleHandleW.argtypes = [wintypes.LPCWSTR] + _kernel32.GetModuleHandleW.restype = wintypes.HMODULE + _kernel32.GlobalAlloc.argtypes = [wintypes.UINT, ctypes.c_size_t] + _kernel32.GlobalAlloc.restype = wintypes.HGLOBAL + _kernel32.GlobalLock.argtypes = [wintypes.HGLOBAL] + _kernel32.GlobalLock.restype = wintypes.LPVOID + _kernel32.GlobalUnlock.argtypes = [wintypes.HGLOBAL] + _kernel32.GlobalFree.argtypes = [wintypes.HGLOBAL] + _kernel32.GlobalFree.restype = wintypes.HGLOBAL + + +def asset_path(*parts: str) -> Path: + """Bundle-relative asset (PyInstaller unpacks --add-data under _MEIPASS).""" + root = getattr(sys, "_MEIPASS", None) + base = Path(root) if root else Path(__file__).resolve().parent.parent + return base.joinpath(*parts) + + +def copy_text(text: str) -> bool: + """Put text on the clipboard (CF_UNICODETEXT). False when it cannot.""" + if not SUPPORTED or not text: + return False + if not _user32.OpenClipboard(None): + return False + handle = None + try: + _user32.EmptyClipboard() + buf = ctypes.create_unicode_buffer(text) + size = ctypes.sizeof(buf) + handle = _kernel32.GlobalAlloc(GMEM_MOVEABLE, size) + if not handle: + return False + pointer = _kernel32.GlobalLock(handle) + if not pointer: + return False + ctypes.memmove(pointer, buf, size) + _kernel32.GlobalUnlock(handle) + if not _user32.SetClipboardData(CF_UNICODETEXT, handle): + return False + handle = None # the clipboard owns the block now + return True + finally: + if handle: + _kernel32.GlobalFree(handle) + _user32.CloseClipboard() + + +class TrayIcon: + """One notification-area icon with a right-click menu. + + menu: ordered (command_id, label) pairs; command_id None is a separator. + on_activate runs on a left click, on_command(command_id) on a menu pick. + Both run on the tray thread and must return quickly. + """ + + def __init__(self, tooltip: str, menu, on_activate=None, on_command=None, + icon_path=None, class_name: str = TRAY_WINDOW_CLASS) -> None: + self.tooltip = (tooltip or "Zcode Gateway")[:127] + self.menu = list(menu) + self.on_activate = on_activate + self.on_command = on_command + self.icon_path = str(icon_path) if icon_path else "" + self.class_name = class_name + self._hwnd = None + self._hicon = None + self._thread = None + self._ready = threading.Event() + self._lock = threading.Lock() + self._started = False + self._wndproc = None + self._taskbar_created = 0 + self._last_activate = 0.0 + + # -- lifecycle --------------------------------------------------------- + def start(self, timeout: float = 5.0) -> bool: + if not SUPPORTED: + return False + with self._lock: + if self._thread is not None and self._thread.is_alive(): + return self._started + self._ready.clear() + self._started = False + self._thread = threading.Thread(target=self._run, name="tray-icon", + daemon=True) + self._thread.start() + self._ready.wait(timeout) + return self._started + + def stop(self, timeout: float = 5.0) -> None: + with self._lock: + hwnd, thread = self._hwnd, self._thread + if not hwnd or thread is None: + return + if thread is threading.current_thread(): + return + _user32.PostMessageW(hwnd, WM_CLOSE, 0, 0) + thread.join(timeout) + + @property + def alive(self) -> bool: + thread = self._thread + return bool(self._started and thread is not None and thread.is_alive()) + + # -- shell updates (any thread) --------------------------------------- + def set_tooltip(self, text: str) -> None: + self.tooltip = (text or "")[:127] + self._modify(NIF_TIP) + + def notify(self, title: str, message: str, warning: bool = False) -> None: + """Balloon/toast in the corner; silently ignored when unsupported.""" + if not SUPPORTED or not self._hwnd: + return + data = self._nid() + data.uFlags = NIF_INFO + data.szInfoTitle = (title or "")[:63] + data.szInfo = (message or "")[:255] + data.dwInfoFlags = NIIF_WARNING if warning else NIIF_INFO + try: + _shell32.Shell_NotifyIconW(NIM_MODIFY, ctypes.byref(data)) + except OSError: + pass + + def _modify(self, flags: int) -> None: + if not SUPPORTED or not self._hwnd: + return + data = self._nid() + data.uFlags = flags + try: + _shell32.Shell_NotifyIconW(NIM_MODIFY, ctypes.byref(data)) + except OSError: + pass + + # -- internals --------------------------------------------------------- + def _nid(self) -> NOTIFYICONDATAW: + data = NOTIFYICONDATAW() + data.cbSize = ctypes.sizeof(NOTIFYICONDATAW) + data.hWnd = self._hwnd + data.uID = 1 + # without these the shell registers a nameless slot: NIM_ADD still + # returns TRUE but draws no icon and sends no click messages + data.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP + data.uCallbackMessage = WM_TRAY + data.hIcon = self._hicon + data.szTip = self.tooltip + return data + + def _load_icon(self): + if self.icon_path and Path(self.icon_path).is_file(): + size = _user32.GetSystemMetrics(SM_CXSMICON) or 16 + handle = _user32.LoadImageW(None, self.icon_path, IMAGE_ICON, + size, size, LR_LOADFROMFILE) + if handle: + return handle + if getattr(sys, "frozen", False): + # the build embeds assets/zcode.ico as the exe icon + large, small = wintypes.HICON(), wintypes.HICON() + if _shell32.ExtractIconExW(sys.executable, 0, ctypes.byref(large), + ctypes.byref(small), 1) and small.value: + return small.value + return _user32.LoadIconW(None, ctypes.c_void_p(IDI_APPLICATION)) + + def _window_proc(self, hwnd, msg, wparam, lparam): + try: + if msg == WM_TRAY: + event = lparam & 0xFFFF + if event in (WM_RBUTTONUP, WM_CONTEXTMENU): + self._show_menu() + elif event == WM_LBUTTONUP: + self._activate() + return 0 + if msg == self._taskbar_created: + # Explorer restarted and dropped every tray icon with it + self._add_icon() + return 0 + if msg == WM_CLOSE: + self._remove_icon() + _user32.DestroyWindow(hwnd) + return 0 + if msg == WM_DESTROY: + _user32.PostQuitMessage(0) + return 0 + except Exception: + pass + return _user32.DefWindowProcW(hwnd, msg, wparam, lparam) + + def _activate(self) -> None: + if self.on_activate is None: + return + now = time.monotonic() + if now - self._last_activate < 0.4: + # a double click also delivers two LBUTTONUPs + return + self._last_activate = now + try: + self.on_activate() + except Exception: + pass + + def _show_menu(self) -> None: + if not self._hwnd: + return + menu = _user32.CreatePopupMenu() + if not menu: + return + try: + for command_id, label in self.menu: + if command_id is None: + _user32.AppendMenuW(menu, MF_SEPARATOR, 0, None) + else: + _user32.AppendMenuW(menu, MF_STRING, command_id, label) + point = wintypes.POINT() + _user32.GetCursorPos(ctypes.byref(point)) + # the foreground + WM_NULL pair is required or the menu stays up + # after the user clicks elsewhere + _user32.SetForegroundWindow(self._hwnd) + chosen = _user32.TrackPopupMenu( + menu, TPM_RETURNCMD | TPM_RIGHTBUTTON | TPM_NONOTIFY, + point.x, point.y, 0, self._hwnd, None) + _user32.PostMessageW(self._hwnd, WM_NULL, 0, 0) + finally: + _user32.DestroyMenu(menu) + if chosen and self.on_command is not None: + try: + self.on_command(chosen) + except Exception: + pass + + def _add_icon(self) -> bool: + if not self._hwnd: + return False + return bool(_shell32.Shell_NotifyIconW(NIM_ADD, ctypes.byref(self._nid()))) + + def _remove_icon(self) -> None: + if not self._hwnd: + return + try: + _shell32.Shell_NotifyIconW(NIM_DELETE, ctypes.byref(self._nid())) + except OSError: + pass + + def _create_window(self): + module = _kernel32.GetModuleHandleW(None) + self._wndproc = WNDPROC(self._window_proc) + wndclass = WNDCLASSW() + wndclass.lpfnWndProc = self._wndproc + wndclass.hInstance = module + wndclass.lpszClassName = self.class_name + # a class left behind by an earlier crashed run still points at a dead + # Python callback: re-registering is the only safe recovery + _user32.UnregisterClassW(self.class_name, module) + _user32.RegisterClassW(ctypes.byref(wndclass)) + # WS_OVERLAPPED and never ShowWindow: top-level (so the shell's + # TaskbarCreated broadcast reaches it) but invisible + return _user32.CreateWindowExW( + 0, self.class_name, "Zcode Gateway", 0, 0, 0, 0, 0, + None, None, module, None) + + def _run(self) -> None: + try: + self._taskbar_created = _user32.RegisterWindowMessageW("TaskbarCreated") + self._hicon = self._load_icon() + self._hwnd = self._create_window() + if not self._hwnd: + return + self._started = self._add_icon() + if not self._started: + return + self._ready.set() + message = MSG() + while _user32.GetMessageW(ctypes.byref(message), None, 0, 0) > 0: + _user32.TranslateMessage(ctypes.byref(message)) + _user32.DispatchMessageW(ctypes.byref(message)) + except Exception: + self._started = False + finally: + self._started = False + self._ready.set() + hwnd = self._hwnd + if hwnd: + self._remove_icon() + try: + _user32.DestroyWindow(hwnd) + except OSError: + pass + self._hwnd = None + if self._hicon: + try: + _user32.DestroyIcon(self._hicon) + except OSError: + pass + self._hicon = None + try: + _user32.UnregisterClassW(self.class_name, + _kernel32.GetModuleHandleW(None)) + except OSError: + pass + + +def find_window(class_name: str = TRAY_WINDOW_CLASS): + """HWND of a running tray window, or None. Diagnostics/tests only.""" + if not SUPPORTED: + return None + return _user32.FindWindowW(class_name, None) + + +def wait_until_ready(tray: TrayIcon, timeout: float = 5.0) -> bool: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if tray.alive: + return True + time.sleep(0.05) + return False From 1a394127b671338c24d1958781913cdd4ec2ff57 Mon Sep 17 00:00:00 2001 From: B3hnamR Date: Mon, 23 Nov 2026 04:41:32 +0330 Subject: [PATCH 7/7] Keep sessions alive on upstream failures A suspended ZCode account is killed upstream, so the gateway now rotates the request to a healthy account instead of returning the ban text as a 405. If no account can serve, clients get a retryable 503 with a neutral message and Retry-After; the upstream reason stays in the gateway logs. Upstream CDN HTML 405 pages are now recognised as IP-wide edge blocks and fail fast with a retryable 503 instead of parking models with the raw HTML as their reason. Cap messages are sanitised and Retry-After is clamped so a large upstream hint cannot stall a session for hours. --- tests/test_inference_audit.py | 61 ++++++++++- tests/test_zcode_core.py | 186 ++++++++++++++++++++++++++++++++- zcode_gateway/api_anthropic.py | 12 ++- zcode_gateway/api_openai.py | 12 ++- zcode_gateway/pool.py | 8 +- zcode_gateway/service.py | 152 ++++++++++++++++++++------- zcode_gateway/upstream.py | 49 ++++++++- 7 files changed, 421 insertions(+), 59 deletions(-) diff --git a/tests/test_inference_audit.py b/tests/test_inference_audit.py index a0adac3..39f7697 100644 --- a/tests/test_inference_audit.py +++ b/tests/test_inference_audit.py @@ -17,7 +17,7 @@ from zcode_gateway.service import ChatService, UpstreamFailure from zcode_gateway.store import JsonlCapture from zcode_gateway.tokens import TokenManager -from zcode_gateway.upstream import RelayTransportError, UpstreamClient +from zcode_gateway.upstream import RelayTransportError, UpstreamClient, parse_upstream_error from zcode_gateway.zcode_protocol import build_body @@ -524,3 +524,62 @@ async def test_suspended_account_leaves_rotation_instead_of_parking_one_model(): assert account.death_reason == "suspended" assert MODEL not in account.model_caps assert await service.pool.acquire() is None + + +EDGE_405_HTML = ( + '' + '405' + '
the request was blocked by the edge
' + '') + + +def test_parse_upstream_error_sanitizes_html_edge_page(): + info = parse_upstream_error(405, EDGE_405_HTML) + assert info['code'] == 'http_405' + assert ' JSONResponse: + extra: dict | None = None, + retry_after: float | None = None) -> JSONResponse: + headers = ({'Retry-After': retry_after_header(retry_after)} if retry_after is not None else None) return JSONResponse(status_code=status, - content=anthropic_error(status, code, message, extra)) + content=anthropic_error(status, code, message, extra), + headers=headers) @router.post("/v1/messages") @@ -86,7 +89,8 @@ async def messages( return _error(503, "no usable Zcode account in the pool", "NO_USABLE_ACCOUNTS") except UpstreamFailure as exc: - return _error(exc.status, exc.message, exc.code, exc.extra()) + return _error(exc.status, exc.message, exc.code, exc.extra(), + retry_after=exc.retry_after) @router.post("/v1/messages/count_tokens") diff --git a/zcode_gateway/api_openai.py b/zcode_gateway/api_openai.py index 95ec08b..913f8e4 100644 --- a/zcode_gateway/api_openai.py +++ b/zcode_gateway/api_openai.py @@ -14,7 +14,7 @@ from .deps import client_key, get_state from .service import NoAccountsAvailable, UpstreamFailure, aggregate_openai_stream from .translate_anthropic import extract_stream_error, stream_had_content -from .upstream import openai_error +from .upstream import openai_error, retry_after_header router = APIRouter(tags=["openai"]) @@ -26,9 +26,12 @@ def _error_response(status: int, code: str, message: str, - extra: dict | None = None) -> JSONResponse: + extra: dict | None = None, + retry_after: float | None = None) -> JSONResponse: + headers = ({'Retry-After': retry_after_header(retry_after)} if retry_after is not None else None) return JSONResponse(status_code=status, - content=openai_error(status, code, message, extra)) + content=openai_error(status, code, message, extra), + headers=headers) def _valid_messages(messages: Any) -> bool: @@ -121,7 +124,8 @@ async def chat_completions( return _error_response(503, "no_accounts_available", "no usable Zcode account in the pool") except UpstreamFailure as exc: - return _error_response(exc.status, exc.code, exc.message, exc.extra()) + return _error_response(exc.status, exc.code, exc.message, exc.extra(), + retry_after=exc.retry_after) @router.post("/v1/completions") diff --git a/zcode_gateway/pool.py b/zcode_gateway/pool.py index c3189f2..e562141 100644 --- a/zcode_gateway/pool.py +++ b/zcode_gateway/pool.py @@ -17,6 +17,7 @@ from .affinity import AffinityMap from .config import AccountsConfig, PoolConfig +from .upstream import sanitize_cap_message # grant-window clock-skew grace: a starts_at less than this far in the future # counts as "open now" both for routing and for WINDOW_CLOSED parking @@ -923,10 +924,13 @@ async def unavailable_reason(self, model: str) -> dict | None: info = account.model_cap_info.get(model, {}) code = info.get("code", "MODEL_PARKED") until = account.model_caps.get(model, 0.0) + status = 403 if _is_ent(code) else 429 return { - "status": 403 if _is_ent(code) else 429, + "status": status, "code": code, - "message": info.get("message", ""), + # caps persisted before HTML was sanitized at write time must + # not replay a raw CDN page to the client after a restart + "message": sanitize_cap_message(info.get("message", "")), "release_at": info.get("release_at"), "release_in_s": int(max(until - time.time(), 0)), } diff --git a/zcode_gateway/service.py b/zcode_gateway/service.py index efb3165..b108956 100644 --- a/zcode_gateway/service.py +++ b/zcode_gateway/service.py @@ -21,26 +21,50 @@ from .upstream import (build_headers, build_upstream_body, iter_sse_events, sse_frame, parse_upstream_error, anthropic_error, openai_error, TransportError, is_block_code, is_concurrency_code, client_not_supported, - is_account_suspended, CLIENT_NOT_SUPPORTED_PARK_S) + is_account_suspended, CLIENT_NOT_SUPPORTED_PARK_S, + sanitize_error_message, sanitize_cap_message) from .registry import model_caps from .zcode_device import new_account_device_mid log = logging.getLogger('zcode_gateway.service') +# A suspended account is dead upstream, but the pool may still have healthy +# accounts: the request rotates instead of failing. Only a pool that cannot +# serve at all gets this retryable soft error. +SUSPENSION_RETRY_AFTER_S = 30 + class NoAccountsAvailable(Exception): pass class UpstreamFailure(Exception): - def __init__(self, status, code, message, release_at=None, release_in_s=None, details=None, retry_after=None): + def __init__(self, status, code, message, release_at=None, release_in_s=None, details=None, retry_after=None, soft=False): super().__init__(message) self.status, self.code, self.message = status, str(code), message self.release_at, self.release_in_s, self.details = release_at, release_in_s, details or {} self.retry_after = retry_after + self.soft = soft def extra(self): out = dict(self.details) if self.release_at: out['release_at'] = self.release_at if self.release_in_s is not None: out['release_in_s'] = self.release_in_s return out + +def _is_suspension_failure(exc) -> bool: + return isinstance(exc, UpstreamFailure) and is_account_suspended(exc.message) + + +def _soft_suspension_failure() -> UpstreamFailure: + return UpstreamFailure(503, 'server_error', + 'ZCode accounts temporarily unavailable; try again later', + retry_after=SUSPENSION_RETRY_AFTER_S, + details={'reason': 'account_suspended'}, soft=True) + + +def _soft_sse_extra(soft: UpstreamFailure) -> dict: + # vercel/ai marks a stream error retryable from these fields, not the HTTP + # status of the frame; the message alone only matches the plain-text branch. + return {'status': soft.status, 'isRetryable': True} + @dataclass class StreamHandle: account: Account @@ -182,6 +206,13 @@ async def _close(self, handle): async def _apply_error(self, account, model, status, code, message, headers=None, *, expected_credentials=None): if expected_credentials is not None and account.credential_key() != expected_credentials: return + # Defence in depth: an HTML CDN page that slipped past the breaker must + # not become an account/model cap reason or a dashboard error entry. + raw_message = message + message = sanitize_error_message(status, message) + # Cap reasons are replayed to clients when the pool is exhausted; keep + # them short and single-line, while the full text stays in the log. + cap_message = sanitize_cap_message(message) if is_concurrency_code(code): # Upstream still counts a slot as busy for this account: bench it # briefly so the retry rotates instead of immediately re-hitting @@ -197,9 +228,20 @@ async def _apply_error(self, account, model, status, code, message, headers=None try: account.error_history.append( {"ts": time.time(), "status": status, "code": str(code), - "message": str(message)[:200], "model": model}) + "message": str(message), "model": model}) except Exception: pass + if is_account_suspended(message): + # The account itself is banned upstream for proxying: no model on + # it can serve, and retrying only produces another refusal. This + # holds for every envelope (405 JSON, no-code SSE frame, 5xx), so + # key on the message, not the status/code shape. + log.warning('ZCode account %s (%s) SUSPENDED by upstream (status=%s code=%s): %s', + account.id, account.email, status, code, raw_message) + await self.pool.kill(account, reason=str(message)[:200], + cause='suspended', + expected_credentials=expected_credentials) + return if status == 401 or code == 'authentication_error': await self.pool.kill_after_strikes(account, 'ZCode token revoked; sign in again', expected_credentials=expected_credentials) @@ -214,28 +256,18 @@ async def _apply_error(self, account, model, status, code, message, headers=None # not match. Every account then fails identically, so a 900s park # per account only spreads a pool-wide outage over 15 minutes of # misleading state. Park briefly and name the real cause instead. - if is_account_suspended(message): - # The account itself is banned upstream for proxying: no model - # on it can serve, and retrying only produces a 405 per request. - # Take it out of rotation until an operator re-enables it. - log.warning('ZCode account %s (%s) SUSPENDED by upstream (status=%s code=%s): %s', - account.id, account.email, status, code, message) - await self.pool.kill(account, reason=str(message)[:200], - cause='suspended', - expected_credentials=expected_credentials) - return if status == 405: - log.warning('ZCode 405/3012 on account %s model %s: %s', account.id, model, message) + log.warning('ZCode 405/3012 on account %s model %s: %s', account.id, model, raw_message) if client_not_supported(message): await self.pool.cap_model(account, model, CLIENT_NOT_SUPPORTED_PARK_S, reason='CLIENT_NOT_SUPPORTED', - message=message, + message=cap_message, expected_credentials=expected_credentials) else: await self.pool.cap_model(account, model, self.cfg.pool.blocked_model_cooldown_seconds, - reason='UNUSUAL_ACTIVITY', message=message, + reason='UNUSUAL_ACTIVITY', message=cap_message, expected_credentials=expected_credentials) elif code in ('11113', '1005') or status == 402: # 1005 is the SAME "exceed quota limit" rejection under an HTTP @@ -258,7 +290,7 @@ async def _apply_error(self, account, model, status, code, message, headers=None if remaining > 0: await self.pool.cap_model(account, model, 600, reason='11113' if code == '11113' else '1005', - message=message, expected_credentials=expected_credentials) + message=cap_message, expected_credentials=expected_credentials) return seconds = max(1, quota.get('resets_at', 0) - time.time()) if quota else 0 if seconds <= 1: @@ -282,7 +314,7 @@ async def _apply_error(self, account, model, status, code, message, headers=None seconds = 900 # park the model past the churn window await self.pool.cap_model(account, model, seconds, reason='11113' if code == '11113' else '1005', - message=message, expected_credentials=expected_credentials) + message=cap_message, expected_credentials=expected_credentials) elif status == 429 or code == 'rate_limit_error': # reuse the shared parser: handles retry-after-ms, seconds and # HTTP-dates (a millisecond hint used to fall through to the @@ -291,17 +323,17 @@ async def _apply_error(self, account, model, status, code, message, headers=None hinted = retry_after_seconds(headers or {}) seconds = min(3600, max(1, hinted if hinted is not None else self.cfg.pool.cooldown_seconds)) - await self.pool.cap_model(account, model, seconds, reason='RATE_LIMITED', message=message, + await self.pool.cap_model(account, model, seconds, reason='RATE_LIMITED', message=cap_message, expected_credentials=expected_credentials) elif status == 403: - await self.pool.cap_model(account, model, 300, reason='ENTITLEMENT_ERROR', message=message, + await self.pool.cap_model(account, model, 300, reason='ENTITLEMENT_ERROR', message=cap_message, expected_credentials=expected_credentials) elif status == 451: # Geo/legal block tied to this account's egress context: park the # model on THIS account only and let the caller rotate to another # account (different IP) — the account itself stays healthy. await self.pool.cap_model(account, model, 600, - reason='GEO_BLOCKED', message=message or 'HTTP 451', + reason='GEO_BLOCKED', message=cap_message or 'HTTP 451', expected_credentials=expected_credentials) elif status >= 500: await self.pool.cool(account, reason='upstream_error', expected_credentials=expected_credentials) @@ -343,9 +375,12 @@ def _describe_failure(exc) -> str: @staticmethod def _retryable(exc) -> bool: # transport-level only: a dead/cut connection, or a clean EOF with no - # message_stop. Upstream error events and parse errors are not retried. + # message_stop. Upstream error events and parse errors are not retried, + # except a suspension: its account is dead, so a fresh account is the + # only way the request can still succeed. return isinstance(exc, httpx.HTTPError) or ( - isinstance(exc, UpstreamFailure) and exc.code == 'truncated_stream') + isinstance(exc, UpstreamFailure) and ( + exc.code == 'truncated_stream' or _is_suspension_failure(exc))) def _log_stream_failure(self, handle, exc, *, committed, events, retry): acct = handle.account @@ -363,6 +398,8 @@ async def _after_stream_failure(self, handle, exc, *, committed, events, retries will_retry = (not committed) and retries_left > 0 and self._retryable(exc) self._log_stream_failure(handle, exc, committed=committed, events=events, retry=will_retry) if not will_retry: + if _is_suspension_failure(exc): + raise _soft_suspension_failure() return None reopen = getattr(handle, 'reopen', None) if reopen is None: @@ -375,10 +412,19 @@ async def _after_stream_failure(self, handle, exc, *, committed, events, retries return await reopen() except asyncio.CancelledError: raise + except UpstreamFailure as exc2: + if exc2.soft: + raise + log.warning('ZCode stream retry could not open a new upstream stream (%s) - ' + 'reporting the original failure', self._describe_failure(exc2)) except Exception as exc2: log.warning('ZCode stream retry could not open a new upstream stream (%s) - ' 'reporting the original failure', self._describe_failure(exc2)) - return None + if _is_suspension_failure(exc): + # the suspended account is dead and no replacement could be opened: + # the client gets the neutral retryable error, never the raw ban text + raise _soft_suspension_failure() + return None async def open_stream(self, payload, *, model, variant='anthropic', dialect='openai', client_key='anonymous', is_disconnected=None): snapshot = _snapshot_payload(payload) @@ -479,11 +525,15 @@ async def _open_model_stream_once(self, payload, *, model, variant='anthropic', account = await self.pool.acquire(tried, model=model, only_id=target_account, affinity_key=affinity_key) if account is None: - if last: raise last + if last: + if _is_suspension_failure(last): + raise _soft_suspension_failure() + raise last reason = await self.pool.unavailable_reason(model) if reason: raise UpstreamFailure(reason['status'], reason['code'], reason['message'], - reason.get('release_at'), reason.get('release_in_s')) + reason.get('release_at'), reason.get('release_in_s'), + retry_after=reason.get('release_in_s')) raise NoAccountsAvailable() device_mid = account.notes.get('device_mid') if not device_mid: @@ -563,8 +613,10 @@ async def _open_model_stream_once(self, payload, *, model, variant='anthropic', and code != '11113' and not is_block_code(code, status)): raise last # a killed account cannot serve this request; rotating - # now only burns the next account on the same ban - if account.state is AccountState.DEAD: + # now only burns the next account on the same ban. A + # suspension is the exception: the ban is account-wide, + # so the next account may well be healthy. + if account.state is AccountState.DEAD and not _is_suspension_failure(last): raise last tried.add(account.id) continue @@ -595,7 +647,7 @@ async def _open_model_stream_once(self, payload, *, model, variant='anthropic', expected_credentials=credentials) last = UpstreamFailure(status, code, message) if is_model_overload(status, code): raise last - if account.state is AccountState.DEAD: + if account.state is AccountState.DEAD and not _is_suspension_failure(last): raise last tried.add(account.id) break @@ -648,6 +700,8 @@ async def _open_model_stream_once(self, payload, *, model, variant='anthropic', await self.pool.release(account) if attempt + 1 < self.cfg.upstream.max_attempts: await asyncio.sleep(0.1 * (attempt + 1)) + if last is not None and _is_suspension_failure(last): + raise _soft_suspension_failure() raise last or NoAccountsAvailable() async def stream(self, payload, *, model, variant='anthropic', dialect='openai', client_key='anonymous', anthropic=False): @@ -688,14 +742,6 @@ async def events(): text = json.dumps(event, ensure_ascii=False) captured.append(text) capture_size += len(text) - if not committed: - if kind in ('message_start', 'ping'): - prelude.append(event) - continue - committed = True - for held in prelude: - for out in emit(held): yield out - prelude.clear() # OpenAI-shaped mid-stream error frame: {"error":{...}} with # no "type" key (captured 2026-09-16). Without this branch it # fell through to the Anthropic passthrough as `event: None` @@ -708,11 +754,36 @@ async def events(): 429 if code in ('11113', 'rate_limit_error') or is_concurrency_code(code) else 502) await self._apply_error(handle.account, model, status, code, message, expected_credentials=handle.credentials) + suspension = is_account_suspended(message) + # nothing but the buffered prelude has reached the client yet: + # let the outer retry loop re-open on another account + if suspension and not committed: + raise UpstreamFailure(status, code, message) + if not committed: + committed = True + for held in prelude: + for out in emit(held): yield out + prelude.clear() self._log_stream_failure(handle, UpstreamFailure(status, code, message), committed=committed, events=seen, retry=False) - yield _sse_event('error', event) if anthropic else sse_frame(openai_error(status, code, message)) + if suspension: + soft = _soft_suspension_failure() + extra = _soft_sse_extra(soft) + error = anthropic_error(soft.status, soft.code, soft.message, extra) \ + if anthropic else openai_error(soft.status, soft.code, soft.message, extra) + yield _sse_event('error', error) if anthropic else sse_frame(error) + else: + yield _sse_event('error', event) if anthropic else sse_frame(openai_error(status, code, message)) if not anthropic: yield b'data: [DONE]\n\n' return + if not committed: + if kind in ('message_start', 'ping'): + prelude.append(event) + continue + committed = True + for held in prelude: + for out in emit(held): yield out + prelude.clear() for out in emit(event): yield out if kind == 'message_stop': stopped = True @@ -741,10 +812,11 @@ async def events(): status = 499 raise except (httpx.HTTPError, ValueError, KeyError, UpstreamFailure) as exc: - status = 502 + status = exc.status if isinstance(exc, UpstreamFailure) else 502 code = getattr(exc, 'code', 'stream_error') message = getattr(exc, 'message', 'ZCode stream interrupted') - error = anthropic_error(status, code, message) if anthropic else openai_error(status, code, message) + extra = _soft_sse_extra(exc) if getattr(exc, 'soft', False) else None + error = anthropic_error(status, code, message, extra) if anthropic else openai_error(status, code, message, extra) yield _sse_event('error', error) if anthropic else sse_frame(error) if not anthropic: yield b'data: [DONE]\n\n' finally: diff --git a/zcode_gateway/upstream.py b/zcode_gateway/upstream.py index 25f2e63..56c2f39 100644 --- a/zcode_gateway/upstream.py +++ b/zcode_gateway/upstream.py @@ -213,7 +213,47 @@ def _looks_like_edge_block(body: str | bytes | None) -> bool: else (body or "")).lower() if "405 with + # data-spm markers): same IP-wide edge response, not an account or model + # problem. Only HTML bodies qualify. + return re.search(r"\s*[1-5]\d\d\b", text) is not None + + +def _html_edge_message(status: int) -> str: + return f"upstream edge error (HTTP {status}): CDN returned an HTML error page" + + +def sanitize_error_message(status: int, message: str | None) -> str: + """Never let a raw CDN HTML page become a client-visible error message or + a stored account/model cap reason.""" + text = str(message or "") + lowered = text.lower() + if "<html" in lowered or "<!doctype" in lowered: + return _html_edge_message(status) + return text + + +def sanitize_cap_message(message: str | None, limit: int = 300) -> str: + """A model-cap reason is replayed to clients when the pool is exhausted: + keep it short and single-line, never raw HTML.""" + text = str(message or "") + lowered = text.lower() + if "<html" in lowered or "<!doctype" in lowered: + return "upstream error; the provider returned an HTML page (see gateway logs)" + return " ".join(text.split())[:limit] + + +RETRY_AFTER_MAX_S = 120 + + +def retry_after_header(value: float | None) -> str | None: + """Client-facing Retry-After, clamped: upstream hints can run for hours and + clients honour an explicit header exactly.""" + if value is None: + return None + return str(min(RETRY_AFTER_MAX_S, max(1, int(value)))) def classify(status: int, body: str | bytes | None = None) -> ErrorKind: @@ -255,18 +295,21 @@ def edge_block_message(body: str | bytes | None) -> str: def parse_upstream_error(status: int, body: str | bytes | None) -> dict[str, Any]: """Normalise an upstream error body (captured shape) into a dict.""" text = body.decode("utf-8", "replace") if isinstance(body, bytes) else (body or "") + # Never replay the first 400 characters of a CDN HTML page as the error + # message: that raw page used to reach clients and account model caps. + fallback = sanitize_error_message(status, text[:400]) try: parsed = json.loads(text) err = parsed.get("error", parsed) if isinstance(err, dict): return { "code": str(err.get("code") or err.get("statusCode") or err.get("type") or f"http_{status}"), - "message": err.get("message") or err.get("msg") or text[:400], + "message": err.get("message") or err.get("msg") or fallback, "raw": parsed, } except Exception: pass - return {"code": f"http_{status}", "message": text[:400], "raw": None} + return {"code": f"http_{status}", "message": fallback, "raw": None} # Mapping for the OpenAI-compatible error envelope.