The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: run memory-provider session finalization inside ownership too
Zheqing Zeng82c76be69530
diff --git a/hermes_cli/cli_shutdown.py b/hermes_cli/cli_shutdown.pyindex ea735945b2b..8f2f3d76fc0 100644--- a/hermes_cli/cli_shutdown.py+++ b/hermes_cli/cli_shutdown.py@@ -307,34 +307,47 @@ def _finalize_single_query(cli) -> None:Three phases, in this order:1. **Session-owned settlement** — the durable flush (transcript retry, token- drain, ``end_session``) and the finalize hook. These are the only steps that- may still write session-owned state, and the flush's ``end_session`` setter- checks only ``id = ? AND ended_at IS NULL`` — no owner fence — so they must- complete while this process still owns the session. (The order was load-- bearing from the start: #88583 wired the flush ahead of teardown so nothing- later can lose the turn.)- 2. **Ownership handoff** — release the active-session lease. By this point every- turn of the run (main turn, kanban goal loop, notify-completion follow-ups)- has finished and every session-owned write has landed, so a waiting delivery- may acquire and resume the session immediately: releasing only at process- exit let an alive-but-idle one-shot refuse deliveries for the whole exit- linger (bounded, minutes) after its turn had ended (#118826 / #122770).- 3. **Process-only work, lease-free** — the bounded linger for notify_on_complete- children (pipe drain, the boundary the one-shot path itself declares "NOT- part of the spawner's delivery", #113608) and resource teardown. Neither- touches session rows, so they need no ownership.+ drain, ``end_session``), the finalize hook, and memory-provider session+ finalization. Providers finalize THIS session's remote state at+ ``on_session_end`` (OpenViking synchronously commits ``sessions/{sid}``,+ Supermemory flushes pending turns stamped with the session id), so this+ belongs inside ownership — post-release it would run while a successor+ may already be mid-turn on the session. The flush runs first: memory+ shutdown can issue aux-LLM calls and nothing after it may fail in a way+ that loses the turn (#88583). Settlement is best-effort by design:+ failures are logged and the release still happens, because the failure+ mode to avoid is an exited process pinning the lease — a dangling open+ row is recoverable (session_recovery reaps stale rows), a wedged lease+ is not.+ 2. **Ownership handoff** — release the active-session lease. Every turn of+ the run (main turn, kanban goal loop, notify-completion follow-ups) has+ finished and the success path has no session-owned writes left, so a+ waiting delivery may acquire and resume the session immediately:+ releasing only at process exit let an alive-but-idle one-shot refuse+ deliveries for the whole exit linger (bounded, minutes) after its turn+ had ended (#118826 / #122770).+ 3. **Process-only work, lease-free** — the bounded linger for+ notify_on_complete children (pipe drain, the boundary the one-shot path+ itself declares "NOT part of the spawner's delivery", #113608) and+ resource teardown. ``_run_cleanup``'s memory-shutdown call is idempotent+ (``_memory_provider_shutdown``), so its post-release repeat is a no-op;+ neither it nor the linger touches session rows.Releasing between settlement and the linger is what prevents the handoff race:a successor that acquires and reopens the session can never receive thisprocess's stale ``cli_close`` end-stamp, because phase 1 has already run it."""- from cli import _flush_one_shot_session_store, _notify_single_query_session_finalize, _run_cleanup, _wait_for_oneshot_background_completions+ from cli import _flush_one_shot_session_store, _notify_single_query_session_finalize, _run_cleanup, _shutdown_agent_memory_provider, _wait_for_oneshot_background_completionstry:try:_flush_one_shot_session_store(cli)except Exception:logger.debug("one-shot session store flush failed", exc_info=True)_notify_single_query_session_finalize(cli)+ try:+ _shutdown_agent_memory_provider(getattr(cli, "agent", None))+ except Exception:+ logger.debug("one-shot memory provider shutdown failed", exc_info=True)finally:# Even a failed settlement must not pin the lease: the failure mode to avoid# at all costs is a dead-ish process holding ownership, not a dangling row.diff --git a/tests/hermes_cli/test_single_query_session_finalize.py b/tests/hermes_cli/test_single_query_session_finalize.pyindex 1f114070a6a..4dd5304a469 100644--- a/tests/hermes_cli/test_single_query_session_finalize.py+++ b/tests/hermes_cli/test_single_query_session_finalize.py@@ -158,6 +158,52 @@ def test_finalize_settles_session_before_a_successor_can_take_over(tmp_path, montaken_over["lease_b"].release()+def test_finalize_commits_memory_session_before_a_successor_can_take_over(tmp_path, monkeypatch):+ """Memory-provider session finalization is session-owned settlement: providers+ commit THIS session's remote state at ``on_session_end`` (OpenViking posts+ ``sessions/{sid}/commit``; Supermemory flushes pending turns stamped with the+ session id). It must land while this process still owns the lease — post-release+ it would fire while the successor is mid-turn on the session.++ Discriminating: with the phase-1 memory shutdown removed, ``memory_commit`` is+ never recorded before the successor's acquisition and this test fails."""+ from hermes_cli import active_sessions++ home = tmp_path / ".hermes"+ monkeypatch.setenv("HERMES_HOME", str(home))+ events: list[str] = []+ lease_a, message = active_sessions.try_acquire_active_session(+ session_id="s1", surface="cli", config={}, metadata={"live_session_id": "s1"}+ )+ assert lease_a is not None, message++ agent_a = SimpleNamespace(+ session_id="s1", _session_messages=[],+ shutdown_memory_provider=lambda *a, **k: events.append("memory_commit"),+ )+ cli_a = SimpleNamespace(+ agent=agent_a, session_id="s1", conversation_history=[],+ _release_active_session=lambda: (events.append("release"), lease_a.release()),+ )++ def linger_with_takeover(_cli):+ lease_b, msg_b = active_sessions.try_acquire_active_session(+ session_id="s1", surface="cli", config={}, metadata={"live_session_id": "s1"}+ )+ assert lease_b is not None, f"successor could not acquire during the linger: {msg_b}"+ events.append("successor_acquired")+ lease_b.release()++ monkeypatch.setattr(cli, "_wait_for_oneshot_background_completions", linger_with_takeover)+ monkeypatch.setattr(cli, "_flush_one_shot_session_store", lambda _c: None)+ monkeypatch.setattr(cli, "_notify_single_query_session_finalize", lambda _c: None)+ monkeypatch.setattr(cli, "_run_cleanup", lambda **_k: None)++ cli._finalize_single_query(cli_a)++ assert events == ["memory_commit", "release", "successor_acquired"]++def test_notify_single_query_session_finalize_uses_agent_session(monkeypatch):diff --git a/tests/tools/test_oneshot_completion_linger.py b/tests/tools/test_oneshot_completion_linger.pyindex 77f57b9831b..1db628d07f7 100644--- a/tests/tools/test_oneshot_completion_linger.py+++ b/tests/tools/test_oneshot_completion_linger.py@@ -228,11 +228,12 @@ def test_default_timeout_read_from_config(registry, monkeypatch):def test_finalize_single_query_settles_session_then_releases_then_lingers(monkeypatch):"""cli._finalize_single_query ordering contract: session-owned settlement- (durable flush incl. end_session, finalize hook) completes BEFORE the lease- release, so a successor can never receive a stale end-stamp; the lease release- precedes the exit linger, so a finished turn stops refusing deliveries- (#118826); the linger precedes teardown (the parent owns the children's- pipes)."""+ (durable flush incl. end_session, finalize hook, memory-provider session+ finalization — providers commit THIS session's remote state at on_session_end)+ completes BEFORE the lease release, so a successor can never receive a stale+ end-stamp or a remote commit mid-turn; the lease release precedes the exit+ linger, so a finished turn stops refusing deliveries (#118826); the linger+ precedes teardown (the parent owns the children's pipes)."""import cli as cli_modorder = []@@ -249,6 +250,9 @@ def test_finalize_single_query_settles_session_then_releases_then_lingers(monkeymonkeypatch.setattr(cli_mod, "_notify_single_query_session_finalize", lambda cli, **k: order.append("finalize"))+ monkeypatch.setattr(+ cli_mod, "_shutdown_agent_memory_provider", lambda agent: order.append("memory")+ )monkeypatch.setattr(cli_mod, "_run_cleanup", lambda **k: order.append("cleanup"))class _FakeCli:@@ -259,7 +263,7 @@ def test_finalize_single_query_settles_session_then_releases_then_lingers(monkeyorder.append("release")cli_mod._finalize_single_query(_FakeCli())- assert order == ["flush", "finalize", "release", "wait", "cleanup"]+ assert order == ["flush", "finalize", "memory", "release", "wait", "cleanup"]def test_finalize_single_query_survives_wait_failure(monkeypatch):"""A raising wait must not break the durable flush path."""@@ -278,6 +282,9 @@ def test_finalize_single_query_survives_wait_failure(monkeypatch):monkeypatch.setattr(cli_mod, "_notify_single_query_session_finalize", lambda cli, **k: order.append("finalize"))+ monkeypatch.setattr(+ cli_mod, "_shutdown_agent_memory_provider", lambda agent: order.append("memory")+ )monkeypatch.setattr(cli_mod, "_run_cleanup", lambda **k: order.append("cleanup"))class _FakeCli:@@ -288,7 +295,7 @@ def test_finalize_single_query_survives_wait_failure(monkeypatch):order.append("release")cli_mod._finalize_single_query(_FakeCli())- assert order == ["flush", "finalize", "release", "cleanup"]+ assert order == ["flush", "finalize", "memory", "release", "cleanup"]# ── real-process E2E ─────────────────────────────────────────────────────────