The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: seed-copy compensation discards the row without the retirement fence
teknium144212c5a559f
diff --git a/hermes_state_sessions.py b/hermes_state_sessions.pyindex f00c9b69832..e2aa344543a 100644--- a/hermes_state_sessions.py+++ b/hermes_state_sessions.py@@ -1456,6 +1456,24 @@ class SessionSessionsMixin:self._remove_session_files(sessions_dir, sid)return bool(deleted)+ def discard_unadmitted_session(self, session_id: str) -> bool:+ """Abort a row this same flow just created and nobody has been admitted against (seed-copy+ compensation): remove it WITHOUT the retirement fence so the id can be lazily recreated.+ A row with any admission or worker receipt is a real session and takes the fenced+ :meth:`delete_session` path instead."""+ def _do(conn):+ if conn.execute(+ "SELECT 1 FROM session_admissions WHERE target_session_id=? UNION ALL "+ "SELECT 1 FROM worker_executions WHERE session_id=? LIMIT 1", (session_id, session_id)).fetchone():+ return None+ conn.execute("DELETE FROM messages WHERE session_id = ?", (session_id,))+ cur = conn.execute("DELETE FROM sessions WHERE id = ?", (session_id,))+ return cur.rowcount > 0+ result = self._execute_write(_do)+ if result is None:+ return self.delete_session(session_id)+ return bool(result)+def delete_session_if_empty(self, session_id: str, sessions_dir: Optional[Path] = None) -> bool:"""Delete *session_id* only if it has no messages, no title and no children; check and deleteshare one transaction so a concurrent flush can't be lost."""diff --git a/tests/cron/test_cron_mcp_toolset_empty_block.py b/tests/cron/test_cron_mcp_toolset_empty_block.pyindex 36332ded1ee..b71c36524e0 100644--- a/tests/cron/test_cron_mcp_toolset_empty_block.py+++ b/tests/cron/test_cron_mcp_toolset_empty_block.py@@ -7,10 +7,51 @@ discovering profile's registry overlay, so another profile's job sees the name bfrom __future__ import annotations+import asyncio+import json+from types import SimpleNamespacefrom unittest.mock import MagicMock, patchimport cron.jobs as cron_jobs-from cron.scheduler import run_job+++def _run_owned_job(job, tmp_path):+ """Run through the production owner bridge: cron turns execute inside the gateway owner."""+ from gateway.session_contract import SessionRef+ from gateway.session_cron import current_execution, execute+ from hermes_state_registry import acquire, release++ ref = SessionRef("test-profile", "cron-owner-session")+ admission_id = "cron-owner-admission"+ request_id = "cron-owner-request"+ db = acquire(tmp_path / "state.db")+ db.create_session(ref.session_id, source="cron")+ authority = SimpleNamespace(+ db=db,+ sessions={ref.session_id: SimpleNamespace(source=SimpleNamespace(user_id="cron-owner"))},+ pending_results={},+ )+ row = {"admission_id": admission_id, "request_id": request_id,+ "principal_id": "cron-owner", "payload": {"text": ""}}+ policy = SimpleNamespace(request_json=json.dumps({+ "cron_job": job, "extra_prompt": None, "request_id": request_id}))++ async def run():+ previous = current_execution()+ try:+ await execute(authority, ref, row, policy)+ except RuntimeError as exc:+ saved = authority.pending_results.get(admission_id)+ if saved is None:+ raise+ assert str(exc) == saved["result"]["cron_result"][3]+ assert current_execution() is previous+ return tuple(authority.pending_results[admission_id]["result"]["cron_result"])++ try:+ return asyncio.run(run())+ finally:+ release(db)_RUNTIME = {"api_key": "k", "base_url": "https://example.invalid/v1", "provider": "openrouter","api_mode": "chat_completions"}@@ -34,13 +75,12 @@ def _run(job, tmp_path):patch("cron.scheduler_delivery._resolve_origin", return_value=None), \patch("hermes_cli.env_loader.load_hermes_dotenv"), \patch("hermes_cli.env_loader.reset_secret_source_cache"), \- patch("hermes_state_registry.acquire", return_value=MagicMock()), \patch("tools.mcp_tool_discovery.discover_mcp_tools", return_value=[]), \patch("hermes_cli.runtime_provider.resolve_runtime_provider", return_value=dict(_RUNTIME)):agent_cls.return_value.run_conversation.return_value = {"final_response": "ok"}with cron_jobs.use_cron_store(tmp_path):cron_jobs.save_jobs([job])- result = run_job(job)+ result = _run_owned_job(job, tmp_path)return result, agent_cls.calleddiff --git a/tests/gateway/test_terminal_commit_crash.py b/tests/gateway/test_terminal_commit_crash.pyindex 1e59cb3b650..3079c87d3ab 100644--- a/tests/gateway/test_terminal_commit_crash.py+++ b/tests/gateway/test_terminal_commit_crash.py@@ -41,7 +41,7 @@ def test_terminal_commit_before_publication_survives_kill(tmp_path):def snapshot():with sqlite3.connect(home / 'state.db') as db:- rows = dict(db.execute('SELECT request_id,status FROM session_admissions'))+ rows = {rid.rsplit(':', 1)[-1]: status for rid, status in db.execute('SELECT request_id,status FROM session_admissions')}result = db.execute("SELECT value FROM state_meta WHERE key LIKE 'gateway.admission.result.v1.%' AND value LIKE '%RECOVERY_ACK_BLOCK_STARTED%'").fetchone()return rows, json.loads(result[0]) if result else None@@ -81,7 +81,7 @@ def test_terminal_commit_before_publication_survives_kill(tmp_path):async with asyncio.timeout(25):while snapshot()[0][follower] != 'terminal':await asyncio.sleep(.03)- assert snapshot()[0]['chat:once'] == 'terminal'+ assert snapshot()[0]['once'] == 'terminal'assert snapshot()[1] == savedtry:diff --git a/tests/hermes_cli/test_sessions_export_output_dir.py b/tests/hermes_cli/test_sessions_export_output_dir.pyindex 0eaf01df851..65d6f8d872a 100644--- a/tests/hermes_cli/test_sessions_export_output_dir.py+++ b/tests/hermes_cli/test_sessions_export_output_dir.py@@ -19,7 +19,11 @@ class _FakeDB:def _export(monkeypatch, *argv):- monkeypatch.setattr(hermes_state, "SessionDB", lambda: _FakeDB())+ # Read-only observation commands short-circuit when state.db is absent; the fake DB+ # stands in for the file that would otherwise be opened read-only.+ from hermes_constants import get_hermes_home+ (get_hermes_home() / "state.db").touch()+ monkeypatch.setattr(hermes_state, "SessionDB", lambda **_kw: _FakeDB())monkeypatch.setattr(sys, "argv", ["hermes", "sessions", "export", "--session-id", "sess", *argv])main_mod.main()diff --git a/tests/hermes_state/test_ledger_delete_consistency.py b/tests/hermes_state/test_ledger_delete_consistency.pyindex 16d6ba3b5a5..a5b062fe123 100644--- a/tests/hermes_state/test_ledger_delete_consistency.py+++ b/tests/hermes_state/test_ledger_delete_consistency.py@@ -259,3 +259,23 @@ def test_adopted_worker_finish_settles_linked_admission_and_frees_follower(tmp_passert settled['status'] == 'terminal' and settled['outcome'] == 'completed'claimed = rt.claim_session_input(db, epoch=epoch, session_id='s')assert claimed is not None and claimed['admission_id'] == follower['admission_id']+++def test_discarding_an_unadmitted_row_leaves_no_fence_but_an_admitted_row_is_fenced(tmp_path):+ """Seed-copy compensation removes a row nobody was admitted against WITHOUT the retirement+ marker (the lazy first-prompt path must be able to recreate the id); once any receipt+ exists the same call takes the fenced delete so the id cannot be resurrected."""+ from hermes_state_mutation_retirement import RETIRED_PREFIX+ with closing(SessionDB(db_path=tmp_path / 'state.db')) as db:+ db.create_session('fresh', source='desktop')+ assert db.discard_unadmitted_session('fresh') is True+ assert db.get_session('fresh') is None+ assert db.get_meta(RETIRED_PREFIX + 'fresh') is None+ db.create_session('fresh', source='desktop') # lazy recreation still allowed+ assert db.get_session('fresh') is not None++ db.create_session('used', source='desktop')+ epoch = rt.begin_runtime_epoch(db, instance_id='owner')+ _settled_admission(db, epoch, 'used')+ assert db.discard_unadmitted_session('used') is True+ assert db.get_meta(RETIRED_PREFIX + 'used') is not Nonediff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex efc946d44cd..8bb6be216a3 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -245,7 +245,7 @@ def _persist_branch(db, new_key: str, parent_key: str, title: str, history: listfrom hermes_state_errors import is_disk_full_errorif compensate and not is_disk_full_error(exc):try:- db.delete_session(new_key)+ db.discard_unadmitted_session(new_key)except Exception:logger.debug("branch seed compensation delete failed for %s", new_key, exc_info=True)raise@@ -286,7 +286,7 @@ def _seed_row(record: dict) -> None:if not record.get("_branch_seed_persisted"):with contextlib.suppress(Exception), _session_db(record) as db:if db is not None:- db.delete_session(key)+ db.discard_unadmitted_session(key)returntry:if title := record.get("pending_title"):