The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(api-server): the session-chat routes spend the concurrent-run budget without respecting it
John Paul Soliva9934972e212c
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex 02a1bd0081b..b3f1850a912 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -3125,6 +3125,12 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):@_admit_api_agent_requestasync def _handle_session_chat(self, request: "web.Request") -> "web.Response":"""POST /api/sessions/{session_id}/chat — one synchronous agent turn."""+ # This turn runs through _run_agent, so it already COUNTS toward the cap (#7483).+ # Spending the budget without checking it refused every other caller while never+ # refusing this route — and a fleet's cross-machine DMs all arrive here.+ limited = self._concurrency_limited_response()+ if limited is not None:+ return limitedctx, err = await self._prepare_session_chat(request)if err is not None:return err@@ -3147,6 +3153,9 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):@_admit_api_agent_requestasync def _handle_session_chat_stream(self, request: "web.Request") -> "web.StreamResponse":"""POST /api/sessions/{session_id}/chat/stream — SSE wrapper over _run_agent."""+ limited = self._concurrency_limited_response()+ if limited is not None:+ return limitedctx, err = await self._prepare_session_chat(request)if err is not None:return errdiff --git a/tests/gateway/test_api_server.py b/tests/gateway/test_api_server.pyindex 47ddc6a7b34..87c78104256 100644--- a/tests/gateway/test_api_server.py+++ b/tests/gateway/test_api_server.py@@ -345,6 +345,38 @@ class TestConcurrencyCap:assert resp.status == 429assert resp.headers.get("Retry-After")+ @pytest.mark.asyncio+ @pytest.mark.parametrize("at_cap", [True, False], ids=["at-cap", "under-cap"])+ @pytest.mark.parametrize(+ ("endpoint", "payload"),+ [+ ("/api/sessions/s1/chat", {"message": "hi"}),+ ("/api/sessions/s1/chat/stream", {"message": "hi"}),+ ("/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}]}),+ ],+ ids=["session-chat", "session-chat-stream", "chat-completions"],+ )+ async def test_every_route_that_starts_a_turn_is_refused_at_the_cap(self, adapter, endpoint, payload, at_cap):+ """Each of these routes runs its turn through ``_run_agent``, so each already COUNTS+ toward ``max_concurrent_runs``. A route that spends the budget without checking it can+ never be refused while pushing every other caller into 429, and a fleet's cross-machine+ DMs — which all land on the session-chat routes — start a turn apiece regardless of the+ cap. Under the cap every route must still be admitted."""+ adapter._max_concurrent_runs = 2+ adapter._inflight_agent_runs = 2 if at_cap else 0+ app = _create_app(adapter)++ with patch.object(adapter, "_run_agent", new_callable=AsyncMock) as mock_run:+ mock_run.return_value = ({"final_response": "ok", "messages": [], "api_calls": 1},+ {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2})+ async with TestClient(TestServer(app)) as cli:+ response = await cli.post(endpoint, json=payload)++ assert (response.status == 429) is at_cap, await response.text()+ if at_cap:+ assert response.headers.get("Retry-After")+ assert mock_run.await_count == 0, "the turn must not start once the cap is reached"+# ---------------------------------------------------------------------------# Helpers for HTTP testsdiff --git a/website/docs/user-guide/features/api-server.md b/website/docs/user-guide/features/api-server.mdindex f46c01ad192..e5a5508260b 100644--- a/website/docs/user-guide/features/api-server.md+++ b/website/docs/user-guide/features/api-server.md@@ -716,7 +716,7 @@ gateway:### Concurrent-run cap-The API server limits how many agent runs may execute at once across the OpenAI-compatible and Runs endpoints. The cap is read from `gateway.api_server.max_concurrent_runs` (default **10**; `0` disables the limit, negative values clamp to 0). When the cap is reached, new run-starting requests are rejected with **HTTP 429** `Too many concurrent runs (max N)` — clients should back off and retry.+The API server limits how many agent runs may execute at once across every endpoint that starts one: the OpenAI-compatible endpoints, the Runs endpoints, and the session-chat endpoints (`POST /api/sessions/{id}/chat` and its `/stream` variant, which carry cross-machine agent DMs). The cap is read from `gateway.api_server.max_concurrent_runs` (default **10**; `0` disables the limit, negative values clamp to 0). When the cap is reached, new run-starting requests are rejected with **HTTP 429** `Too many concurrent runs (max N)` — clients should back off and retry.## Security Headers