From a5f0fbb26235f8517b153cf26b7db2e24ddc476c Mon Sep 17 00:00:00 2001 From: Futahua <226466458+Futahua@users.noreply.github.com> Date: Tue, 25 Aug 2026 15:49:07 +0700 Subject: [PATCH] fix(sessions): per-session exclusivity is correctness, not a capacity policy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cherry-picked from PR #94595 (author: Futahua) onto current main, with the maintainer-review revision points folded in during the rebase: - the lease engages UNCONDITIONALLY: try_acquire_active_session no longer returns a disabled no-op lease when max_concurrent_sessions is unset; the concurrency cap stays an orthogonal, optional policy checked second - ownership uncertainty fails CLOSED (SESSION_COORDINATION_UNAVAILABLE) instead of degrading to an untracked go-ahead: a corrupt/unreadable registry must not be collapsed into 'no owner exists' (review blocker 2) - the ownership admission sits at the _run_prompt_submit chokepoint that EVERY fresh turn source crosses, and crash auto-continue acquires (or bails) BEFORE emitting message.start — closing the #94778 bypass where backend B's auto-continue ran a duplicate turn while backend A was live (review blocker 1) - the TUI gateway claim helper fails closed on claim exceptions for every surface, not just desktop - CLI and messaging-gateway call sites pass live_session_id metadata so the (pid, live id) re-entrancy identity protects them from self-fencing on a leaked lease Co-authored-by: teknium1 --- cli.py | 4 + gateway/run.py | 6 + hermes_cli/active_sessions.py | 214 ++++++++++++++++++---- tests/test_active_session_exclusivity.py | 224 +++++++++++++++++++++++ tests/test_tui_gateway_server.py | 6 + tui_gateway/methods_prompt.py | 19 +- tui_gateway/server.py | 63 ++++++- 7 files changed, 492 insertions(+), 44 deletions(-) create mode 100644 tests/test_active_session_exclusivity.py diff --git a/cli.py b/cli.py index 3e69298bdc..0b96e16252 100644 --- a/cli.py +++ b/cli.py @@ -5833,6 +5833,10 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin): session_id=self.session_id, surface=surface, config=self.config, + # Writer identity for re-entrancy (#94595): a re-claim by this + # same process for this same session replaces its own entry + # instead of fencing itself out. + metadata={"live_session_id": str(self.session_id)}, ) except Exception as exc: logger.warning("Failed to claim active session slot: %s", exc) diff --git a/gateway/run.py b/gateway/run.py index 8264eedc47..410aa14a14 100644 --- a/gateway/run.py +++ b/gateway/run.py @@ -10665,6 +10665,12 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew "platform": platform, "chat_id": getattr(source, "chat_id", "") or "", "user_id": getattr(source, "user_id", "") or "", + # Writer identity for re-entrancy (#94595): if this + # process leaks a lease for this session (exception path + # skipped release), the next turn re-acquires its own + # entry instead of being fenced out of it forever — + # pruning only reclaims entries whose PROCESS died. + "live_session_id": str(session_key), }, ) except Exception as exc: diff --git a/hermes_cli/active_sessions.py b/hermes_cli/active_sessions.py index e1cd8b0307..6d5fb8d0bb 100644 --- a/hermes_cli/active_sessions.py +++ b/hermes_cli/active_sessions.py @@ -124,6 +124,83 @@ def _registry_home(registry_home: str | Path | None = None) -> Path: return Path(registry_home) if registry_home is not None else Path(get_hermes_home()) +# WHY A REFUSAL IS REFUSED, in a form a caller can branch on. +# +# The two refusals mean opposite things to an automated client. Capacity is +# "the machine is busy, come back later". Ownership is "this specific session +# has a live owner, and writing to it would interleave with theirs". +# +# Callers used to have only the human-readable message, so anything that needed +# to DECIDE had to match prose -- which silently changes meaning whenever the +# wording is improved. The reason is the contract; the message is for people. +SESSION_NOT_OWNED = "SESSION_NOT_OWNED" +MAX_CONCURRENT_SESSIONS = "MAX_CONCURRENT_SESSIONS" +# Ownership could not be PROVEN either way: the registry was unreadable or +# corrupt. Distinct from SESSION_NOT_OWNED on purpose -- "someone else owns +# this" and "I cannot tell who owns this" call for different operator action, +# and collapsing the second into a silent go-ahead is exactly the fail-open +# hole that let two writers share one session (#94595 review, blocker 2). +SESSION_COORDINATION_UNAVAILABLE = "SESSION_COORDINATION_UNAVAILABLE" + +# Advertised through the gateway so a client can tell a build that enforces +# per-session exclusivity from one that does not. +# +# A module constant rather than a config flag, deliberately: it is true because +# try_acquire_active_session below performs the check atomically, so it cannot +# be turned on by an operator who has not got the enforcement, and cannot drift +# out of step with it without this file changing. +PER_SESSION_EXCLUSIVE_SUBMIT = True + + +class ActiveSessionRefusal(str): + """A refusal message that also carries a machine-readable ``reason``. + + A ``str`` subclass so every existing caller keeps working untouched -- they + format it, hand it back as a JSON-RPC message, or just test it for None -- + while a caller that must act on WHICH refusal happened reads ``.reason`` + instead of matching the wording. + """ + + reason: str + + def __new__(cls, message: str, reason: str) -> "ActiveSessionRefusal": + obj = super().__new__(cls, message) + obj.reason = reason + return obj + + +def _is_same_writer(entry: dict[str, Any], metadata: Optional[dict[str, Any]]) -> bool: + """True when an existing lease belongs to the very caller now re-acquiring it. + + Both halves are required. A pid alone would let two live sessions in one + process steal each other's lease -- which is a real hazard, since each holds + its own snapshot of the transcript. A live session id alone would let another + process with a coincidentally equal id do the same. + """ + try: + if int(entry.get("pid") or -1) != os.getpid(): + return False + except (TypeError, ValueError): + return False + existing_live = str((entry.get("metadata") or {}).get("live_session_id") or "") + incoming_live = str((metadata or {}).get("live_session_id") or "") + if not existing_live or not incoming_live: + return False + return existing_live == incoming_live + + +def session_already_owned_message(session_id: str, entry: dict[str, Any]) -> str: + surface = str(entry.get("surface") or "another surface") + pid = entry.get("pid") + started = _optional_float(entry.get("started_at")) + age = f", running {format_age(time.time() - started)}" if started else "" + return ( + f"Session {session_id} already has a live owner ({surface}, pid {pid}{age}). " + "Only one surface at a time may run a session, because a second one would " + "reason from a transcript that does not include the first one's work." + ) + + def _state_dir(registry_home: str | Path | None = None) -> Path: return _registry_home(registry_home) / "runtime" @@ -445,25 +522,27 @@ def try_acquire_active_session( ) -> tuple[Optional[ActiveSessionLease], Optional[str]]: """Acquire an active-session slot. - Returns ``(lease, None)`` on success. When the cap is disabled, the lease is - a no-op object so callers can unconditionally call ``release()`` unless - ``track_liveness`` is true. Liveness tracking keeps a real lease without - imposing a concurrency cap; ``registry_home`` lets profile-scoped backends - share the owning profile's registry even when launched from another home. + Per-session exclusivity is CORRECTNESS and is enforced unconditionally: + at most one live owner may run a given stored session, whether or not an + operator configured ``max_concurrent_sessions`` (#94595). The concurrency + cap remains a resource POLICY and applies only when configured. Liveness + tracking keeps richer desktop lifecycle semantics; ``registry_home`` lets + profile-scoped backends share the owning profile's registry even when + launched from another home. + + Returns ``(lease, None)`` on success and ``(None, refusal)`` otherwise, + where ``refusal`` is an :class:`ActiveSessionRefusal` carrying a + machine-readable ``reason``. Ownership uncertainty fails CLOSED: when the + registry cannot be read, the caller gets ``SESSION_COORDINATION_UNAVAILABLE`` + rather than a silent go-ahead that could reopen the double-writer state. """ max_sessions = resolve_max_concurrent_sessions(config) lease_id = uuid.uuid4().hex - if max_sessions is None and not track_liveness: - return ActiveSessionLease( - lease_id=lease_id, - session_id=session_id, - surface=surface, - enabled=False, - ), None + key = str(session_id or "") entry = _lease_entry( lease_id=lease_id, - session_id=str(session_id), + session_id=key, surface=str(surface), metadata=metadata, track_liveness=track_liveness, @@ -477,39 +556,98 @@ def try_acquire_active_session( except ActiveSessionRegistryError: if track_liveness: raise + # A capacity cap could afford to degrade open -- worst case, more + # sessions than the operator wanted. Exclusivity cannot: "could not + # prove ownership" must never be collapsed into "no owner exists", + # because that silently reopens the exact double-writer state this + # fence guarantees against. Refuse, and say which file to fix. logger.warning( - "Active-session registry is unavailable; allowing an " - "untracked session without overwriting it" + "Active-session registry is unavailable; refusing the session " + "rather than risking a concurrent writer" + ) + return None, ActiveSessionRefusal( + ( + "Hermes could not read the active-session registry at " + f"{state_path}, so it cannot prove this session has no other " + "live owner. Fix or remove that file and try again." + ), + SESSION_COORDINATION_UNAVAILABLE, ) - return ActiveSessionLease( - lease_id=lease_id, - session_id=session_id, - surface=surface, - enabled=False, - state_path=state_path, - lock_path=lock_path, - ), None pruned = len(raw_entries) - len(entries) if pruned: logger.info("Pruned %d stale active session lease(s)", pruned) - active_count = len(entries) - if max_sessions is not None and active_count >= max_sessions: - _write_entries(state_path, entries) - logger.info( - "Active session limit reached: active=%d max=%d surface=%s", - active_count, - max_sessions, - surface, - ) - return None, active_session_limit_message( - active_count, max_sessions, entries - ) + + # Correctness first, and under the same lock that just pruned the dead + # owners -- so an owner that died is never mistaken for one that is + # running, and a live one is never overlooked. + # + # An empty key is exempt: a session with no stored id yet cannot collide + # with another, and treating "" as an identity would make every unsaved + # draft exclude every other one. + if key: + for index, existing in enumerate(entries): + if str(existing.get("session_id") or "") != key: + continue + + # THE SAME WRITER IS NOT A SECOND WRITER. + # + # A live session that lost its lease reference -- its record was + # rebuilt in place, so the object holding the lease is unreachable + # while the session itself is still the one being driven -- would + # otherwise be fenced out of its own session by its own leak, and + # permanently: pruning only removes entries whose PROCESS is dead, + # and this process is very much alive. + # + # Identity here is (pid, live session id). Two processes never + # match, because their pids differ. Two live sessions inside one + # process never match, because their live ids differ. Only the + # exact same writer re-acquiring its own session matches, and that + # is re-entrancy rather than a concurrent writer. + if _is_same_writer(existing, metadata): + entries[index] = entry + _write_entries(state_path, entries) + return ActiveSessionLease( + lease_id=lease_id, + session_id=key, + surface=str(surface), + state_path=state_path, + lock_path=lock_path, + track_liveness=track_liveness, + ), None + + _write_entries(state_path, entries) + logger.info( + "Refused active session %s: already held by pid=%s surface=%s", + key, + existing.get("pid"), + existing.get("surface"), + ) + return None, ActiveSessionRefusal( + session_already_owned_message(key, existing), + SESSION_NOT_OWNED, + ) + + # Capacity second, and only when an operator asked for one. + if max_sessions is not None: + active_count = len(entries) + if active_count >= max_sessions: + _write_entries(state_path, entries) + logger.info( + "Active session limit reached: active=%d max=%d surface=%s", + active_count, + max_sessions, + surface, + ) + return None, ActiveSessionRefusal( + active_session_limit_message(active_count, max_sessions, entries), + MAX_CONCURRENT_SESSIONS, + ) entries.append(entry) _write_entries(state_path, entries) return ActiveSessionLease( lease_id=lease_id, - session_id=str(session_id), + session_id=key, surface=str(surface), state_path=state_path, lock_path=lock_path, @@ -620,8 +758,8 @@ def release_orphaned_leases(live_lease_ids: set[str]) -> int: """ pid = os.getpid() state_path = _state_path() - # With the cap disabled the registry is never written, so don't take a lock - # (or create its file) on the idle-reaper tick for the majority of installs. + # No registry file yet means no leases have ever been written under this + # home — don't take a lock (or create its file) on the idle-reaper tick. if not state_path.exists(): return 0 with _FileLock(_lock_path()): diff --git a/tests/test_active_session_exclusivity.py b/tests/test_active_session_exclusivity.py new file mode 100644 index 0000000000..20860fdc87 --- /dev/null +++ b/tests/test_active_session_exclusivity.py @@ -0,0 +1,224 @@ +"""Per-session exclusivity in the active-session registry. + +The property under test is a correctness one, and it is separate from capacity: +AT MOST ONE LIVE OWNER MAY RUN A GIVEN STORED SESSION, whether or not an +operator configured ``max_concurrent_sessions``. + +It matters because a second owner does not merely duplicate work. It loads its +own snapshot of the transcript, reasons from a history that does not include the +first owner's in-flight turn, and then appends to the same stored session -- so +the conversation ends up containing two replies that never saw each other. That +was observed in practice before this fence existed: two gateway processes +resumed one stored session, neither was refused, and both wrote to it. + +The old behaviour is worth stating precisely, because it looked deliberate: with +no cap configured, ``try_acquire_active_session`` returned a disabled no-op lease +and never touched the registry at all. Capacity being unconfigured was silently +treated as "concurrent writers to one session are fine", which it never is. +""" + +import itertools +import os + +import pytest + +from hermes_cli.active_sessions import ( + MAX_CONCURRENT_SESSIONS, + PER_SESSION_EXCLUSIVE_SUBMIT, + SESSION_NOT_OWNED, + active_session_registry_snapshot, + release_active_session, + try_acquire_active_session, +) + + +@pytest.fixture(autouse=True) +def _isolated_registry(tmp_path, monkeypatch): + monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes")) + + +_owner_seq = itertools.count() + + +def acquire(session_id, config=None, surface="tui", live_id=None): + """Acquire as a DISTINCT owner unless a live id is given explicitly. + + The live session id is half of writer identity, so a helper that reused one + would model every acquisition as the same tab re-acquiring its own session -- + which is re-entrancy, not the concurrent-writer case these tests are about. + Distinct by default; shared only where a test means it. + """ + return try_acquire_active_session( + session_id=session_id, + surface=surface, + config=config if config is not None else {}, + metadata={"live_session_id": live_id or f"live-{next(_owner_seq)}"}, + ) + + +def test_no_cap_configured_still_fences_one_session(): + """The case the old code got wrong, and the reason this fence exists. + + ``max_concurrent_sessions`` unset must not mean "anyone may write to any + session at any time". + """ + lease_a, refused = acquire("S") + assert lease_a is not None and refused is None + + lease_b, refusal = acquire("S") + assert lease_b is None, "a second live owner of one session must be refused" + assert refusal.reason == SESSION_NOT_OWNED + # The message is for a person; the reason is the contract. Both are present. + assert "S" in str(refusal) + + # And exactly one holder is recorded -- a refusal must not leave a slot behind. + assert len(active_session_registry_snapshot()) == 1 + + +def test_different_sessions_still_run_concurrently(): + """Exclusivity is PER SESSION. It is not a global mutex. + + Getting this wrong would be worse than the bug: it would serialise every + conversation on the machine behind whichever one started first. + """ + lease_1, refused_1 = acquire("S1") + lease_2, refused_2 = acquire("S2") + assert lease_1 is not None and refused_1 is None + assert lease_2 is not None and refused_2 is None + assert len(active_session_registry_snapshot()) == 2 + + +def test_global_capacity_still_applies_independently(): + """The capacity policy is untouched, and refuses for its own reason.""" + config = {"max_concurrent_sessions": 2} + assert acquire("S1", config)[0] is not None + assert acquire("S2", config)[0] is not None + + lease, refusal = acquire("S3", config) + assert lease is None + assert refusal.reason == MAX_CONCURRENT_SESSIONS, ( + "a capacity refusal must not be reported as an ownership refusal: a client " + "retries one and must not retry the other the same way" + ) + assert "active session limit (2/2)" in str(refusal) + + +def test_capacity_and_exclusivity_are_not_the_same_switch(): + """Both refusals exist under a configured cap, and say different things.""" + config = {"max_concurrent_sessions": 4} + assert acquire("S", config)[0] is not None + lease, refusal = acquire("S", config) + assert lease is None + assert refusal.reason == SESSION_NOT_OWNED, ( + "with capacity to spare, the refusal can only be about ownership" + ) + + +def test_a_dead_owner_is_pruned_and_a_successor_may_acquire(): + """A crashed owner must not hold a session hostage forever. + + Written as a registry entry for a pid that cannot exist, because that is what + a crashed process leaves behind -- the pruning path is what makes the fence + survivable rather than a way to lock yourself out permanently. + """ + lease, _ = acquire("S") + assert lease is not None + + # Rewrite the holder as a process that is gone. + from hermes_cli.active_sessions import _read_entries, _state_path, _write_entries + + entries = _read_entries(_state_path()) + assert len(entries) == 1 + entries[0]["pid"] = 0x7FFFFFFE + entries[0]["process_start_time"] = 1.0 + _write_entries(_state_path(), entries) + + successor, refusal = acquire("S") + assert successor is not None, f"a dead owner must not block a successor: {refusal}" + assert len(active_session_registry_snapshot()) == 1 + + +def test_a_recycled_pid_does_not_keep_a_lease_alive(): + """Identity is (pid, process start time), not a pid. + + A pid alone is not identity -- the number is reused, and on a busy machine it + is reused quickly. An entry claiming OUR pid but a start time we never had is + a dead owner whose number was handed to somebody else. + """ + lease, _ = acquire("S") + assert lease is not None + + from hermes_cli.active_sessions import _read_entries, _state_path, _write_entries + + entries = _read_entries(_state_path()) + entries[0]["pid"] = os.getpid() + entries[0]["process_start_time"] = 1.0 # not when this process started + _write_entries(_state_path(), entries) + + successor, refusal = acquire("S") + assert successor is not None, f"a recycled pid must not hold a session: {refusal}" + + +def test_release_lets_the_next_owner_in(): + """The ordinary handoff: A finishes, B proceeds.""" + lease_a, _ = acquire("S") + assert lease_a is not None + assert acquire("S")[0] is None + + release_active_session(lease_a) + assert active_session_registry_snapshot() == [] + + lease_b, refusal = acquire("S") + assert lease_b is not None, f"after release the session must be acquirable: {refusal}" + + +def test_release_is_idempotent_and_only_drops_its_own_lease(): + """Releasing twice must not free somebody else's session.""" + lease_a, _ = acquire("S1") + lease_b, _ = acquire("S2") + release_active_session(lease_a) + release_active_session(lease_a) + held = {entry.get("session_id") for entry in active_session_registry_snapshot()} + assert held == {"S2"} + assert lease_b is not None + + +def test_a_session_with_no_stored_id_is_exempt(): + """An unsaved draft has no identity, and must not exclude every other one. + + Treating "" as a session id would make the first unsaved composer on the + machine refuse every other one -- a fence that fires on sessions that cannot + collide by construction. + """ + assert acquire("")[0] is not None + assert acquire("")[0] is not None, "empty ids do not collide with each other" + + +def test_the_same_live_session_may_re_acquire_its_own_lease(): + """Re-entrancy, and the reason it is not a hole in the fence. + + A live session whose record was rebuilt in place loses its reference to the + lease it already holds. Without this it would be fenced out of its own + session by its own leak -- permanently, because pruning only removes entries + whose PROCESS is dead and this one is alive. + + Identity is (pid, live session id): another process differs by pid, another + tab in this process differs by live id. Only the same writer matches. + """ + lease_a, _ = acquire("S", live_id="tab-1") + assert lease_a is not None + + again, refusal = acquire("S", live_id="tab-1") + assert again is not None, f"a writer must not be fenced out by its own leak: {refusal}" + assert len(active_session_registry_snapshot()) == 1, "and it must not double-book" + + # A DIFFERENT live session in the same process is still a second writer: each + # holds its own snapshot of the transcript, so the hazard is unchanged. + other, refusal = acquire("S", live_id="tab-2") + assert other is None + assert refusal.reason == SESSION_NOT_OWNED + + +def test_the_capability_is_advertised_because_the_check_exists(): + """The flag lives beside the enforcement, so it cannot drift from it.""" + assert PER_SESSION_EXCLUSIVE_SUBMIT is True diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.py index 78a3b82f4c..1eaf356c42 100644 --- a/tests/test_tui_gateway_server.py +++ b/tests/test_tui_gateway_server.py @@ -12987,6 +12987,11 @@ def test_prompt_submit_row_id_accepts_full_lineage_ordinal(monkeypatch): assert resp.get("error") is None, f"got error: {resp.get('error')}" assert sess["history"] == tip_history[:2] finally: + # Release the slot the first turn claimed, as _finalize_session does in + # production. Popping alone leaks the lease, and the second session below + # uses the same session_key -- so without this the test fences itself out + # of its own key and never reaches the mismatch it is checking. + server._release_active_session_slot(sess) server._sessions.pop("lineage-row-sid", None) # A genuinely stale ordinal (matches neither the tip space nor the @@ -13013,6 +13018,7 @@ def test_prompt_submit_row_id_accepts_full_lineage_ordinal(monkeypatch): assert resp.get("error") is not None assert resp["error"]["code"] == 4030 finally: + server._release_active_session_slot(sess2) server._sessions.pop("lineage-row-sid-2", None) diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.py index 3525ffcfdd..ee411eb7a0 100644 --- a/tui_gateway/methods_prompt.py +++ b/tui_gateway/methods_prompt.py @@ -424,7 +424,24 @@ def _(rid, params: dict) -> dict: + "Update Hermes Desktop to continue it.", ) if (limit_message := _ensure_active_session_slot(sid, session)) is not None: - return _err(rid, 4090, limit_message) + # The refusal reason travels as machine-readable data, not as prose. + # + # An automated client has to tell "the machine is at capacity, retry later" + # from "this session has a live owner, and your write would interleave with + # theirs". Those call for different behaviour, and a client that had to + # distinguish them by matching the message text would silently change + # behaviour the next time the wording improved. + # + # Refused HERE, before the busy-queue check, before _ensure_session_db_row + # and before _start_agent_build: no user row is persisted and no model turn + # begins, so a refusal leaves the session exactly as it was. + reason = getattr(limit_message, "reason", None) + return _err( + rid, + 4090, + str(limit_message), + {"reason": reason} if reason else None, + ) # Which desktop window this message was typed into. Rewritten on every # submit, because one session can be driven from the app window and the HUD # in turn: a stale "hud" would tell the model the user is still floating diff --git a/tui_gateway/server.py b/tui_gateway/server.py index 4e846e36e3..fabf3d3882 100644 --- a/tui_gateway/server.py +++ b/tui_gateway/server.py @@ -665,11 +665,12 @@ def _claim_active_session_slot( ) except Exception as exc: logger.warning("Failed to claim active session slot: %s", exc) - return ( - (None, _SESSION_OWNERSHIP_UNAVAILABLE) - if track_liveness - else (None, None) - ) + # Fail CLOSED regardless of surface: per-session exclusivity is a + # correctness guarantee (see PER_SESSION_EXCLUSIVE_SUBMIT), and a + # claim that errors out has NOT proven the session is unowned. + # Proceeding without a lease here is the silent double-writer hole + # flagged in the #94595 review (blocker 2). + return (None, _SESSION_OWNERSHIP_UNAVAILABLE) def _ensure_active_session_slot(sid: str, session: dict) -> str | None: @@ -9990,6 +9991,23 @@ def _maybe_schedule_auto_continue(sid: str, session: dict, session_key: str) -> return session["running"] = True session["last_active"] = time.time() + # Ownership admission BEFORE message.start: the interrupted-turn + # marker this continuation is recovering may have been written by a + # sibling backend that is still alive and mid-turn (#94778 — two + # backends share one HERMES_HOME; B resumes S while A runs it and + # sees A's fresh marker). Running the continuation anyway would be + # the double-writer this fence exists to prevent. Leave the marker: + # once the owner finishes or dies, a later resume retries. + if _ensure_active_session_slot(sid, session) is not None: + logger.info( + "auto-continue for %s refused: session has another live owner", + session_key, + ) + with session["history_lock"]: + session["running"] = False + session["_auto_continue_scheduled"] = False + return + with session["history_lock"]: # Hand this turn its own marker inputs (read back by # _run_prompt_submit): count the attempt so a crash during the # continuation trips the breaker, and re-record the ORIGINAL @@ -12740,6 +12758,22 @@ def _run_prompt_submit( queued_prompt_generation: int | None = None, terminal_callback: Callable[[dict[str, Any]], None] | None = None, ) -> bool: + # Ownership admission at the ONE chokepoint every fresh turn source must + # cross. prompt.submit already claims the slot in its RPC handler (so this + # is a no-op re-check there), but crash auto-continue, wake-ups and other + # synthesized turns call _run_prompt_submit directly — the exact bypass + # that let a second backend run a duplicate turn in #94778. When the + # session already holds its lease this is a cheap dict check. + if (ownership_refusal := _ensure_active_session_slot(sid, session)) is not None: + logger.info( + "Refusing turn for session %s at _run_prompt_submit: %s", + session.get("session_key") or sid, + getattr(ownership_refusal, "reason", None) or "refused", + ) + with session["history_lock"]: + session["running"] = False + _emit("error", sid, {"message": str(ownership_refusal)}) + return False with session["history_lock"]: if session.get("_closing"): session["running"] = False @@ -16975,6 +17009,25 @@ def _persist_wake_enabled(enabled: bool) -> bool: return False +@method("gateway.capabilities") +def _(rid, params: dict) -> dict: + """What guarantees THIS BUILD enforces, for a client that must not assume. + + An automated client cannot tell a gateway that fences concurrent writers to + one session from one that silently allows them -- both accept the same calls + and both answer prompt.submit the same way. It only finds out by corrupting a + conversation. So the guarantee is advertised, and a client that does not see + it advertised is expected to withhold rather than hope. + + Sourced from the module that performs the enforcement, never from config: a + capability an operator can switch on without also having the mechanism is + worse than no capability at all, because it is believed. + """ + from hermes_cli.active_sessions import PER_SESSION_EXCLUSIVE_SUBMIT + + return _ok(rid, {"per_session_exclusive_submit": bool(PER_SESSION_EXCLUSIVE_SUBMIT)}) + + @method("ping") def _(rid, params: dict) -> dict: """Cheapest possible liveness probe for the desktop client.