Skip to content

The agent that grows with you

fix: legacy serve turns refuse sessions the gateway's durable ledger still holds

Tekniumec5ee66b645f
diff --git a/tests/tui_gateway/test_legacy_turn_canonical_barrier.py b/tests/tui_gateway/test_legacy_turn_canonical_barrier.py
new file mode 100644
index 00000000000..ce1437ef992
--- /dev/null
+++ b/tests/tui_gateway/test_legacy_turn_canonical_barrier.py
@@ -0,0 +1,62 @@
+"""Standalone ``serve`` (no session authority) must not run a legacy turn past the gateway's
+durable ledger: an ``unknown`` admission is never replayed, queued input runs in FIFO order."""
+
+import pytest
+
+from hermes_state import SessionDB
+from hermes_state_runtime import (
+ admit_session_input, begin_runtime_epoch, claim_session_input, list_session_admissions,
+ recover_session_inputs, resolve_unknown_session_input,
+)
+from tui_gateway import server
+
+
+class _InlineThread:
+ def __init__(self, target, **_kwargs):
+ self.target = target
+
+ def start(self):
+ self.target()
+
+
[email protected]("ledger", ["unknown", "queued"])
+def test_legacy_submit_refuses_while_canonical_ledger_holds_work(monkeypatch, tmp_path, ledger):
+ db = SessionDB(db_path=tmp_path / "state.db")
+ monkeypatch.setattr(server, "_get_db", lambda: db)
+ for name in ("_schedule_agent_build", "_schedule_session_cap_enforcement", "_register_session_cwd",
+ "_start_agent_build"):
+ monkeypatch.setattr(server, name, lambda *_a, **_k: None)
+ monkeypatch.setattr(server, "_restart_completed_failed_agent_build", lambda *_a: False)
+ turns = []
+ monkeypatch.setattr(server, "_run_after_agent_ready", lambda *a: turns.append(a[1]))
+ monkeypatch.setattr(server.threading, "Thread", _InlineThread)
+ created = server.handle_request({"id": "c", "method": "session.create", "params": {"source": "desktop"}})
+ sid, key = created["result"]["session_id"], created["result"]["stored_session_id"]
+ db.create_session(key, "cli")
+ first = begin_runtime_epoch(db, instance_id="gateway-1")
+ admit_session_input(db, epoch=first, principal_id="owner", session_id=key, request_id="r1",
+ payload={"text": "lost?"})
+ epoch = first
+ if ledger == "unknown":
+ claim_session_input(db, epoch=first, session_id=key)
+ epoch = begin_runtime_epoch(db, instance_id="gateway-2")
+ recover_session_inputs(db, epoch=epoch)
+
+ def submit():
+ return server.handle_request({"id": "p", "method": "prompt.submit", "params": {"session_id": sid, "text": "hi"}})
+
+ try:
+ refused = submit()
+ assert refused["error"]["code"] == 4090, refused
+ assert refused["error"]["data"] == {"reason": "SESSION_NOT_OWNED"}
+ assert turns == [] and db.get_messages_as_conversation(key) == []
+ if ledger == "unknown":
+ # Once the operator discards the lost turn through the gateway the barrier lifts.
+ (row,) = list_session_admissions(db, session_id=key)
+ resolve_unknown_session_input(db, epoch=epoch, admission_id=row["admission_id"],
+ generation=row["generation"])
+ assert submit()["result"]["status"] == "streaming"
+ assert turns == [sid]
+ finally:
+ server._sessions.pop(sid, None)
+ db.close()
diff --git a/tui_gateway/session_lifecycle.py b/tui_gateway/session_lifecycle.py
index 8092c5f0e47..a24b606e6d8 100644
--- a/tui_gateway/session_lifecycle.py
+++ b/tui_gateway/session_lifecycle.py
@@ -123,6 +123,8 @@ def _ensure_active_session_slot(sid: str, session: dict) -> str | None:
do NOT claim: tile paints, reconnect-resumes and abandoned drafts would hold invisible slots (no DB row)
that starve the messaging gateway sharing the cap. Anything holding a slot must be user-visible. An
inert borrowed token (see _install_borrowed_lease) also lands here: present = slot held upstream."""
+ if (canonical := _canonical_ledger_refusal(session)) is not None:
+ return canonical
if session.get("active_session_lease") is not None:
return None
key = str(session.get("session_key") or "")
@@ -137,6 +139,43 @@ def _ensure_active_session_slot(sid: str, session: dict) -> str | None:
return limit_message
+_CANONICAL_PENDING_SQL = """SELECT status FROM session_admissions WHERE target_session_id=? AND status!='terminal'
+ UNION ALL SELECT status FROM worker_executions WHERE session_id=? AND status!='terminal' LIMIT 1"""
+
+
+def _canonical_ledger_refusal(session: dict):
+ """Refusal when the gateway's durable ledger still holds work for this stored session, else None.
+
+ The registry lease only fences other legacy backends. A session a gateway once owned can carry
+ an ``unknown`` admission (outcome lost across an owner restart: never replayed, only Discard
+ resolves it), queued input or a running worker; a legacy turn would run past that barrier
+ and write the transcript beside the canonical FIFO. Checked on every turn, not only at the
+ first claim, because a gateway may admit work while this backend still holds its lease."""
+ import sqlite3
+ from hermes_cli.active_sessions import (
+ ActiveSessionRefusal, SESSION_COORDINATION_UNAVAILABLE, SESSION_NOT_OWNED)
+ key = str(session.get("session_key") or "")
+ if not key:
+ return None
+ try:
+ with _session_db(session) as db:
+ read_ctx = getattr(db, "_read_ctx", None)
+ if read_ctx is None:
+ return None
+ with read_ctx() as conn:
+ row = next(iter(conn.execute(_CANONICAL_PENDING_SQL, (key, key))), None)
+ except sqlite3.Error:
+ logger.warning("canonical ledger read failed for %s", key, exc_info=True)
+ return ActiveSessionRefusal(_SESSION_OWNERSHIP_UNAVAILABLE, SESSION_COORDINATION_UNAVAILABLE)
+ if row is None:
+ return None
+ logger.info("Refusing legacy turn for %s: canonical ledger holds %s work", key, row[0])
+ return ActiveSessionRefusal(
+ f"Session {key} has {'outcome-unknown' if row[0] == 'unknown' else 'pending'} work in the gateway's "
+ "durable queue. Resume it through the gateway (hermes chat --resume, Desktop or the TUI) to "
+ "resolve it; nothing was run here.", SESSION_NOT_OWNED)
+
+
def _attach_lease(session: dict, lease) -> None:
session["active_session_lease"] = lease
session.pop("_lease_taken_over", None) # owning again: its finalize ends the row like any owner