Skip to content

The agent that grows with you

fix: fence a messaging chat pick with a mutation receipt and revision bump

Teknium12d6383e0168
diff --git a/gateway/session_messaging_picks.py b/gateway/session_messaging_picks.py
index b0f708855b7..7ef1047e195 100644
--- a/gateway/session_messaging_picks.py
+++ b/gateway/session_messaging_picks.py
@@ -23,17 +23,6 @@ def is_chat_pick(live, operation):
return operation in CHAT_PICKS and live is not None and live.source.platform != Platform.LOCAL
-def _require_fences(authority, ref, params):
- row = authority.db.get_session(ref.session_id)
- if row is None:
- raise RuntimeStoreError('not_found')
- if row['runtime_revision'] != params['expected_revision']:
- raise RuntimeStoreError('revision_conflict')
- if row['runtime_generation'] != params['expected_generation']:
- raise RuntimeStoreError('stale_generation')
- return row
-
-
def _platform_key(live):
from gateway.run import _platform_config_key
return _platform_config_key(live.source.platform)
@@ -73,15 +62,23 @@ async def _pick_model(authority, owner, live, payload, row):
return fields
-async def apply_chat_pick(authority, ref, owner, live, params):
+async def apply_chat_pick(authority, ref, owner, live, params, *, principal_id):
"""Apply a ``model`` / ``reasoning`` mutation to the messaging chat *live* mounted on *owner* (the
caller authorized control and holds its mutation lock). The fences are the mount's, the ones
``session.resume`` handed the viewer; comparing them with a compression segment's row refused a
- pick on a compressed chat with ``stale_generation``."""
+ pick on a compressed chat with ``stale_generation``. The receipt is keyed on that mount too: an
+ exact retry answers its stored receipt without re-applying the override, and the commit bumps the
+ mount's revision, so a retry of an older pick refuses ``revision_conflict``."""
+ from hermes_state_mutation_chat_pick import chat_pick_key, commit_chat_pick, prepare_chat_pick
from hermes_state_mutations import validate_action
operation, payload = params['operation'], params['payload']
validate_action(operation, payload)
- row = await asyncio.to_thread(_require_fences, authority, owner, params)
+ key, digest = chat_pick_key(principal_id, owner.session_id, params)
+ fenced = dict(epoch=authority.epoch, key=key, digest=digest, session_id=owner.session_id, params=params)
+ prepared = await asyncio.to_thread(prepare_chat_pick, authority.db, **fenced)
+ if 'receipt' in prepared:
+ return prepared['receipt']
+ row = prepared['row']
runner = authority.runner
if operation == 'reasoning':
await asyncio.to_thread(_apply_reasoning, runner, live, payload['effort'])
@@ -89,10 +86,11 @@ async def apply_chat_pick(authority, ref, owner, live, params):
else:
async with runner._model_switch_lock():
fields = await _pick_model(authority, owner, live, payload, row)
- result = {'session_id': ref.session_id, 'operation': operation, 'revision': row['runtime_revision'],
- 'execution_generation': row['runtime_generation'], **fields}
if fields.get('status') == 'confirmation_required':
return {'session_id': ref.session_id, 'operation': operation, **fields}
+ result = {'session_id': ref.session_id, 'operation': operation, 'revision': row['runtime_revision'],
+ 'execution_generation': row['runtime_generation'], **fields}
+ result = await asyncio.to_thread(commit_chat_pick, authority.db, **fenced, result=result)
from gateway.session_local import local_session_info
# Every viewer repaints its model and reasoning pill, as after a LOCAL pick.
live.event_stream.publish(owner.session_id, local_session_info(authority, owner), event_type='session.info')
diff --git a/gateway/session_mutations.py b/gateway/session_mutations.py
index bff02d4a2ea..e9b3f3e3ccd 100644
--- a/gateway/session_mutations.py
+++ b/gateway/session_mutations.py
@@ -163,7 +163,7 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None, ow
if is_chat_pick(live, operation):
# No frozen policy to commit into: the chat's own /model and /reasoning override (#141152).
from gateway.session_messaging_picks import apply_chat_pick
- return await apply_chat_pick(authority, ref, owner or ref, live, params)
+ return await apply_chat_pick(authority, ref, owner or ref, live, params, principal_id=actor.subject)
def authorize_write(conn):
from hermes_state_mutation_binding import authorize_history, import_history_control
diff --git a/hermes_state_mutation_chat_pick.py b/hermes_state_mutation_chat_pick.py
new file mode 100644
index 00000000000..4b5517720c9
--- /dev/null
+++ b/hermes_state_mutation_chat_pick.py
@@ -0,0 +1,67 @@
+"""Exact-retry receipts for a viewer's pick on a messaging chat (gateway/session_messaging_picks.py).
+
+A messaging chat has no frozen policy for ``apply_action`` to write: its pick is the chat's own
+``/model`` / ``/reasoning`` override. It still answers ``session.mutate`` like a LOCAL pick: the
+same ``gateway.mutation.v1.*`` receipt key and digest (``mutation_receipt_key``), checked before the
+override is applied so an exact retry never re-applies it, and committed with the revision bump in
+one fenced transaction.
+"""
+import json
+
+from hermes_state_runtime import (
+ RuntimeStoreError, _epoch, _json, _text, mutation_receipt_key, replay_mutation_receipt,
+)
+
+
+def chat_pick_key(principal_id, session_id, params):
+ """``(key, digest)`` of the pick *params* on *session_id* (the mount the fences name)."""
+ for value in (principal_id, session_id, params['request_id']):
+ _text(value)
+ for fence in (params['expected_revision'], params.get('expected_generation')):
+ if type(fence) is not int or fence < 0:
+ raise RuntimeStoreError('invalid_params')
+ payload = json.loads(_json(params['payload']))
+ key, digest = mutation_receipt_key(
+ principal_id, session_id, params['request_id'], operation=params['operation'], payload=payload,
+ expected_revision=params['expected_revision'], expected_generation=params['expected_generation'])
+ return key, digest
+
+
+def _fenced_row(conn, session_id, params):
+ row = conn.execute('SELECT * FROM sessions WHERE id=?', (session_id,)).fetchone()
+ if row is None:
+ raise RuntimeStoreError('not_found')
+ if row['runtime_revision'] != params['expected_revision']:
+ raise RuntimeStoreError('revision_conflict')
+ if row['runtime_generation'] != params['expected_generation']:
+ raise RuntimeStoreError('stale_generation')
+ return row
+
+
+def prepare_chat_pick(db, *, epoch, key, digest, session_id, params):
+ """The stored receipt of an exact retry (``{'receipt': ...}``), else the fenced mount row
+ (``{'row': ...}``); a reused request id with another payload refuses ``admission_conflict``."""
+ with db._read_ctx() as conn:
+ _epoch(conn, epoch)
+ replay = replay_mutation_receipt(conn, key, digest)
+ if replay is not None:
+ return {'receipt': replay}
+ return {'row': dict(_fenced_row(conn, session_id, params))}
+
+
+def commit_chat_pick(db, *, epoch, key, digest, session_id, params, result):
+ """Bump the mount's revision and store *result* (plus the new revision) as the receipt, in one
+ write that re-checks the fences. Returns the committed receipt result."""
+ def write(conn):
+ _epoch(conn, epoch)
+ replay = replay_mutation_receipt(conn, key, digest)
+ if replay is not None:
+ return replay
+ _fenced_row(conn, session_id, params)
+ conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?', (session_id,))
+ revision = conn.execute('SELECT runtime_revision FROM sessions WHERE id=?', (session_id,)).fetchone()[0]
+ committed = {**result, 'revision': revision}
+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)',
+ (key, _json({'digest': digest, 'result': committed})))
+ return committed
+ return db._execute_write(write)
diff --git a/tests/gateway/test_messaging_session_picks.py b/tests/gateway/test_messaging_session_picks.py
index 128f4e855c3..321b0592291 100644
--- a/tests/gateway/test_messaging_session_picks.py
+++ b/tests/gateway/test_messaging_session_picks.py
@@ -91,3 +91,30 @@ async def test_a_model_pick_on_a_messaging_chat_is_the_chats_next_turn_model(tmp
finally:
await viewer.close()
runner.session_store.close_all_db_handles()
+
+
+async def test_a_messaging_pick_is_fenced_by_its_receipt_and_revision(tmp_path):
+ """An exact retry of an older pick answers its stored receipt (the chat keeps the newer level); a
+ reused request id with another payload and a retry on stale fences are refused, as on LOCAL."""
+ runner, source, route, viewer, root, fences = await _compressed_chat(tmp_path)
+ try:
+ first = await viewer.dispatch(_mutate(root, fences, 'reasoning', {'effort': 'high'}, 'pick-a'))
+ assert first['result']['revision'] == fences['revision'] + 1, first
+ second = await viewer.dispatch(_mutate(root, first['result'], 'reasoning', {'effort': 'low'}, 'pick-b'))
+ assert second['result']['revision'] == fences['revision'] + 2, second
+
+ retried = await viewer.dispatch(_mutate(root, fences, 'reasoning', {'effort': 'high'}, 'pick-a'))
+
+ assert retried.get('result') == first['result'], retried
+ level = runner._resolve_session_reasoning_config(source=source, session_key=route, model='')
+ assert level and level.get('effort') == 'low', level
+ reused = await viewer.dispatch(_mutate(root, fences, 'reasoning', {'effort': 'medium'}, 'pick-a'))
+ assert reused.get('error', {}).get('data', {}).get('reason') == 'admission_conflict', reused
+ stale = await viewer.dispatch(_mutate(root, fences, 'reasoning', {'effort': 'medium'}, 'pick-c'))
+ assert stale.get('error', {}).get('data', {}).get('reason') == 'revision_conflict', stale
+ level = runner._resolve_session_reasoning_config(source=source, session_key=route, model='')
+ assert level.get('effort') == 'low', level
+ finally:
+ await viewer.close()
+ runner.session_store.close_all_db_handles()