Skip to content

The agent that grows with you

fix(gateway): retain mutation ownership through publication and retirement

David Dudok de Wite1cca25c9988
diff --git a/gateway/run_runtime.py b/gateway/run_runtime.py
index d785e4c55a5..619593d40c5 100644
--- a/gateway/run_runtime.py
+++ b/gateway/run_runtime.py
@@ -164,6 +164,8 @@ def _authority_tasks(authority):
"""Snapshot every async task family owned directly by one session authority."""
tasks = [live.task for live in authority.sessions.values() if live.task is not None]
tasks.extend(getattr(authority, '_bot_receipt_tasks', ()))
+ from gateway.session_runtime_workers import mutation_tasks
+ tasks.extend(mutation_tasks(authority))
return list(dict.fromkeys(tasks))
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 86527b10fba..7660433c2d3 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -34,6 +34,7 @@ class LiveSession:
# The messaging ingress tells the platform user once per pause episode (unknown head,
# preflight refusal), not per message; the drain clears it when the FIFO moves again.
pause_notified: bool = False
+ mutation_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
def __post_init__(self):
self.controls = PendingControls(self.event_stream)
@@ -304,6 +305,12 @@ class SessionAuthority:
async def submit(self, actor: Principal, request: Submission, *, _authorize_write=None):
self.authorize(actor, request.ref, 'session:submit')
+ async with self.sessions[request.ref.session_id].mutation_lock:
+ # Deletion can retire this session while the caller waits on its writer.
+ self.authorize(actor, request.ref, 'session:submit')
+ return await self._submit(actor, request, _authorize_write=_authorize_write)
+
+ async def _submit(self, actor, request, *, _authorize_write=None):
self._require_admission_open()
if (request.intent != 'queue' or not {'text'} <= set(request.payload) <= {
'text', 'attachments', 'finite', 'unattended', 'surface', 'voice_context', 'interrupted',
@@ -470,71 +477,74 @@ class SessionAuthority:
raise RuntimeStoreError("invalid_params")
return live.controls.respond(ref.session_id, generation, prompt_id, response, kind=kind)
+ 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:
+ pending = list_session_admissions(self.db, session_id=ref.session_id)
+ if any(row['status'] == 'unknown' for row in pending):
+ raise RuntimeStoreError('unknown_execution')
+ first = next((row for row in pending if row['status'] == 'queued'), None)
+ from gateway.config import Platform
+ if first is not None and live.source.platform == Platform.LOCAL:
+ from gateway.session_local_recovery import restore_local_session
+ restore_local_session(self, ref.session_id)
+ if first['request_id'].startswith('hosted:'):
+ from gateway.session_hosted_transport import check_remote_hosted_admission
+ if not await asyncio.to_thread(check_remote_hosted_admission, self, ref, first):
+ service = getattr(self, 'hosted_room_service', None)
+ if service is None:
+ raise RuntimeStoreError('permission_denied')
+ await asyncio.to_thread(service.check_admission, ref, first)
+ # Cancellation may advance the FIFO while the source owner is awaited;
+ # the successor must earn its own reauthorization, not inherit this one.
+ current = get_session_admission(self.db, admission_id=first['admission_id'])
+ if current is None or current['status'] != 'queued':
+ return False, first
+ if 'local_automation_v1' in first['payload']:
+ from gateway.session_automation import check_local_automation
+ check_local_automation(self, ref, first)
+ else:
+ from gateway.session_operator import check_local_input
+ check_local_input(self, ref, first)
+ # The first real turn reopens a finalized row (#85303): mounts are reads, and
+ # SessionStore would route a stamped row as stale onto a FRESH session.
+ from gateway.session_local_recovery import reopen_local_session
+ reopen_local_session(self, ref)
+ if first is not None and 'native_text_v1' in first['payload']:
+ from gateway.session_envelope import check_native_route
+ await check_native_route(self.runner, first['payload'], self.physical_target(ref), live.source,
+ self.runner._adapter_for_source(live.source))
+ # Cancellation may advance FIFO while the connector is awaited.
+ # Never let the successor inherit this row's fresh verdict.
+ current = get_session_admission(self.db, admission_id=first['admission_id'])
+ if current is None or current['status'] != 'queued':
+ return False, first
+ if first is not None and live.source.platform == Platform.API_SERVER:
+ from gateway.session_api_turn import check_api_turn
+ check_api_turn(self, ref, first['payload'])
+ self._require_admission_open()
+ row = claim_session_input(self.db, epoch=self.epoch, session_id=ref.session_id)
+ return row, first
+
async def _drain(self, ref):
from gateway.session_finite import execute_finite_admission
live = self.sessions[ref.session_id]
while True:
try:
- pending = list_session_admissions(self.db, session_id=ref.session_id)
- if any(row['status'] == 'unknown' for row in pending):
- self._pause(ref, 'unknown_execution')
- return
- first = next((row for row in pending if row['status'] == 'queued'), None)
- from gateway.config import Platform
- if first is not None and live.source.platform == Platform.LOCAL:
- from gateway.session_local_recovery import restore_local_session
- restore_local_session(self, ref.session_id)
- if first['request_id'].startswith('hosted:'):
- from gateway.session_hosted_transport import check_remote_hosted_admission
- if not await asyncio.to_thread(check_remote_hosted_admission, self, ref, first):
- service = getattr(self, 'hosted_room_service', None)
- if service is None:
- raise RuntimeStoreError('permission_denied')
- await asyncio.to_thread(service.check_admission, ref, first)
- # Cancellation may advance the FIFO while the source owner is awaited;
- # the successor must earn its own reauthorization, not inherit this one.
- current = get_session_admission(self.db, admission_id=first['admission_id'])
- if current is None or current['status'] != 'queued':
- continue
- if 'local_automation_v1' in first['payload']:
- from gateway.session_automation import check_local_automation
- check_local_automation(self, ref, first)
- else:
- from gateway.session_operator import check_local_input
- check_local_input(self, ref, first)
- # The first real turn reopens a finalized row (#85303): mounts are reads, and
- # SessionStore would route a stamped row as stale onto a FRESH session.
- from gateway.session_local_recovery import reopen_local_session
- reopen_local_session(self, ref)
- if first is not None and 'native_text_v1' in first['payload']:
- from gateway.session_envelope import check_native_route
- await check_native_route(self.runner, first['payload'], self.physical_target(ref), live.source,
- self.runner._adapter_for_source(live.source))
- # Cancellation may advance FIFO while the connector is awaited.
- # Never let the successor inherit this row's fresh verdict.
- current = get_session_admission(self.db, admission_id=first['admission_id'])
- if current is None or current['status'] != 'queued':
- continue
- if first is not None and live.source.platform == Platform.API_SERVER:
- from gateway.session_api_turn import check_api_turn
- check_api_turn(self, ref, first['payload'])
- self._require_admission_open()
- row = claim_session_input(self.db, epoch=self.epoch, session_id=ref.session_id)
+ row, first = await self._claim_next(ref, live)
except RuntimeStoreError as exc:
import logging
logging.getLogger(__name__).warning('Session %s paused: %s', ref.session_id, exc.reason)
self._pause(ref, exc.reason)
return
- if row is None and first is not None:
- # Not empty: a live worker (or a claim this drain does not own) blocks the head.
- # Release the delivery waiters like any pause; the worker's finish wakes the FIFO
- # (``wake_after_worker``) and the drain then answers through the adapter.
- self._pause(ref, 'session_busy')
- return
+ if row is False:
+ continue
# The FIFO is moving again (or empty): the next pause is a new episode.
live.pause_notified = False
if row is None:
- # A viewer that left while this work ran could not end the ACP session then.
+ if first is not None:
+ self._pause(ref, 'session_busy')
+ return
from gateway.session_acp_lifecycle import end_idle_acp_session
end_idle_acp_session(self, ref.session_id)
return
diff --git a/gateway/session_mutations.py b/gateway/session_mutations.py
index 12a8791a305..6d5b5129d5d 100644
--- a/gateway/session_mutations.py
+++ b/gateway/session_mutations.py
@@ -49,6 +49,31 @@ def _authorize_control(authority, actor, ref, params):
async def mutate_session(authority, actor, ref, params):
+ from gateway.session_runtime_workers import track_mutation
+ authority._require_admission_open()
+ # A request socket can disappear while its writer is inside to_thread. The owner task keeps
+ # the session gate until commit AND publication finish, and retirement joins that same task.
+ task = track_mutation(authority, _owned_mutation(authority, actor, ref, params))
+ return await asyncio.shield(task)
+
+
+async def _owned_mutation(authority, actor, ref, params):
+ if (params.get('operation') in {'model', 'compress', 'reset', 'rewind'}
+ and ref.session_id not in authority.sessions and 'request_id' in params):
+ _authorize_control(authority, actor, ref, params)
+ live = authority.sessions.get(ref.session_id)
+ if live is None:
+ 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') in {'model', 'compress', 'reset'}:
+ authority._schedule(ref)
+ return result
+
+
+async def _mutate_session(authority, actor, ref, params):
if (set(params) - {'expected_generation'} != _FIELDS
or params['session_id'] != ref.session_id):
raise RuntimeStoreError('invalid_params')
@@ -122,14 +147,13 @@ async def mutate_session(authority, actor, ref, params):
_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.
- _project_committed(authority, ref, operation, result)
+ 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:
- # The cached agent is the rewind's to repair only while the session is still at the
- # receipt's execution generation (rewind advances the expected one by exactly one):
- # once a later admission claimed, the cache holds ITS agent, and evicting it would
- # make Stop latch instead of arriving.
- if (operation == 'rewind' and authority.db.get_session(ref.session_id)['runtime_generation']
- == params['expected_generation'] + 1):
+ 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')
diff --git a/gateway/session_runtime_workers.py b/gateway/session_runtime_workers.py
index e6f7b081d31..7b788b72801 100644
--- a/gateway/session_runtime_workers.py
+++ b/gateway/session_runtime_workers.py
@@ -19,7 +19,27 @@ def uncounted_runtime_work(runner):
managed = sum(not worker.closed.is_set() for authority in authorities
for worker in getattr(authority, '_managed_workers', {}).values())
return (managed + sum(live.route not in running and sid not in getattr(authority, '_managed_workers', {})
- for authority in authorities for sid, live, _ in executing_sessions(authority)))
+ for authority in authorities for sid, live, _ in executing_sessions(authority))
+ + sum(len(mutation_tasks(authority)) for authority in authorities))
+
+
+def mutation_tasks(authority):
+ tasks = getattr(authority, '_mutation_tasks', ())
+ return [task for task in tasks if not task.done()]
+
+
+def track_mutation(authority, operation):
+ tasks = getattr(authority, '_mutation_tasks', None)
+ if tasks is None:
+ tasks = authority._mutation_tasks = set()
+ task = asyncio.create_task(operation)
+ tasks.add(task)
+ def finished(done):
+ tasks.discard(done)
+ if not done.cancelled():
+ done.exception() # the observer may already have disconnected
+ task.add_done_callback(finished)
+ return task
def start_turn_worker(runner, worker, agent_holder, run_sync):
@@ -67,7 +87,7 @@ async def join_authority_work(authority, timeout):
deadline = asyncio.get_running_loop().time() + timeout
while True:
stop_authority_work(authority)
- if not list(physical_workers(authority)) and not list(executing_sessions(authority)):
+ if not list(physical_workers(authority)) and not list(executing_sessions(authority)) and not mutation_tasks(authority):
return
if asyncio.get_running_loop().time() >= deadline:
raise TimeoutError('Profile workers did not stop; ownership retained')
diff --git a/hermes_state_runtime.py b/hermes_state_runtime.py
index 71323058c72..71fe2a380b9 100644
--- a/hermes_state_runtime.py
+++ b/hermes_state_runtime.py
@@ -271,6 +271,7 @@ def mutate_runtime_session(db, *, epoch: int, principal_id: str, session_id: str
[(target,) for target in affected])
updated = conn.execute('SELECT * FROM sessions WHERE id=?', (session_id,)).fetchone()
result = {'session_id': session_id, 'revision': updated['runtime_revision'] if updated else expected_revision + 1,
+ 'execution_generation': updated['runtime_generation'] if updated else expected_generation,
'operation': operation, **projection}
conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)',
(key, _json({'digest': digest, 'result': result})))
diff --git a/tests/gateway/test_adversarial_mutation_lifecycle.py b/tests/gateway/test_adversarial_mutation_lifecycle.py
new file mode 100644
index 00000000000..869a251de16
--- /dev/null
+++ b/tests/gateway/test_adversarial_mutation_lifecycle.py
@@ -0,0 +1,87 @@
+"""Independent review probes: mutation publication survives caller cancellation and retirement."""
+import asyncio
+from dataclasses import asdict, replace
+import json
+import threading
+
+import pytest
+
+from gateway.session_contract import Submission
+from tests.gateway.test_local_authority_transitions import local_session
+
+
+async def pending_model(tmp_path, monkeypatch):
+ from gateway import session_mutations
+ from gateway.session_policy import restore_policy
+ owner, connection, ref = await local_session(tmp_path, monkeypatch)
+ entered, release, completed = threading.Event(), threading.Event(), threading.Event()
+ original = session_mutations.mutate_runtime_session
+
+ def blocked(*args, **kwargs):
+ if kwargs.get('_prepare_only'):
+ return original(*args, **kwargs)
+ entered.set()
+ assert release.wait(10)
+ try:
+ return original(*args, **kwargs)
+ finally:
+ completed.set()
+
+ async def prepare(authority, live, payload, prepared):
+ old = restore_policy(prepared['snapshot']['receipt']['policy'])
+ config = old.config()
+ config['model'] = {'default': 'new', 'provider': 'fixture'}
+ return {**prepared, 'policy': asdict(replace(old, model='new', config_json=json.dumps(config)))}
+
+ monkeypatch.setattr(session_mutations, 'mutate_runtime_session', blocked)
+ monkeypatch.setattr('gateway.session_mutation_model.prepare_model', prepare)
+ handle = owner._handle(ref)
+ task = asyncio.create_task(session_mutations.mutate_session(owner, connection.actor, ref,
+ dict(session_id=ref.session_id, request_id='model', operation='model', payload={'model': 'new'},
+ expected_revision=handle.revision, expected_generation=handle.execution_generation)))
+ assert await asyncio.to_thread(entered.wait, 5)
+ return owner, connection, ref, task, release, completed
+
+
+async def test_cancelling_model_request_cannot_strand_next_admission(tmp_path, monkeypatch):
+ owner, connection, ref, task, release, completed = await pending_model(tmp_path, monkeypatch)
+ seen = []
+ async def execute(authority, ref, row):
+ seen.append(row['request_id'])
+ return 'done'
+ monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)
+ try:
+ task.cancel()
+ await asyncio.sleep(0)
+ release.set()
+ await asyncio.gather(task, return_exceptions=True)
+ assert await asyncio.to_thread(completed.wait, 5)
+ await owner.submit(connection.actor, Submission('next', ref, {'text': 'next'}, 'queue'))
+ await owner.sessions[ref.session_id].task
+ assert seen == ['next']
+ finally:
+ release.set()
+ await asyncio.gather(task, return_exceptions=True)
+ await asyncio.to_thread(completed.wait, 5)
+ await connection.close()
+ owner.db.close()
+
+
+async def test_profile_retirement_waits_for_mutation_thread(tmp_path, monkeypatch):
+ from gateway.run_runtime import _retire_profile_authority
+ owner, connection, ref, task, release, completed = await pending_model(tmp_path, monkeypatch)
+ retirement = asyncio.create_task(_retire_profile_authority(owner))
+ try:
+ # Retirement must not finish while the writer can still mutate this profile.
+ done, _ = await asyncio.wait({retirement}, timeout=2)
+ assert not done, 'profile authority retired while its mutation writer remained alive'
+ release.set()
+ await asyncio.gather(task, retirement)
+ finally:
+ release.set()
+ await asyncio.gather(task, retirement, return_exceptions=True)
+ await asyncio.to_thread(completed.wait, 5)
+ await connection.close()
+ owner.db.close()
diff --git a/tests/gateway/test_local_authority_transitions.py b/tests/gateway/test_local_authority_transitions.py
new file mode 100644
index 00000000000..d19839e6f28
--- /dev/null
+++ b/tests/gateway/test_local_authority_transitions.py
@@ -0,0 +1,153 @@
+"""Local policy publication and detached lifecycle respect the durable FIFO."""
+import asyncio
+from dataclasses import asdict, replace
+import json
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.session_contract import Submission
+
+
+async def local_session(tmp_path, monkeypatch, source='cli'):
+ from gateway import run
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_controls import AuthorityConnection
+ from gateway.session_local import create_local_session
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': [], 'acp': []}})
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,
+ _cached_agent_for=lambda route: None, _adapter_for_source=lambda source: None,
+ _evict_cached_agent=lambda route: None)
+ authority = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='fixture')
+ connection = AuthorityConnection(authority, object(), {'user_id': 'owner'})
+ ref = create_local_session(authority, connection.actor, {'request_id': 'create', 'source': source,
+ 'cwd': str(tmp_path), 'model': 'old', 'toolsets': []})
+ return authority, connection, ref
+
+
+async def test_detached_acp_session_ends_when_running_work_settles(tmp_path, monkeypatch):
+ owner, connection, ref = await local_session(tmp_path, monkeypatch, 'acp')
+ running, release = asyncio.Event(), asyncio.Event()
+ async def execute(authority, ref, row):
+ running.set()
+ await release.wait()
+ return 'done'
+ monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)
+ snapshot = await owner.attach(connection.actor, ref)
+ try:
+ await owner.submit(connection.actor, Submission('turn', ref, {'text': 'work'}, 'queue'))
+ await asyncio.wait_for(running.wait(), 10)
+ await owner.detach(connection.actor, snapshot.subscription_id)
+ assert owner.db.get_session(ref.session_id)['ended_at'] is None
+ release.set()
+ await owner.sessions[ref.session_id].task
+ assert owner.db.get_session(ref.session_id)['end_reason'] == 'acp_disconnect'
+ finally:
+ release.set()
+ await connection.close()
+ owner.db.close()
+
+
+async def test_model_commit_and_live_publication_hold_admission_and_claim_gate(tmp_path, monkeypatch):
+ from gateway import session_mutations
+ from gateway.session_policy import restore_policy
+ from hermes_state_local import local_receipt
+ from hermes_state_runtime import admit_session_input
+ owner, connection, ref = await local_session(tmp_path, monkeypatch)
+ live = owner.sessions[ref.session_id]
+ committed, publish, attempted = asyncio.Event(), asyncio.Event(), asyncio.Event()
+ original_to_thread = asyncio.to_thread
+ async def barrier(function, *args, **kwargs):
+ result = await original_to_thread(function, *args, **kwargs)
+ if function is session_mutations.mutate_runtime_session:
+ committed.set()
+ await publish.wait()
+ return result
+ async def prepare(authority, live, payload, prepared):
+ old = restore_policy(prepared['snapshot']['receipt']['policy'])
+ config = old.config()
+ config['model'] = {'default': 'new', 'provider': 'fixture'}
+ return {**prepared, 'policy': asdict(replace(old, model='new', config_json=json.dumps(config)))}
+ seen = []
+ async def execute(authority, ref, row):
+ seen.append(local_receipt(authority.db, ref.session_id)['policy']['model'])
+ return 'done'
+ monkeypatch.setattr('gateway.session_mutation_model.prepare_model', prepare)
+ monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)
+ monkeypatch.setattr(asyncio, 'to_thread', barrier)
+ admit_session_input(owner.db, epoch=owner.epoch, principal_id=connection.actor.subject,
+ session_id=ref.session_id, request_id='queued', payload={'text': 'queued'})
+ handle = owner._handle(ref)
+ task = asyncio.create_task(session_mutations.mutate_session(owner, connection.actor, ref,
+ dict(session_id=ref.session_id, request_id='model', operation='model', payload={'model': 'new'},
+ expected_revision=handle.revision, expected_generation=handle.execution_generation)))
+ submit = None
+ try:
+ await asyncio.wait_for(committed.wait(), 10)
+ async def send():
+ attempted.set()
+ return await owner.submit(connection.actor, Submission('follower', ref, {'text': 'next'}, 'queue'))
+ submit = asyncio.create_task(send())
+ owner._schedule(ref)
+ await attempted.wait()
+ await asyncio.sleep(0)
+ publish.set()
+ await task
+ await submit
+ await live.task
+ assert seen == ['new', 'new']
+ finally:
+ publish.set()
+ await asyncio.gather(task, *([submit] if submit else []), return_exceptions=True)
+ await connection.close()
+ owner.db.close()
+
+
+async def test_provider_switch_drops_launch_key_but_retains_config_secrets(tmp_path, monkeypatch):
+ from gateway.session_policy import build_policy, bind_launch_key, launch_key
+ from gateway.session_policy_credentials import recover_config_secrets
+ from gateway.session_mutation_model import prepare_model
+ owner, connection, ref = await local_session(tmp_path, monkeypatch)
+ secrets = {('providers', 'old', 'api_key'): 'config-secret'}
+ policy = build_policy({'source': 'cli', 'cwd': str(tmp_path), 'model': 'old', 'provider': 'old'},
+ {'model': {'default': 'old', 'provider': 'old'},
+ 'providers': {'old': {'api_key': 'config-secret'}}}, private_secrets=secrets)
+ policy = bind_launch_key(owner, ref.session_id, policy, 'launch-secret', config_secrets=secrets)
+ owner.runner._resolve_session_agent_runtime = lambda **kwargs: ('old', {'api_key': 'launch-secret'})
+ monkeypatch.setattr('hermes_cli.model_switch.switch_model', lambda **kwargs: SimpleNamespace(
+ success=True, new_model='new', target_provider='new-provider', base_url=None, provider_changed=True))
+ try:
+ prepared = await prepare_model(owner, owner.sessions[ref.session_id], {'model': 'new'},
+ {'snapshot': {'receipt': {'session_id': ref.session_id, 'policy': asdict(policy)}}})
+ changed = type(policy)(**prepared['policy'])
+ assert launch_key(owner, changed) is None
+ assert recover_config_secrets(owner, changed) == secrets
+ assert launch_key(owner, policy) == 'launch-secret'
+ finally:
+ await connection.close()
+ owner.db.close()
+
+
+async def test_branch_route_uses_store_clock_and_deleted_policy_is_retired(tmp_path, monkeypatch):
+ from gateway.session_mutations import mutate_session
+ from hermes_state_local import POLICY_PREFIX
+ owner, connection, ref = await local_session(tmp_path, monkeypatch)
+ try:
+ result = await mutate_session(owner, connection.actor, ref,
+ dict(session_id=ref.session_id, request_id='branch', operation='branch', payload={},
+ expected_revision=0, expected_generation=0))
+ assert owner.runner.session_store.prune_old_entries(1) == 0
+ child = result['branched_session_id']
+ owner.db.delete_session(child)
+ with owner.db._read_ctx() as conn:
+ assert conn.execute('SELECT 1 FROM state_meta WHERE key=?', (POLICY_PREFIX + child,)).fetchone() is None
+ finally:
+ await connection.close()
+ owner.db.close()
diff --git a/tests/gateway/test_rewind_receipt_projection.py b/tests/gateway/test_rewind_receipt_projection.py
new file mode 100644
index 00000000000..8f3d4af3f57
--- /dev/null
+++ b/tests/gateway/test_rewind_receipt_projection.py
@@ -0,0 +1,58 @@
+"""Receipt retries preserve transcript boundaries, successor ownership and media identity."""
+
+
+
+from pathlib import Path
+
+
+
+from types import SimpleNamespace
+
+
+
+import pytest
+
+
+
+from gateway.session_authority import LiveSession
+
+
+
+from gateway.session_contract import Principal, SessionRef, Submission
+
+
+
+from gateway.session_results import admission_result, finish_result
+
+
+
+from hermes_state_runtime import (RuntimeStoreError, admit_session_input, begin_runtime_epoch,
+ claim_session_input, get_session_admission, recover_session_inputs)
+
+
+
+async def test_rewind_retry_does_not_evict_successor_agent(owner):
+ from gateway.session_mutations import mutate_session
+ owner.db.create_session('s', source='test')
+ owner.db.append_message('s', 'user', 'keep')
+ owner.db.append_message('s', 'assistant', 'discard')
+ owner.db.append_message('s', 'user', 'rewind this')
+ owner.sessions['s'] = LiveSession(None, 'route')
+ agent = SimpleNamespace(interrupts=0)
+ cached = {'route': agent}
+ agent.interrupt = lambda: setattr(agent, 'interrupts', agent.interrupts + 1)
+ owner.runner._evict_cached_agent = lambda route: cached.pop(route, None)
+ owner.runner._cached_agent_for = cached.get
+ actor = Principal('human', owner.profile_id, frozenset({'session:submit', 'session:control'}), 't')
+ ref = SessionRef(owner.profile_id, 's')
+ params = dict(session_id='s', request_id='rewind', expected_revision=0, expected_generation=0,
+ operation='rewind', payload={'target_message_id': owner.db.get_messages('s')[2]['id']})
+ result = await mutate_session(owner, actor, ref, params)
+ admit_session_input(owner.db, epoch=owner.epoch, principal_id='human', session_id='s',
+ request_id='next', payload={'text': 'next'})
+ started = claim_session_input(owner.db, epoch=owner.epoch, session_id='s')
+ cached['route'] = agent
+ assert await mutate_session(owner, actor, ref, params) == result
+ await owner.interrupt(actor, ref, started['generation'])
+ assert cached.get('route') is agent and agent.interrupts == 1
diff --git a/tests/gateway/test_submit_after_delete_gate.py b/tests/gateway/test_submit_after_delete_gate.py
new file mode 100644
index 00000000000..649d773df41
--- /dev/null
+++ b/tests/gateway/test_submit_after_delete_gate.py
@@ -0,0 +1,50 @@
+"""A submit waiting on deletion must revalidate the session before staging its input."""
+import asyncio
+import threading
+
+import pytest
+
+from gateway.session_contract import Submission
+from tests.gateway.test_local_authority_transitions import local_session
+
+
+async def test_submit_waiting_on_delete_reports_not_found(tmp_path, monkeypatch):
+ from gateway import session_mutations
+ from hermes_state_runtime import RuntimeStoreError
+
+ owner, connection, ref = await local_session(tmp_path, monkeypatch)
+ entered, release = threading.Event(), threading.Event()
+ attempted = asyncio.Event()
+ original = session_mutations.mutate_runtime_session
+
+ def blocked(*args, **kwargs):
+ entered.set()
+ assert release.wait(10)
+ return original(*args, **kwargs)
+
+ monkeypatch.setattr(session_mutations, 'mutate_runtime_session', blocked)
+ handle = owner._handle(ref)
+ deletion = asyncio.create_task(session_mutations.mutate_session(owner, connection.actor, ref,
+ dict(session_id=ref.session_id, request_id='delete', operation='delete', payload={},
+ expected_revision=handle.revision, expected_generation=handle.execution_generation)))
+ submission = None
+ try:
+ assert await asyncio.to_thread(entered.wait, 5)
+
+ async def send():
+ attempted.set()
+ return await owner.submit(connection.actor, Submission('next', ref, {'text': 'next'}, 'queue'))
+
+ submission = asyncio.create_task(send())
+ await asyncio.wait_for(attempted.wait(), 5)
+ release.set()
+ await asyncio.wait_for(deletion, 5)
+ with pytest.raises(RuntimeStoreError, match='not_found'):
+ await asyncio.wait_for(submission, 5)
+ assert owner.db.get_session(ref.session_id) is None
+ finally:
+ release.set()
+ await asyncio.gather(deletion, *([submission] if submission is not None else []), return_exceptions=True)
+ await connection.close()
+ owner.db.close()
diff --git a/website/docs/developer-guide/gateway-internals.md b/website/docs/developer-guide/gateway-internals.md
index 9f7b9f5c172..742e637ddca 100644
--- a/website/docs/developer-guide/gateway-internals.md
+++ b/website/docs/developer-guide/gateway-internals.md
@@ -216,8 +216,11 @@ the original result without incrementing the revision again; reusing its ID with
different contents returns `admission_conflict`. A competing edit with a stale
revision returns `revision_conflict`. Draining rejects new mutations and fresh
session registration before routing or transcript creation. These edits
-do not interrupt a running turn. This RPC does not yet migrate legacy direct
-writers, expose arbitrary SQL, or implement reset, delete, or rewind.
+do not interrupt a running turn. Canonical reset, delete, rewind, model, branch,
+and compression operations use the same receipt boundary. A request disconnect
+does not cancel its owner-held mutation: the commit, live projection and queue
+wakeup finish together, and profile retirement joins that work before releasing
+the store. An exact old receipt cannot evict a newer running agent.
Canonical wire models live in `tui_gateway/contracts/canonical*.py` and generate
`CanonicalRpcMethods` plus the OpenRPC `x-canonical-methods` catalog, separately