The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(api): a confirmed model lock on a canonical API turn never falls back
Teknium3d0c8d3fbef8
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex 88c9bbc4421..5f0c9fa32eb 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -115,6 +115,22 @@ from gateway.run_turn_progress import GatewayTurnProgressMixinfrom gateway.session_execution import GatewaySessionAgentMixin+def _settle_api_runtime_lock(agent, result, captured):+ """A confirmed API model lock settles only on the runtime it named (main's+ ``_finish_turn_result``): the served runtime rides the usage, a mismatch fails the turn."""+ from gateway.session_api_turn import api_runtime_locked+ api = api_runtime_locked()+ if api is None or not isinstance(result, dict):+ return+ settings = api['settings']+ try:+ captured['usage']['runtime'] = api['adapter']._turn_runtime_metadata(+ agent, route=settings.get('route'), requested_runtime=settings.get('requested_runtime'),+ route_source=settings.get('route_source') or '', confirmed_runtime_lock=True)+ except RuntimeError as exc:+ result.update(final_response='', failed=True, completed=False, error=str(exc))++class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):"""Per-turn collaborator carrying ``GatewayRunner._run_agent_inner``'s tool-progress callbacks."""@@ -887,6 +903,7 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):outgoing = max(0, (getattr(agent, 'session_completion_tokens', 0) or 0) - before[1])captured['usage'] = {'input_tokens': incoming, 'output_tokens': outgoing,'total_tokens': incoming + outgoing}+ _settle_api_runtime_lock(agent, result, captured)return resultfinally:unregister_gateway_notify(session_key)diff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.pyindex be82c8ac31f..22e90385632 100644--- a/gateway/session_api_turn.py+++ b/gateway/session_api_turn.py@@ -515,6 +515,14 @@ def publish_api_tool_event(authority, session_id, generation, event_type, call_i_notify_observers(authority, session_id, 'tool_complete_callback', call_id, tool_name, args or {}, result)+def api_runtime_locked():+ """The executing API admission's settings when they carry a confirmed Browser model lock, else+ None. Main's ``_create_agent`` passes ``fallback_model=None`` under the lock and refuses a+ settled turn whose served runtime differs from it (``_turn_runtime_metadata``)."""+ current = api_execution.get()+ return current if current and current['settings'].get('confirmed_runtime_lock') else None++def prepare_api_runtime(model, runtime_kwargs):current = api_execution.get()if current is None:diff --git a/gateway/session_execution.py b/gateway/session_execution.pyindex 918f25b1086..80d0da46479 100644--- a/gateway/session_execution.py+++ b/gateway/session_execution.py@@ -18,6 +18,7 @@ from agent.replay_cleanup import strip_stale_dangerous_confirmationsfrom gateway.config import Platformfrom gateway.media_repair import repair_explicit_computer_use_media_pathsfrom gateway.platforms.base import BasePlatformAdapter+from gateway.session_api_turn import api_runtime_lockedfrom gateway.turn_context import TurnContextfrom hermes_cli.config import cfg_getfrom utils import is_truthy_value@@ -173,7 +174,7 @@ class GatewaySessionAgentMixin:session_db=getattr(runner._session_db, "_db", runner._session_db),# Reload from disk — do not reuse the startup snapshot.# See #60955.- fallback_model=self._runner._refresh_fallback_model(),+ fallback_model=None if api_runtime_locked() else self._runner._refresh_fallback_model(),skip_context_files=skip_context_files,# Keep the persona even with minimal context: soul identity is one small file.load_soul_identity=not bool(policy and policy.ignore_rules),@@ -203,8 +204,14 @@ class GatewaySessionAgentMixin:# Lock released — refresh the reused agent's fallback chain from disk OUTSIDE the cache lock# (disk I/O under the lock stalls the idle-sweep watcher and Discord heartbeats). A chain# configured after caching must reach the next turn; per-session serialization keeps it safe.+ locked = api_runtime_locked() is not None+ if found.reused and agent is not None and locked and getattr(agent, "_fallback_activated", False):+ # A cached agent already moved onto a fallback provider cannot serve a confirmed lock.+ found.evicted, found.reused, agent = agent, False, None+ with cache_lock:+ cache.pop(ctx.session_key, None)if found.reused and agent is not None:- self._runner._apply_fallback_chain_to_agent(agent, runner._refresh_fallback_model())+ self._runner._apply_fallback_chain_to_agent(agent, None if locked else runner._refresh_fallback_model())if found.evicted is not None:self._release_evicted_agent(found.evicted)if agent is None:diff --git a/tests/gateway/test_api_model_lock_fallback.py b/tests/gateway/test_api_model_lock_fallback.pynew file mode 100644index 00000000000..74164bdb074--- /dev/null+++ b/tests/gateway/test_api_model_lock_fallback.py@@ -0,0 +1,86 @@+"""A confirmed Browser model lock on a canonical API turn never falls back (main parity).++One ordinary daemon with the API server: the locked primary answers 429 ``insufficient_quota``+and ``fallback_providers`` names a healthy backup. Main builds the locked agent with+``fallback_model=None`` and fails a turn served by another runtime; the shared owner must too.+"""+import asyncio+import json+import os+from pathlib import Path+import socket++import aiohttp+import pytest++from tests.gateway.fixtures.local_recovery_probe import child_env, daemon+from tests.gateway.test_managed_worker_construct import Backup, Primary, _serve++[email protected]("linux")+def test_locked_session_chat_does_not_fall_back_to_the_profile_chain(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ primary, backup = _serve(Primary), _serve(Backup)+ primary.refuse = True+ purl, burl = (f'http://127.0.0.1:{s.server_port}/v1' for s in (primary, backup))+ with socket.socket() as sock:+ sock.bind(('127.0.0.1', 0))+ api_port = sock.getsockname()[1]+ config = {'model': {'provider': 'custom', 'default': 'primary-model', 'base_url': purl},+ 'gateway': {'multiplex_profiles': False,+ 'platforms': {'api_server': {'enabled': True, 'port': api_port, 'host': '127.0.0.1'}}},+ 'auxiliary': {'title_generation': {'enabled': False}}, 'terminal': {'cwd': str(home)},+ 'platform_toolsets': {'api_server': []},+ 'fallback_providers': [{'provider': 'custom', 'model': 'backup-model', 'base_url': burl,+ 'api_key': 'loopback-only'}]}+ (home / 'config.yaml').write_text(json.dumps(config))+ env = {**child_env(), **{k: os.environ[k] for k in ('TIRITH_ENABLED',) if k in os.environ}}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=purl, API_SERVER_KEY='lock-owned-secret',+ API_SERVER_ENABLED='true', API_SERVER_PORT=str(api_port), PYTHONUNBUFFERED='1')++ async def exercise():+ headers = {'Authorization': 'Bearer lock-owned-secret'}+ async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=90)) as client:+ base = f'http://127.0.0.1:{api_port}/api/sessions'+ async with client.post(base, json={'id': 'locked', 'title': 'Locked'}, headers=headers) as response:+ assert response.status in (200, 201), await response.text()+ async with client.post(f'{base}/locked/chat', headers=headers, json={+ 'message': 'NEED_FALLBACK', 'provider': 'custom', 'model': 'primary-model',+ 'require_model_lock': True}) as response:+ return response.status, await response.text()+ try:+ with daemon(root, home, env, barrier=False):+ status, text = asyncio.run(exercise())+ finally:+ for server in (primary, backup):+ server.shutdown()+ server.server_close()+ assert primary.requests, (status, text)+ assert backup.requests == [], 'a confirmed model lock was served by the profile fallback chain'+ body = json.loads(text)+ assert body['status'] == 'failed' and 'BACKUP_OK' not in text, body+ assert body['usage']['runtime']['model_lock'] == 'confirmed', body+++def test_locked_turn_served_by_another_runtime_settles_failed(api):+ """Main's settlement refusal: a locked turn whose agent ran on another provider/model is a+ failed turn carrying the mismatch, never a completed answer from the wrong runtime."""+ from types import SimpleNamespace+ from gateway.run_turn_runner import _settle_api_runtime_lock+ from gateway.session_api_turn import api_execution++ agent = SimpleNamespace(provider='custom', model='backup-model', _hermes_api_runtime={'provider': 'custom'})+ result, captured = {'final_response': 'BACKUP_OK', 'completed': True}, {'usage': {}}+ token = api_execution.set({'adapter': api, 'settings': {+ 'confirmed_runtime_lock': True, 'route': {'provider': 'custom', 'model': 'primary-model'},+ 'route_source': 'raw_request'}})+ try:+ _settle_api_runtime_lock(agent, result, captured)+ finally:+ api_execution.reset(token)+ assert result['failed'] is True and result['completed'] is False and result['final_response'] == ''+ assert 'confirmed model lock runtime mismatch' in result['error']