The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): let a sweep's retired marker age out; user deletes stay fenced
unsupportedpastelsf7301c74ccc1
diff --git a/hermes_state_mutation_retirement.py b/hermes_state_mutation_retirement.pyindex cc0e08d117f..31cbc09a275 100644--- a/hermes_state_mutation_retirement.py+++ b/hermes_state_mutation_retirement.py@@ -89,19 +89,20 @@ _LIVE_LEDGER_SQL = """SELECT 1 FROM session_admissions WHERE target_session_id=?UNION ALL SELECT 1 FROM worker_executions WHERE session_id=? AND status IN ('registered','running','unknown') LIMIT 1"""-def retire_sessions(conn, session_ids):+def retire_sessions(conn, session_ids, *, expiring=()):"""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 exactretry of a settled request reports ``not_found`` instead of its terminal receipt, a lateaccounting/constructor backfill recreates the deleted row, and the same request is thenadmitted 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."""+ ``delete_session*``, prunes and sweeps) must publish the whole fence, so it lives here once.+ The marker of an id in *expiring* (a housekeeping sweep's) ages out at the retry horizon."""from hermes_state_media import retire_spilloverretire_spillover(conn, session_ids) # before the caller's DELETEs take the pointers awayretire_terminal_receipts(conn, session_ids)retire_mutation_receipts(conn, session_ids)- retire_routes(conn, session_ids)+ retire_routes(conn, session_ids, expiring=expiring)from hermes_state_local import retire_local_receiptsretire_local_receipts(conn, session_ids)@@ -135,11 +136,12 @@ def retire_mutation_receipts(conn, session_ids):def _local_conversations(conn):- """Member id -> every id of its local conversation: the creation id (policy, FIFO, generation),- each receipt lineage segment and the current target. One prefix scan, not a lookup per swept- id. Malformed receipts name nothing."""+ """``(members, bot_chats)``: member id -> every id of its local conversation (the creation id+ (policy, FIFO, generation), each receipt lineage segment and the current target), and the ids+ of every Bot Chat conversation. One prefix scan, not a lookup per swept id. Malformed receipts+ name nothing."""from hermes_state_local import POLICY_PREFIX- members = {}+ members, bot_chats = {}, set()for (raw,) in conn.execute('SELECT value FROM state_meta WHERE key GLOB ?', (POLICY_PREFIX + '*',)):try:receipt = json.loads(raw)@@ -151,7 +153,9 @@ def _local_conversations(conn):ids = tuple(x for x in [receipt.get('session_id'), *(lineage if isinstance(lineage, list) else []),entry.get('session_id') if isinstance(entry, dict) else None] if isinstance(x, str))members.update(dict.fromkeys(ids, ids))- return members+ if str(receipt.get('request_id') or '').startswith('bot-chat:'):+ bot_chats.update(ids)+ return members, bot_chatsdef retire_prunable(conn, session_ids):@@ -159,14 +163,18 @@ def retire_prunable(conn, session_ids):A session with live or unknown work is skipped, so one busy row cannot abort a wholeprune/empty-session sweep (explicit deletes still refuse with ``session_busy``). A localreset/compression conversation is swept only whole: while any of its ids is kept or has live- work (the owner's queued admission continues on the current segment), every one is skipped."""- swept, conversations = set(session_ids), _local_conversations(conn)+ work (the owner's queued admission continues on the current segment), every one is skipped.++ A sweep's markers age out at the retry horizon: housekeeping retires thousands of ids a pass+ (cron), and a permanent marker each would grow ``state_meta`` without bound. A Bot Chat's stays:+ its mailbox receipts outlive the horizon and its generation walk would reissue the id."""+ swept, (conversations, bot_chats) = set(session_ids), _local_conversations(conn)def removable(sid):whole = conversations.get(sid, (sid,))return swept.issuperset(whole) and not any(conn.execute(_LIVE_LEDGER_SQL, (x, x)).fetchone() for x in whole)quiet = [sid for sid in session_ids if removable(sid)]- retire_sessions(conn, quiet)+ retire_sessions(conn, quiet, expiring=[sid for sid in quiet if sid not in bot_chats])return quiet@@ -195,12 +203,20 @@ def entry_session_id(raw):return value.get('session_id') if isinstance(value, dict) else None-def retire_routes(conn, session_ids):+def retire_routes(conn, session_ids, *, expiring=()):# 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).+ # An ``expiring`` (sweep) marker ages out at the horizon and never shortens a permanent one.+ expiring = set(expiring)for sid in session_ids:- conn.execute('INSERT OR REPLACE INTO state_meta(key,value) VALUES(?,?)',- (RETIRED_PREFIX + sid, json.dumps({'retired_at': time.time()})))+ if sid in expiring:+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE '+ "SET value=excluded.value WHERE json_valid(state_meta.value) "+ "AND json_extract(state_meta.value, '$.expires')",+ (RETIRED_PREFIX + sid, json.dumps({'retired_at': time.time(), 'expires': True})))+ else:+ 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,))conn.execute('DELETE FROM state_meta WHERE key=?', (VIEWER_CLOSE_PREFIX + sid,))targets = set(session_ids)@@ -216,9 +232,10 @@ _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, and terminal workers. The retired-session marker- is the deletion fence itself and is never reclaimed: it holds only ``retired_at``, and without it- a deleted id could be recreated, re-admitted or reissued as a Bot Chat generation.+ with its identity pointer and compacted result, terminal workers and a sweep's (``expires``)+ retired-session marker. A user delete's marker is the deletion fence itself and is never+ reclaimed: it holds only ``retired_at``, and without it a deleted id could be recreated,+ re-admitted or reissued as a Bot Chat generation.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_keyprefixes = (ADMISSION_PREFIX, WORKER_PREFIX)@@ -233,3 +250,5 @@ def prune_retired_tombstones(conn, older_than=RETRY_HORIZON_S):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'])))conn.execute(f'DELETE FROM state_meta WHERE key GLOB ? AND {_EXPIRED}', (WORKER_PREFIX + '*', cutoff))+ conn.execute(f"DELETE FROM state_meta WHERE key GLOB ? AND {_EXPIRED} AND json_extract(value, '$.expires')",+ (RETIRED_PREFIX + '*', cutoff))diff --git a/hermes_state_sessions.py b/hermes_state_sessions.pyindex 5fc8f6b1497..28b7cf60121 100644--- a/hermes_state_sessions.py+++ b/hermes_state_sessions.py@@ -1805,9 +1805,10 @@ class SessionSessionsMixin:if eligible is None:return False# Same BEGIN IMMEDIATE transaction as the check above: retire the ledger rows- # (ON DELETE RESTRICT) and delete without re-evaluating eligibility.+ # (ON DELETE RESTRICT) and delete without re-evaluating eligibility. Housekeeping, not+ # a user delete: its fence ages out at the horizon (an untitled row is never a Bot Chat).from hermes_state_mutation_retirement import retire_sessions- retire_sessions(conn, [session_id])+ retire_sessions(conn, [session_id], expiring=[session_id])conn.execute("DELETE FROM sessions WHERE id = ?", (session_id,))self._delete_unreferenced_system_prompts(conn)return Truediff --git a/tests/gateway/test_swept_bot_chat_fence.py b/tests/gateway/test_swept_bot_chat_fence.pynew file mode 100644index 00000000000..f978927c181--- /dev/null+++ b/tests/gateway/test_swept_bot_chat_fence.py@@ -0,0 +1,22 @@+"""A Bot Chat retired by a housekeeping sweep keeps its deletion fence past the retry horizon.++Sweep markers age out at the horizon, but a Bot Chat's must not: its mailbox receipts outlive the+horizon, and the generation walk would otherwise reissue the swept id to a new Bot Chat.+"""+++def test_a_swept_bot_chat_generation_is_never_reissued(owner, tmp_path):+ from gateway.session_bot import _bot_chat_creation_id+ from gateway.session_controls import AuthorityConnection+ from gateway.session_local import create_local_session+ from hermes_state_mutation_retirement import RETIRED_PREFIX, prune_retired_tombstones+ owner.runner.adapters = {}+ actor = AuthorityConnection(owner, object(), {'user_id': 'human'}).actor+ request_id = _bot_chat_creation_id(owner, actor)+ ref = create_local_session(owner, actor, dict(source='cli', cwd=str(tmp_path), model='m', toolsets=[],+ request_id=request_id))+ owner.db.end_session(ref.session_id, 'test')+ assert owner.db.prune_sessions(older_than_days=None) == 1+ owner.db._execute_write(lambda conn: prune_retired_tombstones(conn, older_than=0))+ assert owner.db.get_meta(RETIRED_PREFIX + ref.session_id) is not None+ assert _bot_chat_creation_id(owner, actor) != request_iddiff --git a/tests/hermes_state/test_retired_fence_outlives_horizon.py b/tests/hermes_state/test_retired_fence_outlives_horizon.pyindex e8c3d9923fc..c0a9c2a3158 100644--- a/tests/hermes_state/test_retired_fence_outlives_horizon.py+++ b/tests/hermes_state/test_retired_fence_outlives_horizon.py@@ -1,5 +1,6 @@"""The retired-session marker is the deletion fence: the prune pass reclaims a deleted session's-tombstones after the retry horizon, but never the marker, so the id stays deleted."""+tombstones after the retry horizon, but never a user delete's marker, so the id stays deleted.+A housekeeping sweep's marker ages out at the horizon (it retires thousands of ids a pass)."""import timefrom types import SimpleNamespace@@ -50,3 +51,22 @@ def test_a_deleted_bot_chat_generation_is_never_reissued(tmp_path):_delete_8_days_ago(db, epoch, sid)db.prune_sessions(older_than_days=90)assert _bot_chat_creation_id(authority, actor) == "bot-chat:owned:1"+++def test_a_swept_session_fence_ages_out_at_the_horizon(tmp_path):+ from hermes_state_mutation_retirement import RETIRED_PREFIX, prune_retired_tombstones+ with SessionDB(tmp_path / "state.db") as db:+ epoch = rt.begin_runtime_epoch(db, instance_id="owner")+ db.create_session("swept", source="cron")+ db.end_session("swept", "test")+ db.create_session("empty", source="cli")+ db.create_session("deleted", source="cli")+ _delete_8_days_ago(db, epoch, "deleted")+ assert db.prune_sessions(older_than_days=None) == 1+ assert db.delete_session_if_empty("empty") # the /clear and exit cleanup of an unused session+ for sid in ("swept", "empty"):+ assert db.get_meta(RETIRED_PREFIX + sid) is not None # fenced within the horizon+ db._execute_write(lambda conn: prune_retired_tombstones(conn, older_than=0))+ for sid in ("swept", "empty"):+ assert db.get_meta(RETIRED_PREFIX + sid) is None, f"{sid}: a sweep's marker never ages out"+ assert db.get_meta(RETIRED_PREFIX + "deleted") is not None