The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): compress no longer holds the session mutation lock through summarization
Teknium409f46007088
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 8cc157e4eb4..51259b6882a 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -39,6 +39,10 @@ class LiveSession:# preflight refusal), not per message; the drain clears it when the FIFO moves again.pause_notified: bool = Falsemutation_lock: asyncio.Lock = field(default_factory=asyncio.Lock)+ # Held by the FIFO claim and by compress across its summarization (which runs outside+ # ``mutation_lock``, so admissions are not parked behind an LLM call): no turn is claimed+ # under a compression that is still preparing its replacement transcript.+ claim_gate: asyncio.Lock = field(default_factory=asyncio.Lock)# admission id -> its started claim, from the moment the settlement worker starts the terminal# write until the completion frame is published. The write runs outside ``event_stream.lock``# (a contended SQLite writer must not stall loop-side lock takers); readers holding that lock@@ -638,7 +642,7 @@ class SessionAuthority:async def _claim_next(self, ref, live):# False asks the pump to re-read after a queued head changed during preflight.- async with live.mutation_lock:+ async with live.claim_gate, live.mutation_lock:pending = list_session_admissions(self.db, session_id=ref.session_id)if any(row['status'] == 'unknown' for row in pending):raise RuntimeStoreError('unknown_execution')diff --git a/gateway/session_mutations.py b/gateway/session_mutations.pyindex 41d44bba482..23355b0cb11 100644--- a/gateway/session_mutations.py+++ b/gateway/session_mutations.py@@ -5,6 +5,7 @@ transactions. Local reset prepares its replacement in the receipt transaction;branch/compress/model still require their own prepared runtime publication."""import asyncio+from contextlib import nullcontextfrom hermes_state_runtime import RuntimeStoreError, mutate_runtime_session@@ -80,14 +81,21 @@ async def _owned_mutation(authority, actor, ref, params):return await _mutate_session(authority, actor, ref, params)# Prepared policy/route publication is inseparable from its durable commit# for admission and claim: neither may observe a half-published policy.- async with live.mutation_lock:- result = await _mutate_session(authority, actor, ref, params)+ if params.get('operation') == 'compress':+ # The summarization (an LLM call) runs outside the session gate, so a submit or metadata+ # edit is not parked behind it; the commit is revision/generation-fenced against anything+ # that lands meanwhile. Claims wait on ``claim_gate``, so no turn runs under it.+ async with live.claim_gate:+ result = await _mutate_session(authority, actor, ref, params, commit_lock=live.mutation_lock)+ else:+ async with live.mutation_lock:+ result = await _mutate_session(authority, actor, ref, params)if params.get('operation') in {'model', 'compress', 'reset'}:authority._schedule(ref)return result-async def _mutate_session(authority, actor, ref, params):+async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):if (set(params) - {'expected_generation'} != _FIELDSor params['session_id'] != ref.session_id):raise RuntimeStoreError('invalid_params')@@ -147,31 +155,32 @@ async def _mutate_session(authority, actor, ref, params):# ``--preview`` is a read-only report and a guarded model target awaits the user's# confirmation: no receipt, no publication, no eviction.return {'session_id': ref.session_id, 'operation': operation, **prepared}- if prepared is not None and 'snapshot' not in prepared:- # Exact retry: the durable receipt is the result. Never re-prepare (compress- # would summarize again); the runtime repairs below still run, because the- # first attempt may have committed and then failed before publishing them.- result = prepared- else:- # The receipt transaction is synchronous SQLite: run it off the event loop so a large- # state.db or a contended writer lock never stalls other clients (main 1769024ca3b).- result = await asyncio.to_thread(mutate_runtime_session, authority.db, epoch=authority.epoch,- principal_id=actor.subject, session_id=ref.session_id, request_id=params['request_id'],- expected_revision=params['expected_revision'], expected_generation=params.get('expected_generation'),- operation=operation, payload=params['payload'], _live_guard=live_guard, _prepared=prepared,- _authorize_write=authorize_write if cold_history or operation == 'import' else None)- # Post-commit projections are idempotent reads of the committed receipt, so exact- # retries repeat them (like delete's retirement); only the one-shot event is fenced.- current = authority.db.get_session(ref.session_id)- owns_projection = current is not None and (- current['runtime_generation'] == result.get('execution_generation', params.get('expected_generation')))- if operation not in {'model', 'reset', 'compress', 'rewind'} or owns_projection:- _project_committed(authority, ref, operation, result)- if live is not None:- if operation == 'rewind' and owns_projection:- authority.runner._evict_cached_agent(live.route)- if applied:- live.event_stream.publish(ref.session_id, result, event_type='session.updated')+ async with commit_lock or nullcontext():+ if prepared is not None and 'snapshot' not in prepared:+ # Exact retry: the durable receipt is the result. Never re-prepare (compress+ # would summarize again); the runtime repairs below still run, because the+ # first attempt may have committed and then failed before publishing them.+ result = prepared+ else:+ # The receipt transaction is synchronous SQLite: run it off the event loop so a large+ # state.db or a contended writer lock never stalls other clients (main 1769024ca3b).+ result = await asyncio.to_thread(mutate_runtime_session, authority.db, epoch=authority.epoch,+ principal_id=actor.subject, session_id=ref.session_id, request_id=params['request_id'],+ expected_revision=params['expected_revision'], expected_generation=params.get('expected_generation'),+ operation=operation, payload=params['payload'], _live_guard=live_guard, _prepared=prepared,+ _authorize_write=authorize_write if cold_history or operation == 'import' else None)+ # Post-commit projections are idempotent reads of the committed receipt, so exact+ # retries repeat them (like delete's retirement); only the one-shot event is fenced.+ current = authority.db.get_session(ref.session_id)+ owns_projection = current is not None and (+ current['runtime_generation'] == result.get('execution_generation', params.get('expected_generation')))+ if operation not in {'model', 'reset', 'compress', 'rewind'} or owns_projection:+ _project_committed(authority, ref, operation, result)+ if live is not None:+ if operation == 'rewind' and owns_projection:+ authority.runner._evict_cached_agent(live.route)+ if applied:+ live.event_stream.publish(ref.session_id, result, event_type='session.updated')if operation == 'delete':# After the synchronous projections (no yield before retirement), off the loop: the# retired-media owner check is a messages-table pass (exact retries repeat it too).diff --git a/tests/gateway/test_session_mutation_compress_preview.py b/tests/gateway/test_session_mutation_compress_preview.pyindex 005acc8cc60..72506ef8e45 100644--- a/tests/gateway/test_session_mutation_compress_preview.py+++ b/tests/gateway/test_session_mutation_compress_preview.py@@ -32,7 +32,7 @@ async def test_preview_mutation_reports_without_summarizing_or_writing(tmp_path,from gateway.session import SessionStorefrom agent.context_compressor import ContextCompressor- monkeypatch.setattr(run, '_load_gateway_config', lambda: {})+ monkeypatch.setattr(run, '_load_gateway_config', dict)store = SessionStore(tmp_path / 'sessions', GatewayConfig())db = store._dbepoch = rt.begin_runtime_epoch(db, instance_id='owner')@@ -84,7 +84,7 @@ async def test_canonical_compress_runs_the_live_agents_pre_compress_memory_hook(from gateway.session import SessionStorefrom agent.context_compressor import ContextCompressor- monkeypatch.setattr(run, '_load_gateway_config', lambda: {})+ monkeypatch.setattr(run, '_load_gateway_config', dict)store = SessionStore(tmp_path / 'sessions', GatewayConfig())db = store._dbepoch = rt.begin_runtime_epoch(db, instance_id='owner')@@ -121,3 +121,62 @@ async def test_canonical_compress_runs_the_live_agents_pre_compress_memory_hook(assert summarized and 'PROVIDER_INSIGHT' in summarized[0]finally:await owner.close()+++async def test_input_is_admitted_while_compress_summarizes_but_not_claimed_until_it_commits(tmp_path, monkeypatch):+ """The summarization runs outside the session mutation lock: a submit on the session being+ compressed is admitted at once (a 30 s client RPC timeout must not report it lost), while the+ FIFO claim still waits for the fenced compress commit."""+ import asyncio+ import threading+ from gateway import run+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_contract import Submission+ from agent.context_compressor import ContextCompressor++ monkeypatch.setattr(run, '_load_gateway_config', dict)+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ db = store._db+ epoch = rt.begin_runtime_epoch(db, instance_id='owner')+ summarizing, release = threading.Event(), threading.Event()++ def compress(self, messages, **kw):+ summarizing.set()+ release.wait(10)+ return [{'role': 'user', 'content': 'summary', '_compressed_summary': True}]+ monkeypatch.setattr(ContextCompressor, '__init__', lambda self, *a, **k: None)+ monkeypatch.setattr(ContextCompressor, 'compress', compress)+ runner = SimpleNamespace(session_store=store, _session_db=db, adapters={}, _draining=False,+ _evict_cached_agent=lambda route: None,+ _resolve_session_agent_runtime=lambda **k: ('frozen', {}))+ authority = SessionAuthority(runner, profile_id='owned', instance_id='owner', db=db, epoch=epoch)+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)+ owner = AuthorityConnection(authority, object(), {'user_id': 'human'})+ ref = create_local_session(authority, owner.actor, dict(request_id='busy', source='cli', cwd=str(tmp_path),+ model='frozen', toolsets=[]))+ for i in range(4):+ db.append_message(ref.session_id, 'user', f'question {i}')+ db.append_message(ref.session_id, 'assistant', f'answer {i}')+ before = db.get_session(ref.session_id)+ try:+ compressing = asyncio.create_task(owner.dispatch({'id': 1, 'method': 'session.mutate', 'params': {+ 'session_id': ref.session_id, 'request_id': 'compress', 'expected_revision': before['runtime_revision'],+ 'expected_generation': before['runtime_generation'], 'operation': 'compress', 'payload': {}}}))+ assert await asyncio.to_thread(summarizing.wait, 10)+ receipt = await asyncio.wait_for(authority.submit(owner.actor, Submission(+ 'during', ref, {'text': 'typed while compressing'}, 'queue')), 2)+ assert receipt.status == 'queued'+ claim = asyncio.create_task(authority._claim_next(ref, authority.sessions[ref.session_id]))+ await asyncio.sleep(0.2)+ assert not claim.done(), 'a turn was claimed under a compression still preparing its transcript'+ release.set()+ reply = await asyncio.wait_for(compressing, 10)+ assert reply.get('result', {}).get('operation') == 'compress', reply+ row, _ = await asyncio.wait_for(claim, 10)+ assert row['admission_id'] == receipt.admission_id+ assert row['generation'] == reply['result']['execution_generation'] + 1+ finally:+ release.set()+ await owner.close()