From 114288f9218e271251a46af0698069ca163d00e7 Mon Sep 17 00:00:00 2001 From: B3hnamR Date: Sat, 21 Nov 2026 05:46:04 +0330 Subject: [PATCH 1/4] 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/4] 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/4] 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/4] 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(); }