Skip to content

The agent that grows with you

perf(state): route 39 pure-read SessionDB methods off the writer lock + gate

kshitijk4poor0534f1033b45
diff --git a/hermes_state.py b/hermes_state.py
index 3da58aa600d..96064d007a1 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -6314,8 +6314,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
def load_gateway_routing_entries(self, *, scope: str = "") -> Dict[str, str]:
"""Load routing entries for *scope* as {session_key: entry_json}."""
- with self._lock:
- rows = self._conn.execute(
+ with self._read_ctx() as conn:
+ rows = conn.execute(
"SELECT session_key, entry_json FROM gateway_routing WHERE scope = ?",
(scope,),
).fetchall()
@@ -6360,8 +6360,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
user intent to keep the row around.
"""
cutoff = time.time() - (float(older_than_days) * 86400.0)
- with self._lock:
- rows = self._conn.execute(
+ with self._read_ctx() as conn:
+ rows = conn.execute(
"""
SELECT s.id, s.session_key, s.source, s.chat_id,
s.chat_type, s.user_id, s.started_at
@@ -6397,8 +6397,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
"""
if not session_ids:
return 0
- with self._lock:
- rows = self._conn.execute(
+ with self._read_ctx() as conn:
+ rows = conn.execute(
"SELECT scope, session_key, entry_json FROM gateway_routing"
).fetchall()
doomed: List[Tuple[str, str]] = []
@@ -6586,8 +6586,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
"""
if not session_key:
return None
- with self._lock:
- row = self._conn.execute(
+ with self._read_ctx() as conn:
+ row = conn.execute(
f"""
SELECT s.*,
COALESCE(sp.prompt, s.system_prompt)
@@ -6623,7 +6623,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
# tuple so we never cross chats/threads/users.
if chat_id is None or chat_type is None:
return None
- row = self._conn.execute(
+ row = conn.execute(
f"""
SELECT s.*,
COALESCE(sp.prompt, s.system_prompt)
@@ -6709,8 +6709,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
)
records: List[Dict[str, Any]] = []
- with self._lock:
- orphans = self._conn.execute(
+ with self._read_ctx() as conn:
+ orphans = conn.execute(
f"""
SELECT o.id, o.source, o.user_id, o.started_at,
o.parent_session_id,
@@ -6737,7 +6737,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
if orphan["parent_session_id"]:
evidence = "lineage"
- donor = self._conn.execute(
+ donor = conn.execute(
f"""
SELECT {donor_columns}
FROM sessions d
@@ -6754,7 +6754,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
)
else:
evidence = "contiguity"
- candidates = self._conn.execute(
+ candidates = conn.execute(
f"""
SELECT {donor_columns}, {donor_active} AS last_active
FROM sessions d
@@ -6921,8 +6921,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
"""
if not parent_session_id:
return None
- with self._lock:
- parent = self._conn.execute(
+ with self._read_ctx() as conn:
+ parent = conn.execute(
"SELECT ended_at, end_reason FROM sessions WHERE id = ?",
(parent_session_id,),
).fetchone()
@@ -6932,7 +6932,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
or parent["end_reason"] != "compression"
):
return None
- rows = self._conn.execute(
+ rows = conn.execute(
"""
SELECT s.*,
COALESCE(sp.prompt, s.system_prompt)
@@ -7460,8 +7460,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
if not session_id:
return None
now = time.time()
- with self._lock:
- row = self._conn.execute(
+ with self._read_ctx() as conn:
+ row = conn.execute(
"SELECT compression_failure_cooldown_until, compression_failure_error "
"FROM sessions WHERE id = ?",
(session_id,),
@@ -7502,8 +7502,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
"""
if not session_id:
return {"session_exists": False, "cooldown_until": None, "error": None}
- with self._lock:
- row = self._conn.execute(
+ with self._read_ctx() as conn:
+ row = conn.execute(
"SELECT compression_failure_cooldown_until, compression_failure_error "
"FROM sessions WHERE id = ?",
(session_id,),
@@ -9567,8 +9567,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
return exact["id"]
escaped = _escape_like(session_id_or_prefix)
- with self._lock:
- cursor = self._conn.execute(
+ with self._read_ctx() as conn:
+ cursor = conn.execute(
"SELECT id FROM sessions WHERE id LIKE ? ESCAPE '\\' ORDER BY started_at DESC LIMIT 2",
(f"{escaped}%",),
)
@@ -9843,8 +9843,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
def get_session_title(self, session_id: str) -> Optional[str]:
"""Get the title for a session, or None."""
- with self._lock:
- cursor = self._conn.execute(
+ with self._read_ctx() as conn:
+ cursor = conn.execute(
"SELECT title FROM sessions WHERE id = ?", (session_id,)
)
row = cursor.fetchone()
@@ -9852,8 +9852,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
def get_session_title_source(self, session_id: str) -> Optional[str]:
"""Get the provenance of a session's title, or None when untitled."""
- with self._lock:
- cursor = self._conn.execute(
+ with self._read_ctx() as conn:
+ cursor = conn.execute(
"SELECT title, title_source FROM sessions WHERE id = ?",
(session_id,),
)
@@ -10267,8 +10267,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
# Find all existing numbered variants
# Escape SQL LIKE wildcards (%, _) in the base to prevent false matches
escaped = _escape_like(base)
- with self._lock:
- cursor = self._conn.execute(
+ with self._read_ctx() as conn:
+ cursor = conn.execute(
"SELECT title FROM sessions WHERE title = ? OR title LIKE ? ESCAPE '\\'",
(base, f"{escaped} #%"),
)
@@ -10312,8 +10312,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
# Bound the walk defensively — compression chains this deep are
# pathological and shouldn't happen in practice. 100 = plenty.
for _ in range(100):
- with self._lock:
- cursor = self._conn.execute(
+ with self._read_ctx() as conn:
+ cursor = conn.execute(
f"""
SELECT child.id
FROM sessions parent
@@ -11394,8 +11394,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
if not session_id or message_row_id is None:
return []
- with self._lock:
- row = self._conn.execute(
+ with self._read_ctx() as conn:
+ row = conn.execute(
"SELECT display_metadata FROM messages WHERE id = ? AND session_id = ?",
(message_row_id, session_id),
).fetchone()
@@ -11492,8 +11492,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
"AND content IS NOT NULL AND TRIM(content) != '' " if require_text else ""
)
- with self._lock:
- row = self._conn.execute(
+ with self._read_ctx() as conn:
+ row = conn.execute(
"SELECT id FROM messages WHERE session_id = ? AND role = ? "
f"AND active = 1 {text_filter}ORDER BY id DESC LIMIT 1 OFFSET ?",
(session_id, role, int(offset)),
@@ -11519,8 +11519,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
if not session_id:
return None
- with self._lock:
- row = self._conn.execute(
+ with self._read_ctx() as conn:
+ row = conn.execute(
"SELECT role FROM messages WHERE id = ? AND session_id = ? AND active = 1",
(int(row_id), session_id),
).fetchone()
@@ -11729,8 +11729,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
unconditionally — a probe can fail open or race a concurrent
``archive_and_compact``, #80216); kept for tests and diagnostics.
"""
- with self._lock:
- cursor = self._conn.execute(
+ with self._read_ctx() as conn:
+ cursor = conn.execute(
"SELECT 1 FROM messages WHERE session_id = ? AND active = 0 LIMIT 1",
(session_id,),
)
@@ -12245,7 +12245,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
if tip and tip != session_id:
session_id = tip
- with self._lock:
+ with self._read_ctx() as conn:
current = session_id
seen = {current}
best = None # tracks the last (deepest) node with messages
@@ -12253,7 +12253,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
for _ in range(32):
# Check if the current node has messages.
try:
- row = self._conn.execute(
+ row = conn.execute(
"SELECT 1 FROM messages WHERE session_id = ? LIMIT 1",
(current,),
).fetchone()
@@ -12272,7 +12272,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
# the resume target to an unrelated session (e.g. a subagent
# run). This mirrors the child-exclusion in ``get_compression_tip``.
try:
- child_row = self._conn.execute(
+ child_row = conn.execute(
"SELECT id FROM sessions AS child "
"WHERE child.parent_session_id = ? "
" AND json_extract(COALESCE(child.model_config, '{}'), '$._branched_from') IS NULL "
@@ -13247,8 +13247,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
where_sql = f" WHERE {' AND '.join(where_clauses)}" if where_clauses else ""
- with self._lock:
- cursor = self._conn.execute(f"SELECT COUNT(*) FROM sessions s{where_sql}", params)
+ with self._read_ctx() as conn:
+ cursor = conn.execute(f"SELECT COUNT(*) FROM sessions s{where_sql}", params)
return cursor.fetchone()[0]
def session_count_ge(self, n: int = 1) -> bool:
@@ -13262,8 +13262,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
Use this instead of ``session_count() >= n`` when the exact count
is irrelevant.
"""
- with self._lock:
- cursor = self._conn.execute("SELECT 1 FROM sessions LIMIT ?", (n,))
+ with self._read_ctx() as conn:
+ cursor = conn.execute("SELECT 1 FROM sessions LIMIT ?", (n,))
rows = cursor.fetchall()
return len(rows) >= n
@@ -13300,10 +13300,10 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
where_sql = f" WHERE {' AND '.join(where_clauses)}" if where_clauses else ""
- with self._lock:
+ with self._read_ctx() as conn:
if self._conn is None:
raise RuntimeError("SessionDB connection is closed")
- rows = self._conn.execute(
+ rows = conn.execute(
"SELECT COALESCE(NULLIF(s.source, ''), 'cli') AS source, COUNT(*) AS count "
f"FROM sessions s{where_sql} "
"GROUP BY COALESCE(NULLIF(s.source, ''), 'cli') "
@@ -13314,13 +13314,13 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
def message_count(self, session_id: str = None) -> int:
"""Count messages, optionally for a specific session."""
- with self._lock:
+ with self._read_ctx() as conn:
if session_id:
- cursor = self._conn.execute(
+ cursor = conn.execute(
"SELECT COUNT(*) FROM messages WHERE session_id = ?", (session_id,)
)
else:
- cursor = self._conn.execute("SELECT COUNT(*) FROM messages")
+ cursor = conn.execute("SELECT COUNT(*) FROM messages")
return cursor.fetchone()[0]
def has_platform_message_id(
@@ -13333,8 +13333,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
to skip re-persisting a user message that was already saved on a
prior retry of the same inbound platform message.
"""
- with self._lock:
- cursor = self._conn.execute(
+ with self._read_ctx() as conn:
+ cursor = conn.execute(
"SELECT 1 FROM messages "
"WHERE session_id = ? AND platform_message_id = ? LIMIT 1",
(session_id, platform_message_id),
@@ -13401,8 +13401,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
seen = {root["id"]}
current = root
while current.get("end_reason") == "compression":
- with self._lock:
- rows = self._conn.execute(
+ with self._read_ctx() as conn:
+ rows = conn.execute(
"""
SELECT * FROM sessions
WHERE parent_session_id = ?
@@ -13474,8 +13474,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
included because deletion preserves them by orphaning their parent
reference.
"""
- with self._lock:
- exists = self._conn.execute(
+ with self._read_ctx() as conn:
+ exists = conn.execute(
"SELECT 1 FROM sessions WHERE id = ? LIMIT 1", (session_id,)
).fetchone()
if not exists:
@@ -13709,8 +13709,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
to clean up, and pre-populate the confirm dialog with the actual
count.
"""
- with self._lock:
- cursor = self._conn.execute(
+ with self._read_ctx() as conn:
+ cursor = conn.execute(
f"SELECT COUNT(*) FROM sessions WHERE {self._EMPTY_SESSION_WHERE}"
)
return cursor.fetchone()[0]
@@ -13962,8 +13962,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
"""
self._apply_prune_age_filter(older_than_days, filters)
where, params = self._prune_filter_where(source=source, **filters)
- with self._lock:
- cursor = self._conn.execute(
+ with self._read_ctx() as conn:
+ cursor = conn.execute(
f"""SELECT s.id, s.source, s.title, s.model, s.started_at,
COALESCE(
(SELECT MAX(m.timestamp) FROM messages m
@@ -13991,8 +13991,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
"""
self._apply_prune_age_filter(older_than_days, filters)
where, params = self._prune_filter_where(source=source, **filters)
- with self._lock:
- cursor = self._conn.execute(
+ with self._read_ctx() as conn:
+ cursor = conn.execute(
f"SELECT COUNT(*) FROM sessions s WHERE {where}", params
)
return int(cursor.fetchone()[0])
@@ -14016,8 +14016,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
if not where.startswith(ended_guard):
raise RuntimeError("prune filter lost its ended-session safety guard")
open_where = f"s.ended_at IS NULL{where[len(ended_guard):]}"
- with self._lock:
- cursor = self._conn.execute(
+ with self._read_ctx() as conn:
+ cursor = conn.execute(
f"SELECT COUNT(*) FROM sessions s WHERE {open_where}", params
)
return int(cursor.fetchone()[0])
@@ -14077,8 +14077,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
return 0
cutoff = time.time() - float(idle_days) * 86400.0
pin_clause = "AND s.pinned = 0" if exclude_pinned else ""
- with self._lock:
- rows = self._conn.execute(
+ with self._read_ctx() as conn:
+ rows = conn.execute(
f"""
SELECT s.id FROM sessions s
WHERE s.archived = 0
@@ -14283,8 +14283,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
# committed data — a pending write transaction's uncommitted
# meta writes would be invisible. This is a cheap point lookup,
# not the convoy bottleneck the read-path split targets.
- with self._lock:
- row = self._conn.execute(
+ with self._read_ctx() as conn:
+ row = conn.execute(
"SELECT value FROM state_meta WHERE key = ?", (key,)
).fetchone()
if row is None:
@@ -14364,8 +14364,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
if not prefix:
return []
escaped = prefix.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
- with self._lock:
- rows = self._conn.execute(
+ with self._read_ctx() as conn:
+ rows = conn.execute(
"SELECT key, value FROM state_meta WHERE key LIKE ? ESCAPE '\\'",
(escaped + "%",),
).fetchall()
@@ -14555,9 +14555,9 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
def is_telegram_topic_mode_enabled(self, *, chat_id: str, user_id: str) -> bool:
"""Return whether Telegram DM topic mode is enabled for this chat/user."""
- with self._lock:
+ with self._read_ctx() as conn:
try:
- row = self._conn.execute(
+ row = conn.execute(
"""
SELECT enabled FROM telegram_dm_topic_mode
WHERE chat_id = ? AND user_id = ?
@@ -14578,9 +14578,9 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
thread_id: str,
) -> Optional[Dict[str, Any]]:
"""Return the session binding for a Telegram DM topic, if present."""
- with self._lock:
+ with self._read_ctx() as conn:
try:
- row = self._conn.execute(
+ row = conn.execute(
"""
SELECT * FROM telegram_dm_topic_bindings
WHERE chat_id = ? AND thread_id = ?
@@ -14601,9 +14601,9 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
Read-only; returns [] if the bindings table doesn't exist yet
(does not trigger the topic-mode migration).
"""
- with self._lock:
+ with self._read_ctx() as conn:
try:
- rows = self._conn.execute(
+ rows = conn.execute(
"SELECT * FROM telegram_dm_topic_bindings "
"WHERE chat_id = ? ORDER BY updated_at DESC",
(str(chat_id),),
@@ -14623,9 +14623,9 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
efficient reverse lookup. Returns None when the session has no binding or
the table does not exist yet.
"""
- with self._lock:
+ with self._read_ctx() as conn:
try:
- row = self._conn.execute(
+ row = conn.execute(
"""
SELECT * FROM telegram_dm_topic_bindings
WHERE session_id = ?
@@ -14785,9 +14785,9 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
``/topic`` in this profile), the session is by definition unbound
and we return False.
"""
- with self._lock:
+ with self._read_ctx() as conn:
try:
- row = self._conn.execute(
+ row = conn.execute(
"""
SELECT 1 FROM telegram_dm_topic_bindings
WHERE session_id = ?
@@ -14813,9 +14813,9 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
just returns this user's Telegram sessions — there can't be any
bindings yet.
"""
- with self._lock:
+ with self._read_ctx() as conn:
try:
- rows = self._conn.execute(
+ rows = conn.execute(
f"""
SELECT s.*,
COALESCE(sp.prompt, s.system_prompt)
@@ -14846,7 +14846,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
except sqlite3.OperationalError:
# telegram_dm_topic_bindings doesn't exist yet — no bindings
# means every telegram session for this user is "unlinked".
- rows = self._conn.execute(
+ rows = conn.execute(
f"""
SELECT s.*,
COALESCE(sp.prompt, s.system_prompt)
@@ -14904,11 +14904,11 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
Returns None if the pragmas cannot be read.
"""
try:
- with self._lock:
+ with self._read_ctx() as conn:
if self._conn is None:
return None
- page_count = self._conn.execute("PRAGMA page_count").fetchone()[0]
- page_size = self._conn.execute("PRAGMA page_size").fetchone()[0]
+ page_count = conn.execute("PRAGMA page_count").fetchone()[0]
+ page_size = conn.execute("PRAGMA page_size").fetchone()[0]
return int(page_count) * int(page_size)
except Exception as exc:
logger.debug("Could not read logical DB size: %s", exc)
diff --git a/tests/state/test_no_locked_readers_gate.py b/tests/state/test_no_locked_readers_gate.py
new file mode 100644
index 00000000000..f544e6b62dc
--- /dev/null
+++ b/tests/state/test_no_locked_readers_gate.py
@@ -0,0 +1,188 @@
+"""Pattern-C gate: pure-read SessionDB methods must not take the writer lock.
+
+The gateway shares ONE SessionDB across every agent. ``self._lock`` guards
+the single writer connection — any read-only query executed under it
+convoys every concurrent turn's persistence behind that reader (Pattern C
+of the 2026-08 perf triage; #90734 shipped the unlocked-reader subset,
+this gate covers the locked-reader subset).
+
+``_read_ctx()`` exists precisely for reads: WAL reader from a bounded
+pool, no lock, with a byte-identical fallback to the locked writer when
+WAL is off. Reads have no reason to hold the writer lock.
+
+The gate parses ``hermes_state.py`` with ``ast`` and flags any method
+that (a) opens ``with self._lock:`` and (b) runs ONLY read statements
+(SELECT/PRAGMA-read) on ``self._conn`` inside it — i.e. a pure reader
+convoying on the writer lock. Methods that write under the lock are the
+lock's legitimate users and pass. New violations fail with the method
+name and the fix (route through ``_read_ctx()``).
+
+Deliberately NOT flagged:
+- methods that INSERT/UPDATE/DELETE/REPLACE under the lock (writers);
+- read-modify-write methods (the read is ordered against its own write);
+- ``_read_ctx``'s own writer-fallback (``yield self._conn`` — no execute);
+- SELECTs on ``conn``/other objects (already pooled readers).
+"""
+
+from __future__ import annotations
+
+import ast
+import re
+from pathlib import Path
+
+import pytest
+
+_STATE_PY = Path(__file__).resolve().parents[2] / "hermes_state.py"
+
+_WRITE_RE = re.compile(
+ r"^\s*(INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|ALTER|VACUUM|BEGIN|COMMIT|ANALYZE)\b",
+ re.IGNORECASE,
+)
+# PRAGMA is read-only EXCEPT the checkpoint/optimize family, which mutates
+# the database file and legitimately belongs on the writer connection.
+_PRAGMA_WRITE_RE = re.compile(
+ r"^\s*PRAGMA\s+(wal_checkpoint|optimize|incremental_vacuum|integrity_check)",
+ re.IGNORECASE,
+)
+_READ_RE = re.compile(r"^\s*(SELECT|PRAGMA)\b", re.IGNORECASE)
+
+# Methods allowed to keep a pure-read body under the writer lock, each with
+# the reason. Keep this list SHRINKING — never add to it without the same
+# scrutiny a new blocking call would get.
+_ALLOWED_LOCKED_READERS: dict[str, str] = {
+ # _enter_fts_fail_open reads schema state under the lock as part of the
+ # fail-open WRITE transition (the writes live in sibling statements the
+ # simple statement scanner attributes to other calls).
+ "_enter_fts_fail_open": "fail-open transition; lock orders vs FTS writes",
+}
+
+
+def _first_sql_text(call: ast.Call) -> str | None:
+ """Best-effort SQL text from an execute()'s first argument."""
+ if not call.args:
+ return None
+ arg = call.args[0]
+ text = None
+ if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
+ text = arg.value
+ elif isinstance(arg, ast.JoinedStr):
+ parts = [
+ v.value for v in arg.values
+ if isinstance(v, ast.Constant) and isinstance(v.value, str)
+ ]
+ text = "".join(parts)
+ if not text or not text.strip():
+ return None
+ return text.strip()
+
+
+def _is_self_conn_execute(call: ast.Call) -> bool:
+ f = call.func
+ return (
+ isinstance(f, ast.Attribute)
+ and f.attr in ("execute", "executemany", "executescript")
+ and isinstance(f.value, ast.Attribute)
+ and f.value.attr == "_conn"
+ and isinstance(f.value.value, ast.Name)
+ and f.value.value.id == "self"
+ )
+
+
+def _is_self_lock_with(item: ast.withitem) -> bool:
+ ctx = item.context_expr
+ return (
+ isinstance(ctx, ast.Attribute)
+ and ctx.attr == "_lock"
+ and isinstance(ctx.value, ast.Name)
+ and ctx.value.id == "self"
+ )
+
+
+def _scan_locked_readers(state_py: "Path | None" = None) -> list[str]:
+ target = state_py if state_py is not None else _STATE_PY
+ tree = ast.parse(target.read_text(encoding="utf-8"))
+ violations: list[str] = []
+
+ session_db = None
+ for node in tree.body:
+ if isinstance(node, ast.ClassDef) and node.name == "SessionDB":
+ session_db = node
+ break
+ assert session_db is not None, "SessionDB class not found"
+
+ for method in session_db.body:
+ if not isinstance(method, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ for node in ast.walk(method):
+ if not isinstance(node, ast.With):
+ continue
+ if not any(_is_self_lock_with(i) for i in node.items):
+ continue
+ reads, writes, unknown = 0, 0, 0
+ for inner in ast.walk(node):
+ if isinstance(inner, ast.Call) and _is_self_conn_execute(inner):
+ word_full = _first_sql_text(inner)
+ word = word_full.split(None, 1)[0].upper() if word_full else None
+ if word is None:
+ unknown += 1
+ elif _PRAGMA_WRITE_RE.match(word_full or ""):
+ writes += 1
+ elif _WRITE_RE.match(word):
+ writes += 1
+ elif _READ_RE.match(word):
+ reads += 1
+ else:
+ unknown += 1
+ # Method calls under the lock may write internally
+ # (e.g. self._execute_write, cursor ops) — treat any
+ # self.<something>() as potentially writing.
+ elif isinstance(inner, ast.Call):
+ f = inner.func
+ if (
+ isinstance(f, ast.Attribute)
+ and isinstance(f.value, ast.Name)
+ and f.value.id == "self"
+ and (
+ "write" in f.attr
+ or "commit" in f.attr
+ or f.attr.startswith(("set_", "record_", "insert_",
+ "update_", "delete_", "clear_"))
+ )
+ ):
+ writes += 1
+ if reads > 0 and writes == 0 and unknown == 0:
+ if method.name not in _ALLOWED_LOCKED_READERS:
+ violations.append(
+ f"{method.name} (line {node.lineno}): pure-read "
+ f"body under `with self._lock:` — route through "
+ f"_read_ctx() instead"
+ )
+ return violations
+
+
+class TestNoPureReadersUnderWriterLock:
+ def test_no_locked_pure_readers(self):
+ violations = _scan_locked_readers()
+ assert violations == [], (
+ "Pure-read SessionDB methods holding the writer lock "
+ "(Pattern C — every concurrent turn's persistence convoys "
+ "behind these reads):\n " + "\n ".join(violations)
+ )
+
+ def test_gate_detects_a_locked_reader(self, tmp_path):
+ """Sabotage self-check: the scanner must flag a synthetic violation."""
+ sabotage = (
+ "class SessionDB:\n"
+ " def innocent_writer(self):\n"
+ " with self._lock:\n"
+ " self._conn.execute(\"UPDATE t SET x = 1\")\n"
+ " def guilty_reader(self):\n"
+ " with self._lock:\n"
+ " return self._conn.execute(\"SELECT 1\").fetchone()\n"
+ )
+ p = tmp_path / "fake_state.py"
+ p.write_text(sabotage, encoding="utf-8")
+ violations = _scan_locked_readers(p)
+ assert len(violations) == 1
+ assert "guilty_reader" in violations[0]
+ assert "innocent_writer" not in violations[0]