Skip to content

Keep the gateway serving: concurrency, account identity, and the tray - #4

Closed
mahyartdb wants to merge 7 commits into
B3hnamR:masterfrom
mahyartdb:account-identity-and-tray
Closed

mahyartdb wants to merge 7 commits into
B3hnamR:masterfrom
mahyartdb:account-identity-and-tray

Conversation

@mahyartdb

@mahyartdb mahyartdb commented Nov 22, 2026 •

Copy link
Copy Markdown

One PR for the three things that kept the gateway from serving reliably: requests lost to ZCode's per-account concurrency limit, accounts suspended for looking like one machine, and closing the window killing the process.

Problem

Concurrency. 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. A 405/3012 suspension parked only the requested model, so the banned account stayed in rotation and returned 405 on every request, and the dashboard hid all of it behind an N err tooltip.

Account identity. Every account imported or logged in on one machine shared the same x-device-mid and the same timezone, so upstream saw one device cycling through many credentials — the pattern its risk control suspends. Hard state (DEAD / EXHAUSTED / cooling) lived only in memory, so a restart resurrected suspended accounts as READY and kept retrying them.

No way to stay running. Closing the window quit the gateway.

Changes

Concurrency refusals

  • Treat 3008/3009/3010 as retryable capacity errors and normalize them to HTTP 429.
  • 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.
  • Refusal strikes decay after a quiet gap instead of stacking to the maximum hold forever.
  • A released account waits concurrency_settle_seconds (default 5) before re-admission, because upstream still counts the finished request; this removes most of the remaining 3008 churn.
  • Detect the account-suspension message and mark the account DEAD with death_reason=suspended, log the upstream text, and abort the request instead of rotating the ban onto the next account.

Account identity and ban safety

  • Each account gets its own stable device id: uuid4 stored with the credentials for new logins, uuid5 of the account id for imports and backfills. The generator (plan_check.py, invite_claim.py) derives the same id, so a plan check and a message report the same device instead of a hardcoded shared one.
  • Each account keeps its own timezone instead of the host's.
  • DEAD, EXHAUSTED and active COOLING states are written back to the live account source, so a restart no longer re-admits a suspended account.
  • scripts/accounts/backfill_device_mids.py migrates existing snapshots and is a dry run unless --apply is passed.

Tray

  • Closing the window hides it to a notification-area icon and the gateway keeps serving. The menu has the dashboard, the address, the log, the data folder and Quit.
  • The icon is drawn with ctypes (Shell_NotifyIcon on a hidden top-level window) rather than pystray/Pillow, which would add roughly 15 MB to a onefile exe that is already 60 MB. The hidden window is top-level so TaskbarCreated re-registers the icon after an Explorer restart.
  • --no-tray restores close-to-quit, --tray starts hidden in the tray, --headless is unchanged.
  • Tray failure is non-fatal: start() returns False and the app keeps its old behaviour. If the tray thread dies, closing the window quits instead of stranding a process with no window and no icon.

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.

Testing

  • python -m pytest tests -q → 1424 passed, 147 skipped.
  • ruff check --select E9,F63,F7,F82,F811,F841 → clean.
  • New regressions cover queueing, hold escalation and clearing, the settle window, affinity skipping a held account, burst routing, suspension removal, per-account device ids, hard-state write-back, and the tray registration flags.
  • Built with scripts/build/windows.ps1 and run as the deployed exe: 12/12 concurrent requests returned 200 with 9/9 accounts ready, a suspended account left rotation on the first upstream 405, closing the window hid it while both processes and /health stayed up, the icon was present in the notification area (Shell_NotifyIconGetRect returns S_OK with a real rect), left-click reopened the dashboard, the menu opened, Quit exited cleanly, and a restart came back healthy.

Notes

  • The new pool settings have defaults, so an existing config.yaml keeps working without edits.
  • backfill_device_mids.py is the only migration step; without it, existing snapshots keep their shared mid until they are next rewritten.
  • Supersedes Make sessions survive ZCode concurrency refusals #3, which carried the first four commits on their own.

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.
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).
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.
@mahyartdb mahyartdb changed the title Keep accounts distinct, and keep the gateway running in the tray Keep the gateway serving: concurrency, account identity, and the tray Nov 22, 2026

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

30 issues found across 38 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="zcode_gateway/dashboard/assets/js/views/accounts.js">

<violation number="1" location="zcode_gateway/dashboard/assets/js/views/accounts.js:216">
P3: This hold also represents 3009 and 3010 refusals, so the fixed `3008` explanation misidentifies those errors. Remove the code number from both concurrency descriptions.</violation>

<violation number="2" location="zcode_gateway/dashboard/assets/js/views/accounts.js:220">
P2: A COOLING account shows as 'Settling' here whenever a release just happened, which hides the cooldown and drops it from Issues. Check `a.state !== "cooling"` before treating the account as settling.</violation>

<violation number="3" location="zcode_gateway/dashboard/assets/js/views/accounts.js:239">
P2: A stale or transient quota-check error puts a still-serving account under 'Needs attention' and counts it as an issue. Limit this check to accounts that are not already serving, or drop it from the attention card.</violation>
</file>

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

<violation number="1" location="zcode_gateway/device_auth.py:100">
P2: A re-login keeps the snapshot's existing `device_mid`, including the legacy shared one, so the account stays correlated with other accounts. Replace the stored mid when it is empty or equals the shared fingerprint mid, so a re-login migrates it.</violation>
</file>

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

<violation number="1" location="zcode_gateway/tray.py:329">
P3: `ExtractIconExW` also returns the large icon, which is never released. Destroy `large` after extraction, since only the small icon is used.</violation>

<violation number="2" location="zcode_gateway/tray.py:345">
P2: The Explorer-restart handler ignores a failed icon re-add, while `alive` remains true; closing the dashboard afterward can hide the only window with no tray icon to reopen it. Propagate re-add failure and restore the dashboard when the tray becomes unavailable.</violation>

<violation number="3" location="zcode_gateway/tray.py:460">
P3: `_run` destroys the icon handle on exit, but the `LoadIconW(None, IDI_APPLICATION)` fallback returns a shared system icon. `DestroyIcon` should not be called on shared icons. Track whether the handle was loaded from a file or extracted, and destroy only those.</violation>
</file>

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

<violation number="1" location="zcode_gateway/app.py:88">
P2: The state saver is wired only for `accounts_dir` and `pool_file`. With `accounts.source: providers_json` (selectable in the dashboard and GUI), DEAD and EXHAUSTED states are never persisted, so a restart resurrects a banned account as READY, the exact outcome this block is meant to prevent. Either persist to that source or state explicitly that it is read-only and that hard state is intentionally not kept for it.</violation>
</file>

<file name="scripts/accounts/backfill_device_mids.py">

<violation number="1" location="scripts/accounts/backfill_device_mids.py:42">
P1: `parse_snapshot` returns `{}` on read or decode errors instead of raising, so this `except` never fires. An unreadable snapshot (for example non-UTF-8 bytes) is treated as having no `device_mid` and gets overwritten with only that field, destroying its credentials under `--apply`. Skip any snapshot that parses to an empty dict.</violation>
</file>

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

<violation number="1" location="zcode_gateway/config.py:247">
P1: The new `max_in_flight_per_account` default of 1 never reaches fresh installs. The first-run template in `paths.py` (`DEFAULT_CONFIG_YAML`) still writes `max_in_flight_per_account: 4` and `acquire_wait_seconds: 5`, so new installs keep the oversubscribed behavior this change is meant to fix. Update the template, `gui.py` default config, and `install-linux.sh` to match the new defaults.</violation>

<violation number="2" location="zcode_gateway/config.py:262">
P2: These new pool timing fields accept `inf` because they lack `allow_inf_nan=False`, unlike the new upstream retry fields in this diff. With `inf`, `settled_until` or `concurrency_hold_until` becomes unreachable, so the account is never picked again. Add `allow_inf_nan=False` to match the other timing fields.</violation>
</file>

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

<violation number="1" location="zcode_gateway/service.py:490">
P2: Accounts loaded without a `device_mid` get a fresh UUID only in memory, so pool-file accounts without this field change device identity after every restart. Derive the fallback from `account.id` or persist it to the account source.</violation>

<violation number="2" location="zcode_gateway/service.py:707">
P3: This inline status mapping duplicates `_stream_error_status` and has drifted: it omits the block-code -> 405 branch. Replace it with a call to the helper so all three stream paths classify errors the same way.</violation>
</file>

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

<violation number="1" location="zcode_gateway/pool.py:397">
P2: `quota_aware` selection can retain a settling account as the sole max-quota candidate, then `pick()` rejects it and queues despite another free account. Exclude settling accounts from `available`, as holds already are.</violation>

<violation number="2" location="zcode_gateway/pool.py:688">
P2: `restore()` moves DEAD and EXHAUSTED accounts back to READY but never calls `self._schedule_state_save()`. The account source keeps the old state, so after a restart the account comes back DEAD or EXHAUSTED until the next balance or plan check. Add the same debounced save that `enable()` uses after the lock is released.</violation>

<violation number="3" location="zcode_gateway/pool.py:692">
P2: `_flush_state()` leaves `_state_dirty` true on failure, but this return ends the saver task; no retry occurs until another mutation. Continue the debounce loop so transient I/O errors do not lose persisted account state.</violation>

<violation number="4" location="zcode_gateway/pool.py:1134">
P1: Only DEAD auth-strike outcomes reach the saver here; first-strike `COOLING` and `cool()` do not. `restore()` also clears persisted state without saving, so restart can lose cooldowns or re-disable recovered accounts; schedule each persisted-state transition.</violation>
</file>

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

<violation number="1" location="zcode_gateway/zcode_device.py:30">
P2: `account_device_mid` returns the same UUID for every empty `account_id`, so accounts with no user_id, sub, or email all share one device ID. Reject empty input here, and make callers handle the missing identity before deriving a device ID.</violation>
</file>

<file name="generator/plan_check.py">

<violation number="1" location="generator/plan_check.py:264">
P2: Non-JWT tokens now fall back to the shared legacy `DEVICE_MID`, which reintroduces the cross-account correlation this PR removes. The poll token from `get_zcode_jwt` is `secrets.token_hex(32)`, so it has no `user_id`/`sub` and every signup flow sends the same device ID. Keep the per-token derivation as the fallback for non-empty tokens.</violation>
</file>

<file name="tests/test_zcode_core.py">

<violation number="1" location="tests/test_zcode_core.py:815">
P2: This decay test never reaches the decay branch: strikes is still 1 when the quiet gap is simulated, so `strikes > 1` is false. The assertion `strikes==2 and hold<=20.0` also holds with no decay logic. Bank at least two strikes first (e.g. set `one.concurrency_strikes=3` before expiring the hold). Then expect strikes==2 and hold<=20, which fails without decay (strikes 4, hold 60).</violation>
</file>

<file name="scripts/accounts/import_account.py">

<violation number="1" location="scripts/accounts/import_account.py:19">
P2: The dataset path no longer reads the captured `x-device-mid` from `captures/model-api`. For a single-account MITM import without `data/telemetry-state.json`, the account now gets a derived uuid5 instead of the desktop's real mid. Either keep the captured mid as a fallback for single-account datasets, or call out this behavior change in the PR description.</violation>
</file>

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

<violation number="1" location="zcode_gateway/tokens.py:221">
P2: The fresh UUID is kept only in memory, so an account without a stored `device_mid` gets a new device ID on every restart or pool reload. Derive it deterministically with `account_device_mid(account.id)` instead, which survives restarts and matches the migration script. Also switch the import on line 17 to `account_device_mid`.</violation>
</file>

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

<violation number="1" location="zcode_gateway/api_dash.py:1151">
P2: Passing a derived `account_device_mid(...)` here overwrites the device_mid already saved for an existing account when it is re-registered. Pass `""` instead; `mint_and_register` already derives the default for new accounts and keeps an existing mid, as `test_existing_snapshot_casing_and_metadata_are_preserved` expects. The `account_device_mid` import at line 30 then becomes unused and should be removed.</violation>
</file>

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

<violation number="1" location="zcode_gateway/api_admin.py:209">
P2: Re-importing a raw JWT for an existing account validates it under a freshly generated device ID, which is then discarded. Look up `existing` before choosing the device so the billing check uses the account's stored `device_mid`.</violation>
</file>

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

<violation number="1" location="zcode_gateway/token_utils.py:93">
P2: `persist_pool_states` reads `pool.json` outside the directory lock that `_atomic_write` uses. A concurrent `persist_pool_snapshot` from the dashboard can land between that read and the write, and the stale copy then overwrites it. Move the read and the write into one `snapshot_transaction(p.parent)` block.</violation>
</file>

<file name="gui_main.py">

<violation number="1" location="gui_main.py:286">
P2: `main()` also calls `_shutdown_generator()` after `window.destroy()` returns, so this fallback can start a second generator shutdown while the first is still running. Coordinate the fallback with the main shutdown path before issuing cleanup or exiting.</violation>

<violation number="2" location="gui_main.py:314">
P2: "Open data folder" opens the exe folder, not the data folder. When the exe folder is read-only the gateway stores its data in `%LOCALAPPDATA%/ZcodeGateway`, and this item opens the wrong place. Open the folder that holds the active config instead.</violation>

<violation number="3" location="gui_main.py:432">
P1: This handler also runs when Windows logs off or shuts down. Hiding the window and returning False may veto the OS session end while the gateway is running. The handler needs to detect session end and allow the close, for example by setting `quitting` on WM_QUERYENDSESSION in the tray window procedure. The tray thread can then avoid the veto.</violation>
</file>

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

<violation number="1" location="zcode_gateway/accounts_dir.py:340">
P1: If `parse_snapshot` fails to read a file, it returns `{}`, and this loop still writes the four state keys over it. For an account whose filename is its account id, that replaces the whole credential file with only the state fields, losing `access_token` and `refresh_token`. Skip the file when the parse returned nothing.</violation>
</file>

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

<violation number="1" location="zcode_gateway/zcode_accounts.py:73">
P2: The single-account branch stamps the desktop-wide `telemetry-state.json` mid on a lone account, replacing its per-account ID. The install's mid is shared across sign-ins, so two accounts imported one at a time from the same desktop both get the same device ID. The same account also flips between its derived ID and the shared one on each import, because `save_account_snapshot` overwrites the stored `device_mid`. Derive the per-account ID here and keep the install mid out of snapshots, or document that single-account imports intentionally share it.</violation>
</file>

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

View guided diff | Re-trigger cubic

if path.suffix.casefold() != '.txt' or not path.is_file() or path.is_symlink():
continue
try:
fields = parse_snapshot(path)

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: parse_snapshot returns {} on read or decode errors instead of raising, so this except never fires. An unreadable snapshot (for example non-UTF-8 bytes) is treated as having no device_mid and gets overwritten with only that field, destroying its credentials under --apply. Skip any snapshot that parses to an empty dict.

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 scripts/accounts/backfill_device_mids.py, line 42:

<comment>`parse_snapshot` returns `{}` on read or decode errors instead of raising, so this `except` never fires. An unreadable snapshot (for example non-UTF-8 bytes) is treated as having no `device_mid` and gets overwritten with only that field, destroying its credentials under `--apply`. Skip any snapshot that parses to an empty dict.</comment>

<file context>
@@ -0,0 +1,71 @@
+            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}")
</file context>

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: The new max_in_flight_per_account default of 1 never reaches fresh installs. The first-run template in paths.py (DEFAULT_CONFIG_YAML) still writes max_in_flight_per_account: 4 and acquire_wait_seconds: 5, so new installs keep the oversubscribed behavior this change is meant to fix. Update the template, gui.py default config, and install-linux.sh to match the new defaults.

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>The new `max_in_flight_per_account` default of 1 never reaches fresh installs. The first-run template in `paths.py` (`DEFAULT_CONFIG_YAML`) still writes `max_in_flight_per_account: 4` and `acquire_wait_seconds: 5`, so new installs keep the oversubscribed behavior this change is meant to fix. Update the template, `gui.py` default config, and `install-linux.sh` to match the new defaults.</comment>

<file context>
@@ -235,11 +241,25 @@ 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 zcode_gateway/pool.py
account.auth_strikes = n
if n >= strikes:
killed = n >= strikes
if killed:

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: Only DEAD auth-strike outcomes reach the saver here; first-strike COOLING and cool() do not. restore() also clears persisted state without saving, so restart can lose cooldowns or re-disable recovered accounts; schedule each persisted-state transition.

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 1134:

<comment>Only DEAD auth-strike outcomes reach the saver here; first-strike `COOLING` and `cool()` do not. `restore()` also clears persisted state without saving, so restart can lose cooldowns or re-disable recovered accounts; schedule each persisted-state transition.</comment>

<file context>
@@ -913,7 +1130,8 @@ async def kill_after_strikes(self, account: Account, reason: str = "",
             account.auth_strikes = n
-            if n >= strikes:
+            killed = n >= strikes
+            if killed:
                 account.state = AccountState.DEAD
                 account.death_reason = reason or 'authentication_error'
</file context>

Comment thread gui_main.py
# hiding here would strand an invisible, unclosable app
if quitting.is_set() or not tray_icon.alive:
return True
window.hide()

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: This handler also runs when Windows logs off or shuts down. Hiding the window and returning False may veto the OS session end while the gateway is running. The handler needs to detect session end and allow the close, for example by setting quitting on WM_QUERYENDSESSION in the tray window procedure. The tray thread can then avoid the veto.

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 gui_main.py, line 432:

<comment>This handler also runs when Windows logs off or shuts down. Hiding the window and returning False may veto the OS session end while the gateway is running. The handler needs to detect session end and allow the close, for example by setting `quitting` on WM_QUERYENDSESSION in the tray window procedure. The tray thread can then avoid the veto.</comment>

<file context>
@@ -315,10 +413,36 @@ def main() -> None:
+            # 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",
</file context>

}
if all(fields.get(key, "") == value for key, value in update.items()):
continue
fields.update(update)

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: If parse_snapshot fails to read a file, it returns {}, and this loop still writes the four state keys over it. For an account whose filename is its account id, that replaces the whole credential file with only the state fields, losing access_token and refresh_token. Skip the file when the parse returned nothing.

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/accounts_dir.py, line 340:

<comment>If `parse_snapshot` fails to read a file, it returns `{}`, and this loop still writes the four state keys over it. For an account whose filename is its account id, that replaces the whole credential file with only the state fields, losing `access_token` and `refresh_token`. Skip the file when the parse returned nothing.</comment>

<file context>
@@ -304,3 +307,35 @@ def write_snapshot(path: Path, fields: dict[str, str]) -> None:
+            }
+            if all(fields.get(key, "") == value for key, value in update.items()):
+                continue
+            fields.update(update)
+            write_snapshot(path, fields)
</file context>
Suggested change
fields.update(update)
if not fields:
continue
fields.update(update)

Comment thread zcode_gateway/service.py
raise NoAccountsAvailable()
device_mid = account.notes.get('device_mid')
if not device_mid:
device_mid = account.notes['device_mid'] = new_account_device_mid()

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: Accounts loaded without a device_mid get a fresh UUID only in memory, so pool-file accounts without this field change device identity after every restart. Derive the fallback from account.id or persist it to the account source.

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 490:

<comment>Accounts loaded without a `device_mid` get a fresh UUID only in memory, so pool-file accounts without this field change device identity after every restart. Derive the fallback from `account.id` or persist it to the account source.</comment>

<file context>
@@ -430,11 +485,16 @@ async def _open_model_stream_once(self, payload, *, model, variant='anthropic',
                 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()
</file context>

Comment thread zcode_gateway/tray.py
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),

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: ExtractIconExW also returns the large icon, which is never released. Destroy large after extraction, since only the small icon is used.

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/tray.py, line 329:

<comment>`ExtractIconExW` also returns the large icon, which is never released. Destroy `large` after extraction, since only the small icon is used.</comment>

<file context>
@@ -0,0 +1,484 @@
+        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
</file context>

Comment thread zcode_gateway/tray.py
self._hwnd = None
if self._hicon:
try:
_user32.DestroyIcon(self._hicon)

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: _run destroys the icon handle on exit, but the LoadIconW(None, IDI_APPLICATION) fallback returns a shared system icon. DestroyIcon should not be called on shared icons. Track whether the handle was loaded from a file or extracted, and destroy only those.

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/tray.py, line 460:

<comment>`_run` destroys the icon handle on exit, but the `LoadIconW(None, IDI_APPLICATION)` fallback returns a shared system icon. `DestroyIcon` should not be called on shared icons. Track whether the handle was loaded from a file or extracted, and destroy only those.</comment>

<file context>
@@ -0,0 +1,484 @@
+            self._hwnd = None
+            if self._hicon:
+                try:
+                    _user32.DestroyIcon(self._hicon)
+                except OSError:
+                    pass
</file context>

Comment thread zcode_gateway/service.py
Comment on lines +707 to +708
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: This inline status mapping duplicates _stream_error_status and has drifted: it omits the block-code -> 405 branch. Replace it with a call to the helper so all three stream paths classify errors the same way.

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 707:

<comment>This inline status mapping duplicates `_stream_error_status` and has drifted: it omits the block-code -> 405 branch. Replace it with a call to the helper so all three stream paths classify errors the same way.</comment>

<file context>
@@ -640,7 +704,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)

if (hold > 0) {
return {
tone: "warn", label: "Throttled " + duration(hold),
detail: "Upstream reported a concurrency limit (3008); retries resume on their own.",

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 also represents 3009 and 3010 refusals, so the fixed 3008 explanation misidentifies those errors. Remove the code number from both concurrency descriptions.

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 216:

<comment>This hold also represents 3009 and 3010 refusals, so the fixed `3008` explanation misidentifies those errors. Remove the code number from both concurrency descriptions.</comment>

<file context>
@@ -112,18 +112,171 @@ function tokenCell(a) {
+  if (hold > 0) {
+    return {
+      tone: "warn", label: "Throttled " + duration(hold),
+      detail: "Upstream reported a concurrency limit (3008); retries resume on their own.",
+    };
+  }
</file context>

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.

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

3 issues found across 7 files (changes from recent commits).

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="zcode_gateway/service.py">

<violation number="1" location="zcode_gateway/service.py:231">
P3: This stores upstream error messages without a size limit; one oversized JSON/SSE error can inflate account history and dashboard responses. Bound the stored message while retaining full diagnostic text separately if needed.</violation>

<violation number="2" location="zcode_gateway/service.py:402">
P2: This returns `server_error` before `_open_stream` can try fallback models, so an eligible account on a fallback model is skipped. Keep suspension failures fallback-eligible and convert them to the soft 503 only after the model fallback chain is exhausted.</violation>
</file>

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

<violation number="1" location="zcode_gateway/upstream.py:221">
P1: The new generic `<title>[1-5]xx` match in `_looks_like_edge_block` also matches ordinary origin 5xx pages such as nginx's `<title>502 Bad Gateway</title>`. The breaker is status-agnostic, so one transient 5xx HTML page now blocks the whole gateway for every account: requests get 503 for at least 60s and the probe backoff can extend that to 30 min. Narrow the generic match to the captured 405 page, or keep the marker-only check for other statuses.</violation>
</file>

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

View guided diff | Re-trigger cubic

Comment thread zcode_gateway/upstream.py
# Generic CDN error page (captured 2026-11: <title>405</title> with
# data-spm markers): same IP-wide edge response, not an account or model
# problem. Only HTML bodies qualify.
return re.search(r"<title>\s*[1-5]\d\d\b", text) is not None

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: The new generic <title>[1-5]xx match in _looks_like_edge_block also matches ordinary origin 5xx pages such as nginx's <title>502 Bad Gateway</title>. The breaker is status-agnostic, so one transient 5xx HTML page now blocks the whole gateway for every account: requests get 503 for at least 60s and the probe backoff can extend that to 30 min. Narrow the generic match to the captured 405 page, or keep the marker-only check for other statuses.

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 221:

<comment>The new generic `<title>[1-5]xx` match in `_looks_like_edge_block` also matches ordinary origin 5xx pages such as nginx's `<title>502 Bad Gateway</title>`. The breaker is status-agnostic, so one transient 5xx HTML page now blocks the whole gateway for every account: requests get 503 for at least 60s and the probe backoff can extend that to 30 min. Narrow the generic match to the captured 405 page, or keep the marker-only check for other statuses.</comment>

<file context>
@@ -213,7 +213,47 @@ def _looks_like_edge_block(body: str | bytes | None) -> bool:
+    # Generic CDN error page (captured 2026-11: <title>405</title> with
+    # data-spm markers): same IP-wide edge response, not an account or model
+    # problem. Only HTML bodies qualify.
+    return re.search(r"<title>\s*[1-5]\d\d\b", text) is not None
+
+
</file context>
Suggested change
return re.search(r"<title>\s*[1-5]\d\d\b", text) is not None
return re.search(r"<title>\s*405\b", text) is not None

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

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: This returns server_error before _open_stream can try fallback models, so an eligible account on a fallback model is skipped. Keep suspension failures fallback-eligible and convert them to the soft 503 only after the model fallback chain is exhausted.

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 402:

<comment>This returns `server_error` before `_open_stream` can try fallback models, so an eligible account on a fallback model is skipped. Keep suspension failures fallback-eligible and convert them to the soft 503 only after the model fallback chain is exhausted.</comment>

<file context>
@@ -363,6 +398,8 @@ async def _after_stream_failure(self, handle, exc, *, committed, events, retries
         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)
</file context>

Comment thread zcode_gateway/service.py
account.error_history.append(
{"ts": time.time(), "status": status, "code": str(code),
"message": str(message)[:200], "model": model})
"message": str(message), "model": model})

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 stores upstream error messages without a size limit; one oversized JSON/SSE error can inflate account history and dashboard responses. Bound the stored message while retaining full diagnostic text separately if needed.

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 231:

<comment>This stores upstream error messages without a size limit; one oversized JSON/SSE error can inflate account history and dashboard responses. Bound the stored message while retaining full diagnostic text separately if needed.</comment>

<file context>
@@ -197,9 +228,20 @@ async def _apply_error(self, account, model, status, code, message, headers=None
             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
</file context>
Suggested change
"message": str(message), "model": model})
"message": str(message)[:2000], "model": model})

@mahyartdb mahyartdb closed this Nov 23, 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