Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,18 @@ 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
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

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>

acquire_wait_seconds: 120
concurrency_hold_seconds: 10
concurrency_hold_max_seconds: 60
balance_poll_seconds: 60
blocked_model_cooldown_seconds: 900
accounts:
Expand Down
59 changes: 58 additions & 1 deletion tests/test_acquire_wait.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
16 changes: 16 additions & 0 deletions tests/test_affinity.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
16 changes: 16 additions & 0 deletions tests/test_inference_audit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
30 changes: 29 additions & 1 deletion tests/test_model_retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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', [
Expand Down Expand Up @@ -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):
Expand Down
Loading