Skip to content

The agent that grows with you

fix: retain local admission ownership across transcript rotation

Teknium42ee0d341a77
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index 9b4777c8870..a4bda0c4b0a 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -57,9 +57,12 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
self._ctx = ctx
authority = getattr(runner, "session_authority", None)
self._approval_owner = None
- if authority is not None and ctx.session_id in authority.sessions:
- generation = authority.db.get_session(ctx.session_id)["runtime_generation"]
- self._approval_owner = (authority, ctx.session_id, generation)
+ if authority is not None:
+ owner_id = next((sid for sid, live in authority.sessions.items()
+ if live.route == ctx.session_key), ctx.session_id)
+ if owner_id in authority.sessions:
+ generation = authority.db.get_session(owner_id)["runtime_generation"]
+ self._approval_owner = (authority, owner_id, generation)
def _publish_execution(self, event_type, payload):
diff --git a/gateway/session.py b/gateway/session.py
index d102e593888..9331207b3ae 100644
--- a/gateway/session.py
+++ b/gateway/session.py
@@ -1073,6 +1073,9 @@ class SessionStore(
return None
now = _now()
session_id = _new_session_id(now)
+ if old_entry.origin and old_entry.origin.platform == Platform.LOCAL and old_entry.origin.chat_id.startswith("local-"):
+ from gateway.session_local_recovery import reset_local_session
+ return reset_local_session(self, old_entry, session_id, now, display_name)
new_entry = self._replace_route_locked(
session_key, old_entry, session_id, now,
display_name=display_name if display_name is not None else old_entry.display_name,
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 6e3615fe3a6..44e54f28e4e 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -95,6 +95,7 @@ class SessionAuthority:
async def attach(self, actor, ref):
self.authorize(actor, ref, 'session:read')
live = self.sessions[ref.session_id]
+ from gateway.session_local_recovery import local_history
with live.event_stream.lock:
subscription = next((key for key, member in live.subscribers.items()
if member == actor), None) or uuid.uuid4().hex
@@ -107,7 +108,7 @@ class SessionAuthority:
prompts = live.controls.snapshot(ref.session_id, active_generation)
epoch, sequence = live.event_stream.watermark()
return SubscriptionSnapshot(subscription, handle, epoch,
- sequence, tuple(self.db.get_messages_as_conversation(ref.session_id)),
+ sequence, tuple(local_history(self, ref)),
tuple(self._pending_receipt(r) for r in list_session_admissions(
self.db, session_id=ref.session_id)), prompts)
@@ -352,6 +353,7 @@ async def initialize_session_authority(runner, *, profile_id, instance_id):
recover_session_inputs(db, epoch=epoch)
authority = SessionAuthority(runner, profile_id=profile_id, instance_id=instance_id, db=db, epoch=epoch)
runner.session_authority = authority
+ runner.session_store._local_authority_epoch = epoch
from gateway.session_local_recovery import recover_local_sessions
recover_local_sessions(authority)
return authority
diff --git a/gateway/session_local_recovery.py b/gateway/session_local_recovery.py
index 0ba5240aa6c..c54b3740997 100644
--- a/gateway/session_local_recovery.py
+++ b/gateway/session_local_recovery.py
@@ -34,15 +34,16 @@ def restore_local_session(authority, sid):
raise ValueError('route mismatch')
policy = restore_policy(receipt['policy'])
entry = SessionEntry.from_dict(receipt['entry'])
- if (entry.session_id != sid or entry.session_key != route
+ target = entry.session_id
+ if (entry.session_key != route
or entry.origin.to_dict() != source.to_dict()):
raise ValueError('entry mismatch')
- row = authority.db.get_session(sid)
+ row = authority.db.get_session(target)
if row is None or (row['session_key'], row['chat_id'], row['user_id']) != (route, chat_id, source.user_id):
raise ValueError('stored identity mismatch')
- if authority.db.get_compression_chain(sid)[-1] != sid:
- # A creation receipt cannot authorize a different execution target.
- raise RuntimeStoreError('storage_unavailable')
+ from hermes_state_local_lineage import validate_local_lineage
+ with authority.db._read_ctx() as conn:
+ validate_local_lineage(conn, receipt)
except (KeyError, TypeError, ValueError, AttributeError) as exc:
if isinstance(exc, RuntimeStoreError):
raise
@@ -58,7 +59,7 @@ def restore_local_session(authority, sid):
with store._lock:
store._ensure_loaded_locked()
current = store._entries.get(route)
- if current is not None and current.session_id != sid:
+ if current is not None and current.session_id != target:
raise RuntimeStoreError('admission_conflict')
entry.origin = source
store._entries[route] = entry
@@ -69,9 +70,36 @@ def restore_local_session(authority, sid):
or live.source.to_dict() != source.to_dict()
or adapter.policies.get(chat_id) != policy):
raise RuntimeStoreError('storage_unavailable')
+ else:
+ with store._lock:
+ current = store._entry_locked(route)
+ if current is None or current.session_id not in receipt.get('lineage', [sid]):
+ raise RuntimeStoreError('admission_conflict')
+ current.session_id = target
return SessionRef(authority.profile_id, sid)
+def local_history(authority, ref):
+ live = authority.sessions[ref.session_id]
+ target = ref.session_id
+ if live.source is not None and live.source.platform == Platform.LOCAL:
+ restore_local_session(authority, ref.session_id)
+ target = local_receipt(authority.db, ref.session_id)['entry']['session_id']
+ return authority.db.get_messages_as_conversation(target)
+
+
+def reset_local_session(store, old_entry, session_id, now, display_name):
+ from hermes_state_local_lineage import reset_local_target
+ entry = SessionEntry(old_entry.session_key, session_id, now, now,
+ origin=old_entry.origin, platform=old_entry.platform, chat_type=old_entry.chat_type,
+ display_name=display_name if display_name is not None else old_entry.display_name,
+ is_fresh_reset=True)
+ reset_local_target(store._db_for_key(old_entry.session_key), epoch=store._local_authority_epoch,
+ parent_session_id=old_entry.session_id, entry=entry.to_dict())
+ store._entries[old_entry.session_key] = entry
+ return entry
+
+
def recover_local_sessions(authority, *, schedule=False):
with authority.db._read_ctx() as conn:
ids = [row[0][len(POLICY_PREFIX):] for row in conn.execute(
diff --git a/hermes_state_compression.py b/hermes_state_compression.py
index dd5dd1b12a0..6acd1c98969 100644
--- a/hermes_state_compression.py
+++ b/hermes_state_compression.py
@@ -259,6 +259,8 @@ class SessionCompressionMixin:
"WHERE id = ? AND ended_at IS NULL", (time.time(), parent_session_id))
if updated.rowcount != 1:
raise RuntimeError(f"Compression parent changed during publication: {parent_session_id}")
+ from hermes_state_local_lineage import advance_local_target
+ advance_local_target(conn, parent_session_id, child_session_id)
self._execute_write(_do)
def _write_sql_logged(self, op: str, session_id: str, sql: str, params) -> None:
diff --git a/hermes_state_local_lineage.py b/hermes_state_local_lineage.py
new file mode 100644
index 00000000000..679aff07fd7
--- /dev/null
+++ b/hermes_state_local_lineage.py
@@ -0,0 +1,86 @@
+"""Local physical-target handoff inside the existing publication transaction.
+
+The creation ID remains the admission/execution owner. Transcript rotation must
+not re-key idempotency digests, queued inputs, subscribers or uncertain claims.
+"""
+import json
+
+from hermes_state_local import POLICY_PREFIX
+from hermes_state_runtime import RuntimeStoreError, _epoch, _json
+
+
+def validate_local_lineage(conn, receipt):
+ from hermes_state_compression import _CHAIN_STEP_SQL
+ lineage = receipt.get('lineage', [receipt['session_id']])
+ if (not isinstance(lineage, list) or not lineage or len(set(lineage)) != len(lineage)
+ or lineage[0] != receipt['session_id'] or lineage[-1] != receipt['entry']['session_id']):
+ raise RuntimeStoreError('storage_unavailable')
+ for parent_id, child_id in zip(lineage, lineage[1:]):
+ parent = conn.execute('SELECT end_reason FROM sessions WHERE id=?', (parent_id,)).fetchone()
+ child = conn.execute('SELECT parent_session_id,model_config FROM sessions WHERE id=?', (child_id,)).fetchone()
+ if parent is None or child is None or child['parent_session_id'] != parent_id:
+ raise RuntimeStoreError('storage_unavailable')
+ if parent['end_reason'] == 'session_reset':
+ valid = json.loads(child['model_config'] or '{}').get('_reset_from') == parent_id
+ else:
+ tip = conn.execute(_CHAIN_STEP_SQL, (parent_id,)).fetchone()
+ valid = parent['end_reason'] == 'compression' and tip is not None and tip['id'] == child_id
+ if not valid:
+ raise RuntimeStoreError('storage_unavailable')
+ if conn.execute(_CHAIN_STEP_SQL, (lineage[-1],)).fetchone() is not None:
+ raise RuntimeStoreError('storage_unavailable')
+ return lineage[-1]
+
+
+def advance_local_target(conn, parent_session_id, child_session_id, *, entry=None):
+ parent = conn.execute('SELECT * FROM sessions WHERE id=?', (parent_session_id,)).fetchone()
+ logical_id = parent['chat_id'] if parent else None
+ if not logical_id or not logical_id.startswith('local-'):
+ return
+ key = POLICY_PREFIX + logical_id
+ raw = conn.execute('SELECT value FROM state_meta WHERE key=?', (key,)).fetchone()
+ if raw is None:
+ raise RuntimeStoreError('storage_unavailable')
+ try:
+ receipt = json.loads(raw[0])
+ if (receipt['session_id'] != logical_id or receipt['entry']['session_id'] != parent_session_id
+ or receipt['principal_id'] != parent['user_id'] or receipt['route'] != parent['session_key']):
+ raise RuntimeStoreError('storage_unavailable')
+ route_row = conn.execute("SELECT entry_json FROM gateway_routing WHERE scope='' AND session_key=?",
+ (receipt['route'],)).fetchone()
+ routed = json.loads(route_row[0]) if route_row else None
+ if routed is None or routed['session_id'] != parent_session_id:
+ raise RuntimeStoreError('admission_conflict')
+ candidate = dict(entry or routed, session_id=child_session_id)
+ receipt['entry'] = candidate
+ receipt['lineage'] = [*receipt.get('lineage', [logical_id]), child_session_id]
+ validate_local_lineage(conn, receipt)
+ except (KeyError, TypeError, ValueError) as exc:
+ if isinstance(exc, RuntimeStoreError):
+ raise
+ raise RuntimeStoreError('storage_unavailable') from exc
+ conn.execute("UPDATE gateway_routing SET entry_json=? WHERE scope='' AND session_key=?",
+ (_json(candidate), receipt['route']))
+ conn.execute('UPDATE state_meta SET value=? WHERE key=?', (_json(receipt), key))
+ conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?', (logical_id,))
+
+
+def reset_local_target(db, *, epoch, parent_session_id, entry):
+ def write(conn):
+ _epoch(conn, epoch)
+ parent = conn.execute('SELECT * FROM sessions WHERE id=?', (parent_session_id,)).fetchone()
+ if parent is None or parent['end_reason'] == 'compression':
+ raise RuntimeStoreError('admission_conflict')
+ receipt = conn.execute('SELECT value FROM state_meta WHERE key=?',
+ (POLICY_PREFIX + parent['chat_id'],)).fetchone()
+ if receipt is None:
+ raise RuntimeStoreError('storage_unavailable')
+ policy = json.loads(receipt[0])['policy']
+ db._publish_child_session_row(conn, parent, parent_session_id=parent_session_id,
+ child_session_id=entry['session_id'], source=policy['source'], model=policy['model'],
+ model_config={'_reset_from': parent_session_id}, system_prompt=None,
+ cwd=policy['cwd'], profile_name=parent['profile_name'])
+ conn.execute("UPDATE sessions SET ended_at=strftime('%s','now'),end_reason='session_reset' WHERE id=?",
+ (parent_session_id,))
+ advance_local_target(conn, parent_session_id, entry['session_id'], entry=entry)
+ db._execute_write(write)
diff --git a/tests/gateway/test_local_session_lineage.py b/tests/gateway/test_local_session_lineage.py
new file mode 100644
index 00000000000..4d666e866c9
--- /dev/null
+++ b/tests/gateway/test_local_session_lineage.py
@@ -0,0 +1,101 @@
+"""A local conversation keeps one admission owner across physical transcript boundaries."""
+import json
+from types import SimpleNamespace
+
+import pytest
+
+
+async def test_local_lineage_transitions_preserve_owner_or_roll_back(tmp_path, monkeypatch):
+ from gateway import run
+ from gateway.config import GatewayConfig, Platform
+ from gateway.session import SessionStore
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_contract import Principal, SessionRef
+ from gateway.session_local import create_local_session
+ from hermes_state_local import local_receipt
+ from hermes_state_runtime import (RuntimeStoreError, admit_session_input, claim_session_input,
+ get_session_admission, list_session_admissions)
+
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {})
+ def runner():
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ return SimpleNamespace(session_store=store, _session_db=store._db,
+ adapters={}, _draining=False)
+ first = runner()
+ authority = await initialize_session_authority(first, profile_id='fixture', instance_id='first')
+ actor = Principal('owner', 'fixture', frozenset({'session:create', 'session:read'}), 'socket')
+ params = dict(request_id='lineage', source='gui', cwd=str(tmp_path), model='frozen', toolsets=[])
+ ref = create_local_session(authority, actor, params)
+ db = authority.db
+ live = authority.sessions[ref.session_id]
+ original = local_receipt(db, ref.session_id)
+ queued = admit_session_input(db, epoch=authority.epoch, principal_id=actor.subject,
+ session_id=ref.session_id, request_id='pending', payload={'text': 'pending'})
+ history = [{'role': 'user', 'content': 'retained'}, {'role': 'assistant', 'content': 'history'}]
+ def compress(parent, child):
+ assert db.try_acquire_compression_lock(parent, 'fixture')
+ try:
+ db.publish_compression_child(parent_session_id=parent, child_session_id=child,
+ source='gui', messages=history, compression_lock_holder='fixture')
+ finally:
+ db.release_compression_lock(parent, 'fixture')
+ compress(ref.session_id, 'compressed')
+ second = runner()
+ cold = await initialize_session_authority(second, profile_id='fixture', instance_id='second')
+ assert ref.session_id in cold.sessions, 'atomic compression lost the private local owner'
+ assert create_local_session(cold, actor, params) == ref
+ snapshot = await cold.attach(actor, ref)
+ assert [(m['role'], m['content']) for m in snapshot.history] == [(m['role'], m['content']) for m in history]
+ assert snapshot.pending[0].admission_id == queued['admission_id']
+ assert second.session_store._entries[live.route].session_id == 'compressed'
+ assert local_receipt(db, ref.session_id)['policy'] == original['policy']
+ write = db._execute_write
+ def abort(callback, **kwargs):
+ def fail(conn):
+ callback(conn)
+ raise RuntimeError('transaction abort')
+ return write(fail, **kwargs)
+ # Use the owning SessionStore DB: reset must not publish any in-memory target on failure.
+ db = cold.db
+ write = db._execute_write
+ before = local_receipt(db, ref.session_id)
+ monkeypatch.setattr(db, '_execute_write', abort)
+ with pytest.raises(RuntimeError, match='transaction abort'):
+ second.session_store.reset_session(live.route)
+ monkeypatch.setattr(db, '_execute_write', write)
+ assert local_receipt(db, ref.session_id) == before
+ assert second.session_store._entries[live.route].session_id == 'compressed'
+ reset = second.session_store.reset_session(live.route)
+ assert reset.session_id != 'compressed'
+ assert db.get_session(reset.session_id)['cwd'] == params['cwd']
+ assert db.get_session(reset.session_id)['model'] == params['model']
+ third = runner()
+ recovered = await initialize_session_authority(third, profile_id='fixture', instance_id='third')
+ snapshot = await recovered.attach(actor, ref)
+ assert snapshot.history == () # reset is a deliberate history boundary, not a fork
+ assert snapshot.pending[0].admission_id == queued['admission_id']
+ assert create_local_session(recovered, actor, params) == ref
+ policy = third.adapters[Platform.LOCAL].policies[live.source.chat_id]
+ assert policy.cwd == params['cwd'] and policy.source == params['source']
+ # An interrupted claim remains owned by the logical conversation, even after another rotation.
+ claimed = claim_session_input(recovered.db, epoch=recovered.epoch, session_id=ref.session_id)
+ compress(reset.session_id, 'compressed-again')
+ fourth = runner()
+ restarted = await initialize_session_authority(fourth, profile_id='fixture', instance_id='fourth')
+ assert get_session_admission(restarted.db, admission_id=claimed['admission_id'])['status'] == 'unknown'
+ with pytest.raises(RuntimeStoreError, match='unknown_execution'):
+ claim_session_input(restarted.db, epoch=restarted.epoch, session_id=ref.session_id)
+ assert len(list_session_admissions(restarted.db, session_id=ref.session_id)) == 1
+ foreign = Principal('foreign', 'fixture', actor.capabilities, 'foreign')
+ with pytest.raises(RuntimeStoreError, match='permission_denied'):
+ await restarted.attach(foreign, ref)
+ db.create_session('unrelated-fork', source='gui', parent_session_id='compressed-again',
+ model_config={'_branch': True}, chat_id=live.source.chat_id,
+ user_id=actor.subject, session_key=live.route)
+ with pytest.raises(RuntimeStoreError, match='storage_unavailable'):
+ await restarted.attach(actor, SessionRef('fixture', 'unrelated-fork'))
+ # Copying the receipt onto a fork does not turn it into the canonical owner.
+ db.set_meta('gateway.local_policy.v1:unrelated-fork', json.dumps(local_receipt(db, ref.session_id)))
+ with pytest.raises(RuntimeStoreError, match='storage_unavailable'):
+ await restarted.attach(actor, SessionRef('fixture', 'unrelated-fork'))