Skip to content

The agent that grows with you

fix(state): session reads on the gateway loop never wait on the token writer

Tekniumf972443f6a6a
diff --git a/hermes_state_gateway.py b/hermes_state_gateway.py
index 3556599b64e..3359e196553 100644
--- a/hermes_state_gateway.py
+++ b/hermes_state_gateway.py
@@ -473,7 +473,7 @@ class SessionGatewayMixin:
"""List gateway sessions (rows with a session_key): newest row per key, one live
mapping per routing key. ``platform`` filters on ``source``."""
# Full rows carry token/cost totals — drain queued async accounting deltas first.
- self.flush_token_counts()
+ self.flush_for_read()
query = f"""
SELECT sessions.*,
COALESCE(sp.prompt, sessions.system_prompt)
diff --git a/hermes_state_sessions.py b/hermes_state_sessions.py
index c386b47e70e..f3fc4c28543 100644
--- a/hermes_state_sessions.py
+++ b/hermes_state_sessions.py
@@ -833,7 +833,7 @@ class SessionSessionsMixin:
def get_session(self, session_id: str) -> Optional[dict[str, Any]]:
"""Get a session by ID (drains queued token deltas first so cost readers see exact totals)."""
- self.flush_token_counts()
+ self.flush_for_read()
row = self._read_one(
"SELECT s.*, COALESCE(sp.prompt, s.system_prompt) AS _system_prompt_resolved, "
"COALESCE(tp.prompt, s.tool_names) AS _tool_names_resolved "
@@ -859,7 +859,7 @@ class SessionSessionsMixin:
highest ``api_call_count`` forever, and /status and /usage would keep calling it current.
``rowid DESC`` breaks same-timestamp ties toward the route that first appeared later; without
it SQLite's temp-sort order is unspecified and the retired route can win."""
- self.flush_token_counts()
+ self.flush_for_read()
row = self._read_one(
"""SELECT model, billing_provider, billing_base_url, billing_mode,
api_call_count
@@ -1315,7 +1315,7 @@ class SessionSessionsMixin:
filters except archived: a pin is an explicit keep, so a pinned row stamped
archived must still return. ``local_created_sources`` restricts ``source='local'``
rows to those surfaces before LIMIT/OFFSET."""
- self.flush_token_counts() # rows carry token/cost totals
+ self.flush_for_read() # rows carry token/cost totals
where_clauses, params = _session_filter_where(
exclude_children=not include_children, source=source, sources=sources, session_key=session_key,
exclude_sources=exclude_sources, cwd_prefix=cwd_prefix, min_message_count=min_message_count,
diff --git a/hermes_state_usage.py b/hermes_state_usage.py
index ca5474e285e..b7a98deda0a 100644
--- a/hermes_state_usage.py
+++ b/hermes_state_usage.py
@@ -3,6 +3,7 @@ per-model usage rows, and billing-route columns. Writer thread state lives on th
from __future__ import annotations
+import asyncio
import atexit
import contextlib
import logging
@@ -144,6 +145,17 @@ class SessionUsageMixin:
self._token_writer_busy = False
self._token_queue_cond.notify_all()
+ def flush_for_read(self) -> bool:
+ """Read-side token barrier. On a thread running an asyncio loop it never waits: the writer can sit
+ behind another connection's write lock, and a gateway handler reading a session there froze every
+ socket for up to the 5 s flush budget (#141966). That read sees totals stale by the queued deltas,
+ which the next read picks up; write barriers keep calling ``flush_token_counts`` and still wait."""
+ try:
+ asyncio.get_running_loop()
+ except RuntimeError:
+ return self.flush_token_counts()
+ return self.flush_token_counts(timeout=0.0)
+
def flush_token_counts(self, timeout: float = 5.0) -> bool:
"""Block until every queued token delta has been applied. False on timeout (callers
then read totals stale by the queued deltas). Never raises."""
diff --git a/tests/agent/test_token_read_barrier_on_loop.py b/tests/agent/test_token_read_barrier_on_loop.py
new file mode 100644
index 00000000000..36eca7956ad
--- /dev/null
+++ b/tests/agent/test_token_read_barrier_on_loop.py
@@ -0,0 +1,49 @@
+"""A session read on an event-loop thread never waits on the token writer (#141966).
+
+Gateway handlers read sessions on the loop; when the writer sits behind another connection's write
+lock, waiting for it froze every socket for the whole flush budget. Off the loop the read barrier
+still gives read-your-writes (``test_async_token_accounting``).
+"""
+
+import asyncio
+import threading
+import time
+
+from hermes_state import SessionDB
+
+
+def test_loop_thread_session_read_does_not_wait_for_a_stuck_writer(tmp_path):
+ db = SessionDB(db_path=tmp_path / "state.db")
+ try:
+ db.create_session("s-loop", "test")
+ db.flush_token_counts()
+ entered, release = threading.Event(), threading.Event()
+ original = db.update_token_counts
+
+ def stuck(session_id, **kwargs):
+ entered.set()
+ release.wait(timeout=30) # the writer is held up, like a write lock held elsewhere
+ return original(session_id, **kwargs)
+
+ db.update_token_counts = stuck
+ db.queue_token_counts("s-loop", input_tokens=7, api_call_count=1)
+ assert entered.wait(timeout=10)
+
+ async def read_on_loop():
+ started = time.monotonic()
+ row = db.get_session("s-loop")
+ listed = db.list_sessions_rich(limit=5)
+ return row, listed, time.monotonic() - started
+
+ row, listed, elapsed = asyncio.run(read_on_loop())
+ assert elapsed < 1.0, f"loop-thread read waited {elapsed:.2f}s on the token writer"
+ assert row is not None and row["id"] == "s-loop"
+ assert any(r["id"] == "s-loop" for r in listed)
+
+ release.set()
+ db.update_token_counts = original
+ # Off the loop the read barrier still waits, so the queued delta is visible.
+ assert db.get_session("s-loop")["input_tokens"] == 7
+ finally:
+ release.set()
+ db.close()