Skip to content

The agent that grows with you

fix(tui-gateway): spare durable rows while a sibling backend holds them

Brooklyn Nicholson39f1e1881a02
diff --git a/tests/tui_gateway/test_cross_process_orphan_ownership.py b/tests/tui_gateway/test_cross_process_orphan_ownership.py
new file mode 100644
index 00000000000..157f2215079
--- /dev/null
+++ b/tests/tui_gateway/test_cross_process_orphan_ownership.py
@@ -0,0 +1,416 @@
+from __future__ import annotations
+
+import contextlib
+import os
+import subprocess
+import sys
+import threading
+import time
+from pathlib import Path
+
+import pytest
+
+from hermes_cli.active_sessions import (
+ active_session_liveness_guard,
+ active_session_registry_snapshot,
+ try_acquire_active_session,
+)
+from tui_gateway import server
+
+
+_LEASE_HOLDER_SCRIPT = """
+import os
+import time
+from pathlib import Path
+
+from hermes_cli import active_sessions
+from hermes_cli.active_sessions import try_acquire_active_session
+
+boundary_file = os.environ.get("BOUNDARY_FILE")
+if boundary_file:
+ original_enter = active_sessions._FileLock.__enter__
+ def instrumented_enter(self):
+ Path(boundary_file).write_text("boundary", encoding="utf-8")
+ return original_enter(self)
+ active_sessions._FileLock.__enter__ = instrumented_enter
+
+go_file = os.environ.get("GO_FILE")
+if go_file:
+ Path(os.environ["WAITING_FILE"]).write_text("waiting", encoding="utf-8")
+ deadline = time.monotonic() + 120
+ while not Path(go_file).exists():
+ if time.monotonic() >= deadline:
+ raise RuntimeError("timed out waiting for acquisition signal")
+ time.sleep(0.02)
+lease, message = try_acquire_active_session(
+ session_id=os.environ["SESSION_ID"],
+ surface="desktop",
+ config={},
+ track_liveness=True,
+)
+assert lease is not None and message is None, message
+Path(os.environ["READY_FILE"]).write_text("ready", encoding="utf-8")
+try:
+ deadline = time.monotonic() + 120
+ release_file = Path(os.environ["RELEASE_FILE"])
+ while not release_file.exists():
+ if time.monotonic() >= deadline:
+ raise RuntimeError("timed out waiting for release signal")
+ time.sleep(0.02)
+finally:
+ lease.release()
+"""
+
+
+def _spawn_lease_holder(
+ *,
+ home: Path,
+ session_id: str,
+ ready_file: Path,
+ release_file: Path,
+ boundary_file: Path | None = None,
+ go_file: Path | None = None,
+ waiting_file: Path | None = None,
+) -> subprocess.Popen[str]:
+ repo_root = Path(__file__).resolve().parents[2]
+ env = os.environ.copy()
+ for key in list(env):
+ if key.endswith("_API_KEY") or key.endswith("_TOKEN"):
+ env.pop(key)
+ env.update({
+ "HERMES_HOME": str(home),
+ "PYTHONPATH": os.pathsep.join(
+ part for part in (str(repo_root), env.get("PYTHONPATH", "")) if part
+ ),
+ "READY_FILE": str(ready_file),
+ "RELEASE_FILE": str(release_file),
+ "SESSION_ID": session_id,
+ })
+ if boundary_file is not None:
+ env["BOUNDARY_FILE"] = str(boundary_file)
+ if go_file is not None and waiting_file is not None:
+ env["GO_FILE"] = str(go_file)
+ env["WAITING_FILE"] = str(waiting_file)
+ return subprocess.Popen(
+ [sys.executable, "-c", _LEASE_HOLDER_SCRIPT],
+ env=env,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ )
+
+
+def _wait_for_child_file(
+ child: subprocess.Popen[str],
+ path: Path,
+ *,
+ label: str,
+ timeout: float = 60.0,
+) -> None:
+ deadline = time.monotonic() + timeout
+ while not path.exists():
+ if child.poll() is not None:
+ stdout, stderr = child.communicate()
+ pytest.fail(
+ f"{label} process exited before signalling readiness\n"
+ f"stdout: {stdout}\nstderr: {stderr}"
+ )
+ if time.monotonic() >= deadline:
+ pytest.fail(f"timed out waiting for {label} process")
+ time.sleep(0.02)
+
+
+def _stop_child(child: subprocess.Popen[str], release_file: Path) -> None:
+ release_file.touch()
+ if child.poll() is None:
+ child.kill()
+ child.communicate()
+
+
+def test_unlimited_session_lease_remains_noop_without_liveness_tracking(
+ tmp_path: Path,
+) -> None:
+ home = tmp_path / "untracked-home"
+
+ lease, message = try_acquire_active_session(
+ session_id="untracked-session",
+ surface="tui",
+ config={},
+ registry_home=home,
+ )
+
+ assert lease is not None and message is None
+ assert lease.enabled is False
+ assert active_session_registry_snapshot(registry_home=home) == []
+
+
+def test_orphan_guard_fails_closed_when_registry_is_unavailable(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from hermes_cli import active_sessions
+
+ def _unavailable(*_args, **_kwargs):
+ raise OSError("registry unavailable")
+
+ monkeypatch.setattr(
+ active_sessions,
+ "active_session_liveness_guard",
+ _unavailable,
+ )
+
+ with server._other_runtime_lease_guard(
+ "preserved-session",
+ {"profile_home": None},
+ ) as sibling_active:
+ assert sibling_active is True
+
+
+def test_desktop_claim_fails_closed_when_registry_setup_fails(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ server,
+ "_load_cfg",
+ lambda: (_ for _ in ()).throw(OSError("config unavailable")),
+ )
+
+ desktop_lease, desktop_message = server._claim_active_session_slot(
+ "desktop-session",
+ live_session_id="desktop-runtime",
+ surface="desktop",
+ )
+ tui_lease, tui_message = server._claim_active_session_slot(
+ "tui-session",
+ live_session_id="tui-runtime",
+ surface="tui",
+ )
+
+ assert desktop_lease is None
+ assert desktop_message == server._SESSION_OWNERSHIP_UNAVAILABLE
+ assert (tui_lease, tui_message) == (None, None)
+
+
+def test_server_release_retries_liveness_lease_before_dropping_reference(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ class _Lease:
+ enabled = True
+ released = False
+ track_liveness = True
+ calls = 0
+
+ def release(self):
+ self.calls += 1
+ if self.calls == 1:
+ raise OSError("replace failed once")
+ self.released = True
+
+ lease = _Lease()
+ session = {"active_session_lease": lease}
+ monkeypatch.setattr(server.time, "sleep", lambda *_args: None)
+
+ assert server._release_active_session_slot(session) is True
+ assert lease.calls == 2
+ assert "active_session_lease" not in session
+
+
+def test_automatic_cleanup_preserves_corrupt_registry_without_overwrite(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ profile_home = tmp_path / "profile-home"
+ state_path = profile_home / "runtime" / "active_sessions.json"
+ state_path.parent.mkdir(parents=True)
+ corrupt = "{not-json"
+ state_path.write_text(corrupt, encoding="utf-8")
+ ended: list[tuple[str, str]] = []
+
+ class _FakeDB:
+ def get_session(self, target: str) -> dict[str, str]:
+ return {"id": target, "source": "desktop"}
+
+ def end_session(self, target: str, reason: str) -> None:
+ ended.append((target, reason))
+
+ @contextlib.contextmanager
+ def _profile_db(_session: dict):
+ yield _FakeDB()
+
+ monkeypatch.setattr(server, "_session_db", _profile_db)
+ monkeypatch.setattr(
+ server, "_notify_session_boundary", lambda *args, **kwargs: None
+ )
+ monkeypatch.setattr(
+ "tools.async_delegation.interrupt_for_session", lambda *args, **kwargs: None
+ )
+ session = {
+ "agent": None,
+ "history": [],
+ "history_lock": threading.Lock(),
+ "profile_home": str(profile_home),
+ "session_key": "preserved-session",
+ "slash_worker": None,
+ "source": "desktop",
+ }
+
+ server._finalize_session(session, end_reason="idle_timeout")
+
+ assert ended == []
+ assert state_path.read_text(encoding="utf-8") == corrupt
+
+
+def test_liveness_guard_serializes_cross_process_acquire(tmp_path: Path) -> None:
+ home = tmp_path / "guard-home"
+ waiting_file = tmp_path / "child-waiting"
+ boundary_file = tmp_path / "child-lock-boundary"
+ go_file = tmp_path / "child-go"
+ acquired_file = tmp_path / "child-acquired"
+ release_file = tmp_path / "child-release"
+ session_id = "guarded-session"
+ child: subprocess.Popen[str] | None = None
+
+ try:
+ child = _spawn_lease_holder(
+ home=home,
+ session_id=session_id,
+ ready_file=acquired_file,
+ release_file=release_file,
+ boundary_file=boundary_file,
+ go_file=go_file,
+ waiting_file=waiting_file,
+ )
+ _wait_for_child_file(child, waiting_file, label="lease contender bootstrap")
+
+ with active_session_liveness_guard(
+ session_id,
+ registry_home=home,
+ ) as active:
+ assert active is False
+ go_file.write_text("go", encoding="utf-8")
+ _wait_for_child_file(child, boundary_file, label="lease lock boundary")
+ time.sleep(0.25)
+ assert not acquired_file.exists()
+ assert child.poll() is None
+
+ assert child is not None
+ _wait_for_child_file(child, acquired_file, label="lease contender")
+ release_file.write_text("release", encoding="utf-8")
+ stdout, stderr = child.communicate(timeout=30)
+ assert child.returncode == 0, f"stdout: {stdout}\nstderr: {stderr}"
+ assert active_session_registry_snapshot(registry_home=home) == []
+ finally:
+ if child is not None:
+ _stop_child(child, release_file)
+
+
+def test_automatic_desktop_cleanup_preserves_sibling_and_ends_sole_owner(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Every automatic cleanup reason must preserve another Desktop backend."""
+ profile_home = tmp_path / "profile-home"
+ ready_file = tmp_path / "child-ready"
+ release_file = tmp_path / "child-release"
+ session_id = "shared-profile-session"
+ child = _spawn_lease_holder(
+ home=profile_home,
+ session_id=session_id,
+ ready_file=ready_file,
+ release_file=release_file,
+ )
+ ended: list[tuple[str, str]] = []
+
+ class _FakeDB:
+ def get_session(self, target: str) -> dict[str, str] | None:
+ return {"id": target, "source": "desktop"}
+
+ def end_session(self, target: str, reason: str) -> None:
+ ended.append((target, reason))
+
+ @contextlib.contextmanager
+ def _profile_db(_session: dict):
+ yield _FakeDB()
+
+ monkeypatch.setattr(server, "_load_cfg", lambda: {})
+ monkeypatch.setattr(server, "_get_db", lambda: None)
+ monkeypatch.setattr(server, "_session_db", _profile_db)
+ monkeypatch.setattr(
+ server, "_notify_session_boundary", lambda *args, **kwargs: None
+ )
+ monkeypatch.setattr(
+ "tools.async_delegation.interrupt_for_session", lambda *args, **kwargs: None
+ )
+
+ def _session(lease) -> dict:
+ return {
+ "active_session_lease": lease,
+ "agent": None,
+ "history": [],
+ "history_lock": threading.Lock(),
+ "profile_home": str(profile_home),
+ "session_key": session_id,
+ "slash_worker": None,
+ "source": "desktop",
+ }
+
+ try:
+ _wait_for_child_file(child, ready_file, label="lease holder")
+
+ reasons = (
+ "ws_orphan_reap",
+ "ws_disconnect",
+ "idle_timeout",
+ "lru_evict",
+ "tui_shutdown",
+ )
+ assert set(reasons) == server._AUTOMATIC_SESSION_END_REASONS
+
+ for index, reason in enumerate(reasons):
+ local_lease, message = server._claim_active_session_slot(
+ session_id,
+ live_session_id=f"local-runtime-{index}",
+ surface="desktop",
+ profile_home=profile_home,
+ )
+ assert local_lease is not None and message is None
+ assert (
+ len(active_session_registry_snapshot(registry_home=profile_home)) == 2
+ )
+
+ server._finalize_session(_session(local_lease), end_reason=reason)
+
+ assert ended == []
+ remaining = active_session_registry_snapshot(registry_home=profile_home)
+ assert len(remaining) == 1
+ assert remaining[0]["session_id"] == session_id
+
+ # Explicit user close retains force/end semantics even with a sibling.
+ explicit_lease, message = server._claim_active_session_slot(
+ session_id,
+ live_session_id="explicit-runtime",
+ surface="desktop",
+ profile_home=profile_home,
+ )
+ assert explicit_lease is not None and message is None
+ server._finalize_session(_session(explicit_lease), end_reason="tui_close")
+ assert ended == [(session_id, "tui_close")]
+ ended.clear()
+
+ release_file.write_text("release", encoding="utf-8")
+ stdout, stderr = child.communicate(timeout=30)
+ assert child.returncode == 0, f"stdout: {stdout}\nstderr: {stderr}"
+ assert active_session_registry_snapshot(registry_home=profile_home) == []
+
+ for index, reason in enumerate(reasons):
+ sole_lease, message = server._claim_active_session_slot(
+ session_id,
+ live_session_id=f"sole-runtime-{index}",
+ surface="desktop",
+ profile_home=profile_home,
+ )
+ assert sole_lease is not None and message is None
+
+ server._finalize_session(_session(sole_lease), end_reason=reason)
+ assert active_session_registry_snapshot(registry_home=profile_home) == []
+
+ assert ended == [(session_id, reason) for reason in reasons]
+ finally:
+ _stop_child(child, release_file)
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 1266c7bcda0..a2fe9bd5cb0 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -631,12 +631,27 @@ def _notify_session_boundary(
pass
+_SESSION_OWNERSHIP_UNAVAILABLE = (
+ "Hermes could not safely reserve this session. Try again."
+)
+
+_AUTOMATIC_SESSION_END_REASONS = frozenset({
+ "ws_orphan_reap",
+ "ws_disconnect",
+ "idle_timeout",
+ "lru_evict",
+ "tui_shutdown",
+})
+
+
def _claim_active_session_slot(
session_key: str,
*,
live_session_id: str,
surface: str = "tui",
+ profile_home: str | Path | None = None,
) -> tuple[Any, str | None]:
+ track_liveness = str(surface or "").strip().lower() == "desktop"
try:
from hermes_cli.active_sessions import try_acquire_active_session
@@ -645,10 +660,16 @@ def _claim_active_session_slot(
surface=surface,
config=_load_cfg(),
metadata={"live_session_id": live_session_id},
+ registry_home=profile_home,
+ track_liveness=track_liveness,
)
except Exception as exc:
logger.warning("Failed to claim active session slot: %s", exc)
- return None, None
+ return (
+ (None, _SESSION_OWNERSHIP_UNAVAILABLE)
+ if track_liveness
+ else (None, None)
+ )
def _ensure_active_session_slot(sid: str, session: dict) -> str | None:
@@ -671,6 +692,7 @@ def _ensure_active_session_slot(sid: str, session: dict) -> str | None:
str(session.get("session_key") or ""),
live_session_id=sid,
surface=_session_source(session),
+ profile_home=session.get("profile_home"),
)
if limit_message is not None:
return limit_message
@@ -678,16 +700,89 @@ def _ensure_active_session_slot(sid: str, session: dict) -> str | None:
return None
-def _release_active_session_slot(session: dict | None) -> None:
+def _release_active_session_lease(lease) -> bool:
+ if lease is None:
+ return True
+ attempts = 3 if getattr(lease, "track_liveness", False) else 1
+ for attempt in range(attempts):
+ try:
+ lease.release()
+ break
+ except Exception:
+ if attempt + 1 >= attempts:
+ logger.warning("Failed to release active session slot", exc_info=True)
+ return False
+ time.sleep(0.05 * (attempt + 1))
+ released = getattr(lease, "released", True)
+ enabled = getattr(lease, "enabled", True)
+ return bool(released or not enabled)
+
+
+def _release_active_session_slot(session: dict | None) -> bool:
if not session:
+ return True
+ lease = session.get("active_session_lease")
+ if _release_active_session_lease(lease):
+ if session.get("active_session_lease") is lease:
+ session.pop("active_session_lease", None)
+ return True
+ return False
+
+
+def _other_runtime_lease_guard(session_id: str, session: dict):
+ """Release this runtime and lock sibling ownership through the DB write."""
+ lease = session.get("active_session_lease")
+ try:
+ from hermes_cli.active_sessions import (
+ active_session_liveness_guard,
+ release_active_session_liveness_guard,
+ )
+ except Exception as exc:
+ logger.warning(
+ "Failed to load active session ownership guard; preserving session %s: %s",
+ session_id,
+ exc,
+ )
+ yield True
return
- lease = session.pop("active_session_lease", None)
- if lease is None:
+
+ last_error: Exception | None = None
+ stack = contextlib.ExitStack()
+ for attempt in range(3):
+ try:
+ if lease is not None and getattr(lease, "enabled", False):
+ guard = release_active_session_liveness_guard(lease, session_id)
+ else:
+ guard = active_session_liveness_guard(
+ session_id, registry_home=session.get("profile_home")
+ )
+ active = stack.enter_context(guard)
+ break
+ except Exception as exc:
+ stack.close()
+ stack = contextlib.ExitStack()
+ last_error = exc
+ if attempt < 2:
+ time.sleep(0.05 * (attempt + 1))
+ else:
+ logger.warning(
+ "Failed to inspect active session leases; preserving session %s: %s",
+ session_id,
+ last_error,
+ )
+ yield True
return
try:
- lease.release()
- except Exception:
- logger.debug("Failed to release active session slot", exc_info=True)
+ yield active
+ finally:
+ stack.close()
+ if (
+ lease is not None
+ and getattr(lease, "released", False)
+ and session.get("active_session_lease") is lease
+ ):
+ session.pop("active_session_lease", None)
def _transfer_active_session_slot(
@@ -713,6 +808,9 @@ def _transfer_active_session_slot(
except Exception:
logger.debug("Failed to transfer active session slot", exc_info=True)
+ if getattr(lease, "track_liveness", False):
+ return False
+
# Fallback: the in-place transfer could not move the lease (entry pruned /
# pid-check transiently failed). Reserve the new slot BEFORE releasing the
# old one, so a concurrent gateway at the session cap cannot grab the freed
@@ -722,6 +820,7 @@ def _transfer_active_session_slot(
new_session_id,
live_session_id=sid,
surface=_session_source(session),
+ profile_home=session.get("profile_home"),
)
if new_lease is not None:
old_lease = session.pop("active_session_lease", None)
@@ -796,7 +895,14 @@ def _finalize_session(session: dict | None, end_reason: str = "tui_close") -> No
if history_ready is not None and not history_ready.is_set():
session["resume_history_error"] = "session resume cancelled"
history_ready.set()
- _release_active_session_slot(session)
+ _desktop_automatic_cleanup = bool(
+ end_reason in _AUTOMATIC_SESSION_END_REASONS
+ and _session_source(session).strip().lower() == "desktop"
+ )
+ # Automatic Desktop cleanup removes its lease inside the lock-held lifecycle
+ # guard below. Explicit close and non-Desktop paths keep force/end semantics.
+ if not _desktop_automatic_cleanup:
+ _release_active_session_slot(session)
stop_event = session.get("_notif_stop")
if stop_event is not None:
stop_event.set()
@@ -864,27 +970,42 @@ def _finalize_session(session: dict | None, end_reason: str = "tui_close") -> No
# Use session_id (from agent.session_id) not session_key — after compression,
# session_key may be stale (the ended parent) while session_id is the live
# continuation. Fix for #20001.
- _tui_owns_lifecycle = True
- if session_id:
- try:
- # End the row in the *session's* profile state.db (app-global
- # remote mode), not the launch profile's shared handle.
- with _session_db(session) as db:
- if db is not None:
- # Don't end gateway-originated sessions — the gateway owns
- # their lifecycle. The TUI is a viewer, not the owner.
- # Ending a gateway session in state.db triggers a Groundhog
- # Day routing loop: the gateway's #54878 self-heal detects
- # the stale entry, recovers to the parent session, context
- # compression splits back to the reaped child, and the cycle
- # repeats on every inbound message. (#60609)
- row = db.get_session(session_id)
- source = (row or {}).get("source", "")
- _tui_owns_lifecycle = not _is_gateway_owned_source(source)
- if _tui_owns_lifecycle:
- db.end_session(session_id, end_reason)
- except Exception:
- pass
+ if _desktop_automatic_cleanup and not session_id:
+ _release_active_session_slot(session)
+ _lifecycle_guard = (
+ _other_runtime_lease_guard(session_id, session)
+ if _desktop_automatic_cleanup and session_id
+ else contextlib.nullcontext(False)
+ )
+ with _lifecycle_guard as _other_runtime_owns_lifecycle:
+ _tui_owns_lifecycle = not _other_runtime_owns_lifecycle
+ if _other_runtime_owns_lifecycle:
+ logger.info(
+ "Preserving session %s during %s: another backend owns an active lease",
+ session_id,
+ end_reason,
+ )
+ if session_id:
+ try:
+ # End the row in the *session's* profile state.db (app-global
+ # remote mode), not the launch profile's shared handle.
+ with _session_db(session) as db:
+ if db is not None:
+ # Don't end gateway-originated sessions — the gateway owns
+ # their lifecycle. The TUI is a viewer, not the owner.
+ # Ending a gateway session in state.db triggers a Groundhog
+ # Day routing loop: the gateway's #54878 self-heal detects
+ # the stale entry, recovers to the parent session, context
+ # compression splits back to the reaped child, and the cycle
+ # repeats on every inbound message. (#60609)
+ row = db.get_session(session_id)
+ source = (row or {}).get("source", "")
+ if _is_gateway_owned_source(source):
+ _tui_owns_lifecycle = False
+ elif _tui_owns_lifecycle:
+ db.end_session(session_id, end_reason)
+ except Exception:
+ pass
# A session's in-flight async delegations end WITH the session (#55578):
# once nobody owns the return address, a still-running background subagent