Skip to content

Make sessions survive ZCode concurrency refusals - #3

Closed
mahyartdb wants to merge 4 commits into
B3hnamR:masterfrom
mahyartdb:fix/concurrency-resilience
Closed

mahyartdb wants to merge 4 commits into
B3hnamR:masterfrom
mahyartdb:fix/concurrency-resilience

Conversation

@mahyartdb

@mahyartdb mahyartdb commented Nov 21, 2026 •

Copy link
Copy Markdown

Problem

ZCode answers a second concurrent request on one account with
3008/3009/3010 (user concurrency limit exceeded). The gateway admitted up
to four requests per account, treated the refusal like a generic error, and
retried the same account immediately. A burst of real sessions therefore lost
requests even when the pool had free accounts.

Suspended accounts had a similar failure: a 405/3012 saying the account was
suspended for proxying parked only the requested model, so the banned account
stayed in rotation and returned 405 on every request. The dashboard hid all of
this behind an N err tooltip.

Changes

  • Treat 3008/3009/3010 as retryable capacity errors.
  • Admit one in-flight request per account and queue the rest
    (acquire_wait_seconds, default 120s) instead of over-admitting.
  • After a refusal, hold the account with exponential backoff (10s doubling to
    60s, cleared by the next success). State stays READY; no cooldown, model
    park, or error history.
  • Detect the account-suspension message and mark the account DEAD with
    death_reason=suspended, so it leaves rotation until an operator re-enables
    it.
  • Accounts page: add an Issues metric and a Needs attention panel naming each
    blocked account, its reason, and an Enable action for dead accounts. Show the
    last error inline with its age, and show concurrency holds / cooldowns under
    the state badge.

Tests

  • pytest -q: 1393 passed, 147 skipped.
  • New regressions cover queueing, hold escalation and clearing, affinity
    skipping a held account, burst routing, and suspension removal.
  • Validated on a live gateway: 12/12 concurrent requests returned 200, 9/9
    accounts ready, and a suspended account left rotation on the first upstream
    405.

Summary by cubic

Fixes request loss when ZCode enforces per-account concurrency limits and removes suspended accounts from rotation instead of retrying them on every request.

Bug Fixes

  • Treats 3008/3009/3010 as retryable capacity errors and normalizes them to HTTP 429.
  • Limits each account to one in-flight request and queues the rest (default 120s wait) instead of over-admitting.
  • After a refusal, benches the account with exponential backoff (10s doubling to 60s, cleared by success) without cooling, parking, or error history.
  • Recognizes the account-suspension message and marks the account DEAD with reason suspended; it stays out of rotation until an operator re-enables it.

New Features

  • Accounts page: added an Issues metric and a Needs attention panel listing blocked accounts with reasons and an Enable action for dead ones.
  • Shows the last error inline with its age and surfaces concurrency holds and cooldowns under the state badge.

Written for commit ae03463. Summary will update on new commits.

View guided diff

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.
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.
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.
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.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

8 issues found across 12 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="config.example.yaml">

<violation number="1" location="config.example.yaml:27">
P2: Standalone installs without a bundled `config.example.yaml` still receive the old `4`/`5` pool settings from `paths.DEFAULT_CONFIG_YAML`, so this concurrency fix does not apply to them. Synchronize the built-in first-run template with these new values.</violation>
</file>

<file name="zcode_gateway/config.py">

<violation number="1" location="zcode_gateway/config.py:247">
P1: These new defaults are bypassed for fresh installs because the actual bootstrap and Linux installer templates still write `4` concurrent requests per account and a `5s` queue timeout. Update those templates so the concurrency fix applies without manual config edits.</violation>

<violation number="2" location="zcode_gateway/config.py:256">
P2: `concurrency_hold_seconds` accepts positive infinity, which permanently removes an account from rotation after one refusal. Add `allow_inf_nan=False` to the new pool duration fields so malformed YAML or environment overrides fail validation.</violation>
</file>

<file name="zcode_gateway/pool.py">

<violation number="1" location="zcode_gateway/pool.py:77">
P2: Re-login and manual re-enable leave `concurrency_hold_until` and `concurrency_strikes` from the previous credential/state. Clear both fields whenever an account is re-enabled or its credentials are replaced, otherwise a recovered account can remain unavailable for up to the old hold and inherit its old backoff.</violation>
</file>

<file name="zcode_gateway/dashboard/assets/js/views/accounts.js">

<violation number="1" location="zcode_gateway/dashboard/assets/js/views/accounts.js:122">
P3: This hold can result from 3008, 3009, or 3010, but the dashboard always reports 3008. Use a generic concurrency-limit label or list all three codes in both the tooltip and Needs attention detail.</violation>

<violation number="2" location="zcode_gateway/dashboard/assets/js/views/accounts.js:212">
P2: The attention panel marks expired cooldowns as active issues. Require a positive `cooldown_in_s` here, otherwise the dashboard shows `Cooling —` for an account that can already serve.</violation>
</file>

<file name="zcode_gateway/upstream.py">

<violation number="1" location="zcode_gateway/upstream.py:177">
P2: `is_account_suspended()` matches any `"has been suspended"` message, so a model- or service-level suspension can permanently mark a healthy account `DEAD`. Require an account-specific marker such as `"account has been suspended"` before calling `pool.kill()`.</violation>
</file>

<file name="zcode_gateway/service.py">

<violation number="1" location="zcode_gateway/service.py:691">
P3: Use `_stream_error_status(code)` here instead of duplicating the conditional. The duplicate omits the helper's 405/block mapping, so mid-stream `3012`/`405` errors report 502 while the other stream paths report 405.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic

Comment thread zcode_gateway/config.py
# (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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: These new defaults are bypassed for fresh installs because the actual bootstrap and Linux installer templates still write 4 concurrent requests per account and a 5s queue timeout. Update those templates so the concurrency fix applies without manual config edits.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At zcode_gateway/config.py, line 247:

<comment>These new defaults are bypassed for fresh installs because the actual bootstrap and Linux installer templates still write `4` concurrent requests per account and a `5s` queue timeout. Update those templates so the concurrency fix applies without manual config edits.</comment>

<file context>
@@ -235,11 +241,20 @@ class PoolConfig(BaseModel):
+    # (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)
</file context>

Comment thread config.example.yaml
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Standalone installs without a bundled config.example.yaml still receive the old 4/5 pool settings from paths.DEFAULT_CONFIG_YAML, so this concurrency fix does not apply to them. Synchronize the built-in first-run template with these new values.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At config.example.yaml, line 27:

<comment>Standalone installs without a bundled `config.example.yaml` still receive the old `4`/`5` pool settings from `paths.DEFAULT_CONFIG_YAML`, so this concurrency fix does not apply to them. Synchronize the built-in first-run template with these new values.</comment>

<file context>
@@ -16,11 +16,18 @@ upstream:
-  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
</file context>

Comment thread zcode_gateway/config.py
Comment on lines +256 to +257
concurrency_hold_seconds: float = Field(default=10.0, ge=0)
concurrency_hold_max_seconds: float = Field(default=60.0, ge=0)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: concurrency_hold_seconds accepts positive infinity, which permanently removes an account from rotation after one refusal. Add allow_inf_nan=False to the new pool duration fields so malformed YAML or environment overrides fail validation.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At zcode_gateway/config.py, line 256:

<comment>`concurrency_hold_seconds` accepts positive infinity, which permanently removes an account from rotation after one refusal. Add `allow_inf_nan=False` to the new pool duration fields so malformed YAML or environment overrides fail validation.</comment>

<file context>
@@ -235,11 +241,20 @@ class PoolConfig(BaseModel):
+    # 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)
</file context>
Suggested change
concurrency_hold_seconds: float = Field(default=10.0, ge=0)
concurrency_hold_max_seconds: float = Field(default=60.0, ge=0)
concurrency_hold_seconds: float = Field(default=10.0, ge=0, allow_inf_nan=False)
concurrency_hold_max_seconds: float = Field(default=60.0, ge=0, allow_inf_nan=False)

Comment thread zcode_gateway/pool.py
# 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Re-login and manual re-enable leave concurrency_hold_until and concurrency_strikes from the previous credential/state. Clear both fields whenever an account is re-enabled or its credentials are replaced, otherwise a recovered account can remain unavailable for up to the old hold and inherit its old backoff.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At zcode_gateway/pool.py, line 77:

<comment>Re-login and manual re-enable leave `concurrency_hold_until` and `concurrency_strikes` from the previous credential/state. Clear both fields whenever an account is re-enabled or its credentials are replaced, otherwise a recovered account can remain unavailable for up to the old hold and inherit its old backoff.</comment>

<file context>
@@ -70,6 +70,13 @@ 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.
+    concurrency_hold_until: float = 0.0
+    concurrency_strikes: int = 0
+
</file context>

detail: "Upstream reported a concurrency limit (3008); retries resume on their own.",
};
}
if (a.state === "cooling") {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The attention panel marks expired cooldowns as active issues. Require a positive cooldown_in_s here, otherwise the dashboard shows Cooling — for an account that can already serve.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At zcode_gateway/dashboard/assets/js/views/accounts.js, line 212:

<comment>The attention panel marks expired cooldowns as active issues. Require a positive `cooldown_in_s` here, otherwise the dashboard shows `Cooling —` for an account that can already serve.</comment>

<file context>
@@ -112,18 +112,156 @@ function tokenCell(a) {
+      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),
</file context>
Suggested change
if (a.state === "cooling") {
if (a.state === "cooling" && Number(a.cooldown_in_s) > 0) {

Comment thread zcode_gateway/upstream.py
# 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")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: is_account_suspended() matches any "has been suspended" message, so a model- or service-level suspension can permanently mark a healthy account DEAD. Require an account-specific marker such as "account has been suspended" before calling pool.kill().

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At zcode_gateway/upstream.py, line 177:

<comment>`is_account_suspended()` matches any `"has been suspended"` message, so a model- or service-level suspension can permanently mark a healthy account `DEAD`. Require an account-specific marker such as `"account has been suspended"` before calling `pool.kill()`.</comment>

<file context>
@@ -157,6 +169,19 @@ def client_not_supported(message: str | None) -> bool:
+# 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")
+
+
</file context>
Suggested change
SUSPENSION_MARKERS = ("has been suspended", "account suspended")
SUSPENSION_MARKERS = ("account has been suspended", "account suspended")

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). "

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: This hold can result from 3008, 3009, or 3010, but the dashboard always reports 3008. Use a generic concurrency-limit label or list all three codes in both the tooltip and Needs attention detail.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At zcode_gateway/dashboard/assets/js/views/accounts.js, line 122:

<comment>This hold can result from 3008, 3009, or 3010, but the dashboard always reports 3008. Use a generic concurrency-limit label or list all three codes in both the tooltip and Needs attention detail.</comment>

<file context>
@@ -112,18 +112,156 @@ function tokenCell(a) {
+  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.",
+    }));
</file context>

Comment thread zcode_gateway/service.py
Comment on lines +691 to +692
status = 529 if is_model_overload(502, code) else (
429 if code in ('11113', 'rate_limit_error') or is_concurrency_code(code) else 502)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: Use _stream_error_status(code) here instead of duplicating the conditional. The duplicate omits the helper's 405/block mapping, so mid-stream 3012/405 errors report 502 while the other stream paths report 405.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At zcode_gateway/service.py, line 691:

<comment>Use `_stream_error_status(code)` here instead of duplicating the conditional. The duplicate omits the helper's 405/block mapping, so mid-stream `3012`/`405` errors report 502 while the other stream paths report 405.</comment>

<file context>
@@ -640,7 +688,8 @@ async def events():
                             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,
</file context>
Suggested change
status = 529 if is_model_overload(502, code) else (
429 if code in ('11113', 'rate_limit_error') or is_concurrency_code(code) else 502)
status = _stream_error_status(code)

@mahyartdb

Copy link
Copy Markdown
Author

Superseded by #4, which carries these four commits together with the account-identity and tray work on top of them. Keeping one PR so the whole change is reviewed and merged in one piece; nothing here is lost.

@mahyartdb mahyartdb closed this Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants