Skip to content

The agent that grows with you

fix(state): a local reset conversation deletes and sweeps only as a whole

Teknium4f64356f5e78
diff --git a/hermes_state_gateway.py b/hermes_state_gateway.py
index b7ac2326cbb..f5411f40132 100644
--- a/hermes_state_gateway.py
+++ b/hermes_state_gateway.py
@@ -419,9 +419,13 @@ class SessionGatewayMixin:
second write after it commits. ``sessions_skipped`` counts only the guarded rows.
``deleted_ids`` (the owning gateway) receives every candidate id that was not kept."""
candidates = self.list_never_active_keyed_sessions(older_than_days=older_than_days)
- if not candidates:
+ # A fresh local reset tip is its conversation's current target, not a never-active chat:
+ # the conversation holds the earlier segments' history and the owner's queued work.
+ from hermes_state_local import owned_lineage_ids
+ with self._read_ctx() as conn:
+ ids = {str(row["id"]) for row in candidates if owned_lineage_ids(conn, str(row["id"])) == [str(row["id"])]}
+ if not ids:
return (0, 0, 0)
- ids = {str(row["id"]) for row in candidates}
skipped: list[str] = []
# ``delete_sessions`` retires the deleted rows' routing entries inside its own transaction
# (``retire_routes``), so count what pointed at the candidates before it commits; the
diff --git a/hermes_state_local.py b/hermes_state_local.py
index 8b52a91cdbb..0505a1cbe2c 100644
--- a/hermes_state_local.py
+++ b/hermes_state_local.py
@@ -104,11 +104,10 @@ def local_lineage_owner(conn, session_id):
def owned_lineage_ids(conn, session_id):
- """[session_id] for any row, or the whole conversation when *session_id* IS a local creation id
- whose receipt has moved its transcript to later segments: deleting the owner retires its policy,
- so its segments must go with it or they are left readable but never continuable."""
- if local_lineage_owner(conn, session_id) != session_id:
- return [session_id]
+ """[session_id] for any row outside a local reset/compression lineage, else the whole
+ conversation (*session_id* first). Any segment deletes as all of it: the owner's policy goes
+ with its current target, and an earlier segment's gap breaks the lineage, so a lone segment
+ delete strands the rest (and the owner's queued work) readable but never continuable."""
return list(dict.fromkeys([session_id, *local_conversation_ids(conn, session_id)]))
diff --git a/hermes_state_mutation_retirement.py b/hermes_state_mutation_retirement.py
index cf0ba72407d..950d00c8ff2 100644
--- a/hermes_state_mutation_retirement.py
+++ b/hermes_state_mutation_retirement.py
@@ -126,37 +126,38 @@ def retire_mutation_receipts(conn, session_ids):
conn.execute('UPDATE state_meta SET value=? WHERE key=?', (_json(receipt), key))
-def _retained_local_owners(conn, swept):
- """Ids a kept local conversation still needs: the creation id (policy, FIFO, generation) and
- every earlier segment of its receipt lineage, while the current physical target survives.
- A reset/compression ends the root and the sweep would age it alone; the retained child would
- then have history but no owner to admit into or restore from. Malformed receipts name nothing."""
+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."""
from hermes_state_local import POLICY_PREFIX
- kept = set()
+ members = {}
for (raw,) in conn.execute('SELECT value FROM state_meta WHERE key GLOB ?', (POLICY_PREFIX + '*',)):
try:
receipt = json.loads(raw)
except (TypeError, ValueError):
continue
- entry = receipt.get('entry') if isinstance(receipt, dict) else None
- target = entry.get('session_id') if isinstance(entry, dict) else None
- if not isinstance(target, str) or target in swept:
+ if not isinstance(receipt, dict):
continue
- lineage = receipt.get('lineage')
- kept.update(x for x in [receipt.get('session_id'), *(lineage if isinstance(lineage, list) else [])]
- if isinstance(x, str))
- return kept
+ entry, lineage = receipt.get('entry'), receipt.get('lineage')
+ 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
def retire_prunable(conn, session_ids):
"""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``). The logical
- owner of a kept local reset/compression target is skipped too (explicit deletes remove the
- whole conversation through :func:`delete_in_transaction`)."""
- owners = _retained_local_owners(conn, set(session_ids))
- quiet = [sid for sid in session_ids if sid not in owners
- and conn.execute(_LIVE_LEDGER_SQL, (sid, sid)).fetchone() is None]
+ prune/empty-session sweep (explicit deletes still refuse with ``session_busy``). A local
+ reset/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)
+
+ 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)
return quiet
diff --git a/hermes_state_sessions.py b/hermes_state_sessions.py
index 47980d5b393..09eec402d0f 100644
--- a/hermes_state_sessions.py
+++ b/hermes_state_sessions.py
@@ -1705,8 +1705,8 @@ class SessionSessionsMixin:
def _do(conn):
if conn.execute("SELECT 1 FROM sessions WHERE id = ? LIMIT 1", (session_id,)).fetchone() is None:
return False
- # Deleting a local creation id takes its reset/compression segments with it (its policy
- # goes); any other row, a single segment included, is just itself.
+ # A local reset/compression conversation deletes whole from any segment: the listed row
+ # is its latest segment, and a lone segment delete strands the owner's policy and FIFO.
from hermes_state_local import owned_lineage_ids
scope = owned_lineage_ids(conn, session_id)
target_ids = (
@@ -1767,8 +1767,9 @@ class SessionSessionsMixin:
row whose first turn is already leased but not yet flushed would be deleted mid-turn
(#123583). A guarded row is simply not deleted (returns ``False``), like any non-empty row."""
def _do(conn):
- if self._guarded_ids(conn, [session_id]):
- return False
+ from hermes_state_local import owned_lineage_ids
+ if self._guarded_ids(conn, [session_id]) or owned_lineage_ids(conn, session_id) != [session_id]:
+ return False # an empty reset tip is still its conversation's current target
eligible = conn.execute(
"""
SELECT 1 FROM sessions
@@ -1826,12 +1827,16 @@ class SessionSessionsMixin:
).fetchall()]
if not existing:
return 0
- if include_compression_chain:
- # Expand BEFORE the guard pass so a guarded chain member (active turn lease /
- # compression lock anywhere in the lineage) keeps its selected root listed too.
- expanded = self._expand_compression_lineage(conn, existing)
- else:
- expanded = existing
+ from hermes_state_local import owned_lineage_ids
+
+ def expand(ids):
+ # A local reset/compression segment deletes as its whole conversation (delete_session).
+ if include_compression_chain:
+ return self._expand_compression_lineage(conn, ids)
+ return list(dict.fromkeys(x for sid in ids for x in owned_lineage_ids(conn, sid)))
+ # Expand BEFORE the guard pass so a guarded lineage member (active turn lease /
+ # compression lock anywhere in it) keeps its selected root listed too.
+ expanded = expand(existing)
guard_pool = [*expanded, *_collect_delegate_child_ids(conn, expanded)]
if exclude_active_write_guards:
# A root is skipped when it or any delegate child it would cascade is guarded, so the
@@ -1851,17 +1856,15 @@ class SessionSessionsMixin:
else:
active_ids = {
sid for sid in existing
- if self._guarded_ids(conn, [sid, *_collect_delegate_child_ids(conn, [sid])])
+ if self._guarded_ids(conn, [*(members := expand([sid])),
+ *_collect_delegate_child_ids(conn, members)])
}
existing = [sid for sid in existing if sid not in active_ids]
if skipped_ids is not None:
skipped_ids.extend(sorted(active_ids))
if not existing:
return 0
- if include_compression_chain:
- expanded = self._expand_compression_lineage(conn, existing)
- else:
- expanded = existing
+ expanded = expand(existing)
from hermes_state_mutation_retirement import retire_sessions
retire_sessions(conn, expanded)
removed_ids.extend(_delete_delegate_children(conn, expanded))
diff --git a/tests/hermes_state/test_reset_lineage_delete_queued_work.py b/tests/hermes_state/test_reset_lineage_delete_queued_work.py
new file mode 100644
index 00000000000..70ba2c43606
--- /dev/null
+++ b/tests/hermes_state/test_reset_lineage_delete_queued_work.py
@@ -0,0 +1,69 @@
+"""A local reset conversation with accepted queued work survives every legacy delete and sweep
+of its current physical segment (JoaoMarcos44 R1, andrexibiza 8, dokterdok corr-reset-delete).
+
+Canonical reset keeps the creation id S0 as the owner (policy, FIFO, generation) and moves the
+transcript to child S1; a follower queued on S0 runs against S1. Deleting or sweeping S1 alone
+used to retire S0's policy and leave the queued admission with nothing to run on."""
+from contextlib import closing
+import time
+
+import pytest
+
+from hermes_state import SessionDB
+import hermes_state_runtime as rt
+from hermes_state_local import POLICY_PREFIX
+from tests.hermes_state.test_target_advance_fence import _local_session, _mutate
+
+OPERATIONS = {
+ 'single': lambda db, s0, s1: db.delete_session(s1, exclude_active_write_guards=True),
+ 'bulk': lambda db, s0, s1: db.delete_sessions([s1], exclude_active_write_guards=True),
+ 'never-active': lambda db, s0, s1: db.prune_never_active_keyed_sessions(older_than_days=30),
+ 'prune-child': lambda db, s0, s1: db.prune_sessions(older_than_days=30, started_before=time.time() - 30 * 86400),
+ 'prune-all': lambda db, s0, s1: db.prune_sessions(older_than_days=None, last_active_before=time.time() + 60),
+}
+
+
+def _conversation(tmp_path, operation, queued):
+ db = SessionDB(tmp_path / 'state.db')
+ epoch = rt.begin_runtime_epoch(db, instance_id='owner')
+ s0 = _local_session(db, epoch, tmp_path)
+ db.append_message(s0, 'user', 'root history')
+ s1 = _mutate(db, epoch, s0, 'reset')['target_session_id']
+ old = time.time() - 200 * 86400
+ # Aged past every cutoff; the current segment ended for the ended-only prune, open for never-active.
+ db._execute_write(lambda c: c.execute('UPDATE sessions SET started_at=? WHERE id IN (?,?)', (old, s0, s1)))
+ if operation.startswith('prune'):
+ db._execute_write(lambda c: c.execute('UPDATE sessions SET ended_at=? WHERE id=?', (old, s1)))
+ admission = queued and rt.admit_session_input(db, epoch=epoch, principal_id='human', session_id=s0,
+ request_id='queued', payload={'text': 'continue'})
+ return db, s0, s1, admission
+
+
+def _state(db, s0, s1):
+ with db._read_ctx() as conn:
+ policy = conn.execute('SELECT 1 FROM state_meta WHERE key=?', (POLICY_PREFIX + s0,)).fetchone() is not None
+ return {'s0': db.get_session(s0) is not None, 's1': db.get_session(s1) is not None, 'policy': policy}
+
+
[email protected]('operation', sorted(OPERATIONS))
+def test_segment_delete_or_sweep_keeps_a_conversation_with_queued_work(tmp_path, operation):
+ db, s0, s1, admission = _conversation(tmp_path, operation, queued=True)
+ with closing(db):
+ if operation == 'never-active':
+ assert s1 in [r['id'] for r in db.list_never_active_keyed_sessions(older_than_days=30)]
+ try:
+ OPERATIONS[operation](db, s0, s1)
+ except rt.RuntimeStoreError as exc:
+ assert operation in {'single', 'bulk'} and exc.reason == 'session_busy', (operation, exc.reason)
+ assert _state(db, s0, s1) == {'s0': True, 's1': True, 'policy': True}, operation
+ assert rt.get_session_admission(db, admission_id=admission['admission_id'])['status'] == 'queued'
+
+
[email protected]('operation', ['single', 'bulk', 'prune-all'])
+def test_idle_conversation_deletes_whole_from_its_current_segment(tmp_path, operation):
+ db, s0, s1, _ = _conversation(tmp_path, operation, queued=False)
+ with closing(db):
+ if operation == 'never-active':
+ assert s1 in [r['id'] for r in db.list_never_active_keyed_sessions(older_than_days=30)]
+ OPERATIONS[operation](db, s0, s1)
+ assert _state(db, s0, s1) == {'s0': False, 's1': False, 'policy': False}, operation
diff --git a/tests/hermes_state/test_terminal_retirement.py b/tests/hermes_state/test_terminal_retirement.py
index c04fbde182a..cd6bbbee79d 100644
--- a/tests/hermes_state/test_terminal_retirement.py
+++ b/tests/hermes_state/test_terminal_retirement.py
@@ -275,8 +275,8 @@ def test_deleted_history_is_not_recoverable_from_worker_or_mutation_receipts(tmp
def test_mutation_receipts_naming_a_deleted_physical_target_drop_its_text(tmp_path):
"""D7 / pastels M07: a local owner's rewind receipt is keyed by the logical id but copies the
- rewound turn from the physical reset child. Deleting only that child (``hermes sessions delete``
- on the dashboard row) must still strip it, and a full delete also drops the user-set title."""
+ rewound turn from the physical reset child. Deleting that child (``hermes sessions delete`` on
+ the dashboard row, which removes the whole conversation) strips it and the user-set title."""
import json
from tests.hermes_state.test_target_advance_fence import _local_session
@@ -298,14 +298,13 @@ def test_mutation_receipts_naming_a_deleted_physical_target_drop_its_text(tmp_pa
assert 'SECRET_CHILD_TURN' in json.dumps(rt.mutate_runtime_session(db, epoch=epoch, **rewind))
rename = args(db, sid, 'rename', 'rn', {'title': 'SECRET_TITLE'})
rt.mutate_runtime_session(db, epoch=epoch, **rename)
- assert db.delete_session(child) and db.get_session(sid) is not None
+ # The listed row is the reset child; deleting it deletes the whole conversation.
+ assert db.delete_session(child) and db.get_session(sid) is None
def blobs():
with db._read_ctx() as c:
return ''.join(v for (v,) in c.execute('SELECT value FROM state_meta'))
- assert 'SECRET_CHILD_TURN' not in blobs()
+ assert 'SECRET_CHILD_TURN' not in blobs() and 'SECRET_TITLE' not in blobs()
replay = rt.mutate_runtime_session(db, epoch=epoch, **rewind)
assert replay['target_message'] is None and replay['rewound_count'] == 2
- rt.mutate_runtime_session(db, epoch=epoch, **args(db, sid, 'delete', 'del', {}))
- assert 'SECRET_TITLE' not in blobs()
assert rt.mutate_runtime_session(db, epoch=epoch, **rename)['title'] is None