Skip to content

The agent that grows with you

fix(gateway): exact mutation retries repair the runtime projection (X11, reported by @Xipong)

teknium1c1ee92860012
diff --git a/gateway/session_mutations.py b/gateway/session_mutations.py
index c465dc3239b..fac275a84a1 100644
--- a/gateway/session_mutations.py
+++ b/gateway/session_mutations.py
@@ -83,25 +83,32 @@ async def mutate_session(authority, actor, ref, params):
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, _prepare_only=True)
- if 'snapshot' not in prepared:
- return prepared
- from gateway.session_mutation_model import prepare_model
- from gateway.session_mutation_compress import prepare_compress
- prepare = {'model': prepare_model, 'compress': prepare_compress}[operation]
- prepared = await prepare(authority, live, params['payload'], prepared)
- applied = False
- result = 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)
- if operation == 'model' and applied:
+ if 'snapshot' in prepared:
+ from gateway.session_mutation_model import prepare_model
+ from gateway.session_mutation_compress import prepare_compress
+ prepare = {'model': prepare_model, 'compress': prepare_compress}[operation]
+ prepared = await prepare(authority, live, params['payload'], prepared)
+ applied = False
+ 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:
+ result = 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.
+ if operation == 'model':
from gateway.session_local import publish_local_policy
publish_local_policy(authority, ref.session_id)
if operation == 'branch':
from gateway.session_local_recovery import restore_local_session
restore_local_session(authority, result['branched_session_id'])
- if operation in {'reset', 'compress'} and applied:
+ if operation in {'reset', 'compress'}:
from gateway.session_local_recovery import restore_local_session
restore_local_session(authority, ref.session_id)
authority.runner._evict_cached_agent(authority.sessions[ref.session_id].route)
@@ -126,8 +133,9 @@ async def mutate_session(authority, actor, ref, params):
evict = getattr(authority.runner, '_evict_cached_agent', None)
if callable(evict):
evict(candidate.route)
- if applied and live is not None:
+ if live is not None:
if operation == 'rewind':
authority.runner._evict_cached_agent(live.route)
- live.event_stream.publish(ref.session_id, result, event_type='session.updated')
+ if applied:
+ live.event_stream.publish(ref.session_id, result, event_type='session.updated')
return result
diff --git a/tests/gateway/test_session_mutation_retry_repair.py b/tests/gateway/test_session_mutation_retry_repair.py
new file mode 100644
index 00000000000..17ddb00c39e
--- /dev/null
+++ b/tests/gateway/test_session_mutation_retry_repair.py
@@ -0,0 +1,46 @@
+"""An exact mutation retry reconciles the runtime projection the failed first attempt left behind."""
+from types import SimpleNamespace
+
+import pytest
+from gateway.session_authority import LiveSession, SessionAuthority
+from gateway.session_controls import AuthorityConnection
+from hermes_state import SessionDB
+import hermes_state_runtime as rt
+
+
+async def test_exact_retry_repairs_runtime_after_post_commit_failure_without_second_event(tmp_path):
+ with SessionDB(db_path=tmp_path / 'state.db') as db:
+ db.create_session('s', source='test')
+ db.append_message('s', role='user', content='keep')
+ db.append_message('s', role='assistant', content='drop')
+ db.append_message('s', role='user', content='drop too')
+ epoch = rt.begin_runtime_epoch(db, instance_id='owner')
+ evictions = []
+
+ def evict(route):
+ evictions.append(route)
+ if len(evictions) == 1:
+ # The transcript rewind is already committed; the still-running process
+ # fails while repairing its cached agent.
+ raise RuntimeError('injected post-commit failure')
+
+ authority = SessionAuthority(SimpleNamespace(_draining=False, _evict_cached_agent=evict),
+ profile_id='owned', instance_id='owner', db=db, epoch=epoch)
+ live = authority.sessions['s'] = LiveSession(None, 'route')
+ owner = AuthorityConnection(authority, object(), {'user_id': 'human'})
+ watermark = live.event_stream.watermark()
+ request = {'id': 1, 'method': 'session.mutate', 'params': {'session_id': 's',
+ 'request_id': 'rewind', 'expected_revision': 0, 'expected_generation': 0,
+ 'operation': 'rewind', 'payload': {'target_message_id': db.get_messages('s')[2]['id']}}}
+ try:
+ with pytest.raises(RuntimeError, match='injected post-commit failure'):
+ await owner.dispatch(request)
+ assert [m['content'] for m in db.get_messages('s')] == ['keep', 'drop'], 'rewind did not commit'
+ assert live.event_stream.since(*watermark)['events'] == [], 'a failed attempt published its event'
+ retried = await owner.dispatch(request)
+ assert retried['result']['rewound_count'] == 1
+ assert evictions == ['route', 'route'], 'exact retry skipped the runtime repair'
+ assert live.event_stream.since(*watermark)['events'] == [], 'exact retry re-emitted the one-shot event'
+ finally:
+ await owner.close()