The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): legacy deletes and prunes publish the full retirement fence
teknium1866bb0c2953c
diff --git a/hermes_state_mutation_retirement.py b/hermes_state_mutation_retirement.pyindex 02b00e3f346..aa48dc3ca00 100644--- a/hermes_state_mutation_retirement.py+++ b/hermes_state_mutation_retirement.py@@ -59,12 +59,24 @@ _LIVE_LEDGER_SQL = """SELECT 1 FROM session_admissions WHERE target_session_id=?UNION ALL SELECT 1 FROM worker_executions WHERE session_id=? AND status!='terminal' LIMIT 1"""+def retire_sessions(conn, session_ids):+ """The complete deletion fence for ids that are being deleted in this transaction.++ Terminal receipts alone are not enough: without the ``RETIRED_PREFIX`` marker an exact+ retry of a settled request reports ``not_found`` instead of its terminal receipt, a late+ accounting/constructor backfill recreates the deleted row, and the same request is then+ admitted a second time against it. Every delete path (canonical mutate, legacy+ ``delete_session*``, prunes and sweeps) must publish the whole fence, so it lives here once."""+ retire_terminal_receipts(conn, session_ids)+ retire_routes(conn, session_ids)++def retire_prunable(conn, session_ids):- """Sweep variant of :func:`retire_terminal_receipts`: retire the idle sessions' terminal rows and- return only those ids. A session with live or unknown work is skipped, so one busy row cannot- abort a whole prune/empty-session sweep (explicit deletes still refuse with ``session_busy``)."""+ """Sweep variant of :func:`retire_sessions`: fence the idle sessions and return only those ids.+ A session with live or unknown work is skipped, so one busy row cannot abort a whole+ prune/empty-session sweep (explicit deletes still refuse with ``session_busy``)."""quiet = [sid for sid in session_ids if conn.execute(_LIVE_LEDGER_SQL, (sid, sid)).fetchone() is None]- retire_terminal_receipts(conn, quiet)+ retire_sessions(conn, quiet)return quiet@@ -72,8 +84,7 @@ def delete_in_transaction(db, conn, session_id, payload):from hermes_state_mutation_guards import require_idle, delete_targetstargets = delete_targets(conn, session_id)require_idle(db, conn, targets)- retire_terminal_receipts(conn, targets)- retire_routes(conn, targets)+ retire_sessions(conn, targets)for sid in targets:db._bump_conversation_generation(conn, sid, 'session_reset')conn.execute('UPDATE sessions SET parent_session_id=NULL, runtime_revision=runtime_revision+1 WHERE parent_session_id=?', (sid,))@@ -84,8 +95,10 @@ def delete_in_transaction(db, conn, session_id, payload):def retire_routes(conn, session_ids):+ # OR IGNORE: the marker is a fact, not a receipt; re-retiring an id that was recreated+ # beside its tombstone must not abort the delete that removes it again.for sid in session_ids:- conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)',+ conn.execute('INSERT OR IGNORE INTO state_meta(key,value) VALUES(?,?)',(RETIRED_PREFIX + sid, '{}'))targets = set(session_ids)for row in conn.execute('SELECT scope,session_key,entry_json FROM gateway_routing').fetchall():diff --git a/hermes_state_sessions.py b/hermes_state_sessions.pyindex 88da3be160a..f00c9b69832 100644--- a/hermes_state_sessions.py+++ b/hermes_state_sessions.py@@ -158,8 +158,8 @@ def _collect_delegate_child_ids(conn, parent_ids: List[str]) -> List[str]:def _delete_delegate_children(conn, parent_ids: List[str]) -> List[str]:ids = _collect_delegate_child_ids(conn, parent_ids)- from hermes_state_mutation_retirement import retire_terminal_receipts- retire_terminal_receipts(conn, ids)+ from hermes_state_mutation_retirement import retire_sessions+ retire_sessions(conn, ids)for chunk in _id_chunks(ids):ph = _session_ids_placeholders(chunk)conn.execute(f"DELETE FROM messages WHERE session_id IN ({ph})", chunk)@@ -1440,8 +1440,8 @@ class SessionSessionsMixin:session_id, *_collect_delegate_child_ids(conn, [session_id])}:return False- from hermes_state_mutation_retirement import retire_terminal_receipts- retire_terminal_receipts(conn, [session_id])+ from hermes_state_mutation_retirement import retire_sessions+ retire_sessions(conn, [session_id])removed_ids.extend(_delete_delegate_children(conn, [session_id]))conn.execute( # orphan remaining children (branches) so FK is satisfied"UPDATE sessions SET parent_session_id = NULL WHERE parent_session_id = ?", (session_id,),@@ -1479,8 +1479,8 @@ class SessionSessionsMixin:return False# Same BEGIN IMMEDIATE transaction as the check above: retire the ledger rows# (ON DELETE RESTRICT) and delete without re-evaluating eligibility.- from hermes_state_mutation_retirement import retire_terminal_receipts- retire_terminal_receipts(conn, [session_id])+ from hermes_state_mutation_retirement import retire_sessions+ retire_sessions(conn, [session_id])conn.execute("DELETE FROM sessions WHERE id = ?", (session_id,))self._delete_unreferenced_system_prompts(conn)return True@@ -1502,8 +1502,8 @@ class SessionSessionsMixin:).fetchall()]if not existing:return 0- from hermes_state_mutation_retirement import retire_terminal_receipts- retire_terminal_receipts(conn, existing)+ from hermes_state_mutation_retirement import retire_sessions+ retire_sessions(conn, existing)removed_ids.extend(_delete_delegate_children(conn, existing))for chunk in _id_chunks(existing):ph = _session_ids_placeholders(chunk)diff --git a/tests/hermes_state/test_ledger_delete_consistency.py b/tests/hermes_state/test_ledger_delete_consistency.pyindex 9ec5461715c..16d6ba3b5a5 100644--- a/tests/hermes_state/test_ledger_delete_consistency.py+++ b/tests/hermes_state/test_ledger_delete_consistency.py@@ -66,6 +66,53 @@ def test_legacy_delete_retires_terminal_ledger_rows_and_refuses_live_work(tmp_paassert not c.execute('PRAGMA foreign_key_check').fetchall()[email protected]('delete', [+ lambda db, sid: db.delete_session(sid),+ lambda db, sid: db.delete_sessions([sid]),+ lambda db, sid: db.delete_session_if_empty(sid),+ lambda db, sid: db.delete_empty_sessions(),+ lambda db, sid: db.prune_sessions(older_than_days=30),+ lambda db, sid: db.prune_empty_ghost_sessions(),+], ids=['single', 'bulk', 'if_empty', 'empty_sweep', 'prune', 'ghost_prune'])+def test_legacy_delete_publishes_the_full_retirement_fence(tmp_path, delete):+ """Same contract as the canonical mutate(delete): the exact retry of a settled request+ still returns its terminal receipt, and a late accounting backfill cannot recreate the+ row (which would let the same request be admitted a second time)."""+ from hermes_state_mutation_retirement import retired_session+ with closing(SessionDB(tmp_path / 'state.db')) as db:+ epoch = rt.begin_runtime_epoch(db, instance_id='owner')+ _old_ended(db, 's', source='tui')+ db.save_gateway_routing_entry('route:s', '{"session_id": "s"}')+ request = dict(epoch=epoch, principal_id='human', session_id='s', request_id='once',+ payload={'text': 'x'})+ admission_id = _settled_admission(db, epoch, 's', 'once')+ assert delete(db, 's')+ assert db.get_session('s') is None and retired_session(db, 's')+ assert db.load_gateway_routing_entries() == {}+ retry = rt.admit_session_input(db, **request)+ assert retry['status'] == 'terminal' and retry['admission_id'] == admission_id+ with pytest.raises(rt.RuntimeStoreError, match='not_found'):+ db.update_token_counts('s', input_tokens=1, output_tokens=1, model='m')+ assert db.get_session('s') is None+++def test_legacy_delete_fences_cascaded_delegate_children(tmp_path):+ from hermes_state_mutation_retirement import retired_session+ with closing(SessionDB(tmp_path / 'state.db')) as db:+ epoch = rt.begin_runtime_epoch(db, instance_id='owner')+ db.create_session('parent', source='cli')+ db.create_session('child', source='cli', parent_session_id='parent',+ model_config={'_delegate_from': 'parent'})+ admission_id = _settled_admission(db, epoch, 'child', 'sub')+ assert db.delete_session('parent')+ assert db.get_session('child') is None and retired_session(db, 'child')+ retry = rt.admit_session_input(db, epoch=epoch, principal_id='human', session_id='child',+ request_id='sub', payload={'text': 'x'})+ assert retry['status'] == 'terminal' and retry['admission_id'] == admission_id+ with pytest.raises(rt.RuntimeStoreError, match='not_found'):+ db.ensure_session('child', source='unknown')++def test_sweeps_skip_sessions_with_live_work_and_retire_the_rest(tmp_path):with closing(SessionDB(tmp_path / 'state.db')) as db:epoch = rt.begin_runtime_epoch(db, instance_id='owner')