fix(state): deleted history is not replayable from worker or mutation receipts

Two retained receipts still handed deleted transcript content back to an authenticated exact
retry after the session was deleted:

- Worker tombstones kept the LAST receipt's result by position, assuming it was the closing
  `execution.finish`. Settlement terminalizes a failed/interrupted worker without one
  (_retire_admission_workers), so the last receipt can be a `compression.history` read (the
  whole transcript) or a `transcript.append` result. Now only an explicit execution.finish
  receipt keeps its result; every other result is nulled, digests stay for conflict detection.
- `gateway.mutation.v1.*` receipts of a rewind carry `target_message` (the rewound user turn)
  and a compress receipt carries `summary`. Retirement now drops those two fields from the
  deleted session's mutation receipts; the receipt (digest, ids, revision) stays, so an exact
  retry still returns its outcome, with `target_message: null`.

test_used_history_retirement_is_atomic_and_exact asserted that a settlement-terminalized
worker's transcript.append result replays after delete: that is exactly the W5 retention, so
the assertion now pins the refusal (stale_generation, same as every redacted receipt).
terminal_worker_receipt has no production caller that depends on replaying it.
New regression fails on r6-base (secrets in state_meta after delete) and passes here.

Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5460639040 (W5)
Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5462648005 (2.3: rewind / compression.history receipts)
This commit is contained in:
Teknium
2026-10-08 16:21:14 -07:00
parent 4b93b9e84a
commit f7dd0aedab
2 changed files with 82 additions and 6 deletions

View File

@@ -62,11 +62,15 @@ def retire_terminal_receipts(conn, session_ids):
receipts = [dict(r) for r in conn.execute(
'SELECT sequence,payload_digest,result_json FROM worker_receipts WHERE execution_id=? ORDER BY sequence',
(row['execution_id'],))]
# A terminal worker can only replay its closing receipt. Earlier results
# (history/context reads) are user data that must not outlive the delete;
# their digests stay so a late duplicate is still recognised as a conflict.
for receipt in receipts[:-1]:
receipt['result_json'] = None
# A terminal worker can only replay an explicit ``execution.finish`` receipt. Every
# other result (history/context reads) is user data that must not outlive the delete,
# even when it is the last one: settlement terminalizes a failed worker without a
# finish receipt. Digests stay so a late duplicate is still recognised as a conflict.
closing = admission_fingerprint(canonical_target=sid,
payload={'operation': 'execution.finish', 'payload': {}})
for receipt in receipts:
if receipt['payload_digest'] != closing:
receipt['result_json'] = None
row['receipts'] = receipts
conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)',
(WORKER_PREFIX + row['execution_id'], _json(row)))
@@ -88,11 +92,33 @@ def retire_sessions(conn, session_ids):
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_mutation_receipts(conn, session_ids)
retire_routes(conn, session_ids)
from hermes_state_local import retire_local_receipts
retire_local_receipts(conn, session_ids)
# Mutation-receipt fields that copy transcript content: the rewound message and a compaction summary.
_MUTATION_TRANSCRIPT_FIELDS = ('target_message', 'summary')
def retire_mutation_receipts(conn, session_ids):
"""Keep each exact-retry mutation receipt (digest, ids, revision) but drop the transcript
copies a rewind/compress result carries, so a retry after the delete cannot read them back."""
if not session_ids:
return
rows = conn.execute(
"SELECT key,value FROM state_meta WHERE key GLOB 'gateway.mutation.v1.*' AND "
"CASE WHEN json_valid(value) THEN json_extract(value,'$.result.session_id') END "
"IN (SELECT value FROM json_each(?))", (json.dumps(list(session_ids)),)).fetchall()
for key, raw in rows:
receipt = json.loads(raw)
result = receipt.get('result')
if isinstance(result, dict) and any(f in result for f in _MUTATION_TRANSCRIPT_FIELDS):
receipt['result'] = {k: (None if k in _MUTATION_TRANSCRIPT_FIELDS else v) for k, v in result.items()}
conn.execute('UPDATE state_meta SET value=? WHERE key=?', (_json(receipt), key))
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

View File

@@ -57,7 +57,11 @@ def test_used_history_retirement_is_atomic_and_exact(tmp_path, monkeypatch):
worker_args = dict(execution_id='worker', session_id='used', generation=row['generation'], sequence=1,
adoption_secret='owned-proof', payload_digest=rt.admission_fingerprint(canonical_target='used',
payload={'operation': 'transcript.append', 'payload': worker_append}))
assert terminal_worker_receipt(db, **worker_args) == worker_result
# The worker was terminalized by settlement, never by an execution.finish receipt: its
# last result is not a closing receipt, so it is redacted like every earlier one (W5).
assert worker_result['count'] == 1
with pytest.raises(rt.RuntimeStoreError, match='stale_generation'):
terminal_worker_receipt(db, **worker_args)
with pytest.raises(rt.RuntimeStoreError, match='permission_denied'):
terminal_worker_receipt(db, **(worker_args | {'adoption_secret': 'foreign'}))
for change in ({'payload': {'text': 'changed'}}, {'principal_id': 'foreign'}, {'request_id': 'fresh'}):
@@ -221,3 +225,49 @@ def test_a_malformed_unrelated_route_or_policy_row_cannot_abort_a_delete(tmp_pat
with db._read_ctx() as c: # the unrelated row is left exactly as it was
assert c.execute("SELECT (SELECT COUNT(*) FROM gateway_routing) + (SELECT COUNT(*) FROM state_meta "
"WHERE key GLOB 'gateway.local_policy.v1:*')").fetchone()[0] == 1
def test_deleted_history_is_not_recoverable_from_worker_or_mutation_receipts(tmp_path):
"""W5 / pastels 2.3: a failed worker is terminalized by settlement without an execution.finish
receipt, so its last receipt may be a history read; a rewind/compress receipt copies the
rewound message / summary. Neither may replay the deleted transcript after the delete."""
import json
from hermes_state_terminal import terminal_worker_receipt
with SessionDB(tmp_path / 'state.db') as db:
db.create_session('gone', source='cli')
epoch = rt.begin_runtime_epoch(db, instance_id='owner')
db.append_message('gone', 'user', 'first')
db.append_message('gone', 'assistant', 'a1')
rewound = db.append_message('gone', 'user', 'SECRET_REWOUND')
db.append_message('gone', 'assistant', 'a2')
snap = db.get_session('gone')
rewind = dict(principal_id='human', session_id='gone', request_id='rw', operation='rewind',
payload={'target_message_id': rewound}, expected_revision=snap['runtime_revision'],
expected_generation=snap['runtime_generation'])
receipt = rt.mutate_runtime_session(db, epoch=epoch, **rewind)
assert 'SECRET_REWOUND' in json.dumps(receipt)
db.append_message('gone', 'user', 'SECRET_HISTORY_LINE')
rt.admit_session_input(db, epoch=epoch, principal_id='api', session_id='gone', request_id='r',
payload={'text': 'x'})
row = rt.claim_session_input(db, epoch=epoch, session_id='gone')
rt.register_worker_execution(db, epoch=epoch, execution_id='worker', session_id='gone',
generation=row['generation'], kind='compute', adoption_secret='proof')
history = {'target': 'gone', 'include_ancestors': False, 'include_inactive': False,
'repair_alternation': False, 'include_row_ids': False, 'include_compacted': False}
rt.mutate_worker_execution(db, epoch=epoch, execution_id='worker', session_id='gone',
generation=row['generation'], sequence=1, operation='compression.history', payload=history)
rt.settle_session_input(db, epoch=epoch, admission_id=row['admission_id'],
generation=row['generation'], outcome='failed')
snap = db.get_session('gone')
rt.mutate_runtime_session(db, epoch=epoch, principal_id='human', session_id='gone', request_id='d',
operation='delete', payload={}, expected_revision=snap['runtime_revision'],
expected_generation=snap['runtime_generation'])
with db._read_ctx() as c:
blobs = ''.join(v for (v,) in c.execute('SELECT value FROM state_meta'))
assert 'SECRET_REWOUND' not in blobs and 'SECRET_HISTORY_LINE' not in blobs
replay = rt.mutate_runtime_session(db, epoch=epoch, **rewind)
assert replay == {**receipt, 'target_message': None}
with pytest.raises(rt.RuntimeStoreError, match='stale_generation'):
terminal_worker_receipt(db, execution_id='worker', session_id='gone', generation=row['generation'],
sequence=1, adoption_secret='proof', payload_digest=rt.admission_fingerprint(
canonical_target='gone', payload={'operation': 'compression.history', 'payload': history}))