Skip to content

The agent that grows with you

fix: refuse /v1/runs on a natively owned session with a bounded 409

Teknium809fec1567d3
diff --git a/gateway/platforms/api_server_run_idempotency.py b/gateway/platforms/api_server_run_idempotency.py
index 22e9f580f15..ca76a4da2bc 100644
--- a/gateway/platforms/api_server_run_idempotency.py
+++ b/gateway/platforms/api_server_run_idempotency.py
@@ -222,6 +222,12 @@ class RunIdempotencyStore:
(_encode_status(status), time.time(), run_id))
self._conn.commit()
+ def forget(self, scope: str, key: str) -> None:
+ """Release a reservation whose run was refused before it existed."""
+ with self._lock:
+ self._conn.execute("DELETE FROM run_idempotency WHERE scope=? AND idempotency_key=?", (scope, key))
+ self._conn.commit()
+
def close(self) -> None:
with self._lock:
self._conn.close()
diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.py
index 5035c7806bd..de0d09520be 100644
--- a/gateway/platforms/api_server_runs.py
+++ b/gateway/platforms/api_server_runs.py
@@ -459,11 +459,22 @@ async def _handle_runs(self, request: "web.Request", *, _api_server) -> "web.Res
browser_control_transport_family=_api_server._api_request_browser_control_transport_family.get())
if getattr(self.gateway_runner, 'session_authority', None) is not None:
from gateway.session_api_turn import admit_api_turn
- with self._profile_scope(launch.request_profile):
- launch.admission = admit_api_turn(self, user_message=launch.user_message,
- conversation_history=launch.conversation_history, active_run_id=run_id,
- history_from_session=bool(body.get('session_id')) and not previous_response_id,
- **launch.agent_kwargs)
+ from hermes_state_runtime import RuntimeStoreError
+ try:
+ with self._profile_scope(launch.request_profile):
+ launch.admission = admit_api_turn(self, user_message=launch.user_message,
+ conversation_history=launch.conversation_history, active_run_id=run_id,
+ history_from_session=bool(body.get('session_id')) and not previous_response_id,
+ **launch.agent_kwargs)
+ except RuntimeStoreError as exc:
+ # A refused admission owns no run: drop every reservation so an exact
+ # retry is refused again instead of replaying a run nobody executes.
+ _forget_run(
+ self, run_id, self._run_streams, self._run_streams_created, self._run_approval_sessions,
+ self._run_statuses, self._run_owners, self._run_idempotency_ids)
+ if idempotency_key:
+ self._run_idempotency_store.forget(idempotency_scope, idempotency_key)
+ return _json_error(_openai_error, exc.reason, code=exc.reason, status=409)
self._activate_admitted_request()
task = self._active_run_tasks[run_id] = asyncio.create_task(_execute_run(self, launch, _api_server=_api_server))
with suppress(TypeError):
diff --git a/tests/gateway/test_api_runs_native_session_refusal.py b/tests/gateway/test_api_runs_native_session_refusal.py
new file mode 100644
index 00000000000..99c69e90b86
--- /dev/null
+++ b/tests/gateway/test_api_runs_native_session_refusal.py
@@ -0,0 +1,61 @@
+"""/v1/runs against a natively owned session is a bounded 409, never a 500 with a phantom reservation."""
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+
+def test_runs_refuse_native_session_without_phantom_run(tmp_path):
+ result = subprocess.run([sys.executable, __file__], cwd=Path(__file__).resolve().parents[2],
+ env=dict(os.environ, HERMES_HOME=str(tmp_path)), capture_output=True, text=True, timeout=90)
+ assert result.returncode == 0, result.stdout + result.stderr
+ print((tmp_path / 'runs-receipt.json').read_text(encoding='utf-8'))
+
+
+async def probe():
+ import aiohttp
+ from gateway.config import Platform, PlatformConfig
+ from gateway.platforms.api_server import APIServerAdapter
+ from gateway.run import GatewayRunner
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_contract import Principal
+ from gateway.session_local import create_local_session
+
+ runner = GatewayRunner()
+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='runs-test')
+ adapter = APIServerAdapter(PlatformConfig(enabled=True, extra={'key': 'runs-probe-owned-secret', 'port': 0}))
+ adapter.gateway_runner = runner
+ adapter.set_message_handler(runner._handle_message)
+ runner.adapters[Platform.API_SERVER] = adapter
+ assert await adapter.connect()
+ port = adapter._site._server.sockets[0].getsockname()[1]
+ actor = Principal('uid:test', 'default', frozenset({'session:create', 'session:read', 'session:submit', 'session:control'}), 'socket')
+ native = create_local_session(authority, actor, {'request_id': 'native', 'source': 'cli', 'toolsets': []}).session_id
+ headers = {'Authorization': 'Bearer runs-probe-owned-secret', 'Idempotency-Key': 'native-run'}
+ body = {'session_id': native, 'input': 'RUN_ON_NATIVE'}
+ try:
+ async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=20)) as client:
+ async with client.post(f'http://127.0.0.1:{port}/v1/runs', json=body, headers=headers) as response:
+ first_status, first = response.status, json.loads(await response.text() or 'null') if response.content_type == 'application/json' else await response.text()
+ async with client.post(f'http://127.0.0.1:{port}/v1/runs', json=body, headers=headers) as response:
+ retry_status, retry = response.status, json.loads(await response.text() or 'null') if response.content_type == 'application/json' else await response.text()
+ assert first_status == 409 and first['error']['code'] == 'permission_denied', (first_status, first)
+ # The refused request must not leave a reservation that replays a run nobody executes.
+ assert retry_status == 409 and retry['error']['code'] == 'permission_denied', (retry_status, retry)
+ assert not adapter._run_statuses and not adapter._run_streams, adapter._run_statuses
+ Path(os.environ['HERMES_HOME'], 'runs-receipt.json').write_text(encoding='utf-8', data=json.dumps(
+ {'first': [first_status, first], 'retry': [retry_status, retry], 'native_session': native}))
+ finally:
+ await adapter.disconnect()
+
+
+if __name__ == '__main__':
+ import asyncio
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+ # The refusal happens before any model call; a closed loopback port keeps this offline.
+ os.environ.update(OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL='http://127.0.0.1:9/v1')
+ Path(os.environ['HERMES_HOME'], 'config.yaml').write_text(
+ 'model:\n default: local-wire-stub\n provider: custom\n base_url: http://127.0.0.1:9/v1\n'
+ 'auxiliary:\n title_generation:\n enabled: false\n')
+ asyncio.run(probe())