The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): keep a failed Bot receipt's answer; leave the fence horizon
David Dudok de Wit966af60d748b
diff --git a/gateway/session_bot.py b/gateway/session_bot.pyindex 621c4384b59..7e59f21682d 100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@ -315,7 +315,14 @@ def _result(authority, record):status, reply = _admission_outcome(authority, record['admission_id'], record)error = reason = Noneif status == 'failed':- error, reason = _failure(authority, current)+ try:+ error, reason = _failure(authority, current)+ except RuntimeStoreError as exc:+ if exc.reason != 'not_found':+ raise+ # Its admission aged out after the chat was deleted: the receipt's own answer stands.+ from tools.bot_failure_reasons import UNKNOWN+ error, reason = record.get('error') or 'Bot Chat delivery failed', record.get('reason') or UNKNOWNreturn {k: v for k, v in dict(status=status, delivery_id=record['delivery_id'],profile_home=record['profile_home'], session_id=record['session_id'],admission_id=record['admission_id'], message=record['message'], reply=reply,diff --git a/hermes_state_mutation_retirement.py b/hermes_state_mutation_retirement.pyindex cc0e08d117f..e3eb636909b 100644--- a/hermes_state_mutation_retirement.py+++ b/hermes_state_mutation_retirement.py@@ -216,12 +216,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 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)+ 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 ? "@@ -232,4 +230,5 @@ def prune_retired_tombstones(conn, older_than=RETRY_HORIZON_S):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'])))- conn.execute(f'DELETE FROM state_meta WHERE key GLOB ? AND {_EXPIRED}', (WORKER_PREFIX + '*', cutoff))+ for prefix in prefixes[1:]:+ conn.execute(f'DELETE FROM state_meta WHERE key GLOB ? AND {_EXPIRED}', (prefix + '*', cutoff))diff --git a/tests/gateway/test_bot_receipt_tombstone_expiry.py b/tests/gateway/test_bot_receipt_tombstone_expiry.pyindex fcf9d0cb15e..e98437cee1a 100644--- a/tests/gateway/test_bot_receipt_tombstone_expiry.py+++ b/tests/gateway/test_bot_receipt_tombstone_expiry.py@@ -28,7 +28,7 @@ def _delete(db, epoch, session_id, *, days_ago):expected_generation=snap["runtime_generation"])-def _receipt_then_deleted(tmp_path, *, status, days_ago, drop_marker=False):+def _receipt_then_deleted(tmp_path, *, status, days_ago, **fields):db = SessionDB(tmp_path / "state.db")epoch = rt.begin_runtime_epoch(db, instance_id="owner")db.create_session("botchat", source="cli")@@ -40,13 +40,11 @@ def _receipt_then_deleted(tmp_path, *, status, days_ago, drop_marker=False):admission_id=admission["admission_id"], principal_id="owner", message="ping")if status == "settled":record["reply"] = "pong"+ record.update(fields)with _locked(tmp_path) as root:_write(root / f"{KEY}.json", record)_delete(db, epoch, "botchat", days_ago=days_ago)db.prune_sessions(older_than_days=90)- if drop_marker: # a store whose marker an earlier release's prune already reclaimed- db._execute_write(lambda conn: conn.execute(- "DELETE FROM state_meta WHERE key GLOB 'gateway.retired_session.v1.*'"))return db@@ -67,11 +65,22 @@ def test_a_settled_receipt_keeps_its_answer_after_its_chat_is_deleted(tmp_path,db.close()+def test_a_failed_receipt_keeps_its_error_after_its_chat_expired(tmp_path):+ from gateway.session_bot import recover_bot_deliveries+ db = _receipt_then_deleted(tmp_path, status="failed", days_ago=8,+ error="HTTP 401 invalid api key", reason="auth")+ try:+ asyncio.run(recover_bot_deliveries(SimpleNamespace(db=db, waiters={})))+ record = _receipt(tmp_path)+ assert (record["status"], record["error"], record["reason"]) == ("failed", "HTTP 401 invalid api key", "auth")+ finally:+ db.close()++@pytest.mark.parametrize("status", ["queued", "claimed", "canonical"])[email protected]("drop_marker", [False, True])-def test_a_pending_receipt_behind_an_expired_deleted_chat_becomes_ambiguous(tmp_path, status, drop_marker):+def test_a_pending_receipt_behind_an_expired_deleted_chat_becomes_ambiguous(tmp_path, status):from gateway.session_bot import recover_bot_deliveries- db = _receipt_then_deleted(tmp_path, status=status, days_ago=8, drop_marker=drop_marker)+ db = _receipt_then_deleted(tmp_path, status=status, days_ago=8)try:asyncio.run(recover_bot_deliveries(SimpleNamespace(db=db, waiters={})))assert _receipt(tmp_path)["status"] == "ambiguous"@@ -82,7 +91,7 @@ def test_a_pending_receipt_behind_an_expired_deleted_chat_becomes_ambiguous(tmp_def test_the_runtime_api_starts_after_a_deleted_bot_chat_expired(tmp_path, monkeypatch):import gateway.run_apifrom gateway.run_runtime import start_gateway_runtime_api- db = _receipt_then_deleted(tmp_path, status="settled", days_ago=8)+ db = _receipt_then_deleted(tmp_path, status="queued", days_ago=8)try:async def fake_api(runner):return SimpleNamespace(api_origin="http://127.0.0.1:1")@@ -91,14 +100,15 @@ def test_the_runtime_api_starts_after_a_deleted_bot_chat_expired(tmp_path, monkerunner = SimpleNamespace(session_authority=authority, session_runtime_descriptor={})asyncio.run(start_gateway_runtime_api(runner))assert runner.session_runtime_descriptor["api_origin"] == "http://127.0.0.1:1"+ assert _receipt(tmp_path)["status"] == "ambiguous" # recovery ran and answered itfinally:db.close()[email protected]("days_ago, expected", [(6, 200), (8, 409)])[email protected]("days_ago, expected, text", [(6, 200, "answer"), (8, 409, "admission_conflict")])@pytest.mark.asyncioasync def test_a_responses_key_of_a_deleted_session_never_reruns_and_never_503s(- api, owner, days_ago, expected):+ api, owner, days_ago, expected, text):calls = []async def handle(event):@@ -124,5 +134,5 @@ async def test_a_responses_key_of_a_deleted_session_never_reruns_and_never_503s(assert owner.db.delete_session(sid)owner.db.prune_sessions(older_than_days=90)retry = await client.post("/v1/responses", json=body, headers=headers)- assert retry.status == expected, await retry.text()+ assert retry.status == expected and text in await retry.text(), await retry.text()assert calls == ["once-only"]diff --git a/tests/hermes_state/test_retired_fence_outlives_horizon.py b/tests/hermes_state/test_retired_fence_outlives_horizon.pydeleted file mode 100644index e8c3d9923fc..00000000000--- a/tests/hermes_state/test_retired_fence_outlives_horizon.py+++ /dev/null@@ -1,52 +0,0 @@-"""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."""-import time-from types import SimpleNamespace--import pytest--import hermes_state_runtime as rt-from gateway.session_results import retain_result-from hermes_state import SessionDB---def _delete_8_days_ago(db, epoch, sid):- snap = db.get_session(sid)- at = time.time() - 8 * 86400- with pytest.MonkeyPatch.context() as clock:- clock.setattr(time, "time", lambda: 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"])---def test_a_deleted_session_is_never_recreated_after_the_horizon(tmp_path):- from hermes_state_mutation_retirement import RETIRED_PREFIX- with SessionDB(tmp_path / "state.db") as db:- epoch = rt.begin_runtime_epoch(db, instance_id="owner")- db.create_session("s", source="api_server")- args = dict(principal_id="api", session_id="s", request_id="r1", payload={"text": "charge card"})- rt.admit_session_input(db, epoch=epoch, **args)- row = rt.claim_session_input(db, epoch=epoch, session_id="s")- retain_result(db, epoch=epoch, row=row, result={"result": {"final_response": "done"}, "usage": {}})- _delete_8_days_ago(db, epoch, "s")- db.prune_sessions(older_than_days=90)- assert db.get_meta(RETIRED_PREFIX + "s") is not None- with pytest.raises(rt.RuntimeStoreError, match="not_found"):- db.ensure_session("s", source="unknown") # a late backfill- with pytest.raises(rt.RuntimeStoreError, match="not_found"):- rt.admit_session_input(db, epoch=epoch, **args) # the old exact retry- assert db.get_session("s") is None---def test_a_deleted_bot_chat_generation_is_never_reissued(tmp_path):- from gateway.session_bot import _bot_chat_creation_id- from gateway.session_local_recovery import local_identity- with SessionDB(tmp_path / "state.db") as db:- epoch = rt.begin_runtime_epoch(db, instance_id="owner")- authority, actor = SimpleNamespace(profile_id="owned", db=db), SimpleNamespace(subject="owner")- sid = local_identity("owned", "owner", "bot-chat:owned")- db.create_session(sid, source="cli")- _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"diff --git a/tests/hermes_state/test_terminal_retirement.py b/tests/hermes_state/test_terminal_retirement.pyindex 32c4341c850..55949a04b6b 100644--- a/tests/hermes_state/test_terminal_retirement.py+++ b/tests/hermes_state/test_terminal_retirement.py@@ -333,7 +333,7 @@ def test_retirement_drops_the_turn_user_row_copy(tmp_path):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 but the deletion fence itself (B2-06)."""+ prune pass reclaims every row they hold (B2-06)."""import timeimport hermes_state_mutation_retirement as retirementnow = time.time()@@ -365,8 +365,7 @@ def test_tombstones_past_the_retry_horizon_are_reclaimed_by_the_prune_pass(tmp_passert len(rows_naming('old', old_id)) == 4db.prune_sessions(older_than_days=90)assert len(rows_naming('young', young_id)) == 4- assert rows_naming('old', old_id) == [retirement.RETIRED_PREFIX + 'old'], \- 'tombstones past the horizon were not reclaimed (the deletion fence stays)'+ 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)