The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): deletion tombstones expire after a 7-day exact-retry horizon
Teknium3ce8aa8647a3
diff --git a/hermes_state_maintenance.py b/hermes_state_maintenance.pyindex 0c9fee7408a..889e5077c86 100644--- a/hermes_state_maintenance.py+++ b/hermes_state_maintenance.py@@ -342,8 +342,9 @@ class SessionMaintenanceMixin:session_ids = {row["id"] for row in cursor.fetchall()}if exclude_active_write_guards:session_ids -= self._guarded_ids(conn, session_ids)- from hermes_state_mutation_retirement import retire_prunable+ from hermes_state_mutation_retirement import prune_retired_tombstones, retire_prunablesession_ids = retire_prunable(conn, sorted(session_ids))+ prune_retired_tombstones(conn) # every prune pass also reclaims expired deletion tombstonesif not session_ids:return 0# Batched: a cron-heavy store prunes tens of thousands of ids in one call.diff --git a/hermes_state_mutation_retirement.py b/hermes_state_mutation_retirement.pyindex bb98640e9b7..7d3402f3e17 100644--- a/hermes_state_mutation_retirement.py+++ b/hermes_state_mutation_retirement.py@@ -1,5 +1,6 @@"""Durable deletion fences outside prunable transcript rows."""import json+import timefrom hermes_state_runtime import RuntimeStoreError, admission_fingerprint, _json, _textRETIRED_PREFIX = 'gateway.retired_session.v1.'@@ -53,6 +54,7 @@ def retire_terminal_receipts(conn, session_ids):# Keep the digest for exact retries, not another copy of user input/history.row['payload_json'] = '{}'row['lineage_json'] = '[]'+ row['retired_at'] = time.time()_compact_result(conn, row['admission_id'])conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)',(ADMISSION_PREFIX + row['admission_id'], _json(row)))@@ -73,6 +75,7 @@ def retire_terminal_receipts(conn, session_ids):if receipt['payload_digest'] != closing:receipt['result_json'] = Nonerow['receipts'] = receipts+ row['retired_at'] = time.time()conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)',(WORKER_PREFIX + row['execution_id'], _json(row)))conn.execute('DELETE FROM worker_receipts WHERE execution_id=?', (row['execution_id'],))@@ -189,14 +192,38 @@ def entry_session_id(raw):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.+ # OR REPLACE: 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 (and restarts its horizon).for sid in session_ids:- conn.execute('INSERT OR IGNORE INTO state_meta(key,value) VALUES(?,?)',- (RETIRED_PREFIX + sid, '{}'))+ conn.execute('INSERT OR REPLACE INTO state_meta(key,value) VALUES(?,?)',+ (RETIRED_PREFIX + sid, json.dumps({'retired_at': time.time()})))conn.execute('DELETE FROM state_meta WHERE key=?', ('gateway.api.settings.v1.' + sid,))targets = set(session_ids)for row in conn.execute('SELECT scope,session_key,entry_json FROM gateway_routing').fetchall():if entry_session_id(row['entry_json']) in targets:conn.execute('DELETE FROM gateway_routing WHERE scope=? AND session_key=?',(row['scope'], row['session_key']))+++RETRY_HORIZON_S = 7 * 86400 # exact-retry horizon: a retry within it gets the byte-exact settled reply+_EXPIRED = "json_valid(value) AND json_extract(value, '$.retired_at') < ?"+++def prune_retired_tombstones(conn, older_than=RETRY_HORIZON_S):+ """Reclaim deletion tombstones retired more than *older_than* seconds ago: the terminal admission+ with its identity pointer and compacted result, terminal workers and the retired-session marker.+ Tombstones written before ``retired_at`` existed are stamped now and age from this pass."""+ from hermes_state_terminal import ADMISSION_PREFIX, RESULT_PREFIX, WORKER_PREFIX, identity_key+ prefixes = (ADMISSION_PREFIX, WORKER_PREFIX, RETIRED_PREFIX)+ now = time.time()+ for prefix in prefixes:+ conn.execute("UPDATE state_meta SET value=json_set(value, '$.retired_at', ?) WHERE key GLOB ? "+ "AND json_valid(value) AND json_extract(value, '$.retired_at') IS NULL", (now, prefix + '*'))+ cutoff = now - older_than+ for key, raw in conn.execute(f'SELECT key,value FROM state_meta WHERE key GLOB ? AND {_EXPIRED}',+ (ADMISSION_PREFIX + '*', cutoff)).fetchall():+ row = json.loads(raw)+ conn.execute('DELETE FROM state_meta WHERE key IN (?,?,?)', (key, RESULT_PREFIX + row['admission_id'],+ identity_key(row['principal_id'], row['target_session_id'], row['request_id'])))+ for prefix in prefixes[1:]:+ conn.execute(f'DELETE FROM state_meta WHERE key GLOB ? AND {_EXPIRED}', (prefix + '*', cutoff))diff --git a/hermes_state_runtime.py b/hermes_state_runtime.pyindex de82d4fe87b..eb7f2f34613 100644--- a/hermes_state_runtime.py+++ b/hermes_state_runtime.py@@ -80,6 +80,7 @@ def _row(row):result['payload'] = json.loads(result.pop('payload_json'))result.pop('payload_digest')result.pop('lineage_json')+ result.pop('retired_at', None) # tombstone retention stamp, not admission statereturn resultdiff --git a/tests/hermes_state/test_terminal_retirement.py b/tests/hermes_state/test_terminal_retirement.pyindex 2a2874140de..55949a04b6b 100644--- a/tests/hermes_state/test_terminal_retirement.py+++ b/tests/hermes_state/test_terminal_retirement.py@@ -329,3 +329,45 @@ def test_retirement_drops_the_turn_user_row_copy(tmp_path):expected_generation=snap['runtime_generation'])retired = admission_result(db, row['admission_id'])['result']assert retired['final_response'] == 'reply' and '_turn_user_row' not in retired+++def test_tombstones_past_the_retry_horizon_are_reclaimed_by_the_prune_pass(tmp_path, monkeypatch):+ """Deletion tombstones keep byte-exact retry replies for the 7-day horizon, then the maintenance+ prune pass reclaims every row they hold (B2-06)."""+ import time+ import hermes_state_mutation_retirement as retirement+ now = time.time()+ with SessionDB(tmp_path / 'state.db') as db:+ epoch = rt.begin_runtime_epoch(db, instance_id='owner')++ def settle_and_delete(sid, at):+ db.create_session(sid, source='api_server')+ args = dict(principal_id='api', session_id=sid, request_id='r', payload={'text': 'ask ' + sid})+ rt.admit_session_input(db, epoch=epoch, **args)+ row = rt.claim_session_input(db, epoch=epoch, session_id=sid)+ retain_result(db, epoch=epoch, row=row, result={'result': {'final_response': 'reply ' + sid, 'messages': []}})+ snap = db.get_session(sid)+ monkeypatch.setattr(time, 'time', lambda: at) # the delete happened *at*+ rt.mutate_runtime_session(db, epoch=epoch, principal_id='human', session_id=sid, request_id='del',+ operation='delete', payload={}, expected_revision=snap['runtime_revision'],+ expected_generation=snap['runtime_generation'])+ monkeypatch.undo()+ return args, row['admission_id']++ old, old_id = settle_and_delete('old', now - 8 * 86400)+ young, young_id = settle_and_delete('young', now - 6 * 86400)++ def rows_naming(sid, admission_id):+ from hermes_state_terminal import ADMISSION_PREFIX, RESULT_PREFIX, identity_key+ keys = (ADMISSION_PREFIX + admission_id, RESULT_PREFIX + admission_id,+ identity_key('api', sid, 'r'), retirement.RETIRED_PREFIX + sid)+ return [k for k in keys if db.get_meta(k) is not None]+ assert len(rows_naming('old', old_id)) == 4+ db.prune_sessions(older_than_days=90)+ assert len(rows_naming('young', young_id)) == 4+ assert rows_naming('old', old_id) == [], 'tombstones past the horizon were not reclaimed'+ with pytest.raises(rt.RuntimeStoreError, match='not_found'):+ rt.admit_session_input(db, epoch=epoch, **old)+ replay = rt.admit_session_input(db, epoch=epoch, **young)+ assert replay['admission_id'] == young_id and replay['status'] == 'terminal'+ assert admission_result(db, young_id)['result']['final_response'] == 'reply young'