The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): drop a terminal managed worker's full-history read receipts
Teknium1b9362e0425c
diff --git a/hermes_state_runtime.py b/hermes_state_runtime.pyindex cdf86dd143b..c47f8849004 100644--- a/hermes_state_runtime.py+++ b/hermes_state_runtime.py@@ -63,8 +63,14 @@ def _retire_admission_workers(conn, row, owner_epoch):worker assignment to the child while target_session_id stays the logical ID)."""lineage = json.loads(row['lineage_json'])targets = list({row['target_session_id'], lineage[-1] if lineage else row['target_session_id']})- conn.execute(f"UPDATE worker_executions SET status='terminal' WHERE session_id IN ({','.join('?' * len(targets))}) "- "AND generation=? AND owner_epoch=?", (*targets, row['generation'], owner_epoch))+ scope = f"session_id IN ({','.join('?' * len(targets))}) AND generation=? AND owner_epoch=?"+ # Settlement closes an execution that never wrote execution.finish: its read copies go too.+ from hermes_state_runtime_workers import compact_terminal_receipts+ for (execution_id,) in conn.execute(f"SELECT execution_id FROM worker_executions WHERE {scope} "+ "AND status!='terminal'", (*targets, row['generation'], owner_epoch)).fetchall():+ compact_terminal_receipts(conn, execution_id)+ conn.execute(f"UPDATE worker_executions SET status='terminal' WHERE {scope}",+ (*targets, row['generation'], owner_epoch))def _row(row):@@ -680,6 +686,9 @@ def apply_worker_receipt(db, *, epoch, execution_id, session_id, generation, seqif old is not None:if old['payload_digest'] != digest:raise RuntimeStoreError('admission_conflict')+ from hermes_state_runtime_workers import retired_receipt+ if retired_receipt(old['result_json']):+ raise RuntimeStoreError('stale_generation') # a terminal execution's read copyreturn json.loads(old['result_json'])if row['status'] not in ('registered', 'running'):raise RuntimeStoreError('stale_generation')@@ -698,5 +707,8 @@ def apply_worker_receipt(db, *, epoch, execution_id, session_id, generation, seq(sequence, 'terminal' if operation == 'execution.finish' else 'running', execution_id))if changed:conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?', (session_id,))+ if operation == 'execution.finish':+ from hermes_state_runtime_workers import compact_terminal_receipts+ compact_terminal_receipts(conn, execution_id)return resultreturn db._execute_write(write, patience_s=db._TRANSCRIPT_WRITE_PATIENCE_S)diff --git a/hermes_state_runtime_workers.py b/hermes_state_runtime_workers.pyindex 1d76f574a00..1f50e7a6d07 100644--- a/hermes_state_runtime_workers.py+++ b/hermes_state_runtime_workers.py@@ -39,3 +39,23 @@ def discard_orphan_workers_on_reset(conn, session_ids):for sid in session_ids:conn.execute("UPDATE worker_executions SET status='terminal' WHERE session_id=? AND status='unknown' ""AND execution_id NOT LIKE 'admission-worker:%'", (sid,))+++RETIRED_RECEIPT = {'retired': True}+++def compact_terminal_receipts(conn, execution_id):+ """Once an execution is terminal its read receipts are dead weight: a ``compression.history``+ read stores the whole transcript and a context read a full session row, so keeping them leaves+ one full-history copy per managed turn and ``state.db`` grows quadratically. They shrink to a+ marker in the closing transaction (an exact late replay is refused ``stale_generation``, as+ after retirement); ``payload_digest`` stays, so a late duplicate with other content still+ conflicts. Mutation acknowledgements (counts, row annotations, assignments) stay replayable."""+ conn.execute("UPDATE worker_receipts SET result_json=? WHERE execution_id=? AND json_valid(result_json) "+ "AND (json_type(result_json, '$.messages') IS NOT NULL "+ "OR json_type(result_json, '$.session') IS NOT NULL)",+ (json.dumps(RETIRED_RECEIPT), execution_id))+++def retired_receipt(result_json):+ return json.loads(result_json) == RETIRED_RECEIPTdiff --git a/tests/hermes_state/test_runtime_worker_history.py b/tests/hermes_state/test_runtime_worker_history.pyindex 0bae5208191..7112a855195 100644--- a/tests/hermes_state/test_runtime_worker_history.py+++ b/tests/hermes_state/test_runtime_worker_history.py@@ -68,3 +68,33 @@ def test_declared_cache_boundary_matches_local_database(tmp_path):store.close()finally:db.close()+++def test_terminal_worker_keeps_no_full_history_receipt(tmp_path):+ """N19: every managed turn reads compression.history; once execution.finish (or settlement)+ makes the execution terminal, that full-transcript copy must not stay in worker_receipts,+ while its digest still makes a late duplicate with other content conflict."""+ from hermes_state_runtime import RuntimeStoreError+ db = SessionDB(tmp_path / 'state.db')+ try:+ db.create_session('s', 'cli')+ db.append_messages_batch('s', [{'role': 'user', 'content': 'x' * 2000}])+ epoch = begin_runtime_epoch(db, instance_id='fixture')+ scope = dict(epoch=epoch, execution_id='worker', session_id='s', generation=0)+ register_worker_execution(db, **scope, kind='compute', adoption_secret='secret')+ read = dict(target='s', include_ancestors=False, include_inactive=False, repair_alternation=False,+ include_row_ids=False, include_compacted=False)+ history = mutate_worker_execution(db, **scope, sequence=1, operation='compression.history', payload=read)+ assert history['messages'][0]['content'] == 'x' * 2000+ mutate_worker_execution(db, **scope, sequence=2, operation='execution.finish', payload={})+ stored = db._read_all('SELECT sequence, LENGTH(result_json) FROM worker_receipts ORDER BY sequence')+ assert stored[0][1] < 200, 'a terminal execution kept a full-history receipt'+ with pytest.raises(RuntimeStoreError, match='admission_conflict'):+ mutate_worker_execution(db, **scope, sequence=1, operation='compression.history',+ payload=dict(read, include_row_ids=True))+ with pytest.raises(RuntimeStoreError, match='stale_generation'):+ mutate_worker_execution(db, **scope, sequence=1, operation='compression.history', payload=read)+ assert mutate_worker_execution(db, **scope, sequence=2, operation='execution.finish',+ payload={}) == {'status': 'terminal'}+ finally:+ db.close()