Skip to content

The agent that grows with you

refactor(gateway): session — _RouteDecision.schedule_reset, inline route checks, compact store/state/context comments

Teknium1239f383ba37
diff --git a/gateway/session.py b/gateway/session.py
index 64e852460a5..731e8910dc8 100644
--- a/gateway/session.py
+++ b/gateway/session.py
@@ -745,6 +745,12 @@ class _RouteDecision:
reset_had_activity: bool = False
prev_session_id: Optional[str] = None
+ def schedule_reset(self, reason: str, ended: "SessionEntry", had_activity: bool) -> None:
+ """Record that *ended* is auto-reset for *reason* (ends its row, seeds the successor)."""
+ self.reset_reason = reason
+ self.reset_had_activity = had_activity
+ self.prev_session_id = ended.session_id
+
class AsyncSessionStore:
"""Async boundary for the synchronous, thread-safe SessionStore."""
@@ -773,22 +779,20 @@ class SessionStore(
self.config = config
self._entries: Dict[str, SessionEntry] = {}
self._loaded = False
- # A fallback-only initial load must be reconciled with state.db once the handle recovers,
- # before a whole-index save can replace DB rows.
+ # A fallback-only initial load is reconciled with state.db once the handle recovers.
self._routing_db_loaded = False
self._routing_fallback_baseline: Optional[Dict[str, Any]] = None
- self._lock = threading.Lock()
- # Serializes whole-index persistence without holding ``_lock`` across SQLite/fsync.
- self._save_lock = threading.Lock()
+ self._lock = threading.Lock() # guards _entries / _loaded only
+ self._save_lock = threading.Lock() # whole-index persistence, never held with _lock
+ # Fast (single-entry) and full saves share one generation counter so they are totally
+ # ordered; _fast_persisted_entries: key -> (revision, entry_json) since the last rewrite.
self._routing_generation = 0
self._persisted_routing_generation = 0
- # Single-entry upserts since the last full rewrite: key -> (revision, entry_json).
- # Revisions share _routing_generation so fast and full saves are totally ordered.
self._fast_persisted_entries: Dict[str, tuple[int, str]] = {}
self._inflight_lock = threading.Lock()
self._inflight_sessions: Dict[str, _SessionFlight] = {}
- # An unscoped legacy Slack key is claimed once per process so two workspaces cannot both
- # revive the same session.
+ # An unscoped legacy Slack key is claimed once per process (two workspaces must not both
+ # revive one session).
self._legacy_slack_claim_lock = threading.Lock()
self._claimed_legacy_slack_keys: set[str] = set()
self._transcript_retry_lock = threading.Lock()
@@ -799,27 +803,25 @@ class SessionStore(
self._transcript_append_failures: Dict[str, int] = {}
self._fts_rebuild_attempted = False
self._has_active_processes_fn = has_active_processes_fn
- # Keep the legacy sessions.json mirror (disable via gateway.write_sessions_json).
self._write_sessions_json = bool(getattr(config, "write_sessions_json", True))
- # SQLite handles are cached per path and resolved through the ``_db`` property, never
- # bound once here: a multiplexed gateway serves every profile from ONE process and a handle
- # frozen to the root home would land every profile's rows in the root state.db.
+ # SQLite handles are cached per path and resolved through ``_db`` per call, never bound
+ # once: a multiplexed gateway serves every profile from ONE process and a handle frozen to
+ # the root home would land every profile's rows in the root state.db.
self._db_pinned = _DB_UNPINNED
self._db_handles: Dict[Path, Any] = {}
self._db_handles_lock = threading.Lock()
- # profile name -> HERMES_HOME; memoized so per-key store lookup is a dict hit.
- self._profile_home_cache: Dict[str, Optional[Path]] = {}
- # session_id -> owning key for ids proven but not yet published in ``_entries``
- # (a compression child row is written before its reroute is published).
+ self._profile_home_cache: Dict[str, Optional[Path]] = {} # profile -> HERMES_HOME (hits)
+ # session_id -> owning key for ids proven but not yet published in ``_entries`` (a
+ # compression child row is written before its reroute is published).
self._session_owner_hints: Dict[str, str] = {}
from gateway.session_db_recovery import RecoverableHandleCache
self._db_handle_cache = RecoverableHandleCache(
handles=self._db_handles, lock=self._db_handles_lock,
)
- # The routing index is one process-wide structure and needs exactly one home for its
- # lifetime: the gateway's own, captured before any profile scope exists (``_routing_db``).
+ # The routing index needs exactly one home for its lifetime: the gateway's own, captured
+ # before any profile scope exists (see ``_routing_db``).
try:
from hermes_constants import get_hermes_home
@@ -838,7 +840,7 @@ class SessionStore(
return value
def _has_active_processes_safe(self, session_key: str, *, context: str) -> bool:
- """Whether a session has active work, failing closed on registry errors."""
+ """Whether a session has active work, failing closed (True) on registry errors."""
if self._has_active_processes_fn is None:
return False
try:
@@ -851,11 +853,8 @@ class SessionStore(
return True
def has_any_sessions(self) -> bool:
- """Whether any session has ever been created (across all platforms).
-
- SQLite is the source of truth (ended sessions count; ``_entries`` is replaced on reset).
- The current session is already in the DB when this runs, hence ``> 1``.
- """
+ """Whether any session has ever been created. SQLite is the source of truth (ended sessions
+ count); the current session is already in the DB when this runs, hence ``> 1``."""
if self._db:
try:
return self._db.session_count_ge(2)
@@ -868,12 +867,9 @@ class SessionStore(
def get_or_create_session(
self, source: SessionSource, force_new: bool = False, touch_activity: bool = True,
) -> SessionEntry:
- """Single-flight session lookup/create per routing key.
-
- Overlapping calls for the same key (even concurrent ``force_new``) share the owner's
- result so only one routing transition and SQLite row is created. ``touch_activity=False``
- still evaluates reset policy but preserves the user-activity clock (internal events).
- """
+ """Single-flight session lookup/create per routing key: overlapping calls for one key (even
+ concurrent ``force_new``) share the owner's result so only one transition and SQLite row is
+ created. ``touch_activity=False`` (internal events) preserves the user-activity clock."""
session_key = self._generate_session_key(source)
inflight_lock = self._lazy("_inflight_lock", threading.Lock)
self._lazy("_inflight_sessions", dict)
@@ -924,7 +920,11 @@ class SessionStore(
# Phase 1b (no lock): compression tip + stale check + reset policy.
checks = None
if not force_new and observed is not None:
- checks = self._route_checks(observed, source, now)
+ sid = observed.session_id
+ checks = _RouteChecks(
+ sid, self._compression_tip_for_session_id(sid), self._is_session_ended_in_db(sid),
+ self._route_reset_reason(observed, source, now),
+ )
# Phase 2 (lock): apply the decisions to _entries.
decision = self._apply_route_checks(session_key, checks, force_new, touch_activity, now)
@@ -950,15 +950,6 @@ class SessionStore(
)
return decision.entry
- def _route_checks(
- self, entry: SessionEntry, source: SessionSource, now: datetime
- ) -> _RouteChecks:
- """Lock-free DB/config I/O for an existing route."""
- sid = entry.session_id
- canonical = self._compression_tip_for_session_id(sid)
- is_stale = self._is_session_ended_in_db(sid)
- return _RouteChecks(sid, canonical, is_stale, self._route_reset_reason(entry, source, now))
-
def _apply_route_checks(
self, session_key: str, checks: Optional[_RouteChecks], force_new: bool,
touch_activity: bool, now: datetime,
@@ -994,9 +985,7 @@ class SessionStore(
if stale_hit or reset_reason:
# Honour an expiry/reset decision instead of silently reopening via recovery.
if reset_reason:
- decision.reset_reason = reset_reason
- decision.reset_had_activity = entry.last_prompt_tokens > 0
- decision.prev_session_id = entry.session_id
+ decision.schedule_reset(reset_reason, entry, entry.last_prompt_tokens > 0)
self._entries.pop(session_key, None)
decision.needs_recover = True
else:
@@ -1017,9 +1006,7 @@ class SessionStore(
return
reset_reason = self._should_reset(recovered, source)
if reset_reason:
- decision.reset_reason = reset_reason
- decision.reset_had_activity = recovered.reset_had_activity
- decision.prev_session_id = recovered.session_id
+ decision.schedule_reset(reset_reason, recovered, recovered.reset_had_activity)
return
self._reopen_session_row(session_key, recovered.session_id)
with self._lock:
diff --git a/gateway/session_context.py b/gateway/session_context.py
index 1a3edc46479..4032c62356c 100644
--- a/gateway/session_context.py
+++ b/gateway/session_context.py
@@ -10,13 +10,11 @@ from contextlib import contextmanager
from contextvars import ContextVar
from typing import Any, Iterator
-# "Never set in this context" (fall back to os.environ for CLI/cron compat), as distinct
-# from "explicitly set to empty" by clear_session_vars (no fallback).
+# "Never set here" (falls back to os.environ for CLI/cron) vs "" = explicitly cleared (no fallback).
_UNSET: Any = object()
-# Process-level monotonic latch: has any code bound a session via set_session_vars()? The
-# subprocess-env bridge reads it: when engaged, ContextVars are authoritative and an _UNSET
-# var means "no session bound in THIS task", so the os.environ mirror must NOT leak to a child.
+# Process-level latch: has set_session_vars() ever bound a session? When engaged, the subprocess
+# env bridge treats ContextVars as authoritative and an _UNSET var as "no session in THIS task".
_session_context_engaged: bool = False
@@ -25,17 +23,14 @@ def session_context_engaged() -> bool:
return _session_context_engaged
-# --- Per-task session variables --------------------------------------------
-# Bound by set_session_vars / cleared to "" by clear_session_vars; tuple ORDER is the
-# positional order of ``values`` in set_session_vars (they are zipped).
-# * SCOPE_ID: platform-neutral scope (guild / workspace / Matrix server), captured so async
-# producers can persist a completion's full routing origin (relay egress guards need it).
-# * UI_SESSION_ID: in-process UI tab id, separate from the durable SESSION_ID: a precise
-# return address so a stale/rotated durable key is not consumed by the wrong poller.
-# * MESSAGE_ID: reply anchor keeping background notifications inside the originating
-# Telegram private-chat topic.
-# * CRON_SESSION: tri-state — _UNSET keeps the legacy env fallback for CLI/tests; "1"
-# marks cron; "" explicitly marks non-cron and masks leaked env.
+# --- Per-task session variables: bound by set_session_vars / cleared to "" by clear_session_vars;
+# tuple ORDER is the positional order of ``values`` in set_session_vars (zipped).
+# * SCOPE_ID: platform-neutral scope (guild / workspace / Matrix server) so async producers can
+# persist a completion's full routing origin (relay egress guards need it).
+# * UI_SESSION_ID: in-process UI tab id, separate from the durable SESSION_ID, so a stale/rotated
+# durable key is not consumed by the wrong poller.
+# * MESSAGE_ID: reply anchor keeping notifications inside the originating Telegram topic.
+# * CRON_SESSION: tri-state — _UNSET = legacy env fallback; "1" = cron; "" = non-cron, masks env.
_SESSION_VARS = (
_SESSION_PLATFORM, _SESSION_SOURCE, _SESSION_CHAT_ID, _SESSION_CHAT_TYPE,
_SESSION_CHAT_NAME, _SESSION_THREAD_ID, _SESSION_USER_ID, _SESSION_USER_ID_ALT,
@@ -52,11 +47,9 @@ _SESSION_VARS = (
"HERMES_CRON_SESSION",
))
-# Whether this channel can route an ASYNC completion back AFTER the turn ends (read via
-# ``async_delivery_supported()``). False for finite runtimes that may exit first (stateless
-# API-server requests, Kanban workers). Default _UNSET => supported, so the CLI and
-# contextvar-unaware paths keep working; stateless adapters opt OUT via
-# ``supports_async_delivery = False``, propagated at bind time.
+# Whether this channel can route an ASYNC completion back AFTER the turn ends (see
+# ``async_delivery_supported()``). _UNSET => supported (CLI, contextvar-unaware paths); stateless
+# adapters (API server, Kanban workers) opt OUT via ``supports_async_delivery = False`` at bind.
_SESSION_ASYNC_DELIVERY = ContextVar("HERMES_SESSION_ASYNC_DELIVERY", default=_UNSET)
# Cron auto-delivery vars, set per-job in run_job() so concurrent jobs don't clobber.
@@ -64,8 +57,8 @@ _CRON_AUTO_DELIVER_PLATFORM = ContextVar("HERMES_CRON_AUTO_DELIVER_PLATFORM", de
_CRON_AUTO_DELIVER_CHAT_ID = ContextVar("HERMES_CRON_AUTO_DELIVER_CHAT_ID", default=_UNSET)
_CRON_AUTO_DELIVER_THREAD_ID = ContextVar("HERMES_CRON_AUTO_DELIVER_THREAD_ID", default=_UNSET)
-# Legacy env-var name -> ContextVar, for get_session_env. _SESSION_ASYNC_DELIVERY is
-# deliberately absent: it is a bool capability read via async_delivery_supported.
+# Legacy env-var name -> ContextVar for get_session_env (_SESSION_ASYNC_DELIVERY deliberately
+# absent: it is a bool capability, read via async_delivery_supported).
_VAR_MAP = {var.name: var for var in (
*_SESSION_VARS, _CRON_AUTO_DELIVER_PLATFORM, _CRON_AUTO_DELIVER_CHAT_ID,
_CRON_AUTO_DELIVER_THREAD_ID,
@@ -162,11 +155,9 @@ def get_session_env(name: str, default: str = "") -> str:
return os.getenv(name, default)
-# Surfaces that are not a human chat channel (the gateway binds HERMES_SESSION_PLATFORM,
-# CLI/TUI/desktop bind HERMES_SESSION_SOURCE, so both are consulted). ``local``,
-# ``api_server``, ``webhook``, ``msgraph_webhook`` are real Platform values with no
-# attachment channel. Default-deny: an unrecognized identity counts as messaging.
-# Mirrors LOCAL_SESSION_SOURCE_IDS in apps/desktop/src/lib/session-source.ts.
+# Surfaces that are not a human chat channel (gateway binds HERMES_SESSION_PLATFORM, CLI/TUI/
+# desktop bind HERMES_SESSION_SOURCE, so both are consulted). Default-deny: an unrecognized
+# identity counts as messaging. Mirrors LOCAL_SESSION_SOURCE_IDS in apps/desktop session-source.ts.
NON_MESSAGING_SESSION_SURFACES = frozenset({
"", "api_server", "cli", "codex", "desktop", "gateway", "kanban", "local",
"msgraph_webhook", "tool", "tui", "webhook",
diff --git a/gateway/session_state.py b/gateway/session_state.py
index 64b0605753e..bb8b6e14a81 100644
--- a/gateway/session_state.py
+++ b/gateway/session_state.py
@@ -1,8 +1,6 @@
-"""Per-session gateway state consolidated into one container.
-
-Replaces ~19 separate session_key-keyed dicts on GatewayRunner that bred boundary drift,
-turn-release drift and wholesale-reset races. Scopes follow where each dict was CLEARED:
-``turn`` at the end of every turn; ``conversation`` at conversation boundaries (/new,
+"""Per-session gateway state in one container (replaces ~19 session_key-keyed dicts on
+GatewayRunner that bred boundary drift and wholesale-reset races). Scopes follow where each dict
+was CLEARED: ``turn`` at the end of every turn; ``conversation`` at conversation boundaries (/new,
/resume, auto-reset, expiry); ``persistent`` fields have their own lifecycles."""
from __future__ import annotations
@@ -11,8 +9,7 @@ from collections.abc import MutableMapping
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, Iterator, List, NamedTuple, Optional, Tuple
-# Presence-sensitive sentinel: /fast stores "priority" or None (explicit normal), so key
-# PRESENCE — not value truthiness — decides whether the override applies.
+# /fast stores "priority" or None (explicit normal), so key PRESENCE decides, not truthiness.
_UNSET_TIER = object()
SERVICE_TIER_UNSET = _UNSET_TIER # public alias
@@ -26,8 +23,8 @@ class TurnState:
started_ts: float = 0.0 # 0.0 = not running
lease: Any = None # cross-process active-session slot lease
busy_ack_ts: float = 0.0 # debounce; 0.0 = never acked
- # Held turn-lease token + the generation that acquired it: release/rebind only match
- # when the generation is current, so a stale unwind can never free a newer turn's lease.
+ # Held turn-lease token + acquiring generation: release/rebind match only when the
+ # generation is current, so a stale unwind can never free a newer turn's lease.
lease_token: Any = None
lease_generation: Optional[int] = None
@@ -64,14 +61,11 @@ class PersistentState:
approvals: Optional[Dict[str, Any]] = None # {"command": ..., "pattern_key": ...}
update_prompt_pending: bool = False # /update prompt awaiting a reply
native_image_paths: List[str] = field(default_factory=list) # consumed one-shot
- # Legacy runner-level pending text (flushed on shutdown); distinct from gateway/base.py's
- # adapter-level ``_pending_messages``.
+ # Legacy runner-level pending text (flushed on shutdown); not the adapter-level one.
pending_command_text: Optional[str] = None
- # Monotonic run-generation counter. NEVER reset: stale-run detection depends on it.
- run_generation: int = 0
- # Consecutive hygiene compression failures, so hygiene can escalate its cooldown (the
- # in-agent compressor's ladder is unreachable: hygiene builds a FRESH AIAgent per run).
- # Reset only on success. PROCESS-LOCAL; gateway.run mirrors it to the DB by session_key.
+ run_generation: int = 0 # monotonic; NEVER reset (stale-run detection depends on it)
+ # Consecutive hygiene compression failures (the in-agent ladder is unreachable: hygiene builds
+ # a FRESH AIAgent per run). Reset on success; process-local, mirrored to the DB by run.py.
hygiene_failure_streak: int = 0
@@ -84,9 +78,8 @@ class SessionState:
persistent: PersistentState = field(default_factory=PersistentState)
-# --- Legacy dict-view adapters ---------------------------------------------
-# Dozens of tests read/write the old dict attributes directly (``runner._running_agents =
-# {}``). Each view is a LIVE MutableMapping over one SessionState field across sessions.
+# --- Legacy dict-view adapters: tests read/write the old dict attributes directly
+# (``runner._running_agents = {}``); each view is a LIVE MutableMapping over one field.
class _FieldSpec(NamedTuple):
@@ -145,7 +138,8 @@ class SessionFieldView(_RunnerView):
return state if state is not None and self._spec.is_present(self._value(state)) else None
def _held(self, key: str) -> SessionState:
- if (state := self._present(key)) is None:
+ state = self._present(key)
+ if state is None:
raise KeyError(key)
return state
@@ -173,9 +167,8 @@ class SessionFieldView(_RunnerView):
class TurnLeaseTokenView(_RunnerView):
- """Legacy view of ``_turn_lease_tokens``, keyed by (session_key, generation). The lease
- registry serializes acquisition per session, so the single ``TurnState`` slot per key
- equals the old tuple-keyed dict."""
+ """Legacy (session_key, generation)-keyed view of ``_turn_lease_tokens``; the lease registry
+ serializes acquisition per session, so one ``TurnState`` slot per key equals the old dict."""
__slots__ = ()
@@ -234,8 +227,9 @@ LEGACY_FIELD_SPECS: Dict[str, _FieldSpec] = {
def _legacy_property(make_view: Callable[[Any], MutableMapping], doc: str) -> property:
- """Dict-shaped @property over a live view. The setter takes a plain dict (test pattern
+ """Dict-shaped @property over a live view; the setter takes a plain dict (test pattern
``runner._X = {...}``): reset the field on every session, then apply the entries."""
+
def fset(self: Any, mapping: Optional[Dict[Any, Any]]) -> None:
view = make_view(self)
view.clear()
@@ -249,8 +243,7 @@ def legacy_dict_property(attr_name: str) -> property:
spec = LEGACY_FIELD_SPECS[attr_name]
return _legacy_property(
lambda self: SessionFieldView(self, spec),
- f"Legacy dict view over SessionState.{spec.scope}.{spec.name} "
- "(kept for tests that access the pre-SessionState attribute).",
+ f"Legacy dict view over SessionState.{spec.scope}.{spec.name} (for pre-SessionState tests).",
)