Skip to content

The agent that grows with you

fix: settle session-owned state before releasing the lease

Zheqing Zeng1d39a2d3d303
diff --git a/hermes_cli/cli_shutdown.py b/hermes_cli/cli_shutdown.py
index 4c6d93dd7fe..ea735945b2b 100644
--- a/hermes_cli/cli_shutdown.py
+++ b/hermes_cli/cli_shutdown.py
@@ -302,29 +302,45 @@ def _wait_for_oneshot_background_completions(cli) -> None:
def _finalize_single_query(cli) -> None:
- """Close one-shot CLI resources after releasing the active-session lease.
-
- Release order is the point of this routine: by the time finalize runs, every turn
- of the run (main turn, kanban goal loop, notify-completion follow-ups) has
- finished, and none of the remaining steps — the bounded linger for
- notify_on_complete children, the durable flush, cleanup — runs a turn. The lease
- means "a turn may run on this session", so it is released FIRST; holding it
- through the linger let an alive-but-idle one-shot keep refusing new deliveries
- ("Refused active session") for minutes after its turn had ended (#118826).
+ """Settle the session, then release its lease, then linger as a bystander.
+
+ 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.
+
+ Releasing between settlement and the linger is what prevents the handoff race:
+ a successor that acquires and reopens the session can never receive this
+ process'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
- cli._release_active_session()
- # Order matters: linger for spawned background work BEFORE any teardown (the
- # parent owns those children's stdout pipes); then the durable flush, since
- # memory-provider shutdown inside _run_cleanup can issue aux-LLM calls and
- # nothing after it may fail in a way that loses the turn.
- for step, what in (
- (_wait_for_oneshot_background_completions, "background completion wait"),
- (_flush_one_shot_session_store, "session store flush"),
- ):
+ try:
try:
- step(cli)
+ _flush_one_shot_session_store(cli)
except Exception:
- logger.debug("one-shot %s failed", what, exc_info=True)
- _notify_single_query_session_finalize(cli)
+ logger.debug("one-shot session store flush failed", exc_info=True)
+ _notify_single_query_session_finalize(cli)
+ 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.
+ cli._release_active_session()
+ try:
+ _wait_for_oneshot_background_completions(cli)
+ except Exception:
+ logger.debug("one-shot background completion wait failed", exc_info=True)
_run_cleanup(notify_session_finalize=False)
diff --git a/tests/hermes_cli/test_single_query_session_finalize.py b/tests/hermes_cli/test_single_query_session_finalize.py
index 229704fa8b9..1f114070a6a 100644
--- a/tests/hermes_cli/test_single_query_session_finalize.py
+++ b/tests/hermes_cli/test_single_query_session_finalize.py
@@ -1,4 +1,5 @@
from types import SimpleNamespace
+from typing import Any
import pytest
@@ -14,8 +15,8 @@ def reset_single_query_finalize_state(monkeypatch):
def test_finalize_single_query_releases_lease_before_cleanup(monkeypatch):
- """The lease release precedes every remaining step, so a cleanup failure can
- never skip it (the old finally-release could only promise 'eventually')."""
+ """Settlement (finalize hook) runs before the release, the release before
+ cleanup; a cleanup failure can never skip or precede the release."""
calls = []
fake_cli = SimpleNamespace(_release_active_session=lambda: calls.append("release"))
@@ -33,7 +34,7 @@ def test_finalize_single_query_releases_lease_before_cleanup(monkeypatch):
with pytest.raises(RuntimeError, match="cleanup failed"):
cli._finalize_single_query(fake_cli)
- assert calls == ["release", "finalize", "cleanup"]
+ assert calls == ["finalize", "release", "cleanup"]
def test_finalize_single_query_runs_cleanup_when_finalize_hook_fails(monkeypatch):
@@ -54,7 +55,7 @@ def test_finalize_single_query_runs_cleanup_when_finalize_hook_fails(monkeypatch
cli._finalize_single_query(fake_cli)
- assert calls == ["release", "finalize", "cleanup"]
+ assert calls == ["finalize", "release", "cleanup"]
def test_finalize_single_query_frees_the_lease_ahead_of_the_linger(tmp_path, monkeypatch):
@@ -97,6 +98,66 @@ def test_finalize_single_query_frees_the_lease_ahead_of_the_linger(tmp_path, mon
assert not any(str(e.get("session_id") or "") == "s1" for e in entries)
+def test_finalize_settles_session_before_a_successor_can_take_over(tmp_path, monkeypatch):
+ """P1 handoff race: a successor that acquires the session DURING the
+ predecessor's exit linger must never receive the predecessor's stale
+ ``cli_close`` end-stamp — settlement (flush incl. end_session) must complete
+ before the lease is released.
+
+ Exercises the real seam with a real SessionDB and a real lease: the linger is
+ patched to play the successor (acquire the freed lease, reopen the row), and
+ the final assertion is that the successor's open interval survives the
+ predecessor's whole finalize. On the unsafe order (release → linger → flush)
+ the flush's unconditional ``end_session`` stamps the successor's interval and
+ this test fails."""
+ from hermes_cli import active_sessions
+ from hermes_state import SessionDB
+
+ home = tmp_path / ".hermes"
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid = "s1"
+ db.create_session(sid, "cli")
+ lease_a, message = active_sessions.try_acquire_active_session(
+ session_id=sid, surface="cli", config={}, metadata={"live_session_id": sid}
+ )
+ assert lease_a is not None, message
+
+ agent_a = SimpleNamespace(
+ session_id=sid, _session_db=db, _session_messages=[],
+ _persist_disabled=False, _persist_session=lambda *a, **k: None,
+ )
+ cli_a = SimpleNamespace(
+ agent=agent_a, session_id=sid, conversation_history=[], _session_db=db,
+ _release_active_session=lease_a.release,
+ )
+
+ taken_over: dict[str, Any] = {}
+
+ def linger_with_takeover(_cli):
+ # The successor arrives mid-linger. Early admission must hold (the point of
+ # the PR)…
+ lease_b, msg_b = active_sessions.try_acquire_active_session(
+ session_id=sid, surface="cli", config={}, metadata={"live_session_id": sid}
+ )
+ assert lease_b is not None, f"successor could not acquire during the linger: {msg_b}"
+ taken_over["lease_b"] = lease_b
+ # …and it resumes the row (the predecessor's settlement already ended it).
+ db.reopen_session(sid)
+
+ monkeypatch.setattr(cli, "_wait_for_oneshot_background_completions", linger_with_takeover)
+ 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)
+
+ row = db.get_session(sid)
+ assert row is not None and row["ended_at"] is None, (
+ "successor's open interval was end-stamped by the predecessor's finalize"
+ )
+ taken_over["lease_b"].release()
+
+
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.py
index f6531487a01..77f57b9831b 100644
--- a/tests/tools/test_oneshot_completion_linger.py
+++ b/tests/tools/test_oneshot_completion_linger.py
@@ -226,11 +226,13 @@ def test_default_timeout_read_from_config(registry, monkeypatch):
# ── CLI exit paths invoke the linger ─────────────────────────────────────────
-def test_finalize_single_query_releases_lease_then_lingers_before_teardown(monkeypatch):
- """cli._finalize_single_query releases the session lease FIRST (a finished turn
- must not keep refusing deliveries through the exit linger, #118826), then calls
- the registry wait BEFORE the durable flush / cleanup so deliveries land while
- the parent is alive."""
+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)."""
import cli as cli_mod
order = []
@@ -257,7 +259,7 @@ def test_finalize_single_query_releases_lease_then_lingers_before_teardown(monke
order.append("release")
cli_mod._finalize_single_query(_FakeCli())
- assert order == ["release", "wait", "flush", "finalize", "cleanup"]
+ assert order == ["flush", "finalize", "release", "wait", "cleanup"]
def test_finalize_single_query_survives_wait_failure(monkeypatch):
"""A raising wait must not break the durable flush path."""
@@ -286,7 +288,7 @@ def test_finalize_single_query_survives_wait_failure(monkeypatch):
order.append("release")
cli_mod._finalize_single_query(_FakeCli())
- assert order == ["release", "flush", "finalize", "cleanup"]
+ assert order == ["flush", "finalize", "release", "cleanup"]
# ── real-process E2E ─────────────────────────────────────────────────────────