Skip to content

The agent that grows with you

fix(cli): release the one-shot session lease before the exit linger

Zheqing Zeng734ac474e5ba
diff --git a/hermes_cli/cli_shutdown.py b/hermes_cli/cli_shutdown.py
index 0a6fa48f103..4c6d93dd7fe 100644
--- a/hermes_cli/cli_shutdown.py
+++ b/hermes_cli/cli_shutdown.py
@@ -302,22 +302,29 @@ def _wait_for_oneshot_background_completions(cli) -> None:
def _finalize_single_query(cli) -> None:
- """Close one-shot CLI resources before releasing the active session lease."""
+ """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).
+ """
from cli import _flush_one_shot_session_store, _notify_single_query_session_finalize, _run_cleanup, _wait_for_oneshot_background_completions
- try:
- # 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:
- step(cli)
- except Exception:
- logger.debug("one-shot %s failed", what, exc_info=True)
- _notify_single_query_session_finalize(cli)
- _run_cleanup(notify_session_finalize=False)
- finally:
- cli._release_active_session()
+ 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:
+ step(cli)
+ except Exception:
+ logger.debug("one-shot %s failed", what, exc_info=True)
+ _notify_single_query_session_finalize(cli)
+ _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 59711ca697f..229704fa8b9 100644
--- a/tests/hermes_cli/test_single_query_session_finalize.py
+++ b/tests/hermes_cli/test_single_query_session_finalize.py
@@ -13,7 +13,9 @@ def reset_single_query_finalize_state(monkeypatch):
-def test_finalize_single_query_releases_session_when_cleanup_fails(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')."""
calls = []
fake_cli = SimpleNamespace(_release_active_session=lambda: calls.append("release"))
@@ -31,7 +33,7 @@ def test_finalize_single_query_releases_session_when_cleanup_fails(monkeypatch):
with pytest.raises(RuntimeError, match="cleanup failed"):
cli._finalize_single_query(fake_cli)
- assert calls == ["finalize", "cleanup", "release"]
+ assert calls == ["release", "finalize", "cleanup"]
def test_finalize_single_query_runs_cleanup_when_finalize_hook_fails(monkeypatch):
@@ -52,7 +54,47 @@ def test_finalize_single_query_runs_cleanup_when_finalize_hook_fails(monkeypatch
cli._finalize_single_query(fake_cli)
- assert calls == ["finalize", "cleanup", "release"]
+ assert calls == ["release", "finalize", "cleanup"]
+
+
+def test_finalize_single_query_frees_the_lease_ahead_of_the_linger(tmp_path, monkeypatch):
+ """The #118826 contract with a REAL lease: once the one-shot's turns are done,
+ the session entry must be gone from the active-session registry BEFORE the
+ bounded exit linger runs — a alive-but-idle process must not keep refusing
+ deliveries ("Refused active session") for minutes after its turn ended."""
+ from hermes_cli import active_sessions
+
+ home = tmp_path / ".hermes"
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ lease, message = active_sessions.try_acquire_active_session(
+ session_id="s1", surface="cli", config={}, metadata={"live_session_id": "s1"}
+ )
+ assert lease is not None, message
+
+ def wait_only_if_released(_cli):
+ entries = active_sessions._read_entries(active_sessions._state_path(home))
+ # The linger step swallows exceptions by design, so RECORD instead of
+ # asserting here — the assertion below is what must fail on unfixed code.
+ seen["held_during_linger"] = any(
+ str(e.get("session_id") or "") == "s1" for e in entries
+ )
+
+ seen: dict[str, bool] = {}
+ fake_cli = SimpleNamespace(
+ session_id="s1", agent=None, _release_active_session=lease.release
+ )
+ monkeypatch.setattr(cli, "_wait_for_oneshot_background_completions", wait_only_if_released)
+ monkeypatch.setattr(cli, "_flush_one_shot_session_store", lambda _cli: None)
+ monkeypatch.setattr(cli, "_notify_single_query_session_finalize", lambda _cli: None)
+ monkeypatch.setattr(cli, "_run_cleanup", lambda **_k: None)
+
+ cli._finalize_single_query(fake_cli)
+
+ assert seen.get("held_during_linger") is False, (
+ "session lease still held when the exit linger began"
+ )
+ entries = active_sessions._read_entries(active_sessions._state_path(home))
+ assert not any(str(e.get("session_id") or "") == "s1" for e in entries)
diff --git a/tests/tools/test_oneshot_completion_linger.py b/tests/tools/test_oneshot_completion_linger.py
index 39e7cce3530..f6531487a01 100644
--- a/tests/tools/test_oneshot_completion_linger.py
+++ b/tests/tools/test_oneshot_completion_linger.py
@@ -226,9 +226,11 @@ def test_default_timeout_read_from_config(registry, monkeypatch):
# ── CLI exit paths invoke the linger ─────────────────────────────────────────
-def test_finalize_single_query_lingers_before_teardown(monkeypatch):
- """cli._finalize_single_query must call the registry wait BEFORE the
- durable flush / cleanup so deliveries land while the parent is alive."""
+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."""
import cli as cli_mod
order = []
@@ -255,7 +257,7 @@ def test_finalize_single_query_lingers_before_teardown(monkeypatch):
order.append("release")
cli_mod._finalize_single_query(_FakeCli())
- assert order[0] == "wait"
+ assert order == ["release", "wait", "flush", "finalize", "cleanup"]
def test_finalize_single_query_survives_wait_failure(monkeypatch):
"""A raising wait must not break the durable flush path."""
@@ -284,7 +286,7 @@ def test_finalize_single_query_survives_wait_failure(monkeypatch):
order.append("release")
cli_mod._finalize_single_query(_FakeCli())
- assert "flush" in order and "release" in order
+ assert order == ["release", "flush", "finalize", "cleanup"]
# ── real-process E2E ─────────────────────────────────────────────────────────