Merge branch 'simp/r2-state' into simp/integration2

This commit is contained in:
Teknium
2026-09-02 17:05:04 -07:00
16 changed files with 6254 additions and 11762 deletions
+1589 -3934
View File
File diff suppressed because it is too large Load Diff
+117 -218
View File
@@ -13,16 +13,9 @@ import sys
import time
from typing import Any
from agent.skill_commands import (
SKILL_EXCERPT_JOINT,
SKILL_SCAFFOLD_SQL_LIKE,
describe_skill_invocation,
)
from agent.skill_commands import SKILL_EXCERPT_JOINT, SKILL_SCAFFOLD_SQL_LIKE, describe_skill_invocation
from agent.context_compressor import (
LEGACY_SUMMARY_PREFIX,
SUMMARY_PREFIX,
_MERGED_PRIOR_CONTEXT_HEADER,
_MERGED_SUMMARY_DELIMITER,
LEGACY_SUMMARY_PREFIX, SUMMARY_PREFIX, _MERGED_PRIOR_CONTEXT_HEADER, _MERGED_SUMMARY_DELIMITER,
_SUMMARY_END_MARKER,
)
@@ -33,35 +26,26 @@ from agent.context_compressor import (
# (whole message under budget, else head + tail where the typed instruction
# lands) so ``_shape_preview`` can recover ``/work — fix the title leak``.
_PREVIEW_HEAD_CHARS = 63
_PREVIEW_SCAFFOLD_WINDOW = 400
_PREVIEW_MAX_CHARS = 60
def escape_like(text: str) -> str:
"""Escape LIKE wildcards (``%``, ``_``) so derived text matches literally;
pair with ``ESCAPE '\\'``. ``_`` is common in branch names, titles and
paths, and a documented substring/prefix match must not silently widen.
"""
paths, and a documented substring/prefix match must not silently widen."""
return text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
_PREVIEW_CONTENT_SQL = "REPLACE(REPLACE(m.content, X'0A', ' '), X'0D', ' ')"
_PREVIEW_SCAFFOLDED_SQL = f"m.content LIKE '{SKILL_SCAFFOLD_SQL_LIKE}'"
_SQL_WHITESPACE = "CHAR(9) || CHAR(10) || CHAR(13) || CHAR(32)"
def _sql_literal(text: str) -> str:
return "'" + text.replace("'", "''") + "'"
_SQL_WHITESPACE = "CHAR(9) || CHAR(10) || CHAR(13) || CHAR(32)"
def _sql_ltrim_whitespace(expression: str) -> str:
return f"LTRIM({expression}, {_SQL_WHITESPACE})"
@@ -72,28 +56,22 @@ def _sql_trim_whitespace(expression: str) -> str:
def _sql_starts_with(expression: str, prefixes: tuple[str, ...]) -> str:
trimmed = _sql_ltrim_whitespace(expression)
checks = [
f"SUBSTR({trimmed}, 1, {len(prefix)}) = {_sql_literal(prefix)}"
for prefix in prefixes
]
checks = [f"SUBSTR({trimmed}, 1, {len(prefix)}) = {_sql_literal(prefix)}" for prefix in prefixes]
return "(" + " OR ".join(checks) + ")"
def _sql_after_marker(marker: str) -> str:
"""``m.content`` after the first occurrence of *marker*."""
return f"SUBSTR(m.content, INSTR(m.content, {_sql_literal(marker)}) + {len(marker)})"
# Current and legacy long-form prefixes share this whole introduction; matching
# all of it keeps an ordinary message that merely starts with the bracketed
# label from counting as a compaction carrier.
_PREVIEW_LONG_FORM_PREFIX = SUMMARY_PREFIX.split("Do NOT answer", 1)[0]
_PREVIEW_SUMMARY_PREFIXES = (
_PREVIEW_LONG_FORM_PREFIX,
LEGACY_SUMMARY_PREFIX,
)
_PREVIEW_STANDALONE_SUMMARY_SQL = _sql_starts_with(
"m.content", _PREVIEW_SUMMARY_PREFIXES
)
_PREVIEW_MERGED_AFTER_SQL = (
f"SUBSTR(m.content, INSTR(m.content, {_sql_literal(_MERGED_SUMMARY_DELIMITER)})"
f" + {len(_MERGED_SUMMARY_DELIMITER)})"
)
_PREVIEW_SUMMARY_PREFIXES = (_PREVIEW_LONG_FORM_PREFIX, LEGACY_SUMMARY_PREFIX)
_PREVIEW_STANDALONE_SUMMARY_SQL = _sql_starts_with("m.content", _PREVIEW_SUMMARY_PREFIXES)
_PREVIEW_MERGED_AFTER_SQL = _sql_after_marker(_MERGED_SUMMARY_DELIMITER)
_PREVIEW_MERGED_SUMMARY_SQL = (
f"(INSTR(m.content, {_sql_literal(_MERGED_SUMMARY_DELIMITER)}) > 0"
f" AND {_sql_starts_with(_PREVIEW_MERGED_AFTER_SQL, _PREVIEW_SUMMARY_PREFIXES)})"
@@ -101,19 +79,14 @@ _PREVIEW_MERGED_SUMMARY_SQL = (
_PREVIEW_MERGED_PRIOR_SQL = _sql_trim_whitespace(
f"SUBSTR(m.content, 1, INSTR(m.content, {_sql_literal(_MERGED_SUMMARY_DELIMITER)}) - 1)"
)
_PREVIEW_MERGED_PRIOR_LTRIMMED_SQL = _sql_ltrim_whitespace(
_PREVIEW_MERGED_PRIOR_SQL
)
_PREVIEW_MERGED_PRIOR_LTRIMMED_SQL = _sql_ltrim_whitespace(_PREVIEW_MERGED_PRIOR_SQL)
_PREVIEW_MERGED_PRIOR_UNWRAPPED_SQL = (
f"CASE WHEN SUBSTR({_PREVIEW_MERGED_PRIOR_LTRIMMED_SQL}, 1,"
f" {len(_MERGED_PRIOR_CONTEXT_HEADER)}) = {_sql_literal(_MERGED_PRIOR_CONTEXT_HEADER)}"
f" THEN {_sql_ltrim_whitespace(f'SUBSTR({_PREVIEW_MERGED_PRIOR_LTRIMMED_SQL}, {len(_MERGED_PRIOR_CONTEXT_HEADER) + 1})')}"
f" ELSE {_PREVIEW_MERGED_PRIOR_SQL} END"
)
_PREVIEW_FORCE_USER_REMAINDER_SQL = (
f"SUBSTR(m.content, INSTR(m.content, {_sql_literal(_SUMMARY_END_MARKER)})"
f" + {len(_SUMMARY_END_MARKER)})"
)
_PREVIEW_FORCE_USER_REMAINDER_SQL = _sql_after_marker(_SUMMARY_END_MARKER)
# Pure compaction rows are ineligible for previews; force-user-leading and
# merged carriers are eligible only when authentic content survives.
@@ -126,7 +99,6 @@ _PREVIEW_ELIGIBLE_SQL = (
f" AND LENGTH({_sql_trim_whitespace(_PREVIEW_MERGED_PRIOR_UNWRAPPED_SQL)}) > 0))"
)
# Shared ``_preview_raw`` SELECT expression for every listing query (scaffolded
# rows: head + tail spliced around SKILL_EXCERPT_JOINT when over budget).
_PREVIEW_RAW_SELECT = (
@@ -166,6 +138,7 @@ _PREVIEW_RAW_SUBQUERY_SQL = (
f" ORDER BY m.timestamp, m.id LIMIT 1), '') AS _preview_raw"
)
# ── Session lineage predicates ({a} = sessions alias) ───────────────────────
# A /branch child (kept visible, never cascade-deleted): stable marker OR the
# legacy end_reason heuristic.
@@ -176,15 +149,12 @@ _BRANCH_CHILD_SQL = (
" AND p.end_reason = 'branched'"
" AND {a}.started_at >= p.ended_at)"
)
_COMPRESSION_CHILD_SQL = (
"EXISTS (SELECT 1 FROM sessions p"
" WHERE p.id = {a}.parent_session_id"
" AND p.end_reason = 'compression')"
)
_RESET_END_REASONS = (
"session_reset",
# switch_session() creates no child row, but pre-marker DBs hold legacy
@@ -219,10 +189,7 @@ _RECOVERABLE_END_REASONS_SQL = ", ".join(f"'{reason}'" for reason in _RECOVERABL
# prove liveness (e.g. a compression rotation holding the lease) may clear it.
# Superset of the recoverable set plus the TUI gateway's automatic reasons.
_AUTOMATIC_END_REASONS = frozenset(_RECOVERABLE_END_REASONS) | {
"tui_shutdown",
"ws_disconnect",
"idle_timeout",
"lru_evict",
"tui_shutdown", "ws_disconnect", "idle_timeout", "lru_evict",
}
@@ -237,8 +204,7 @@ def _legacy_reset_child_sql(alias: str, reasons_sql: str) -> str:
"""Pre-marker reset-continuation heuristic: child rides its parent's exact
non-empty routing key and the parent ended at a reset boundary. Shared by
``_RESET_CHILD_SQL`` and ``reopen_session()``'s marker-stamping UPDATE so
the two cannot drift; ``reasons_sql`` is a literal or placeholder list.
"""
the two cannot drift; ``reasons_sql`` is a literal or placeholder list."""
return (
f"EXISTS (SELECT 1 FROM sessions p"
f" WHERE p.id = {alias}.parent_session_id"
@@ -257,7 +223,6 @@ _RESET_CHILD_SQL = (
" OR " + _legacy_reset_child_sql("{a}", _RESET_END_REASONS_SQL)
)
# Picker-visible rows: roots + branch/reset children (not subagent runs or
# compression continuations).
_LISTABLE_CHILD_SQL = (
@@ -268,51 +233,19 @@ _LISTABLE_CHILD_SQL = (
def _ephemeral_child_sql(alias: str = "s") -> str:
"""Subagent runs, not branch, reset, or compression children."""
branch = _BRANCH_CHILD_SQL.format(a=alias)
compression = _COMPRESSION_CHILD_SQL.format(a=alias)
reset = _RESET_CHILD_SQL.format(a=alias)
return (
f"({alias}.parent_session_id IS NOT NULL"
f" AND NOT ({branch})"
f" AND NOT ({compression})"
f" AND NOT ({reset}))"
f" AND NOT ({_BRANCH_CHILD_SQL.format(a=alias)})"
f" AND NOT ({_COMPRESSION_CHILD_SQL.format(a=alias)})"
f" AND NOT ({_RESET_CHILD_SQL.format(a=alias)}))"
)
def _sql_session_last_active(alias: str = "s") -> str:
"""Session recency: freshest of ``last_activity_at`` and the latest message
timestamp, else ``started_at``. Heartbeats are rate-limited (~60s) so
``last_activity_at`` can lag a newer message; never prefer it alone.
"""
msg_max = (
f"(SELECT MAX(_act_m.timestamp) FROM messages _act_m "
f"WHERE _act_m.session_id = {alias}.id)"
)
return (
f"COALESCE("
f"(SELECT MAX(_act_v.v) FROM ("
f"SELECT {alias}.last_activity_at AS v "
f"UNION ALL "
f"SELECT {msg_max}"
f") _act_v), "
f"{alias}.started_at)"
)
def _sql_session_last_active_by_id(session_id_expr: str) -> str:
"""Same freshest-of expression keyed by a session-id SQL expression."""
msg_max = (
f"(SELECT MAX(_act_m.timestamp) FROM messages _act_m "
f"WHERE _act_m.session_id = {session_id_expr})"
)
activity = (
f"(SELECT last_activity_at FROM sessions _act_s "
f"WHERE _act_s.id = {session_id_expr})"
)
started = (
f"(SELECT started_at FROM sessions _act_s "
f"WHERE _act_s.id = {session_id_expr})"
)
def _sql_freshest_of(activity: str, session_id_expr: str, started: str) -> str:
"""Freshest of *activity* and the latest message timestamp for
*session_id_expr*, else *started*. Heartbeats are rate-limited (~60s) so
``last_activity_at`` can lag a newer message; never prefer it alone."""
msg_max = f"(SELECT MAX(_act_m.timestamp) FROM messages _act_m WHERE _act_m.session_id = {session_id_expr})"
return (
f"COALESCE("
f"(SELECT MAX(_act_v.v) FROM ("
@@ -324,25 +257,36 @@ def _sql_session_last_active_by_id(session_id_expr: str) -> str:
)
def _sql_session_last_active(alias: str = "s") -> str:
"""Session recency expression for a ``sessions {alias}`` row."""
return _sql_freshest_of(f"{alias}.last_activity_at", f"{alias}.id", f"{alias}.started_at")
def _sql_session_last_active_by_id(session_id_expr: str) -> str:
"""Same freshest-of expression keyed by a session-id SQL expression."""
return _sql_freshest_of(
f"(SELECT last_activity_at FROM sessions _act_s WHERE _act_s.id = {session_id_expr})",
session_id_expr,
f"(SELECT started_at FROM sessions _act_s WHERE _act_s.id = {session_id_expr})",
)
SCHEMA_VERSION = 28
# Auto-maintenance VACUUMs only when at least this fraction of pages is on the
# freelist; below it a full rewrite costs more I/O than it returns.
AUTO_VACUUM_MIN_FREELIST_RATIO = 0.25
# FTS storage layout, tracked INDEPENDENTLY of SCHEMA_VERSION (state_meta
# ``fts_storage_version``): the schema version advances freely on open, but
# the FTS layout only changes when a DB is born fresh or explicitly optimized
# via ``hermes sessions optimize-storage``. Legacy DBs sit at 0 (marker
# absent) with a working inline index. 1 = v23 external-content layout.
# ``fts_storage_version``): schema version advances freely on open, the FTS
# layout only changes when a DB is born fresh or explicitly optimized via
# ``hermes sessions optimize-storage``. Legacy DBs sit at 0 (marker absent)
# with a working inline index; 1 = v23 external-content layout.
FTS_STORAGE_VERSION = 1
# Cap on user-controlled FTS5 query input before sanitizer processing.
MAX_FTS5_QUERY_CHARS = 2_048
# ── Helpers shared by SessionDB, its mixins and the registry ──────────────
def stat_db_file_identity(path) -> "tuple[int, int] | None":
@@ -359,15 +303,10 @@ def stat_db_file_identity(path) -> "tuple[int, int] | None":
_FTS_TRIGGERS = (
"messages_fts_insert",
"messages_fts_delete",
"messages_fts_update",
"messages_fts_trigram_insert",
"messages_fts_trigram_delete",
"messages_fts_trigram_update",
"messages_fts_insert", "messages_fts_delete", "messages_fts_update",
"messages_fts_trigram_insert", "messages_fts_trigram_delete", "messages_fts_trigram_update",
)
SCHEMA_SQL = """
CREATE TABLE IF NOT EXISTS schema_version (
version INTEGER NOT NULL
@@ -611,7 +550,6 @@ CREATE INDEX IF NOT EXISTS idx_async_delegations_delivery
ON async_delegations(delivery_state, completed_at);
"""
# Indexes on columns added in later schema versions must run AFTER
# _reconcile_columns() adds them, or executescript fails on legacy DBs.
DEFERRED_INDEX_SQL = """
@@ -629,18 +567,15 @@ CREATE INDEX IF NOT EXISTS idx_sessions_system_prompt_hash
ON sessions(system_prompt_hash);
"""
# ── Deferred FTS rebuild bookkeeping ──
# While a background rebuild is pending, two state_meta keys define which rows
# are IN the FTS indexes: H = fts_rebuild_high_water (MAX(messages.id) when the
# old indexes were dropped), P = fts_rebuild_progress (highest backfilled id).
# A row is indexed iff id <= P OR id > H (AUTOINCREMENT ids, so post-drop rows
# are indexed live by the insert triggers); rows in (P, H] are not.
#
# Every trigger gates on that predicate: an FTS5 external-content 'delete' for
# a row NOT in the index corrupts it, and skipping one for an indexed row
# leaves a stale entry. With no rebuild pending both keys are absent and
# COALESCE makes the predicate a tautology.
# A row is indexed iff id <= P OR id > H (AUTOINCREMENT ids: post-drop rows are
# indexed live by the insert triggers); rows in (P, H] are not. Every trigger
# gates on that predicate: an external-content 'delete' for a row NOT in the
# index corrupts it, and skipping one for an indexed row leaves a stale entry.
# With no rebuild pending both keys are absent and COALESCE makes it a tautology.
FTS_SQL = """
CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
content,
@@ -690,7 +625,6 @@ BEGIN
END;
"""
# Trigram FTS5 table for CJK substring search (unicode61 splits CJK into single
# tokens, breaking phrase matching). The trigram index is ~2.6x the text it
# covers and ``role='tool'`` rows are ~90% of message bytes of machine noise,
@@ -754,20 +688,15 @@ BEGIN
END;
"""
_FTS_CJK_TRIGGERS = (
"messages_fts_cjk_insert",
"messages_fts_cjk_delete",
"messages_fts_cjk_update",
"messages_fts_cjk_insert", "messages_fts_cjk_delete", "messages_fts_cjk_update",
)
# Set when a tokenizer-less process dropped the cjk triggers to keep writes
# alive: the cjk index is missing rows and must not serve reads until
# `hermes sessions optimize-storage` rebuilds it on a capable host.
FTS_CJK_STALE_KEY = "fts_cjk_stale"
# Set when a base/trigram FTS index was detached after runtime corruption.
# While present, startup must rebuild the complete index before reinstalling
# sync triggers: rows written while they were absent leave an unknown gap.
@@ -776,7 +705,6 @@ FTS_STALE_KEY = "fts_stale"
# Durable diagnostic for stale FTS recovery blocked across process restarts.
FTS_REBUILD_DEFERRAL_KEY = "fts_rebuild_deferral"
# ── Legacy (v22 / inline-content) FTS DDL ──────────────────────────────
# Used ONLY to keep a pre-v23 install's search working and its triggers
# repairable until `optimize_fts_storage()` migrates it: inline copies of
@@ -809,7 +737,6 @@ AFTER UPDATE OF content, tool_name, tool_calls ON messages BEGIN
END;
"""
LEGACY_FTS_TRIGRAM_SQL = """
CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts_trigram USING fts5(
content,
@@ -837,28 +764,23 @@ AFTER UPDATE OF content, tool_name, tool_calls ON messages BEGIN
END;
"""
# ── Cross-process full-FTS-rebuild admission (single authority) ──────────────
#
# Several Hermes processes share one state.db. A full structural FTS rebuild
# (FTS5 'rebuild' or the drop/recreate in `_recover_stale_fts`) must run in
# ONE of them at a time: concurrent rebuilds have structurally corrupted
# state.db in production. This is the single admission authority for
# `rebuild_fts()`, `_rebuild_fts_indexes()` and `_recover_stale_fts()`. The
# chunked backfill (`fts_rebuild_step`) is deliberately NOT routed through it:
# it claims progress under SQLite transaction authority and is multi-process.
#
# Several Hermes processes share one state.db; a full structural FTS rebuild
# (FTS5 'rebuild' or the drop/recreate in `_recover_stale_fts`) must run in ONE
# of them at a time — concurrent rebuilds structurally corrupted state.db in
# production. Single authority for `rebuild_fts()`, `_rebuild_fts_indexes()`
# and `_recover_stale_fts()`; the chunked backfill (`fts_rebuild_step`) is
# deliberately NOT routed through it (it claims progress under SQLite
# transaction authority and is multi-process).
# Semantics mirror `hermes_state._cross_process_repair_lock`: portable (msvcrt
# on Windows, flock elsewhere), bounded wait, FAIL CLOSED. The kernel drops
# the lock when the holder dies UNLESS a forked child inherited the fd (flock
# rides the open file description), which holds it forever; so the holder's
# pid + start time are recorded under the lock and a provably-dead holder's
# lock is broken by unlinking and retaking on a fresh inode. Indeterminate
# liveness still defers. Lives here because the mixins cannot import
# on Windows, flock elsewhere), bounded wait, FAIL CLOSED. flock rides the open
# file description, so a forked child that inherited the fd holds it forever
# after the holder dies; the holder's pid + start time are recorded under the
# lock and a provably-dead holder's lock is broken by unlinking and retaking on
# a fresh inode. Indeterminate liveness still defers. `<db>.fts_rebuild.lock`
# is distinct from `<db>.repair.lock` (schema surgery on an EXCLUSIVE offline
# connection, minutes in VACUUM). Lives here because mixins cannot import
# hermes_state (cycle).
#
# `<db>.fts_rebuild.lock` is distinct from `<db>.repair.lock`: schema surgery
# runs on an EXCLUSIVE offline connection and may take minutes in VACUUM.
logger = logging.getLogger("hermes_state")
@@ -885,9 +807,7 @@ def is_advisory_lock_contention(exc: BaseException) -> bool:
cannot succeed and polling only stalls the caller."""
if isinstance(exc, BlockingIOError):
return True
if not isinstance(exc, OSError):
return False
return exc.errno in _LOCK_CONTENTION_ERRNOS
return isinstance(exc, OSError) and exc.errno in _LOCK_CONTENTION_ERRNOS
def _proc_start_ticks(pid: int):
@@ -923,11 +843,7 @@ def _write_lock_holder_record(handle) -> None:
"""Record this process as holder (best effort), written under the flock so
timed-out contenders can tell an orphaned-fd holder from a live wedged one."""
try:
record = {
"pid": os.getpid(),
"start_ticks": _proc_start_ticks(os.getpid()),
"acquired_at": time.time(),
}
record = {"pid": os.getpid(), "start_ticks": _proc_start_ticks(os.getpid()), "acquired_at": time.time()}
handle.seek(0)
handle.truncate()
handle.write(json.dumps(record, sort_keys=True).encode("utf-8"))
@@ -964,8 +880,7 @@ def _lock_holder_provably_dead(record) -> bool:
except ProcessLookupError:
return True
except OSError:
# PermissionError et al.: the PID exists (or is unknowable) — closed.
return False
return False # PermissionError et al.: PID exists (or unknowable) — closed
recorded_ticks = record.get("start_ticks")
if recorded_ticks is None:
return False
@@ -976,9 +891,17 @@ def _lock_holder_provably_dead(record) -> bool:
return current_ticks != recorded_ticks
def _reopen_lock(lock_path, handle):
"""Close *handle* and reopen *lock_path*; returns the new handle or None."""
try:
handle.close()
return open(lock_path, "a+b")
except OSError:
return None
def _acquire_db_flock(lock_path, handle, timeout_seconds, poll_seconds, description):
"""Bounded POSIX flock acquire with orphaned-holder staleness break.
Returns ``(acquired, handle)``; *handle* may have been re-opened and the
caller closes whichever comes back. *acquired* is True, False (a holder
kept the lock past the deadline), or None (non-contention ``OSError``,
@@ -992,8 +915,7 @@ def _acquire_db_flock(lock_path, handle, timeout_seconds, poll_seconds, descript
is unlinked and retaken on a fresh inode; the orphan's flock stays on the
old inode blocking nobody. Every successful acquire verifies its inode
still names *lock_path*, so a racer that locked a dead inode retries
instead of running alongside the breaker. Indeterminate liveness defers.
"""
instead of running alongside the breaker. Indeterminate liveness defers."""
import fcntl
deadline = time.monotonic() + timeout_seconds
@@ -1008,10 +930,7 @@ def _acquire_db_flock(lock_path, handle, timeout_seconds, poll_seconds, descript
"Could not acquire %s %s (%s) — deferring rather than "
"waiting out the %.0fs holder timeout on a "
"non-contention error.",
description,
lock_path,
exc,
timeout_seconds,
description, lock_path, exc, timeout_seconds,
)
return None, handle
if time.monotonic() < deadline:
@@ -1027,21 +946,14 @@ def _acquire_db_flock(lock_path, handle, timeout_seconds, poll_seconds, descript
"holder pid %s is dead — a forked child inherited the lock "
"fd); breaking the stale lock and retaking it on a fresh "
"file.",
description,
lock_path,
(record or {}).get("pid"),
description, lock_path, (record or {}).get("pid"),
)
try:
os.unlink(lock_path)
handle.close()
handle = open(lock_path, "a+b")
except OSError as exc:
logger.warning(
"Could not break stale %s %s (%s) — deferring.",
description,
lock_path,
exc,
)
logger.warning("Could not break stale %s %s (%s) — deferring.", description, lock_path, exc)
return False, handle
broke_lock = True
deadline = time.monotonic() + _LOCK_BREAK_REACQUIRE_SECONDS
@@ -1051,20 +963,16 @@ def _acquire_db_flock(lock_path, handle, timeout_seconds, poll_seconds, descript
try:
fd_stat = os.fstat(handle.fileno())
path_stat = os.stat(lock_path)
same_file = (
fd_stat.st_dev == path_stat.st_dev
and fd_stat.st_ino == path_stat.st_ino
)
same_file = fd_stat.st_dev == path_stat.st_dev and fd_stat.st_ino == path_stat.st_ino
except OSError:
same_file = False
if same_file:
_write_lock_holder_record(handle)
return True, handle
try:
handle.close()
handle = open(lock_path, "a+b")
except OSError:
reopened = _reopen_lock(lock_path, handle)
if reopened is None:
return False, handle
handle = reopened
if time.monotonic() >= deadline:
return False, handle
@@ -1084,26 +992,44 @@ def _describe_lock_holder(record) -> str:
return f"pid {pid}{age}"
def _acquire_msvcrt_lock(lock_path, handle, timeout):
"""Windows counterpart of ``_acquire_db_flock`` (no orphan break); same
True / False / None contract."""
import msvcrt
deadline = time.monotonic() + timeout
while True:
try:
handle.seek(0)
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
return True
except (BlockingIOError, OSError) as exc:
if not is_advisory_lock_contention(exc):
logger.warning(
"Could not acquire FTS rebuild lock %s (%s) — "
"deferring on a non-contention error.",
lock_path, exc,
)
return None
if time.monotonic() >= deadline:
return False
time.sleep(_FTS_REBUILD_LOCK_POLL_SECONDS)
@contextlib.contextmanager
def fts_rebuild_admission(db_path, *, timeout_seconds=None):
"""Serialize full structural FTS rebuilds on *db_path* across processes.
Yields True when this process holds the authority, False when the bounded
acquire timed out or the lock file could not be opened. On False the
caller must NOT rebuild (fail closed); the stale breadcrumb guarantees a
retry. ``db_path`` None (in-memory DB) yields True.
Opportunistic in-process retries pass ``timeout_seconds=0`` so a live
holder never stalls a long-lived writer; the orphan break still applies.
"""
holder never stalls a long-lived writer; the orphan break still applies."""
if db_path is None:
yield True
return
timeout = (
_FTS_REBUILD_LOCK_TIMEOUT_SECONDS
if timeout_seconds is None
else max(float(timeout_seconds), 0.0)
)
timeout = _FTS_REBUILD_LOCK_TIMEOUT_SECONDS if timeout_seconds is None else max(float(timeout_seconds), 0.0)
lock_path = f"{db_path}.fts_rebuild.lock"
try:
handle = open(lock_path, "a+b")
@@ -1125,38 +1051,13 @@ def fts_rebuild_admission(db_path, *, timeout_seconds=None):
acquired = False
try:
if _IS_WINDOWS:
deadline = time.monotonic() + timeout
while True:
try:
import msvcrt
handle.seek(0)
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
acquired = True
break
except (BlockingIOError, OSError) as exc:
if not is_advisory_lock_contention(exc):
logger.warning(
"Could not acquire FTS rebuild lock %s (%s) — "
"deferring on a non-contention error.",
lock_path, exc,
)
acquired = None
break
if time.monotonic() >= deadline:
break
time.sleep(_FTS_REBUILD_LOCK_POLL_SECONDS)
acquired = _acquire_msvcrt_lock(lock_path, handle, timeout)
else:
acquired, handle = _acquire_db_flock(
lock_path,
handle,
timeout,
_FTS_REBUILD_LOCK_POLL_SECONDS,
"FTS rebuild lock",
lock_path, handle, timeout, _FTS_REBUILD_LOCK_POLL_SECONDS, "FTS rebuild lock",
)
if acquired is None:
# Already logged with the real errno; "held by another process"
# would be a lie.
# Already logged with the real errno; "held by another process" would be a lie.
acquired = False
elif not acquired:
record = None if _IS_WINDOWS else _read_lock_holder_record(handle)
@@ -1166,8 +1067,7 @@ def fts_rebuild_admission(db_path, *, timeout_seconds=None):
"FTS rebuild lock %s is busy — deferring this retry "
"(the stale-FTS breadcrumb keeps it retryable). "
"Recorded holder: %s.",
lock_path,
_describe_lock_holder(record),
lock_path, _describe_lock_holder(record),
)
else:
logger.warning(
@@ -1175,8 +1075,7 @@ def fts_rebuild_admission(db_path, *, timeout_seconds=None):
"%.0fs — deferring this rebuild to avoid racing the holder "
"(the stale-FTS breadcrumb keeps it retryable). "
"Recorded holder: %s.",
lock_path, timeout,
_describe_lock_holder(record),
lock_path, timeout, _describe_lock_holder(record),
)
yield acquired
finally:
File diff suppressed because it is too large Load Diff
+124 -253
View File
@@ -31,31 +31,27 @@ from hermes_state_common import (
# Log-record parity with the origin module (caplog tests pin "hermes_state").
logger = logging.getLogger("hermes_state")
# _read_sqlite_application_id runs on EVERY write via _raise_if_db_replaced,
# against the LIVE state.db. A bare open()/read()/close() there is the
# howtocorrupt §2.2 bug: close() cancels every POSIX advisory lock this
# process holds on the file — measured on Linux/SQLite 3.53.1, one probe call
# drops the WAL-mode DMS shared lock the writer connection holds on state.db
# (see hermes_cli/sqlite_safe_read.py for the module built around this rule).
# With the DMS lock gone, a fresh opener in another process can treat this
# writer as dead and rerun WAL-index recovery underneath it.
# process holds on the file — one probe call drops the WAL-mode DMS shared
# lock the writer connection holds (see hermes_cli/sqlite_safe_read.py). With
# the DMS lock gone, a fresh opener in another process can treat this writer
# as dead and rerun WAL-index recovery underneath it.
#
# The probe therefore reads through a per-path fd cached for the life of the
# process: opening an fd never cancels locks (only close() does), and
# os.pread takes no shared file position. When the path is re-pointed at a
# new inode (the very replacement this probe exists to detect), the stale fd
# is RETIRED, never closed — closing it would cancel the live connection's
# locks on the old file, the exact bug being avoided. Replacement events are
# rare and halt writes anyway, so the leak is bounded.
# locks on the old file. Replacement events are rare and halt writes anyway,
# so the leak is bounded.
_HEADER_PROBE_LOCK = threading.Lock()
_HEADER_PROBE_FDS: "dict[str, tuple[int, int, int]]" = {} # key -> (fd, dev, ino)
_RETIRED_HEADER_PROBE_FDS: "list[int]" = [] # intentionally never closed
_FTS_TABLE_NAMES = ("messages_fts", "messages_fts_trigram", "messages_fts_cjk")
def _pread_db_header(db_path: Path, length: int) -> "Optional[bytes]":
"""Lock-safe raw header read of a possibly-live SQLite database.
@@ -93,8 +89,7 @@ def _pread_db_header(db_path: Path, length: int) -> "Optional[bytes]":
except OSError:
_RETIRED_HEADER_PROBE_FDS.append(fd)
return None
cached = (fd, fst.st_dev, fst.st_ino)
_HEADER_PROBE_FDS[key] = cached
cached = _HEADER_PROBE_FDS[key] = (fd, fst.st_dev, fst.st_ino)
try:
return os.pread(cached[0], length, 0)
except OSError:
@@ -104,24 +99,15 @@ def _pread_db_header(db_path: Path, length: int) -> "Optional[bytes]":
def _read_sqlite_application_id(db_path: Path) -> "Optional[int]":
"""Read application_id from the SQLite header without opening a connection.
Safe against live databases: routed through :func:`_pread_db_header`,
which never issues a ``close()`` that would cancel this process's POSIX
locks on the file (howtocorrupt §2.2).
Routed through :func:`_pread_db_header`, which never issues a ``close()``
that would cancel this process's POSIX locks on the file.
"""
from hermes_state import _STATE_DB_APPLICATION_ID_OFFSET
header = _pread_db_header(db_path, _STATE_DB_APPLICATION_ID_OFFSET + 4)
if header is None:
end = _STATE_DB_APPLICATION_ID_OFFSET + 4
header = _pread_db_header(db_path, end)
if header is None or len(header) < end or header[:16] != b"SQLite format 3\x00":
return None
if len(header) < _STATE_DB_APPLICATION_ID_OFFSET + 4:
return None
if header[:16] != b"SQLite format 3\x00":
return None
return int(
struct.unpack(
">I",
header[_STATE_DB_APPLICATION_ID_OFFSET:_STATE_DB_APPLICATION_ID_OFFSET + 4],
)[0]
)
return int(struct.unpack(">I", header[_STATE_DB_APPLICATION_ID_OFFSET:end])[0])
def _stat_sqlite_sidecar_identity(db_path: Path) -> Dict[str, tuple]:
@@ -142,10 +128,24 @@ def _canonical_sqlite_path(path: str) -> str:
def _watched_sqlite_sidecar_paths(db_path) -> Set[str]:
base = os.path.abspath(os.fspath(db_path))
return {
_canonical_sqlite_path(base + "-wal"),
_canonical_sqlite_path(base + "-shm"),
}
return {_canonical_sqlite_path(base + "-wal"), _canonical_sqlite_path(base + "-shm")}
def _iter_proc_fd_targets():
"""Yield ``(pid, readlink target)`` for every readable ``/proc/<pid>/fd`` entry."""
for pid_str in os.listdir("/proc"):
if not pid_str.isdigit():
continue
fd_dir = f"/proc/{pid_str}/fd"
try:
fds = os.listdir(fd_dir)
except OSError:
continue # process gone or not ours
for fd in fds:
try:
yield int(pid_str), os.readlink(f"{fd_dir}/{fd}")
except OSError:
continue
def iter_deleted_sqlite_sidecar_holders(db_path) -> List[Tuple[int, str]]:
@@ -163,31 +163,14 @@ def iter_deleted_sqlite_sidecar_holders(db_path) -> List[Tuple[int, str]]:
"""
if not sys.platform.startswith("linux"):
return []
holders: List[Tuple[int, str]] = []
watched = _watched_sqlite_sidecar_paths(db_path)
try:
for pid_str in os.listdir("/proc"):
if not pid_str.isdigit():
continue
pid = int(pid_str)
fd_dir = f"/proc/{pid}/fd"
try:
fds = os.listdir(fd_dir)
except OSError:
continue
for fd in fds:
try:
target = os.readlink(f"{fd_dir}/{fd}")
except OSError:
continue
if " (deleted)" not in target:
continue
if _canonical_sqlite_path(target) in watched:
holders.append((pid, target))
for pid, target in _iter_proc_fd_targets():
if " (deleted)" in target and _canonical_sqlite_path(target) in watched:
holders.append((pid, target))
except Exception as exc:
logger.debug("deleted-WAL holder scan failed for %s: %s", db_path, exc)
return holders
return holders
@@ -198,8 +181,7 @@ def refuse_deleted_wal_generation(db_path) -> None:
replacement WAL inode while a live writer still holds the orphan.
"""
from hermes_state import DeletedWalGenerationError, _DELETED_WAL_GENERATION_MSG
holders = iter_deleted_sqlite_sidecar_holders(db_path)
if not holders:
if not iter_deleted_sqlite_sidecar_holders(db_path):
return
logger.error(_DELETED_WAL_GENERATION_MSG)
raise DeletedWalGenerationError(_DELETED_WAL_GENERATION_MSG)
@@ -216,8 +198,7 @@ def _connect_tracked_db(path, tracking_path=None, **kwargs):
The ONLY tolerated fallback is the helper being absent entirely
(scaffold/embed installs that ship hermes_state without hermes_cli). A
real connection failure must propagate: silently retrying an *untracked*
connect would disable the guard for the lifetime of that connection,
which is precisely the failure mode this module exists to prevent.
connect would disable the guard for the lifetime of that connection.
"""
try:
from hermes_cli.sqlite_safe_read import connect_tracked
@@ -228,22 +209,14 @@ def _connect_tracked_db(path, tracking_path=None, **kwargs):
path,
)
return sqlite3.connect(str(path), **kwargs)
# Open through THIS module's sqlite3.connect so callers (and tests) that
# patch hermes_state.sqlite3.connect keep control of connection creation;
# the helper still owns tracking.
return connect_tracked(
path,
tracking_path=tracking_path,
connect_fn=sqlite3.connect,
**kwargs,
)
return connect_tracked(path, tracking_path=tracking_path, connect_fn=sqlite3.connect, **kwargs)
def is_zeroed_state_db(
path: Path, *, probe_bytes: int = 100, force: bool = False
) -> bool:
"""Detect the #68474/#97568 zeroed state.db signature (0-byte or NUL header).
def is_zeroed_state_db(path: Path, *, probe_bytes: int = 100, force: bool = False) -> bool:
"""Detect the zeroed state.db signature (0-byte or NUL header).
Byte-level probe, so it is only safe BEFORE any connection to *path*
exists in this process: ``close()`` cancels every POSIX advisory lock the
@@ -277,10 +250,7 @@ def is_zeroed_state_db(
if not force and has_live_connection(path):
return False
head = read_header_bytes_preopen(
path, length=max(16, probe_bytes), force=force
)
head = read_header_bytes_preopen(path, length=max(16, probe_bytes), force=force)
if head is None:
return False
if len(head) == 0:
@@ -300,67 +270,56 @@ def quarantine_cross_process_lock(path: Path, timeout: float = 5.0):
handle = lock_path.open("a+b")
acquired = False
try:
deadline = time.monotonic() + timeout
if platform.system() == "Windows":
import msvcrt
while True:
try:
handle.seek(0)
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
acquired = True
break
except OSError:
if time.monotonic() >= deadline:
break
time.sleep(0.020)
def _try_lock():
handle.seek(0)
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
def _unlock():
handle.seek(0)
msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
else:
import fcntl
while True:
try:
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
acquired = True
def _try_lock():
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
def _unlock():
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
deadline = time.monotonic() + timeout
while True:
try:
_try_lock()
acquired = True
break
except OSError:
if time.monotonic() >= deadline:
break
except (BlockingIOError, OSError):
if time.monotonic() >= deadline:
break
time.sleep(0.020)
time.sleep(0.020)
yield acquired
finally:
try:
if acquired:
if platform.system() == "Windows":
import msvcrt
handle.seek(0)
msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
else:
import fcntl
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
_unlock()
except (OSError, AttributeError):
pass
finally:
handle.close()
def quarantine_zeroed_state_db(
path: Path, *, already_locked: bool = False
) -> Optional[Path]:
def quarantine_zeroed_state_db(path: Path, *, already_locked: bool = False) -> Optional[Path]:
"""Move a zeroed state.db aside (preserve bytes) and return quarantine path.
Uses a cross-process lock (``#68805``) so two concurrent startups cannot
race: the first process moves the zeroed file and the second re-checks
under the lock, finding the file already gone (or a fresh DB in its place)
instead of clobbering the quarantine.
Uses a cross-process lock so two concurrent startups cannot race: the first
process moves the zeroed file and the second re-checks under the lock,
finding the file already gone (or a fresh DB in its place) instead of
clobbering the quarantine.
"""
def _do_quarantine():
if not path.exists():
logger.info(
"quarantine_zeroed_state_db: %s already moved by another process",
path,
)
logger.info("quarantine_zeroed_state_db: %s already moved by another process", path)
return None
if not is_zeroed_state_db(path):
logger.info(
@@ -369,20 +328,16 @@ def quarantine_zeroed_state_db(
path,
)
return None
try:
ts = time.strftime("%Y%m%d-%H%M%S")
except Exception:
ts = "unknown"
dest = path.with_name(
f"{path.name}.zeroed-{ts}-{os.getpid()}.bak"
)
stem = f"{path.name}.zeroed-{ts}-{os.getpid()}"
dest = path.with_name(f"{stem}.bak")
n = 0
while dest.exists():
n += 1
dest = path.with_name(
f"{path.name}.zeroed-{ts}-{os.getpid()}-{n}.bak"
)
dest = path.with_name(f"{stem}-{n}.bak")
try:
path.rename(dest)
except OSError as exc:
@@ -399,7 +354,6 @@ def quarantine_zeroed_state_db(
if already_locked:
return _do_quarantine()
with quarantine_cross_process_lock(path) as acquired:
if not acquired:
logger.error(
@@ -421,97 +375,69 @@ def collect_state_db_stats(db_path: Path) -> Dict[str, Any]:
run against a *live* database held by a gateway without ever taking a
write lock or mutating the file. Every field is collected independently:
a failed pragma/SELECT yields ``None`` for that field, and the helper
itself never raises.
itself never raises. Deliberately does NOT instantiate :class:`SessionDB`
— its constructor runs schema DDL, which a diagnostics probe must never do.
Deliberately does NOT instantiate :class:`SessionDB` — its constructor
runs schema DDL (migrations, FTS table creation), which is exactly the
kind of write a diagnostics probe must never perform.
Returned keys (all present, any may be None on failure):
- ``page_count``, ``page_size``, ``freelist_count`` — PRAGMA values
- ``logical_size_bytes`` — page_count * page_size (post-checkpoint size)
- ``wal_size_bytes`` — stat() of ``<db>-wal`` (0 when absent)
- ``journal_mode`` — PRAGMA journal_mode string
- ``messages`` / ``sessions`` — row counts
- ``fts_tables`` — dict of {table_name: bool} presence for
messages_fts / messages_fts_trigram / messages_fts_cjk
- ``fts_storage_version`` — int from state_meta, None when the marker is
absent (legacy pre-v23 inline layout)
- ``fts_rebuild_pending`` — True when the deferred v23 backfill has not
finished (high_water present and progress < high_water)
- ``fts_rebuild_high_water`` / ``fts_rebuild_progress`` — raw ints
- ``fts_rebuild_deferral`` — durable blocked-repair diagnostic, when present
Returned keys (all present, any may be None on failure): ``page_count``,
``page_size``, ``freelist_count``, ``logical_size_bytes`` (page_count *
page_size), ``wal_size_bytes`` (stat of ``<db>-wal``, 0 when absent),
``journal_mode``, ``messages`` / ``sessions`` row counts, ``fts_tables``
({name: present}), ``fts_storage_version`` (None = legacy inline layout),
``fts_rebuild_pending`` (deferred backfill unfinished),
``fts_rebuild_high_water`` / ``fts_rebuild_progress`` raw ints, and
``fts_rebuild_deferral`` (durable blocked-repair diagnostic).
"""
from hermes_state import _connect_tracked_db
stats: Dict[str, Any] = {
"page_count": None,
"page_size": None,
"freelist_count": None,
"logical_size_bytes": None,
"wal_size_bytes": None,
"journal_mode": None,
"messages": None,
"sessions": None,
"fts_tables": None,
"fts_storage_version": None,
"fts_rebuild_pending": None,
"fts_rebuild_high_water": None,
"fts_rebuild_progress": None,
"fts_rebuild_deferral": None,
}
stats: Dict[str, Any] = dict.fromkeys((
"page_count", "page_size", "freelist_count", "logical_size_bytes", "wal_size_bytes",
"journal_mode", "messages", "sessions", "fts_tables", "fts_storage_version",
"fts_rebuild_pending", "fts_rebuild_high_water", "fts_rebuild_progress",
"fts_rebuild_deferral",
))
# WAL sidecar size needs no connection at all.
try:
wal_path = Path(str(db_path) + "-wal")
stats["wal_size_bytes"] = wal_path.stat().st_size if wal_path.exists() else 0
except OSError:
pass
conn = None
try:
# mode=ro refuses to create the file and refuses every write; a
# short timeout keeps doctor snappy when a writer holds the lock.
# Route through the tracked connect so byte-probe helpers
# (read_header_bytes_preopen) see this connection and refuse raw
# mode=ro refuses to create the file and refuses every write; a short
# timeout keeps doctor snappy when a writer holds the lock. The tracked
# connect lets byte-probe helpers see this connection and refuse raw
# opens that could cancel our POSIX locks mid-read.
conn = _connect_tracked_db(
f"file:{Path(db_path)}?mode=ro",
tracking_path=Path(db_path),
uri=True,
timeout=2.0,
f"file:{Path(db_path)}?mode=ro", tracking_path=Path(db_path), uri=True, timeout=2.0
)
except Exception as exc:
logger.debug("collect_state_db_stats: cannot open %s read-only: %s",
db_path, exc)
logger.debug("collect_state_db_stats: cannot open %s read-only: %s", db_path, exc)
return stats
def _scalar(sql: str) -> Any:
def _scalar(sql: str, params=()) -> Any:
try:
row = conn.execute(sql).fetchone()
row = conn.execute(sql, params).fetchone()
return row[0] if row else None
except Exception:
return None
def _int(value) -> Optional[int]:
return int(value) if value is not None else None
def _meta_int(key: str) -> Optional[int]:
try:
return _int(_scalar("SELECT value FROM state_meta WHERE key = ?", (key,)))
except Exception:
return None
try:
pc = _scalar("PRAGMA page_count")
ps = _scalar("PRAGMA page_size")
stats["page_count"] = int(pc) if pc is not None else None
stats["page_size"] = int(ps) if ps is not None else None
stats["page_count"] = _int(_scalar("PRAGMA page_count"))
stats["page_size"] = _int(_scalar("PRAGMA page_size"))
if stats["page_count"] is not None and stats["page_size"] is not None:
stats["logical_size_bytes"] = stats["page_count"] * stats["page_size"]
fl = _scalar("PRAGMA freelist_count")
stats["freelist_count"] = int(fl) if fl is not None else None
stats["freelist_count"] = _int(_scalar("PRAGMA freelist_count"))
jm = _scalar("PRAGMA journal_mode")
stats["journal_mode"] = str(jm) if jm is not None else None
msgs = _scalar("SELECT COUNT(*) FROM messages")
stats["messages"] = int(msgs) if msgs is not None else None
sess = _scalar("SELECT COUNT(*) FROM sessions")
stats["sessions"] = int(sess) if sess is not None else None
stats["messages"] = _int(_scalar("SELECT COUNT(*) FROM messages"))
stats["sessions"] = _int(_scalar("SELECT COUNT(*) FROM sessions"))
# FTS table presence via sqlite_master (never SELECTs from the
# virtual tables themselves — a corrupt index must not fail stats).
try:
@@ -520,39 +446,22 @@ def collect_state_db_stats(db_path: Path) -> Dict[str, Any]:
for row in conn.execute(
"SELECT name FROM sqlite_master WHERE type = 'table' "
"AND name IN (?, ?, ?)",
("messages_fts", "messages_fts_trigram", "messages_fts_cjk"),
_FTS_TABLE_NAMES,
).fetchall()
}
stats["fts_tables"] = {
t: (t in names)
for t in ("messages_fts", "messages_fts_trigram", "messages_fts_cjk")
}
stats["fts_tables"] = {t: (t in names) for t in _FTS_TABLE_NAMES}
except Exception:
pass
# Raw state_meta reads — cheap, and independent of SessionDB.
def _meta_int(key: str) -> Optional[int]:
try:
row = conn.execute(
"SELECT value FROM state_meta WHERE key = ?", (key,)
).fetchone()
return int(row[0]) if row and row[0] is not None else None
except Exception:
return None
stats["fts_storage_version"] = _meta_int("fts_storage_version")
high_water = _meta_int("fts_rebuild_high_water")
progress = _meta_int("fts_rebuild_progress")
stats["fts_rebuild_high_water"] = high_water
stats["fts_rebuild_progress"] = progress
if high_water is None:
stats["fts_rebuild_pending"] = False
else:
stats["fts_rebuild_pending"] = (progress or 0) < high_water
stats["fts_rebuild_pending"] = False if high_water is None else (progress or 0) < high_water
try:
row = conn.execute(
"SELECT value FROM state_meta WHERE key = ? LIMIT 1",
(FTS_REBUILD_DEFERRAL_KEY,),
"SELECT value FROM state_meta WHERE key = ? LIMIT 1", (FTS_REBUILD_DEFERRAL_KEY,)
).fetchone()
if row:
parsed = json.loads(row[0])
@@ -565,7 +474,6 @@ def collect_state_db_stats(db_path: Path) -> Dict[str, Any]:
conn.close()
except Exception:
pass
return stats
@@ -582,33 +490,13 @@ def count_db_holders(db_path: Path) -> Optional[int]:
if not sys.platform.startswith("linux"):
return None
target = os.path.realpath(str(db_path))
holders = 0
for pid in os.listdir("/proc"):
if not pid.isdigit():
continue
fd_dir = f"/proc/{pid}/fd"
try:
fds = os.listdir(fd_dir)
except OSError:
continue # process gone or not ours
for fd in fds:
try:
if os.readlink(f"{fd_dir}/{fd}") == target:
holders += 1
break # one hit per PID
except OSError:
continue
return holders
return len({pid for pid, link in _iter_proc_fd_targets() if link == target})
except Exception:
return None
def _is_inactive_orphan_desktop_holder(
*,
ppid: int,
age_seconds: float,
min_age_seconds: float,
ephemeral_backend: bool,
*, ppid: int, age_seconds: float, min_age_seconds: float, ephemeral_backend: bool,
connection_statuses: List[str],
) -> bool:
"""Pure safety predicate for the narrow Desktop holder reap."""
@@ -620,35 +508,21 @@ def _is_inactive_orphan_desktop_holder(
)
def _concrete_state_db_holder_pids(
db_path: Path, holders: List[Tuple[int, str]]
) -> List[int]:
def _concrete_state_db_holder_pids(db_path: Path, holders: List[Tuple[int, str]]) -> List[int]:
"""Return unique PIDs proven to hold this DB or one of its sidecars."""
canonical_db = os.path.normcase(os.path.abspath(os.fspath(db_path)))
watched = {
canonical_db,
canonical_db + "-wal",
canonical_db + "-shm",
}
watched = {canonical_db, canonical_db + "-wal", canonical_db + "-shm"}
pids: List[int] = []
seen = set()
for pid, path in holders:
canonical_path = os.path.normcase(
os.path.abspath(path.removesuffix(" (deleted)"))
)
if pid <= 0 or pid in seen or canonical_path not in watched:
if pid <= 0 or pid in pids or _canonical_sqlite_path(path) not in watched:
continue
seen.add(pid)
pids.append(pid)
return pids
def _read_proc_cmdline(pid: int) -> Optional[str]:
"""Read /proc/<pid>/cmdline, world-readable even when fd table is not.
Returns the cmdline as a space-joined string, or None when unreadable
(process exited, or hidepid mount).
"""
"""Read /proc/<pid>/cmdline (world-readable even when the fd table is not)
as a space-joined string; None when unreadable (exited, hidepid mount)."""
try:
with open(f"/proc/{pid}/cmdline", "rb") as f:
raw = f.read()
@@ -664,11 +538,8 @@ _HERMES_CMDLINE_MARKERS = ("hermes_cli.main", "hermes_cli/main", "hermes serve",
def _looks_like_hermes(cmdline: str) -> bool:
"""Heuristic: does this cmdline look like a Hermes process?
Used to decide whether an uninspectable process (fd table unreadable
due to different user) should be treated as a potential state.db holder.
We only flag processes that look like Hermes, not every system daemon.
"""
"""Heuristic: does this cmdline look like a Hermes process? Decides whether
an uninspectable process (fd table unreadable, different user) is treated
as a potential state.db holder; system daemons are not flagged."""
lower = cmdline.lower()
return any(marker in lower for marker in _HERMES_CMDLINE_MARKERS)
+235 -394
View File
@@ -8,7 +8,6 @@ from __future__ import annotations
import json
import logging
import sqlite3
import sys
import time
from pathlib import Path
@@ -23,6 +22,125 @@ from hermes_state_common import (
# Log-record parity with the origin module (caplog tests pin "hermes_state").
logger = logging.getLogger("hermes_state")
# Recursive CTE naming a session plus its compression ancestors (rows a
# resume must keep on one routing peer); branch/delegate/tool rows stop it.
_COMPRESSION_LINEAGE_CTE = """
WITH RECURSIVE compression_lineage(id) AS (
SELECT ?
UNION
SELECT parent.id
FROM compression_lineage lineage
JOIN sessions child ON child.id = lineage.id
JOIN sessions parent ON parent.id = child.parent_session_id
WHERE parent.end_reason = 'compression'
AND json_extract(
COALESCE(child.model_config, '{}'),
'$._branched_from'
) IS NULL
AND json_extract(
COALESCE(child.model_config, '{}'),
'$._delegate_from'
) IS NULL
AND COALESCE(child.source, '') != 'tool'
)
"""
# Projection shared by both peer-recovery queries (exact key, then peer tuple).
_PEER_SELECT_HEAD = """
SELECT s.*,
COALESCE(sp.prompt, s.system_prompt)
AS _system_prompt_resolved,
(COALESCE(s.message_count, 0) > 0 OR EXISTS (
SELECT 1 FROM messages WHERE messages.session_id = s.id LIMIT 1
)) AS _has_messages
FROM sessions s
LEFT JOIN system_prompts sp ON sp.hash = s.system_prompt_hash
"""
_PEER_BY_KEY_SQL = f"""{_PEER_SELECT_HEAD} WHERE s.session_key = ?
AND s.source = ?
AND (s.ended_at IS NULL OR s.end_reason IN ({_RECOVERABLE_END_REASONS_SQL}))
AND NOT EXISTS (
SELECT 1 FROM sessions b
WHERE b.session_key = s.session_key
AND b.source = s.source
AND b.ended_at IS NOT NULL
AND b.end_reason IN ({_RESET_END_REASONS_SQL})
AND b.ended_at
> COALESCE(s.last_activity_at, s.started_at)
)
ORDER BY _has_messages DESC,
COALESCE(s.last_activity_at, s.started_at) DESC
LIMIT 1
"""
_PEER_BY_TUPLE_SQL = f"""{_PEER_SELECT_HEAD} WHERE s.source = ?
AND COALESCE(s.user_id, '') = COALESCE(?, '')
AND COALESCE(s.chat_id, '') = COALESCE(?, '')
AND COALESCE(s.chat_type, '') = COALESCE(?, '')
AND COALESCE(s.thread_id, '') = COALESCE(?, '')
AND (? IS NULL OR COALESCE(s.profile_name, ?) = ?)
AND (s.ended_at IS NULL OR s.end_reason IN ({_RECOVERABLE_END_REASONS_SQL}))
AND (COALESCE(s.message_count, 0) > 0 OR EXISTS (
SELECT 1 FROM messages WHERE messages.session_id = s.id LIMIT 1
))
AND NOT EXISTS (
SELECT 1 FROM sessions b
WHERE b.source = s.source
AND COALESCE(b.user_id, '') = COALESCE(s.user_id, '')
AND COALESCE(b.chat_id, '') = COALESCE(s.chat_id, '')
AND COALESCE(b.chat_type, '') = COALESCE(s.chat_type, '')
AND COALESCE(b.thread_id, '') = COALESCE(s.thread_id, '')
AND b.ended_at IS NOT NULL
AND b.end_reason IN ({_RESET_END_REASONS_SQL})
AND b.ended_at
> COALESCE(s.last_activity_at, s.started_at)
)
ORDER BY COALESCE(s.last_activity_at, s.started_at) DESC
LIMIT 1
"""
_ORPHAN_DONOR_COLUMNS = (
"d.id, d.session_key, d.chat_id, d.chat_type, d.thread_id, "
"d.user_id, d.origin_json, d.display_name, d.end_reason"
)
_ORPHANS_SQL = f"""
SELECT o.id, o.source, o.user_id, o.started_at,
o.parent_session_id,
{_sql_session_last_active("o")} AS last_active,
(SELECT COUNT(*) FROM messages m
WHERE m.session_id = o.id) AS message_count
FROM sessions o
WHERE o.session_key IS NULL
AND EXISTS (SELECT 1 FROM messages m
WHERE m.session_id = o.id)
AND COALESCE(o.source, '') != 'tool'
AND json_extract(COALESCE(o.model_config, '{{}}'),
'$._branched_from') IS NULL
AND json_extract(COALESCE(o.model_config, '{{}}'),
'$._delegate_from') IS NULL
ORDER BY o.started_at ASC
"""
_ORPHAN_LINEAGE_DONOR_SQL = f"""
SELECT {_ORPHAN_DONOR_COLUMNS}
FROM sessions d
WHERE d.id = ?
AND d.session_key IS NOT NULL
AND COALESCE(d.source, '') = COALESCE(?, '')
"""
_ORPHAN_CONTIGUITY_DONORS_SQL = f"""
SELECT {_ORPHAN_DONOR_COLUMNS}, {_sql_session_last_active("d")} AS last_active
FROM sessions d
WHERE d.session_key IS NOT NULL
AND d.id != ?
AND COALESCE(d.source, '') = COALESCE(?, '')
AND (COALESCE(d.user_id, '') = ''
OR COALESCE(?, '') = ''
OR d.user_id = ?)
AND {_sql_session_last_active("d")} BETWEEN ? AND ?
AND {_sql_session_last_active("d")} < ?
ORDER BY last_active DESC
LIMIT 2
"""
class SessionGatewayMixin:
"""Routing index, session peers/orphans, hygiene streaks, heartbeats, handoffs."""
@@ -48,12 +166,9 @@ class SessionGatewayMixin:
for pid in _concrete_state_db_holder_pids(self.db_path, holders):
try:
process = psutil.Process(pid)
statuses = [
conn.status for conn in process.net_connections(kind="inet")
]
statuses = [conn.status for conn in process.net_connections(kind="inet")]
if not _is_inactive_orphan_desktop_holder(
ppid=process.ppid(),
age_seconds=now - process.create_time(),
ppid=process.ppid(), age_seconds=now - process.create_time(),
min_age_seconds=min_age_seconds,
ephemeral_backend=_is_ephemeral_port_zero_backend(process.cmdline()),
connection_statuses=statuses,
@@ -72,7 +187,6 @@ class SessionGatewayMixin:
continue
if not signalled:
return []
try:
_gone, alive = psutil.wait_procs(candidates, timeout=1.5)
except Exception:
@@ -90,17 +204,9 @@ class SessionGatewayMixin:
return signalled
def record_gateway_session_peer(
self,
session_id: str,
*,
source: str,
user_id: str = None,
session_key: str = None,
chat_id: str = None,
chat_type: str = None,
thread_id: str = None,
display_name: str = None,
origin_json: str = None,
self, session_id: str, *, source: str, user_id: str = None, session_key: str = None,
chat_id: str = None, chat_type: str = None, thread_id: str = None,
display_name: str = None, origin_json: str = None,
include_compression_ancestors: bool = False,
) -> None:
"""Persist the gateway routing peer for an existing session row.
@@ -120,48 +226,17 @@ class SessionGatewayMixin:
"""
if not session_id or not session_key:
return
def _do(conn):
identity = (session_key, source, user_id, chat_id, chat_type, thread_id, display_name, origin_json)
if include_compression_ancestors:
lineage_cte = _COMPRESSION_LINEAGE_CTE
target_clause = "WHERE id IN (SELECT id FROM compression_lineage)"
query_params = [session_id, *identity]
else:
lineage_cte = ""
target_clause = "WHERE id = ?"
query_params = []
if include_compression_ancestors:
lineage_cte = """
WITH RECURSIVE compression_lineage(id) AS (
SELECT ?
UNION
SELECT parent.id
FROM compression_lineage lineage
JOIN sessions child ON child.id = lineage.id
JOIN sessions parent ON parent.id = child.parent_session_id
WHERE parent.end_reason = 'compression'
AND json_extract(
COALESCE(child.model_config, '{}'),
'$._branched_from'
) IS NULL
AND json_extract(
COALESCE(child.model_config, '{}'),
'$._delegate_from'
) IS NULL
AND COALESCE(child.source, '') != 'tool'
)
"""
target_clause = "WHERE id IN (SELECT id FROM compression_lineage)"
query_params.append(session_id)
query_params.extend(
(
session_key,
source,
user_id,
chat_id,
chat_type,
thread_id,
display_name,
origin_json,
)
)
if not include_compression_ancestors:
query_params.append(session_id)
query_params = [*identity, session_id]
def _do(conn):
conn.execute(
f"""{lineage_cte}
UPDATE sessions
@@ -174,13 +249,12 @@ class SessionGatewayMixin:
)
# Self-heal: the UPDATE silently no-ops on a missing row — insert it
# with full identity so the session is durably routable.
if not include_compression_ancestors:
cur = conn.execute(
"SELECT 1 FROM sessions WHERE id = ? LIMIT 1", (session_id,)
)
if cur.fetchone() is None:
conn.execute(
"""INSERT INTO sessions (
if include_compression_ancestors:
return
cur = conn.execute("SELECT 1 FROM sessions WHERE id = ? LIMIT 1", (session_id,))
if cur.fetchone() is None:
conn.execute(
"""INSERT INTO sessions (
id, source, user_id, session_key, chat_id,
chat_type, thread_id, display_name, origin_json,
profile_name, started_at
@@ -193,28 +267,19 @@ class SessionGatewayMixin:
thread_id = COALESCE(sessions.thread_id, excluded.thread_id),
display_name = COALESCE(sessions.display_name, excluded.display_name),
origin_json = COALESCE(sessions.origin_json, excluded.origin_json)""",
(
session_id,
source,
user_id,
session_key,
chat_id,
chat_type,
thread_id,
display_name,
origin_json,
# Same ownership stamp as _insert_session_row: an
# unowned (NULL) row vanishes from profile-keyed consumers.
self._own_profile_name(),
time.time(),
),
)
(
session_id, source, user_id, session_key, chat_id, chat_type, thread_id,
display_name, origin_json,
# Same ownership stamp as _insert_session_row: an
# unowned (NULL) row vanishes from profile-keyed consumers.
self._own_profile_name(),
time.time(),
),
)
self._execute_write(_do)
def save_gateway_routing_entry(
self, session_key: str, entry_json: str, *, scope: str = ""
) -> None:
def save_gateway_routing_entry(self, session_key: str, entry_json: str, *, scope: str = "") -> None:
"""Upsert one gateway routing entry (session_key -> SessionEntry JSON).
``gateway_routing`` durably replaces sessions.json. ``scope`` namespaces
@@ -222,7 +287,6 @@ class SessionGatewayMixin:
"""
if not session_key or not entry_json:
return
self._write_sql(
"""INSERT INTO gateway_routing (scope, session_key, entry_json, updated_at)
VALUES (?, ?, ?, ?)
@@ -232,9 +296,7 @@ class SessionGatewayMixin:
(scope, session_key, entry_json, time.time()),
)
def replace_gateway_routing_entries(
self, entries: Dict[str, str], *, scope: str = ""
) -> None:
def replace_gateway_routing_entries(self, entries: Dict[str, str], *, scope: str = "") -> None:
"""Atomically replace the routing index for *scope* with *entries*.
Full-rewrite semantics: keys absent from *entries* are removed. One
@@ -256,14 +318,11 @@ class SessionGatewayMixin:
def load_gateway_routing_entries(self, *, scope: str = "") -> Dict[str, str]:
"""Load routing entries for *scope* as {session_key: entry_json}."""
rows = self._read_all(
"SELECT session_key, entry_json FROM gateway_routing WHERE scope = ?",
(scope,),
"SELECT session_key, entry_json FROM gateway_routing WHERE scope = ?", (scope,)
)
return {r["session_key"]: r["entry_json"] for r in rows}
def list_never_active_keyed_sessions(
self, *, older_than_days: float
) -> List[Dict[str, Any]]:
def list_never_active_keyed_sessions(self, *, older_than_days: float) -> List[Dict[str, Any]]:
"""Keyed gateway rows that were opened and then never used at all.
Keyed, still-open rows with no evidence of a single turn (no messages,
@@ -321,19 +380,13 @@ class SessionGatewayMixin:
doomed.append((row["scope"], row["session_key"]))
if not doomed:
return 0
self._write_sql(
"DELETE FROM gateway_routing WHERE scope = ? AND session_key = ?",
doomed,
many=True,
"DELETE FROM gateway_routing WHERE scope = ? AND session_key = ?", doomed, many=True
)
return len(doomed)
def prune_never_active_keyed_sessions(
self,
*,
older_than_days: float,
sessions_dir: Optional[Path] = None,
self, *, older_than_days: float, sessions_dir: Optional[Path] = None
) -> Tuple[int, int]:
"""Delete never-active keyed rows and the routing entries naming them.
@@ -343,24 +396,16 @@ class SessionGatewayMixin:
:meth:`delete_session` so the delegate cascade, FTS bookkeeping and
transcript cleanup stay owned by one implementation.
"""
candidates = self.list_never_active_keyed_sessions(
older_than_days=older_than_days
)
candidates = self.list_never_active_keyed_sessions(older_than_days=older_than_days)
if not candidates:
return (0, 0)
ids = {str(row["id"]) for row in candidates}
routing_deleted = self._delete_routing_entries_for_sessions(ids)
deleted = 0
for session_id in ids:
if self.delete_session(session_id, sessions_dir=sessions_dir):
deleted += 1
deleted = sum(1 for sid in ids if self.delete_session(sid, sessions_dir=sessions_dir))
return (deleted, routing_deleted)
def list_gateway_sessions(
self,
*,
platform: Optional[str] = None,
active_only: bool = True,
self, *, platform: Optional[str] = None, active_only: bool = True
) -> List[Dict[str, Any]]:
"""List gateway sessions (rows with a session_key): newest row per key,
one live mapping per routing key. ``platform`` filters on ``source``."""
@@ -388,17 +433,11 @@ class SessionGatewayMixin:
if active_only:
query += " AND ended_at IS NULL"
query += " ORDER BY last_active DESC"
rows = self._read_all(query, params)
return [self._session_row_dict(r) for r in rows]
return [self._session_row_dict(r) for r in self._read_all(query, params)]
def find_latest_gateway_session_for_peer(
self,
*,
source: str,
user_id: Optional[str] = None,
session_key: Optional[str] = None,
chat_id: Optional[str] = None,
chat_type: Optional[str] = None,
self, *, source: str, user_id: Optional[str] = None, session_key: Optional[str] = None,
chat_id: Optional[str] = None, chat_type: Optional[str] = None,
thread_id: Optional[str] = None,
) -> Optional[Dict[str, Any]]:
"""Find the latest recoverable gateway session for a routing peer.
@@ -409,105 +448,38 @@ class SessionGatewayMixin:
``ws_orphan_reap`` are recoverable; explicit boundaries (/new, /resume
switches, compression splits) are not.
Ordering: rank by ``last_activity_at`` (falling back to ``started_at``)
— ``started_at`` alone resurrected days-old zombie rows over the live
conversation. Rows with messages win, but an empty keyed row is still
returned rather than ``None``: ``None`` mints a brand-new session id,
worse than resuming an empty-but-correctly-keyed row (whose transcript
may live under a compression child).
Ranked by ``last_activity_at`` (falling back to ``started_at``) —
``started_at`` alone resurrected days-old zombie rows. Rows with
messages win, but an empty keyed row is still returned rather than
``None`` (``None`` mints a brand-new session id; the transcript may
live under a compression child). Reset fence: a candidate is rejected
when a peer boundary row (``session_reset`` or any non-recoverable
end_reason) ended *after* its last activity, or the has-messages
ranking could reach behind a /new and restore the reset context.
Reset fence: an intentional boundary (``session_reset`` or any
non-recoverable end_reason) must block fallback to an *older* row for
the same peer, or the has-messages ranking could reach behind a /new
and restore the exact context the user reset — so a candidate is
rejected when a peer boundary row ended *after* its last activity.
Fallback for a temporarily-missing exact key still requires the
complete peer tuple (never cross chats/threads/users) plus a profile
fence: a Telegram DM's peer tuple is identical for every bot (chat_id
== user_id, no thread), so a sibling profile's legacy row would
otherwise be adopted. A row is ours when profile_name is the owner or
NULL; stores outside the profile tree derive no owner and stay unfenced.
"""
if not session_key:
return None
with self._read_ctx() as conn:
row = conn.execute(
f"""
SELECT s.*,
COALESCE(sp.prompt, s.system_prompt)
AS _system_prompt_resolved,
(COALESCE(s.message_count, 0) > 0 OR EXISTS (
SELECT 1 FROM messages WHERE messages.session_id = s.id LIMIT 1
)) AS _has_messages
FROM sessions s
LEFT JOIN system_prompts sp ON sp.hash = s.system_prompt_hash
WHERE s.session_key = ?
AND s.source = ?
AND (s.ended_at IS NULL OR s.end_reason IN ({_RECOVERABLE_END_REASONS_SQL}))
AND NOT EXISTS (
SELECT 1 FROM sessions b
WHERE b.session_key = s.session_key
AND b.source = s.source
AND b.ended_at IS NOT NULL
AND b.end_reason IN ({_RESET_END_REASONS_SQL})
AND b.ended_at
> COALESCE(s.last_activity_at, s.started_at)
)
ORDER BY _has_messages DESC,
COALESCE(s.last_activity_at, s.started_at) DESC
LIMIT 1
""",
(session_key, source),
).fetchone()
row = conn.execute(_PEER_BY_KEY_SQL, (session_key, source)).fetchone()
if row is not None:
return self._session_row_dict(row)
# Conservative fallback for a temporarily-missing exact key: still
# require the complete peer tuple so we never cross chats/threads/users.
if chat_id is None or chat_type is None:
return None
# Profile fence: a Telegram DM's peer tuple is identical for every
# bot (chat_id == user_id, no thread), so a sibling profile's legacy
# row would otherwise be adopted. A row is ours when profile_name is
# the owner or NULL (legacy rows this store minted); stores outside
# the profile tree derive no owner and stay unfenced.
owner = self._own_profile_name()
row = conn.execute(
f"""
SELECT s.*,
COALESCE(sp.prompt, s.system_prompt)
AS _system_prompt_resolved,
(COALESCE(s.message_count, 0) > 0 OR EXISTS (
SELECT 1 FROM messages WHERE messages.session_id = s.id LIMIT 1
)) AS _has_messages
FROM sessions s
LEFT JOIN system_prompts sp ON sp.hash = s.system_prompt_hash
WHERE s.source = ?
AND COALESCE(s.user_id, '') = COALESCE(?, '')
AND COALESCE(s.chat_id, '') = COALESCE(?, '')
AND COALESCE(s.chat_type, '') = COALESCE(?, '')
AND COALESCE(s.thread_id, '') = COALESCE(?, '')
AND (? IS NULL OR COALESCE(s.profile_name, ?) = ?)
AND (s.ended_at IS NULL OR s.end_reason IN ({_RECOVERABLE_END_REASONS_SQL}))
AND (COALESCE(s.message_count, 0) > 0 OR EXISTS (
SELECT 1 FROM messages WHERE messages.session_id = s.id LIMIT 1
))
AND NOT EXISTS (
SELECT 1 FROM sessions b
WHERE b.source = s.source
AND COALESCE(b.user_id, '') = COALESCE(s.user_id, '')
AND COALESCE(b.chat_id, '') = COALESCE(s.chat_id, '')
AND COALESCE(b.chat_type, '') = COALESCE(s.chat_type, '')
AND COALESCE(b.thread_id, '') = COALESCE(s.thread_id, '')
AND b.ended_at IS NOT NULL
AND b.end_reason IN ({_RESET_END_REASONS_SQL})
AND b.ended_at
> COALESCE(s.last_activity_at, s.started_at)
)
ORDER BY COALESCE(s.last_activity_at, s.started_at) DESC
LIMIT 1
""",
_PEER_BY_TUPLE_SQL,
(source, user_id, chat_id, chat_type, thread_id, owner, owner, owner),
).fetchone()
return self._session_row_dict(row) if row else None
def find_orphaned_gateway_sessions(
self, *, max_gap_s: Optional[float] = None
) -> List[Dict[str, Any]]:
def find_orphaned_gateway_sessions(self, *, max_gap_s: Optional[float] = None) -> List[Dict[str, Any]]:
"""Report message-bearing session rows that lost their routing identity.
A candidate orphan has messages but no ``session_key``; it is
@@ -523,137 +495,56 @@ class SessionGatewayMixin:
mis-adopting splices one person's conversation into another's chat.
Branch/delegate/tool rows are excluded — unkeyed by design, not damage.
"""
gap = (
self._ORPHAN_ADOPTION_MAX_GAP_S
if max_gap_s is None
else float(max_gap_s)
)
orphan_active = _sql_session_last_active("o")
donor_active = _sql_session_last_active("d")
donor_columns = (
"d.id, d.session_key, d.chat_id, d.chat_type, d.thread_id, "
"d.user_id, d.origin_json, d.display_name, d.end_reason"
)
gap = self._ORPHAN_ADOPTION_MAX_GAP_S if max_gap_s is None else float(max_gap_s)
records: List[Dict[str, Any]] = []
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,
{orphan_active} AS last_active,
(SELECT COUNT(*) FROM messages m
WHERE m.session_id = o.id) AS message_count
FROM sessions o
WHERE o.session_key IS NULL
AND EXISTS (SELECT 1 FROM messages m
WHERE m.session_id = o.id)
AND COALESCE(o.source, '') != 'tool'
AND json_extract(COALESCE(o.model_config, '{{}}'),
'$._branched_from') IS NULL
AND json_extract(COALESCE(o.model_config, '{{}}'),
'$._delegate_from') IS NULL
ORDER BY o.started_at ASC
"""
).fetchall()
for orphan in orphans:
for orphan in conn.execute(_ORPHANS_SQL).fetchall():
donor = None
evidence = ""
reason = ""
if orphan["parent_session_id"]:
evidence = "lineage"
donor = conn.execute(
f"""
SELECT {donor_columns}
FROM sessions d
WHERE d.id = ?
AND d.session_key IS NOT NULL
AND COALESCE(d.source, '') = COALESCE(?, '')
""",
(orphan["parent_session_id"], orphan["source"]),
_ORPHAN_LINEAGE_DONOR_SQL, (orphan["parent_session_id"], orphan["source"])
).fetchone()
if donor is None:
reason = (
"parent session carries no gateway identity of "
"this source"
)
reason = "parent session carries no gateway identity of this source"
else:
evidence = "contiguity"
started = orphan["started_at"] or 0
candidates = conn.execute(
f"""
SELECT {donor_columns}, {donor_active} AS last_active
FROM sessions d
WHERE d.session_key IS NOT NULL
AND d.id != ?
AND COALESCE(d.source, '') = COALESCE(?, '')
AND (COALESCE(d.user_id, '') = ''
OR COALESCE(?, '') = ''
OR d.user_id = ?)
AND {donor_active} BETWEEN ? AND ?
AND {donor_active} < ?
ORDER BY last_active DESC
LIMIT 2
""",
(
orphan["id"],
orphan["source"],
orphan["user_id"],
orphan["user_id"],
(orphan["started_at"] or 0) - gap,
(orphan["started_at"] or 0) + gap,
orphan["last_active"],
),
_ORPHAN_CONTIGUITY_DONORS_SQL,
(orphan["id"], orphan["source"], orphan["user_id"], orphan["user_id"],
started - gap, started + gap, orphan["last_active"]),
).fetchall()
if not candidates:
reason = (
f"no keyed predecessor fell quiet within {gap:.0f}s "
"of this session's start"
)
reason = f"no keyed predecessor fell quiet within {gap:.0f}s of this session's start"
elif len(candidates) > 1:
reason = (
"ambiguous: more than one keyed predecessor "
"matches this window"
)
reason = "ambiguous: more than one keyed predecessor matches this window"
else:
donor = candidates[0]
records.append(
{
"orphan_id": orphan["id"],
"source": orphan["source"],
"message_count": orphan["message_count"],
"started_at": orphan["started_at"],
"last_active": orphan["last_active"],
"donor_id": donor["id"] if donor else None,
"session_key": donor["session_key"] if donor else None,
"evidence": evidence if donor else "",
"adoptable": donor is not None,
"reason": reason,
}
)
records.append({
"orphan_id": orphan["id"], "source": orphan["source"],
"message_count": orphan["message_count"], "started_at": orphan["started_at"],
"last_active": orphan["last_active"],
"donor_id": donor["id"] if donor else None,
"session_key": donor["session_key"] if donor else None,
"evidence": evidence if donor else "",
"adoptable": donor is not None,
"reason": reason,
})
# Two unkeyed successors claiming one predecessor: at most one continues
# that chat, and nothing here says which.
contested = {
r["donor_id"]
for r in records
if r["adoptable"]
and sum(1 for x in records if x["donor_id"] == r["donor_id"]) > 1
r["donor_id"] for r in records
if r["adoptable"] and sum(1 for x in records if x["donor_id"] == r["donor_id"]) > 1
}
for record in records:
if record["donor_id"] in contested:
record["adoptable"] = False
record["reason"] = (
"ambiguous: more than one unkeyed session claims this "
"predecessor"
)
record["reason"] = "ambiguous: more than one unkeyed session claims this predecessor"
return records
def adopt_orphaned_gateway_session(
self, orphan_id: str, donor_id: str
) -> bool:
def adopt_orphaned_gateway_session(self, orphan_id: str, donor_id: str) -> bool:
"""Stamp *orphan_id* with *donor_id*'s routing identity, retire *donor_id*.
Re-verifies the pair inside the write transaction so a concurrent
@@ -670,8 +561,7 @@ class SessionGatewayMixin:
(donor_id,),
).fetchone()
orphan = conn.execute(
"SELECT session_key, source FROM sessions WHERE id = ?",
(orphan_id,),
"SELECT session_key, source FROM sessions WHERE id = ?", (orphan_id,)
).fetchone()
if donor is None or orphan is None:
return False
@@ -679,7 +569,6 @@ class SessionGatewayMixin:
return False
if (donor["source"] or "") != (orphan["source"] or ""):
return False
conn.execute(
"""UPDATE sessions
SET session_key = ?,
@@ -691,17 +580,8 @@ class SessionGatewayMixin:
display_name = COALESCE(display_name, ?),
parent_session_id = COALESCE(parent_session_id, ?)
WHERE id = ? AND session_key IS NULL""",
(
donor["session_key"],
donor["chat_id"],
donor["chat_type"],
donor["thread_id"],
donor["user_id"],
donor["origin_json"],
donor["display_name"],
donor_id,
orphan_id,
),
(donor["session_key"], donor["chat_id"], donor["chat_type"], donor["thread_id"],
donor["user_id"], donor["origin_json"], donor["display_name"], donor_id, orphan_id),
)
# Retire the predecessor under a reason recovery does NOT treat as
# resumable — 'agent_close'/'ws_orphan_reap' would keep it in the
@@ -719,7 +599,6 @@ class SessionGatewayMixin:
"""Atomically increment the session-hygiene failure streak for one chat."""
if not session_key:
return 1
result = []
def _do(conn):
conn.execute(
@@ -733,20 +612,15 @@ class SessionGatewayMixin:
"SELECT failure_streak FROM gateway_hygiene_state WHERE session_key = ?",
(session_key,),
).fetchone()
result.append(int(row[0]))
return int(row[0])
self._execute_write(_do)
return result[0]
return self._execute_write(_do)
def reset_hygiene_failure_streak(self, session_key: str) -> None:
"""Clear the persisted session-hygiene failure streak for one chat."""
if not session_key:
return
self._write_sql(
"DELETE FROM gateway_hygiene_state WHERE session_key = ?",
(session_key,),
)
self._write_sql("DELETE FROM gateway_hygiene_state WHERE session_key = ?", (session_key,))
@staticmethod
def session_gateway_runtime(session_meta: Optional[Dict[str, Any]]) -> Dict[str, Any]:
@@ -769,41 +643,26 @@ class SessionGatewayMixin:
if not isinstance(raw, dict):
raw = {}
runtime = raw.get("gateway_runtime")
# Filter None: the persist path writes or-None to trigger deletion in
# the top-level merge, but gateway_runtime is replaced whole (not
# deep-merged), so None values survive here.
if isinstance(runtime, dict) and runtime.get("provider"):
# Filter None: the persist path writes or-None to trigger deletion
# in the top-level merge, but gateway_runtime is replaced whole
# (not deep-merged), so None values survive here.
return {k: v for k, v in runtime.items() if v is not None}
top_level = {
key: raw.get(key)
for key in ("provider", "base_url", "api_mode")
if raw.get(key)
}
top_level = {key: raw.get(key) for key in ("provider", "base_url", "api_mode") if raw.get(key)}
if top_level:
return top_level
# Last resort: billing_provider, COALESCE-written on the first accounted
# API call — the only durable record for sessions that never ran /model.
# Bare buckets ("auto"/"custom") are not routable identities; filter
# them so resume falls back to the ambient config default.
billing_provider = str(
(session_meta or {}).get("billing_provider") or ""
).strip()
if (
billing_provider
and billing_provider.lower() not in _BARE_BILLING_PROVIDERS
):
billing_provider = str((session_meta or {}).get("billing_provider") or "").strip()
if billing_provider and billing_provider.lower() not in _BARE_BILLING_PROVIDERS:
return {"provider": billing_provider}
return {k: v for k, v in (runtime or {}).items() if v is not None} if isinstance(runtime, dict) else {}
def register_backend_heartbeat(
self,
*,
backend_id: str,
pid: int,
started_at: float,
last_heartbeat: Optional[float] = None,
profile: str = "",
host: str = "",
self, *, backend_id: str, pid: int, started_at: float,
last_heartbeat: Optional[float] = None, profile: str = "", host: str = "",
) -> None:
"""Upsert this backend's liveness row.
@@ -826,8 +685,7 @@ class SessionGatewayMixin:
" last_heartbeat = excluded.last_heartbeat,"
" profile = excluded.profile,"
" host = excluded.host",
(str(backend_id), int(pid), float(started_at), ts,
str(profile), str(host)),
(str(backend_id), int(pid), float(started_at), ts, str(profile), str(host)),
)
def clear_backend_heartbeat(self, backend_id: str) -> bool:
@@ -836,8 +694,7 @@ class SessionGatewayMixin:
if not backend_id:
return False
return self._write_rowcount(
"DELETE FROM gateway_heartbeats WHERE backend_id = ?",
(str(backend_id),),
"DELETE FROM gateway_heartbeats WHERE backend_id = ?", (str(backend_id),)
) > 0
def prune_stale_heartbeats(self, *, max_age_seconds: float) -> List[str]:
@@ -846,6 +703,7 @@ class SessionGatewayMixin:
if max_age_seconds <= 0:
return []
cutoff = time.time() - max_age_seconds
def _do(conn):
cur = conn.execute(
"DELETE FROM gateway_heartbeats WHERE last_heartbeat < ?"
@@ -862,16 +720,7 @@ class SessionGatewayMixin:
" profile, host FROM gateway_heartbeats"
" ORDER BY last_heartbeat DESC",
)
out: List[Dict[str, Any]] = []
for r in rows:
if isinstance(r, sqlite3.Row):
out.append({k: r[k] for k in r.keys()})
else:
out.append({
"backend_id": r[0], "pid": r[1], "started_at": r[2],
"last_heartbeat": r[3], "profile": r[4], "host": r[5],
})
return out
return [dict(r) for r in rows]
def request_handoff(self, session_id: str, platform: str) -> bool:
"""Mark a session pending handoff to *platform*; False if a handoff is already in flight."""
@@ -935,11 +784,7 @@ class SessionGatewayMixin:
)
def fail_handoff(
self,
session_id: str,
error: str,
*,
only_states: Optional[Tuple[str, ...]] = None,
self, session_id: str, error: str, *, only_states: Optional[Tuple[str, ...]] = None
) -> bool:
"""Mark a handoff failed and record the reason; True when a row transitioned.
@@ -952,22 +797,20 @@ class SessionGatewayMixin:
(split-brain: the handoff delivered and ``switch_session`` re-pointed
the session). The watcher fails its OWN claimed row unconditionally.
"""
def _do(conn):
if only_states:
placeholders = ", ".join("?" for _ in only_states)
cur = conn.execute(
"UPDATE sessions SET handoff_state = 'failed', "
f"handoff_error = ? WHERE id = ? AND handoff_state IN ({placeholders})",
(error[:500], session_id, *only_states),
)
else:
cur = conn.execute(
"UPDATE sessions SET handoff_state = 'failed', "
"handoff_error = ? WHERE id = ?",
(error[:500], session_id),
)
return cur.rowcount > 0
return bool(self._execute_write(_do))
if only_states:
placeholders = ", ".join("?" for _ in only_states)
sql = (
"UPDATE sessions SET handoff_state = 'failed', "
f"handoff_error = ? WHERE id = ? AND handoff_state IN ({placeholders})"
)
params = (error[:500], session_id, *only_states)
else:
sql = (
"UPDATE sessions SET handoff_state = 'failed', "
"handoff_error = ? WHERE id = ?"
)
params = (error[:500], session_id)
return self._write_rowcount(sql, params) > 0
def reclaim_stale_running_handoffs(self, error: str) -> List[str]:
"""Fail every handoff stuck in ``running``. Returns the ids reclaimed.
@@ -982,9 +825,7 @@ class SessionGatewayMixin:
delivery; a clean terminal state the user can retry from is right.
"""
def _do(conn):
cur = conn.execute(
"SELECT id FROM sessions WHERE handoff_state = 'running'"
)
cur = conn.execute("SELECT id FROM sessions WHERE handoff_state = 'running'")
ids = [r[0] for r in cur.fetchall()]
if ids:
conn.execute(
+156 -298
View File
@@ -17,6 +17,63 @@ from hermes_state_common import (
# caplog tests pin the "hermes_state" logger name.
logger = logging.getLogger("hermes_state")
_LAST_ACTIVE_SQL = """COALESCE(
(SELECT MAX(m.timestamp) FROM messages m
WHERE m.session_id = s.id),
s.started_at
)"""
_TOKENS_SQL = "(COALESCE(s.input_tokens, 0) + COALESCE(s.output_tokens, 0))"
_COST_SQL = "COALESCE(s.actual_cost_usd, s.estimated_cost_usd, 0)"
def _like(value: str) -> str:
return f"%{_escape_like(value.lower())}%"
def _cwd_prefix_filter(value: str) -> Tuple[List[str], list]:
from hermes_state import _cwd_prefix_clause
clause, params = _cwd_prefix_clause(value)
return [clause], list(params)
def _one(clause: str, conv=None):
return lambda v: ([clause], [conv(v) if conv else v])
# Prune/archive filters in evaluation order: (kwarg, applies-when, builder).
# ``applies-when`` is "notnone" (numeric/time bounds; 0 is a real bound) or
# "truthy" (strings; "" means unset). Builders return (clauses, params).
_PRUNE_FILTERS = (
# Orphan-swept rows age from the sweep, not their old activity, or the
# next prune pass deletes them before the user can recover.
("last_active_before", "notnone", lambda v: (
[_LAST_ACTIVE_SQL + " < ?",
"(COALESCE(s.end_reason, '') != 'startup_orphan_reap' OR s.ended_at < ?)"],
[v, v])),
("last_active_after", "notnone", _one(_LAST_ACTIVE_SQL + " >= ?")),
("started_before", "notnone", _one("s.started_at < ?")),
("started_after", "notnone", _one("s.started_at >= ?")),
("source", "truthy", _one("s.source = ?")),
("title_like", "truthy", _one("LOWER(COALESCE(s.title, '')) LIKE ? ESCAPE '\\'", _like)),
("end_reason", "truthy", _one("s.end_reason = ?")),
("cwd_prefix", "truthy", _cwd_prefix_filter),
("min_messages", "notnone", _one("s.message_count >= ?")),
("max_messages", "notnone", _one("s.message_count <= ?")),
("model_like", "truthy", _one("LOWER(COALESCE(s.model, '')) LIKE ? ESCAPE '\\'", _like)),
("provider", "truthy", _one("LOWER(COALESCE(s.billing_provider, '')) = ?", str.lower)),
("user_id", "truthy", _one("s.user_id = ?")),
("chat_id", "truthy", _one("s.chat_id = ?")),
("chat_type", "truthy", _one("s.chat_type = ?")),
("branch_like", "truthy", _one("LOWER(COALESCE(s.git_branch, '')) LIKE ? ESCAPE '\\'", _like)),
("min_tokens", "notnone", _one(_TOKENS_SQL + " >= ?")),
("max_tokens", "notnone", _one(_TOKENS_SQL + " <= ?")),
("min_cost", "notnone", _one(_COST_SQL + " >= ?")),
("max_cost", "notnone", _one(_COST_SQL + " <= ?")),
("min_tool_calls", "notnone", _one("COALESCE(s.tool_call_count, 0) >= ?")),
("max_tool_calls", "notnone", _one("COALESCE(s.tool_call_count, 0) <= ?")),
)
_PRUNE_FILTER_NAMES = frozenset(name for name, _, _ in _PRUNE_FILTERS) | {"archived", "include_pinned"}
class SessionMaintenanceMixin:
"""Retention pruning, stale-session archiving and VACUUM policy for SessionDB."""
@@ -39,9 +96,7 @@ class SessionMaintenanceMixin:
ids = [r[0] for r in rows]
if ids:
placeholders = ",".join("?" * len(ids))
conn.execute(
f"DELETE FROM sessions WHERE id IN ({placeholders})", ids
)
conn.execute(f"DELETE FROM sessions WHERE id IN ({placeholders})", ids)
self._delete_unreferenced_system_prompts(conn)
return ids
@@ -52,12 +107,9 @@ class SessionMaintenanceMixin:
return len(removed_ids)
def sweep_orphaned_sessions(
self,
*,
max_idle_seconds: float,
self, *, max_idle_seconds: float,
sources: Tuple[str, ...] = ("tui", "desktop", "subagent"),
exclude_ids: Tuple[str, ...] = (),
exclude_pinned: bool = False,
exclude_ids: Tuple[str, ...] = (), exclude_pinned: bool = False,
heartbeat_staleness_seconds: Optional[float] = None,
heartbeat_ownership_grace_seconds: Optional[float] = None,
respect_gateway_heartbeats: bool = True,
@@ -66,18 +118,15 @@ class SessionMaintenanceMixin:
The TUI/desktop gateway reaps disconnected sessions with an in-process
grace timer; a restart destroys the timer and leaves ``ended_at IS
NULL`` forever. This closes rows for ``sources`` whose ``started_at``
AND canonical last activity (newest of ``last_activity_at`` and the
newest message, else ``started_at``) are both older than
``max_idle_seconds``, with ``end_reason='startup_orphan_reap'``. The
separate ``started_at`` predicate protects fresh compression/branch
children whose copied activity is old.
Only pass sources whose lifecycle the caller owns — never messaging
platforms like ``telegram`` (ending those triggers a routing loop).
``exclude_ids`` spares rows this process still holds in memory.
Non-destructive: messages are kept and the row stays resumable;
first-reason-wins via ``ended_at IS NULL``.
NULL`` forever. Closes rows for ``sources`` whose ``started_at`` AND
canonical last activity are both older than ``max_idle_seconds`` with
``end_reason='startup_orphan_reap'`` (the separate ``started_at``
predicate protects fresh compression/branch children whose copied
activity is old). Only pass sources whose lifecycle the caller owns —
never messaging platforms like ``telegram`` (ending those triggers a
routing loop). ``exclude_ids`` spares rows this process still holds in
memory. Non-destructive: messages are kept and the row stays
resumable; first-reason-wins via ``ended_at IS NULL``.
Cross-backend liveness: with ``respect_gateway_heartbeats``, a row is
reaped only when stale AND no live backend (heartbeat within
@@ -89,7 +138,7 @@ class SessionMaintenanceMixin:
Disable the gate only for sources owned by state.db itself.
SELECT, live-lease validation and UPDATE run in one ``BEGIN IMMEDIATE``
transaction. Active turn leases / compression locks spare the row;
transaction; active turn leases / compression locks spare the row, and
expired guards are removed so their former owner is fenced.
"""
from hermes_state import SessionCompressionInProgressError, SessionTurnLeaseLostError
@@ -103,20 +152,15 @@ class SessionMaintenanceMixin:
)
hb_grace = (
heartbeat_ownership_grace_seconds
if heartbeat_ownership_grace_seconds is not None
and heartbeat_ownership_grace_seconds >= 0
if heartbeat_ownership_grace_seconds is not None and heartbeat_ownership_grace_seconds >= 0
else hb_staleness
)
now = time.time()
cutoff = now - max_idle_seconds
hb_cutoff = now - hb_staleness
placeholders = ",".join("?" for _ in srcs)
staleness = (
f"started_at < ? AND {_sql_session_last_active('sessions')} < ?"
)
pin_scope = " AND COALESCE(pinned, 0) = 0" if exclude_pinned else ""
orphan_predicate = f"started_at < ? AND {_sql_session_last_active('sessions')} < ?"
heartbeat_params: Tuple[float, ...] = ()
orphan_predicate = staleness
if respect_gateway_heartbeats:
orphan_predicate += (
" AND NOT EXISTS ("
@@ -125,14 +169,13 @@ class SessionMaintenanceMixin:
" AND h.started_at <= sessions.started_at + ?"
")"
)
heartbeat_params = (hb_cutoff, hb_grace)
heartbeat_params = (now - hb_staleness, hb_grace)
scope_sql = f" AND source IN ({placeholders}){pin_scope} AND {orphan_predicate}"
scope_params = (*srcs, cutoff, cutoff, *heartbeat_params)
def _do(conn):
rows = conn.execute(
f"SELECT id FROM sessions WHERE ended_at IS NULL"
f" AND source IN ({placeholders}){pin_scope}"
f" AND {orphan_predicate}",
(*srcs, cutoff, cutoff, *heartbeat_params),
f"SELECT id FROM sessions WHERE ended_at IS NULL{scope_sql}", scope_params
).fetchall()
excluded = {str(x) for x in exclude_ids if x}
victims = []
@@ -142,37 +185,20 @@ class SessionMaintenanceMixin:
continue
try:
self._check_transcript_write_guards(
conn,
sid,
compression_lock_holder=None,
turn_lease_holder=None,
reject_active_turn_lease=True,
reject_active_compression_lock=True,
conn, sid, compression_lock_holder=None, turn_lease_holder=None,
reject_active_turn_lease=True, reject_active_compression_lock=True,
)
except (
SessionCompressionInProgressError,
SessionTurnLeaseLostError,
):
except (SessionCompressionInProgressError, SessionTurnLeaseLostError):
continue
victims.append(sid)
if not victims:
return []
closed_at = time.time()
marks = ",".join("?" for _ in victims)
# Re-apply every predicate under the write lock.
conn.execute(
f"UPDATE sessions SET ended_at = ?, end_reason = 'startup_orphan_reap'"
f" WHERE id IN ({marks}) AND ended_at IS NULL"
f" AND source IN ({placeholders}){pin_scope}"
f" AND {orphan_predicate}",
(
closed_at,
*victims,
*srcs,
cutoff,
cutoff,
*heartbeat_params,
),
f" WHERE id IN ({marks}) AND ended_at IS NULL{scope_sql}",
(time.time(), *victims, *scope_params),
)
return victims
@@ -180,137 +206,30 @@ class SessionMaintenanceMixin:
@staticmethod
def _prune_filter_where(
*,
last_active_before: Optional[float] = None,
last_active_after: Optional[float] = None,
started_before: Optional[float] = None,
started_after: Optional[float] = None,
source: Optional[str] = None,
title_like: Optional[str] = None,
end_reason: Optional[str] = None,
cwd_prefix: Optional[str] = None,
min_messages: Optional[int] = None,
max_messages: Optional[int] = None,
archived: Optional[bool] = None,
model_like: Optional[str] = None,
provider: Optional[str] = None,
user_id: Optional[str] = None,
chat_id: Optional[str] = None,
chat_type: Optional[str] = None,
branch_like: Optional[str] = None,
min_tokens: Optional[int] = None,
max_tokens: Optional[int] = None,
min_cost: Optional[float] = None,
max_cost: Optional[float] = None,
min_tool_calls: Optional[int] = None,
max_tool_calls: Optional[int] = None,
include_pinned: bool = False,
*, archived: Optional[bool] = None, include_pinned: bool = False, **filters
) -> Tuple[str, list]:
"""Shared WHERE clause for bulk prune/archive selection (alias ``s``).
Filters AND together; only ended sessions are ever candidates.
``archived`` is tri-state (None = both). ``*_like`` filters are
case-insensitive substrings; the rest are exact (provider
Filters (see ``_PRUNE_FILTERS``) AND together; only ended sessions are
ever candidates. ``archived`` is tri-state (None = both). ``*_like``
filters are case-insensitive substrings; the rest are exact (provider
case-insensitive). Token bounds use input+output; cost bounds use
``COALESCE(actual_cost_usd, estimated_cost_usd)``.
"""
from hermes_state import _cwd_prefix_clause
unknown = set(filters) - _PRUNE_FILTER_NAMES
if unknown:
raise TypeError(
"SessionMaintenanceMixin._prune_filter_where() got an unexpected "
f"keyword argument {sorted(unknown)[0]!r}"
)
clauses = ["s.ended_at IS NOT NULL"]
params: list = []
if last_active_before is not None:
clauses.append(
"""COALESCE(
(SELECT MAX(m.timestamp) FROM messages m
WHERE m.session_id = s.id),
s.started_at
) < ?"""
)
params.append(last_active_before)
# Orphan-swept rows age from the sweep, not their old activity, or
# the next prune pass deletes them before the user can recover.
clauses.append(
"(COALESCE(s.end_reason, '') != 'startup_orphan_reap' "
"OR s.ended_at < ?)"
)
params.append(last_active_before)
if last_active_after is not None:
clauses.append(
"""COALESCE(
(SELECT MAX(m.timestamp) FROM messages m
WHERE m.session_id = s.id),
s.started_at
) >= ?"""
)
params.append(last_active_after)
if started_before is not None:
clauses.append("s.started_at < ?")
params.append(started_before)
if started_after is not None:
clauses.append("s.started_at >= ?")
params.append(started_after)
if source:
clauses.append("s.source = ?")
params.append(source)
if title_like:
clauses.append("LOWER(COALESCE(s.title, '')) LIKE ? ESCAPE '\\'")
params.append(f"%{_escape_like(title_like.lower())}%")
if end_reason:
clauses.append("s.end_reason = ?")
params.append(end_reason)
if cwd_prefix:
clause, clause_params = _cwd_prefix_clause(cwd_prefix)
clauses.append(clause)
params.extend(clause_params)
if min_messages is not None:
clauses.append("s.message_count >= ?")
params.append(min_messages)
if max_messages is not None:
clauses.append("s.message_count <= ?")
params.append(max_messages)
if model_like:
clauses.append("LOWER(COALESCE(s.model, '')) LIKE ? ESCAPE '\\'")
params.append(f"%{_escape_like(model_like.lower())}%")
if provider:
clauses.append("LOWER(COALESCE(s.billing_provider, '')) = ?")
params.append(provider.lower())
if user_id:
clauses.append("s.user_id = ?")
params.append(user_id)
if chat_id:
clauses.append("s.chat_id = ?")
params.append(chat_id)
if chat_type:
clauses.append("s.chat_type = ?")
params.append(chat_type)
if branch_like:
clauses.append("LOWER(COALESCE(s.git_branch, '')) LIKE ? ESCAPE '\\'")
params.append(f"%{_escape_like(branch_like.lower())}%")
if min_tokens is not None:
clauses.append(
"(COALESCE(s.input_tokens, 0) + COALESCE(s.output_tokens, 0)) >= ?"
)
params.append(min_tokens)
if max_tokens is not None:
clauses.append(
"(COALESCE(s.input_tokens, 0) + COALESCE(s.output_tokens, 0)) <= ?"
)
params.append(max_tokens)
if min_cost is not None:
clauses.append(
"COALESCE(s.actual_cost_usd, s.estimated_cost_usd, 0) >= ?"
)
params.append(min_cost)
if max_cost is not None:
clauses.append(
"COALESCE(s.actual_cost_usd, s.estimated_cost_usd, 0) <= ?"
)
params.append(max_cost)
if min_tool_calls is not None:
clauses.append("COALESCE(s.tool_call_count, 0) >= ?")
params.append(min_tool_calls)
if max_tool_calls is not None:
clauses.append("COALESCE(s.tool_call_count, 0) <= ?")
params.append(max_tool_calls)
for name, applies, build in _PRUNE_FILTERS:
value = filters.get(name)
if (value is not None) if applies == "notnone" else bool(value):
new_clauses, new_params = build(value)
clauses.extend(new_clauses)
params.extend(new_params)
if archived is True:
clauses.append("s.archived = 1")
elif archived is False:
@@ -322,33 +241,28 @@ class SessionMaintenanceMixin:
return " AND ".join(clauses), params
@staticmethod
def _apply_prune_age_filter(
older_than_days: Optional[float], filters: Dict[str, Any]
) -> None:
def _apply_prune_age_filter(older_than_days: Optional[float], filters: Dict[str, Any]) -> None:
"""Translate the legacy age window into the shared activity filter."""
if (
filters.get("last_active_before") is None
and filters.get("started_before") is None
and older_than_days is not None
):
filters["last_active_before"] = time.time() - (
older_than_days * 86400
)
filters["last_active_before"] = time.time() - (older_than_days * 86400)
def _prune_where(self, older_than_days, source, filters) -> Tuple[str, list]:
self._apply_prune_age_filter(older_than_days, filters)
return self._prune_filter_where(source=source, **filters)
def list_prune_candidates(
self,
older_than_days: Optional[float] = None,
source: str = None,
**filters,
self, older_than_days: Optional[float] = None, source: str = None, **filters
) -> List[Dict[str, Any]]:
"""Sessions a matching prune/archive would touch (dry-run), oldest
first. Same filters as :meth:`_prune_filter_where`; ``older_than_days``
is an inactivity threshold (latest message, else ``started_at``)."""
self._apply_prune_age_filter(older_than_days, filters)
where, params = self._prune_filter_where(source=source, **filters)
with self._read_ctx() as conn:
cursor = conn.execute(
f"""SELECT s.id, s.source, s.title, s.model, s.started_at,
where, params = self._prune_where(older_than_days, source, filters)
rows = self._read_all(
f"""SELECT s.id, s.source, s.title, s.model, s.started_at,
COALESCE(
(SELECT MAX(m.timestamp) FROM messages m
WHERE m.session_id = s.id),
@@ -357,50 +271,32 @@ class SessionMaintenanceMixin:
s.ended_at, s.message_count, s.archived
FROM sessions s WHERE {where}
ORDER BY last_active ASC, s.started_at ASC""",
params,
)
return [dict(row) for row in cursor.fetchall()]
params,
)
return [dict(row) for row in rows]
def count_prune_matches(
self,
older_than_days: Optional[float] = None,
source: str = None,
**filters,
self, older_than_days: Optional[float] = None, source: str = None, **filters
) -> int:
"""Count-only variant of :meth:`list_prune_candidates` (the CLI uses it
to report how many pinned sessions are spared)."""
self._apply_prune_age_filter(older_than_days, filters)
where, params = self._prune_filter_where(source=source, **filters)
with self._read_ctx() as conn:
cursor = conn.execute(
f"SELECT COUNT(*) FROM sessions s WHERE {where}", params
)
return int(cursor.fetchone()[0])
where, params = self._prune_where(older_than_days, source, filters)
return int(self._read_one(f"SELECT COUNT(*) FROM sessions s WHERE {where}", params)[0])
def count_open_prune_matches(
self,
older_than_days: Optional[float] = None,
source: str = None,
**filters,
self, older_than_days: Optional[float] = None, source: str = None, **filters
) -> int:
"""Count open sessions a matching prune skips: every normal filter with
only the ``ended_at`` guard inverted. Visibility-only; live sessions
never become prune-eligible."""
self._apply_prune_age_filter(older_than_days, filters)
where, params = self._prune_filter_where(source=source, **filters)
where, params = self._prune_where(older_than_days, source, filters)
ended_guard = "s.ended_at IS NOT NULL"
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._read_ctx() as conn:
cursor = conn.execute(
f"SELECT COUNT(*) FROM sessions s WHERE {open_where}", params
)
return int(cursor.fetchone()[0])
return int(self._read_one(f"SELECT COUNT(*) FROM sessions s WHERE {open_where}", params)[0])
def archive_stale_sessions(
self, idle_days: float, *, exclude_pinned: bool = True
) -> int:
def archive_stale_sessions(self, idle_days: float, *, exclude_pinned: bool = True) -> int:
"""Archive every session untouched for ``idle_days`` (real recency:
freshest of ``last_activity_at`` / latest message / ``started_at``).
Unlike :meth:`archive_sessions`, this can archive unended sessions.
@@ -432,11 +328,8 @@ class SessionMaintenanceMixin:
return len(ids)
def prune_sessions(
self,
older_than_days: Optional[float] = 90,
source: str = None,
sessions_dir: Optional[Path] = None,
exclude_active_write_guards: bool = False,
self, older_than_days: Optional[float] = 90, source: str = None,
sessions_dir: Optional[Path] = None, exclude_active_write_guards: bool = False,
**filters,
) -> int:
"""Delete ended sessions matching the filters; returns the count.
@@ -454,46 +347,32 @@ class SessionMaintenanceMixin:
while expired/dead holders are reclaimed and fenced in the same write.
"""
from hermes_state import SessionCompressionInProgressError, SessionTurnLeaseLostError
self._apply_prune_age_filter(older_than_days, filters)
where, where_params = self._prune_filter_where(source=source, **filters)
where, where_params = self._prune_where(older_than_days, source, filters)
removed_ids: list[str] = []
def _do(conn):
cursor = conn.execute(
f"SELECT s.id FROM sessions s WHERE {where}", where_params
)
cursor = conn.execute(f"SELECT s.id FROM sessions s WHERE {where}", where_params)
session_ids = {row["id"] for row in cursor.fetchall()}
if exclude_active_write_guards:
protected = set()
for sid in session_ids:
try:
self._check_transcript_write_guards(
conn,
sid,
compression_lock_holder=None,
turn_lease_holder=None,
reject_active_turn_lease=True,
reject_active_compression_lock=True,
conn, sid, compression_lock_holder=None, turn_lease_holder=None,
reject_active_turn_lease=True, reject_active_compression_lock=True,
allow_closed_compression_parent=True,
)
except (
SessionCompressionInProgressError,
SessionTurnLeaseLostError,
):
except (SessionCompressionInProgressError, SessionTurnLeaseLostError):
protected.add(sid)
session_ids.difference_update(protected)
if not session_ids:
return 0
placeholders = ",".join("?" * len(session_ids))
conn.execute(
f"UPDATE sessions SET parent_session_id = NULL "
f"WHERE parent_session_id IN ({placeholders})",
list(session_ids),
)
for sid in session_ids:
conn.execute("DELETE FROM messages WHERE session_id = ?", (sid,))
conn.execute("DELETE FROM sessions WHERE id = ?", (sid,))
@@ -506,6 +385,14 @@ class SessionMaintenanceMixin:
self._remove_session_files(sessions_dir, sid)
return count
def _page_pragmas(self, *names: str) -> Optional[list]:
"""Read integer PRAGMAs over the existing connection (never a byte probe
of the live file); None if the connection is closed or a pragma fails."""
with self._read_ctx() as conn:
if self._conn is None:
return None
return [conn.execute(f"PRAGMA {name}").fetchone()[0] for name in names]
def logical_size_bytes(self) -> Optional[int]:
"""``page_count * page_size``: the main-file size once the WAL is
checkpointed back in. Prefer over ``os.path.getsize`` when reporting a
@@ -514,28 +401,24 @@ class SessionMaintenanceMixin:
understates the win and can go negative. None if pragmas fail.
"""
try:
with self._read_ctx() as conn:
if self._conn is None:
return None
page_count = conn.execute("PRAGMA page_count").fetchone()[0]
page_size = conn.execute("PRAGMA page_size").fetchone()[0]
values = self._page_pragmas("page_count", "page_size")
if values is None:
return None
page_count, page_size = values
return int(page_count) * int(page_size)
except Exception as exc:
logger.debug("Could not read logical DB size: %s", exc)
return None
def _freelist_ratio(self) -> Optional[float]:
"""Reclaimable fraction (``freelist_count / page_count``) over the
existing connection — never a byte-level probe of the live file. Gates
VACUUM in :meth:`maybe_auto_prune_and_vacuum`. None if pragmas fail
(callers then fall back to the time throttle alone).
"""
"""Reclaimable fraction (``freelist_count / page_count``); gates VACUUM
in :meth:`maybe_auto_prune_and_vacuum`. None if pragmas fail (callers
then fall back to the time throttle alone)."""
try:
with self._read_ctx() as conn:
if self._conn is None:
return None
page_count = int(conn.execute("PRAGMA page_count").fetchone()[0])
freelist = int(conn.execute("PRAGMA freelist_count").fetchone()[0])
values = self._page_pragmas("page_count", "freelist_count")
if values is None:
return None
page_count, freelist = int(values[0]), int(values[1])
if page_count <= 0:
return 0.0
return freelist / page_count
@@ -553,13 +436,11 @@ class SessionMaintenanceMixin:
:meth:`optimize_fts` so the VACUUM reclaims those pages too. Returns
the number of FTS indexes optimized (0 on merge failure / no FTS).
"""
# optimize_fts() manages its own lock.
optimized = 0
try:
optimized = self.optimize_fts()
optimized = self.optimize_fts() # manages its own lock
except Exception as exc:
logger.warning("FTS optimize before VACUUM failed: %s", exc)
# VACUUM cannot be executed inside a transaction.
with self._lock:
# PASSIVE, not TRUNCATE: a manual `hermes sessions vacuum` runs in
# a transient CLI process, and a TRUNCATE reset here would race a
@@ -570,8 +451,7 @@ class SessionMaintenanceMixin:
logger.debug("WAL checkpoint (PASSIVE) before VACUUM failed: %s", exc)
self._conn.execute("VACUUM")
# VACUUM rewrites every page THROUGH the WAL; without this TRUNCATE
# a 3 GB database leaves a 3 GB -wal behind and the command is a
# net loss on disk.
# a 3 GB database leaves a 3 GB -wal behind.
try:
self._conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
except Exception as exc:
@@ -582,12 +462,8 @@ class SessionMaintenanceMixin:
return optimized
def maybe_auto_prune_and_vacuum(
self,
retention_days: int = 90,
min_interval_hours: int = 24,
vacuum: bool = True,
sessions_dir: Optional[Path] = None,
min_vacuum_interval_days: int = 30,
self, retention_days: int = 90, min_interval_hours: int = 24, vacuum: bool = True,
sessions_dir: Optional[Path] = None, min_vacuum_interval_days: int = 30,
min_vacuum_freelist_ratio: float = AUTO_VACUUM_MIN_FREELIST_RATIO,
) -> Dict[str, Any]:
"""Idempotent startup auto-maintenance: prune inactive sessions,
@@ -611,12 +487,7 @@ class SessionMaintenanceMixin:
failure.
"""
from hermes_state import _release_auto_maintenance_lock, _try_acquire_auto_maintenance_lock
result: Dict[str, Any] = {
"skipped": False,
"pruned": 0,
"closed": 0,
"vacuumed": False,
}
result: Dict[str, Any] = {"skipped": False, "pruned": 0, "closed": 0, "vacuumed": False}
maintenance_lock = _try_acquire_auto_maintenance_lock(self.db_path)
if maintenance_lock is None:
result["skipped"] = True
@@ -626,8 +497,7 @@ class SessionMaintenanceMixin:
now = time.time()
if last_raw:
try:
last_ts = float(last_raw)
if now - last_ts < min_interval_hours * 3600:
if now - float(last_raw) < min_interval_hours * 3600:
result["skipped"] = True
return result
except (TypeError, ValueError):
@@ -635,23 +505,18 @@ class SessionMaintenanceMixin:
# Prune first: orphans closed below get a full retention window.
pruned = self.prune_sessions(
older_than_days=retention_days,
sessions_dir=sessions_dir,
older_than_days=retention_days, sessions_dir=sessions_dir,
exclude_active_write_guards=True,
)
result["pruned"] = pruned
closed = self.sweep_orphaned_sessions(
max_idle_seconds=float(retention_days) * 86400.0,
sources=self._AUTO_PRUNE_STALE_OPEN_SOURCES,
exclude_pinned=True,
# State-owned lifecycles, not gateway heartbeats.
respect_gateway_heartbeats=False,
sources=self._AUTO_PRUNE_STALE_OPEN_SOURCES, exclude_pinned=True,
respect_gateway_heartbeats=False, # state-owned lifecycles, not gateway heartbeats
)
result["closed"] = len(closed)
# VACUUM only if rows were freed, the time throttle passed ("not
# too often") AND the freelist ratio passed ("only when it pays
# off") — it holds an exclusive lock for a full rewrite.
# VACUUM only if rows were freed, the time throttle passed AND the
# freelist ratio passed — it holds an exclusive lock for a full rewrite.
last_vacuum_raw = self.get_meta("last_vacuum")
vacuum_due = True
if last_vacuum_raw:
@@ -673,21 +538,15 @@ class SessionMaintenanceMixin:
logger.debug(
"state.db auto-maintenance: skipping VACUUM, only "
"%.1f%% of pages reclaimable (threshold %.0f%%)",
ratio * 100.0,
min_vacuum_freelist_ratio * 100.0,
ratio * 100.0, min_vacuum_freelist_ratio * 100.0,
)
# Record even when pruned == 0 so the throttle holds.
self.set_meta("last_auto_prune", str(now))
if closed or pruned > 0:
logger.info(
"state.db auto-maintenance: closed %d stale open session(s), "
"pruned %d session(s) inactive for %d days%s",
len(closed),
pruned,
retention_days,
" + VACUUM" if result["vacuumed"] else "",
len(closed), pruned, retention_days, " + VACUUM" if result["vacuumed"] else "",
)
except Exception as exc:
# Maintenance must never block startup.
@@ -695,5 +554,4 @@ class SessionMaintenanceMixin:
result["error"] = str(exc)
finally:
_release_auto_maintenance_lock(maintenance_lock)
return result
+781 -1756
View File
File diff suppressed because it is too large Load Diff
+319 -407
View File
@@ -12,16 +12,74 @@ import time
from typing import Any, Dict, List, Optional
from agent.skill_commands import SKILL_SCAFFOLD_SQL_LIKE
from hermes_state_common import (
SCHEMA_SQL,
_PREVIEW_RAW_SUBQUERY_SQL,
_shape_preview,
_sql_session_last_active,
)
from hermes_state_common import SCHEMA_SQL, _PREVIEW_RAW_SUBQUERY_SQL, _shape_preview, _sql_session_last_active
# Keep the pre-split logger identity so log filtering/capture is unchanged.
logger = logging.getLogger("hermes_state")
_IMPORT_SESSION_TEXT_FIELDS = (
"source", "user_id", "model", "system_prompt", "end_reason", "cwd",
"git_branch", "git_repo_root", "billing_provider", "billing_base_url",
"billing_mode", "cost_status", "cost_source", "pricing_version", "title",
)
# ``role`` is validated separately (non-empty string).
_IMPORT_MESSAGE_TEXT_FIELDS = (
"tool_call_id", "tool_name", "effect_disposition", "finish_reason",
"reasoning", "reasoning_content", "platform_message_id", "message_id",
)
_IMPORT_MESSAGE_JSON_FIELDS = ("reasoning_details", "codex_reasoning_items", "codex_message_items")
_IMPORT_SESSION_INSERT_SQL = """INSERT INTO sessions (
id, source, user_id, model, model_config, system_prompt,
system_prompt_hash,
parent_session_id, started_at, ended_at, end_reason,
message_count, tool_call_count, input_tokens, output_tokens,
cache_read_tokens, cache_write_tokens, reasoning_tokens,
cwd, git_branch, git_repo_root,
billing_provider, billing_base_url, billing_mode,
estimated_cost_usd, actual_cost_usd, cost_status, cost_source,
pricing_version, title, api_call_count, archived
)
VALUES (
:id, :source, :user_id, :model, :model_config,
NULL, :system_prompt_hash, NULL, :started_at, :ended_at,
:end_reason, 0, 0, :input_tokens, :output_tokens,
:cache_read_tokens, :cache_write_tokens,
:reasoning_tokens, :cwd, :git_branch, :git_repo_root,
:billing_provider, :billing_base_url, :billing_mode,
:estimated_cost_usd, :actual_cost_usd, :cost_status,
:cost_source, :pricing_version, :title,
:api_call_count, :archived
)"""
# Columns copied verbatim from the payload; typed columns are converted below.
_IMPORT_PASSTHROUGH_COLS = (
"user_id", "model", "model_config", "end_reason", "cwd", "git_branch", "git_repo_root",
"billing_provider", "billing_base_url", "billing_mode", "cost_status", "cost_source",
"pricing_version", "title",
)
_IMPORT_INT_COLS = (
"input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens", "reasoning_tokens",
"api_call_count",
)
_IMPORT_FLOAT_COLS = ("ended_at", "estimated_cost_usd", "actual_cost_usd")
def _rich_select(select_cols: str, where: str, tail: str = "", prompt_select: Optional[str] = "") -> str:
"""``list_sessions_rich``-shaped SELECT: resolved prompt (``prompt_select``
fragment; None omits prompt columns AND the join), preview, last_active.
Whitespace matches the historical inline queries (SQL text is pinned)."""
prompt_join = "" if prompt_select is None else "LEFT JOIN system_prompts sp ON sp.hash = s.system_prompt_hash"
return f"""
SELECT {select_cols}{prompt_select or ""},
{_PREVIEW_RAW_SUBQUERY_SQL},
{_sql_session_last_active("s")} AS last_active
FROM sessions s
{prompt_join}
WHERE {where}{tail}
"""
_PROMPT_RESOLVED_SQL = "COALESCE(sp.prompt, s.system_prompt) AS _system_prompt_resolved"
class SessionPortabilityMixin:
"""See module docstring — mixin for SessionDB (Port cluster)."""
@@ -33,8 +91,7 @@ class SessionPortabilityMixin:
if cls._session_compact_cols_sql is None:
declared = cls._parse_schema_columns(SCHEMA_SQL)["sessions"]
cls._session_compact_cols_sql = ", ".join(
f"s.{name}" for name in declared
if name not in cls._SESSION_COMPACT_EXCLUDED
f"s.{name}" for name in declared if name not in cls._SESSION_COMPACT_EXCLUDED
)
return cls._session_compact_cols_sql
@@ -45,82 +102,58 @@ class SessionPortabilityMixin:
s["preview"] = _shape_preview(s.pop("_preview_raw", ""))
return s
def _locked_rows(self, sql: str, params=()) -> list:
with self._lock:
return self._conn.execute(sql, params).fetchall()
def distinct_session_cwds(self, include_archived: bool = False) -> List[Dict[str, Any]]:
"""Distinct non-empty session cwds with usage stats, for repo discovery.
Aggregates across ALL history (not one page) so every repo the user
worked in surfaces. Children/branches count: a worktree session is a
real workspace signal.
"""
Aggregates across ALL history so every repo the user worked in
surfaces; children/branches count (a worktree session is a real
workspace signal)."""
where = "cwd IS NOT NULL AND TRIM(cwd) != ''"
if not include_archived:
where += " AND archived = 0"
with self._lock:
rows = self._conn.execute(
"SELECT cwd AS cwd, COUNT(*) AS sessions, "
"MAX(COALESCE(ended_at, started_at, 0)) AS last_active "
f"FROM sessions WHERE {where} GROUP BY cwd"
).fetchall()
rows = self._locked_rows(
"SELECT cwd AS cwd, COUNT(*) AS sessions, "
"MAX(COALESCE(ended_at, started_at, 0)) AS last_active "
f"FROM sessions WHERE {where} GROUP BY cwd"
)
return [
{
"cwd": r["cwd"],
"sessions": int(r["sessions"] or 0),
"last_active": float(r["last_active"] or 0),
}
{"cwd": r["cwd"], "sessions": int(r["sessions"] or 0), "last_active": float(r["last_active"] or 0)}
for r in rows
]
def list_cron_job_runs(
self,
job_id: str,
limit: int = 20,
offset: int = 0,
) -> List[Dict[str, Any]]:
def list_cron_job_runs(self, job_id: str, limit: int = 20, offset: int = 0) -> List[Dict[str, Any]]:
"""List the run sessions produced by a single cron job, newest first.
Cron runs are flat sessions with id ``cron_{job_id}_{timestamp}``; they
never compress or branch, so this skips ``list_sessions_rich``'s
compression-chain CTE / leading-wildcard ``id_query`` path, which seeds
from EVERY ``source='cron'`` row and scales with the whole cron pile.
Instead: a ``[prefix, prefix_hi)`` index range scan on id, filtered to
``source='cron'``, so work scales with the requested window.
Returns the ``list_sessions_rich`` row shape (``preview`` + ``last_active``).
"""
compression-chain CTE / leading-wildcard ``id_query`` path (which
seeds from EVERY ``source='cron'`` row). Instead a ``[prefix,
prefix_hi)`` index range scan on id filtered to ``source='cron'``, so
work scales with the requested window. Returns the
``list_sessions_rich`` row shape (``preview`` + ``last_active``)."""
prefix = f"cron_{job_id}_"
# Half-open upper bound: bump the final byte so the range covers exactly
# the ids starting with ``prefix``.
prefix_hi = prefix[:-1] + chr(ord(prefix[-1]) + 1)
query = f"""
SELECT s.*,
COALESCE(sp.prompt, s.system_prompt) AS _system_prompt_resolved,
{_PREVIEW_RAW_SUBQUERY_SQL},
{_sql_session_last_active("s")} AS last_active
FROM sessions s
LEFT JOIN system_prompts sp ON sp.hash = s.system_prompt_hash
WHERE s.source = 'cron' AND s.id >= ? AND s.id < ?
ORDER BY s.started_at DESC, s.id DESC
LIMIT ? OFFSET ?
"""
with self._lock:
rows = self._conn.execute(query, (prefix, prefix_hi, limit, offset)).fetchall()
query = _rich_select(
"s.*", "s.source = 'cron' AND s.id >= ? AND s.id < ?",
"\n ORDER BY s.started_at DESC, s.id DESC\n LIMIT ? OFFSET ?",
prompt_select=f",\n {_PROMPT_RESOLVED_SQL}",
)
rows = self._locked_rows(query, (prefix, prefix_hi, limit, offset))
return [self._rich_row(row) for row in rows]
def _get_session_rich_row(self, session_id: str, compact_rows: bool = False) -> Optional[Dict[str, Any]]:
"""One session with the ``list_sessions_rich`` enriched columns, or
None. ``compact_rows=True`` omits the ``system_prompt`` blob."""
return self._get_session_rich_rows_batch(
[session_id], compact_rows=compact_rows
).get(session_id)
return self._get_session_rich_rows_batch([session_id], compact_rows=compact_rows).get(session_id)
def _get_session_rich_rows_batch(
self, session_ids, compact_rows: bool = False
) -> Dict[str, Dict[str, Any]]:
def _get_session_rich_rows_batch(self, session_ids, compact_rows: bool = False) -> Dict[str, Dict[str, Any]]:
"""Enriched rows for many sessions in one query, keyed by id; missing
ids are simply absent. Resolves a page of compression tips in one
round trip instead of one query per root row.
"""
round trip instead of one query per root row."""
ids = [sid for sid in session_ids if sid]
if not ids:
return {}
@@ -130,34 +163,16 @@ class SessionPortabilityMixin:
if len(ids) > _CHUNK:
result: Dict[str, Dict[str, Any]] = {}
for start in range(0, len(ids), _CHUNK):
result.update(
self._get_session_rich_rows_batch(
ids[start:start + _CHUNK], compact_rows=compact_rows
)
)
result.update(self._get_session_rich_rows_batch(ids[start:start + _CHUNK], compact_rows=compact_rows))
return result
# Same read-your-writes guarantee as list_sessions_rich.
self.flush_token_counts()
_sel = self._compact_session_cols() if compact_rows else "s.*"
placeholders = ",".join("?" for _ in ids)
prompt_select = (
"" if compact_rows
else ", COALESCE(sp.prompt, s.system_prompt) AS _system_prompt_resolved"
query = _rich_select(
self._compact_session_cols() if compact_rows else "s.*",
f"s.id IN ({','.join('?' for _ in ids)})",
prompt_select=None if compact_rows else f", {_PROMPT_RESOLVED_SQL}",
)
prompt_join = (
"" if compact_rows
else "LEFT JOIN system_prompts sp ON sp.hash = s.system_prompt_hash"
)
query = f"""
SELECT {_sel}{prompt_select},
{_PREVIEW_RAW_SUBQUERY_SQL},
{_sql_session_last_active("s")} AS last_active
FROM sessions s
{prompt_join}
WHERE s.id IN ({placeholders})
"""
with self._lock:
rows = self._conn.execute(query, ids).fetchall()
rows = self._locked_rows(query, ids)
return {s["id"]: s for s in map(self._rich_row, rows)}
def get_session_rich_row(self, session_id: str, compact_rows: bool = False) -> Optional[Dict[str, Any]]:
@@ -166,14 +181,11 @@ class SessionPortabilityMixin:
def list_skill_scaffolded_sessions(self, limit: int = 200) -> List[Dict[str, Any]]:
"""Titled sessions whose first user turn was a ``/skill`` invocation.
Their titles were generated from the expanded skill body, so they
describe the skill, not the request. Returns ``id``, ``title`` and the
first-turn ``content`` so callers can re-derive what was typed. Newest first.
"""
with self._lock:
rows = self._conn.execute(
"""
first-turn ``content`` so callers can re-derive what was typed. Newest first."""
rows = self._locked_rows(
"""
SELECT s.id, s.title, m.content
FROM sessions s
JOIN messages m ON m.id = (
@@ -186,16 +198,19 @@ class SessionPortabilityMixin:
ORDER BY s.started_at DESC
LIMIT ?
""",
(SKILL_SCAFFOLD_SQL_LIKE, int(limit)),
).fetchall()
(SKILL_SCAFFOLD_SQL_LIKE, int(limit)),
)
return [dict(row) for row in rows]
# ── Export ─────────────────────────────────────────────────────────────
def _with_messages(self, session: Dict[str, Any]) -> Dict[str, Any]:
return {**session, "messages": self.get_messages(session["id"])}
def export_session(self, session_id: str) -> Optional[Dict[str, Any]]:
"""Export a single session with all its messages as a dict."""
session = self.get_session(session_id)
if not session:
return None
return {**session, "messages": self.get_messages(session_id)}
return self._with_messages(session) if session else None
def export_session_lineage(self, session_id: str) -> Optional[Dict[str, Any]]:
"""Export a compression lineage as one logical session dict."""
@@ -207,51 +222,38 @@ class SessionPortabilityMixin:
return None
messages = [msg for seg in segments for msg in (seg.get("messages") or [])]
return {
**segments[-1],
"segments": segments,
"lineage_session_ids": [seg["id"] for seg in segments],
"message_count": len(messages),
**segments[-1], "segments": segments,
"lineage_session_ids": [seg["id"] for seg in segments], "message_count": len(messages),
"messages": messages,
}
def export_all(self, source: str = None) -> List[Dict[str, Any]]:
"""Export all sessions (with messages) as dicts, e.g. for JSONL backup."""
return [
{**session, "messages": self.get_messages(session["id"])}
for session in self.search_sessions(source=source, limit=100000)
]
return [self._with_messages(s) for s in self.search_sessions(source=source, limit=100000)]
def adopt_session_lineage_from(
self,
donor_db: Any, # a full SessionDB (mixin cannot import it — cycle)
session_id: str,
*,
retire_donor: bool = True,
self, donor_db: Any, session_id: str, *, retire_donor: bool = True
) -> Dict[str, Any]:
"""Adopt *session_id*'s full compression lineage from *donor_db*.
"""Adopt *session_id*'s full compression lineage from *donor_db* (a
full SessionDB — the mixin cannot import it).
Stranded-bot-session heal: before the desktop routed session RPCs by
target session, a profile bot's rows accumulated in the DEFAULT
profile's state.db; this moves the conversation to where routing now
looks. Pure composition: ``donor_db.export_session_lineage()`` ->
``self.import_sessions()`` — routing/handoff/activity fields reset,
already-present ids skipped (idempotent re-adoption).
With ``retire_donor`` and a complete adoption, donor rows are ARCHIVED
(never deleted) with ``end_reason='adopted_by_profile'``. That
end_reason is deliberately NOT in the recoverable set
(agent_close/ws_orphan_reap): resurrection must not undo an adoption.
looks. Pure composition ``donor_db.export_session_lineage()`` ->
``self.import_sessions()``: routing/handoff/activity fields reset,
already-present ids skipped (idempotent re-adoption). With
``retire_donor`` and a complete adoption, donor rows are ARCHIVED
(never deleted) with ``end_reason='adopted_by_profile'`` — deliberately
NOT in the recoverable set, so resurrection cannot undo an adoption.
Returns the ``import_sessions`` dict plus ``adopted`` and
``donor_retired`` (True only when EVERY segment's retirement applied).
"""
``donor_retired`` (True only when EVERY segment's retirement applied)."""
payload = donor_db.export_session_lineage(session_id)
if not payload:
return {
"ok": False, "adopted": False, "donor_retired": False,
"error": f"session {session_id!r} not found in donor store",
}
segments = payload.get("segments") or [payload]
# Divergence guard: a segment we will SKIP (already here) may have kept
@@ -281,57 +283,50 @@ class SessionPortabilityMixin:
logger.warning(
"adoption of %s did not complete: imported=%s skipped=%s "
"of %s segment(s); errors=%s",
session_id, imported, skipped, len(segments),
result.get("errors"),
session_id, imported, skipped, len(segments), result.get("errors"),
)
donor_retired = False
if adopted and retire_donor and not donor_ahead:
retire_ok = True
for seg in segments:
seg_id = seg.get("id")
if not seg_id:
continue
try:
# TOCTOU close-out: the guard above used EXPORT-TIME counts;
# re-read both stores right before stamping so donor growth
# never lands behind a non-recoverable archive. (Equal-count
# CONTENT divergence is accepted: bytes stay in the donor
# either way, only reachability differs.)
donor_now = len(donor_db.get_messages(seg_id))
local_now = len(self.get_messages(seg_id))
if donor_now > local_now:
retire_ok = False
logger.warning(
"adoption divergence at retire time: donor "
"segment %s grew to %d messages (local %d) — "
"leaving donor unretired",
seg_id, donor_now, local_now,
)
continue
# First end_reason wins in end_session(); reopen so the
# adoption boundary is stamped even on ended segments.
donor_db.reopen_session(seg_id)
donor_db.end_session(seg_id, "adopted_by_profile")
donor_db.set_session_archived(seg_id, True)
except Exception:
# Best-effort: a retirement failure must not fail the adoption
# (a later resume retries idempotently) — but never claim
# success we didn't have.
retire_ok = False
logger.warning(
"failed to retire donor segment %s after adoption",
seg_id, exc_info=True,
)
donor_retired = retire_ok
donor_retired = all(
self._retire_donor_segment(donor_db, seg["id"]) for seg in segments if seg.get("id")
)
return {**result, "adopted": adopted, "donor_retired": donor_retired}
def _retire_donor_segment(self, donor_db: Any, seg_id: str) -> bool:
"""Archive one adopted donor segment; False when skipped or failed.
TOCTOU close-out: the divergence guard used EXPORT-TIME counts; re-read
both stores right before stamping so donor growth never lands behind a
non-recoverable archive (equal-count CONTENT divergence is accepted —
bytes stay in the donor either way, only reachability differs). A
retirement failure must not fail the adoption (a later resume retries
idempotently), but never claims success it didn't have."""
try:
donor_now = len(donor_db.get_messages(seg_id))
local_now = len(self.get_messages(seg_id))
if donor_now > local_now:
logger.warning(
"adoption divergence at retire time: donor "
"segment %s grew to %d messages (local %d) — "
"leaving donor unretired",
seg_id, donor_now, local_now,
)
return False
# First end_reason wins in end_session(); reopen so the adoption
# boundary is stamped even on ended segments.
donor_db.reopen_session(seg_id)
donor_db.end_session(seg_id, "adopted_by_profile")
donor_db.set_session_archived(seg_id, True)
return True
except Exception:
logger.warning("failed to retire donor segment %s after adoption", seg_id, exc_info=True)
return False
# ── Import ─────────────────────────────────────────────────────────────
@staticmethod
def _import_text_or_none(value: Any, field: str) -> Optional[str]:
if value is None:
return None
if isinstance(value, str):
if value is None or isinstance(value, str):
return value
raise ValueError(f"{field} must be a string")
@@ -355,13 +350,22 @@ class SessionPortabilityMixin:
raise ValueError(f"{field} must be JSON serializable") from exc
@staticmethod
def _float_or_none(value: Any) -> Optional[float]:
def _coerce_or(value: Any, cast, default):
"""``cast(value)``; *default* for None or an unparsable value."""
if value is None:
return None
return default
try:
return float(value)
return cast(value)
except (TypeError, ValueError):
return None
return default
@classmethod
def _float_or_none(cls, value: Any) -> Optional[float]:
return cls._coerce_or(value, float, None)
@classmethod
def _int_or_default(cls, value: Any, default: int = 0) -> int:
return cls._coerce_or(value, int, default)
@staticmethod
def _import_int_or_none(value: Any, field: str) -> Optional[int]:
@@ -372,15 +376,6 @@ class SessionPortabilityMixin:
except (TypeError, ValueError) as exc:
raise ValueError(f"{field} must be an integer") from exc
@staticmethod
def _int_or_default(value: Any, default: int = 0) -> int:
if value is None:
return default
try:
return int(value)
except (TypeError, ValueError):
return default
@staticmethod
def _reasoning_json_value(value: Any) -> Any:
if not isinstance(value, str):
@@ -397,9 +392,147 @@ class SessionPortabilityMixin:
item["session_id"] = session_id
return item
def _normalize_import_session(self, raw: Dict[str, Any], session_id: str, messages: list) -> Dict[str, Any]:
"""Type-check one payload session + its messages; raises ValueError."""
clean_session = dict(raw)
clean_session["id"] = session_id
clean_session["model_config"] = self._import_json_object_or_none(clean_session.get("model_config"), "model_config")
clean_session["parent_session_id"] = self._import_text_or_none(
clean_session.get("parent_session_id"), "parent_session_id"
)
for field in _IMPORT_SESSION_TEXT_FIELDS:
clean_session[field] = self._import_text_or_none(clean_session.get(field), field)
clean_messages: List[Dict[str, Any]] = []
for message_index, message in enumerate(messages):
clean_message = dict(message)
role = clean_message.get("role")
if not isinstance(role, str) or not role:
raise ValueError(f"messages[{message_index}].role must be a non-empty string")
for field in _IMPORT_MESSAGE_TEXT_FIELDS:
clean_message[field] = self._import_text_or_none(clean_message.get(field), field)
clean_message["token_count"] = self._import_int_or_none(clean_message.get("token_count"), "token_count")
clean_messages.append(clean_message)
return {"session": clean_session, "messages": clean_messages}
def _validate_import_payload(self, sessions: List[Dict[str, Any]]) -> tuple:
"""Size/shape/type validation of the whole payload; returns
``(normalized_items, errors)``. Every rejected entry is reported."""
normalized: List[Dict[str, Any]] = []
errors: List[Dict[str, Any]] = []
seen_ids: set[str] = set()
total_messages = 0
total_bytes = 0
for index, raw in enumerate(sessions):
if not isinstance(raw, dict):
errors.append(self._import_error(index, "", "session must be an object"))
continue
session_id = str(raw.get("id") or "").strip()
if not session_id:
errors.append(self._import_error(index, "", "session id is required"))
continue
def _reject(msg: str) -> None:
errors.append(self._import_error(index, session_id, msg))
if session_id in seen_ids:
_reject("duplicate session id")
continue
messages = raw.get("messages") or []
if not isinstance(messages, list):
_reject("messages must be a list")
continue
if len(messages) > self._IMPORT_MAX_MESSAGES_PER_SESSION:
_reject("messages exceeds the per-session import limit")
continue
if any(not isinstance(msg, dict) for msg in messages):
_reject("messages must contain only objects")
continue
try:
session_bytes = len(json.dumps(raw, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))
except (TypeError, ValueError):
_reject("session must be JSON serializable")
continue
if session_bytes > self._IMPORT_MAX_SESSION_BYTES:
_reject("session exceeds the import size limit")
continue
total_bytes += session_bytes
if total_bytes > self._IMPORT_MAX_TOTAL_BYTES:
_reject("import exceeds the total size limit")
continue
try:
item = self._normalize_import_session(raw, session_id, messages)
except ValueError as exc:
_reject(str(exc))
continue
total_messages += len(item["messages"])
if total_messages > self._IMPORT_MAX_TOTAL_MESSAGES:
_reject("messages exceeds the total import limit")
continue
seen_ids.add(session_id)
normalized.append({"index": index, **item})
return normalized, errors
def _import_session_row(self, conn, raw: Dict[str, Any], messages: List[Dict[str, Any]], session_id: str) -> None:
"""INSERT one normalized session + its messages; counts fixed up after."""
started_at = self._float_or_none(raw.get("started_at"))
params = {
"id": session_id, "source": str(raw.get("source") or "import"),
"system_prompt_hash": self._store_system_prompt(conn, raw.get("system_prompt")),
"started_at": time.time() if started_at is None else started_at,
"archived": 1 if raw.get("archived") else 0,
**{col: raw.get(col) for col in _IMPORT_PASSTHROUGH_COLS},
**{col: self._float_or_none(raw.get(col)) for col in _IMPORT_FLOAT_COLS},
**{col: self._int_or_default(raw.get(col)) for col in _IMPORT_INT_COLS},
}
conn.execute(_IMPORT_SESSION_INSERT_SQL, params)
sanitized_messages = [
{**msg, **{key: self._reasoning_json_value(msg.get(key)) for key in _IMPORT_MESSAGE_JSON_FIELDS}}
for msg in messages
]
total_messages, total_tool_calls = self._insert_message_rows(conn, session_id, sanitized_messages)
conn.execute(
"UPDATE sessions SET message_count = ?, tool_call_count = ? WHERE id = ?",
(total_messages, total_tool_calls, session_id),
)
@staticmethod
def _attach_import_parents(conn, parent_updates: List[tuple]) -> int:
"""Re-attach imported children whose parent exists (in the store or
the same payload) without creating a cycle; returns the detached count.
Only the closing edge of a cycle is dropped, so later entries can
still attach to the now-root session."""
parent_by_child = dict(parent_updates)
def _would_create_cycle(session_id: str, parent_id: str) -> bool:
seen = {session_id}
current = parent_id
while current:
if current in seen:
return True
seen.add(current)
if current in parent_by_child:
current = parent_by_child[current]
continue
row = conn.execute(
"SELECT parent_session_id FROM sessions WHERE id = ? LIMIT 1", (current,),
).fetchone()
if row is None:
return False
current = row["parent_session_id"]
return False
detached = 0
for session_id, parent_id in parent_updates:
parent_exists = conn.execute("SELECT 1 FROM sessions WHERE id = ? LIMIT 1", (parent_id,)).fetchone()
if parent_exists and not _would_create_cycle(session_id, parent_id):
conn.execute("UPDATE sessions SET parent_session_id = ? WHERE id = ?", (parent_id, session_id))
else:
parent_by_child.pop(session_id, None)
detached += 1
return detached
def import_sessions(self, sessions: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Import sessions exported by :meth:`export_session` or ``export_all``.
Existing ids are skipped. A child keeps its parent only when the parent
exists or is in the same payload; otherwise it is detached so partial
imports pass FK validation. Gateway routing, handoff, rewind and other
@@ -409,107 +542,12 @@ class SessionPortabilityMixin:
Activity contract: export INCLUDES ``last_activity_*`` (durable row
fields) but import RESETS them to NULL — resurrecting a stale
"working ..." label would fabricate activity the watchdog and listings
act on. Intentional asymmetry, pinned by regression test.
"""
act on. Intentional asymmetry, pinned by regression test."""
if not isinstance(sessions, list):
raise ValueError("sessions must be a list")
if len(sessions) > self._IMPORT_MAX_SESSIONS:
raise ValueError(
f"sessions must contain at most {self._IMPORT_MAX_SESSIONS} entries"
)
normalized: List[Dict[str, Any]] = []
errors: List[Dict[str, Any]] = []
seen_ids: set[str] = set()
total_messages = 0
total_bytes = 0
session_text_fields = (
"source", "user_id", "model", "system_prompt", "end_reason", "cwd",
"git_branch", "git_repo_root", "billing_provider", "billing_base_url",
"billing_mode", "cost_status", "cost_source", "pricing_version", "title",
)
# ``role`` is validated separately below (non-empty string).
message_text_fields = (
"tool_call_id", "tool_name", "effect_disposition", "finish_reason",
"reasoning", "reasoning_content", "platform_message_id", "message_id",
)
for index, raw in enumerate(sessions):
if not isinstance(raw, dict):
errors.append(self._import_error(index, "", "session must be an object"))
continue
session_id = str(raw.get("id") or "").strip()
if not session_id:
errors.append(self._import_error(index, "", "session id is required"))
continue
if session_id in seen_ids:
errors.append(self._import_error(index, session_id, "duplicate session id"))
continue
messages = raw.get("messages") or []
if not isinstance(messages, list):
errors.append(self._import_error(index, session_id, "messages must be a list"))
continue
if len(messages) > self._IMPORT_MAX_MESSAGES_PER_SESSION:
errors.append(self._import_error(index, session_id, "messages exceeds the per-session import limit"))
continue
if any(not isinstance(msg, dict) for msg in messages):
errors.append(self._import_error(index, session_id, "messages must contain only objects"))
continue
try:
session_bytes = len(json.dumps(raw, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))
except (TypeError, ValueError):
errors.append(self._import_error(index, session_id, "session must be JSON serializable"))
continue
if session_bytes > self._IMPORT_MAX_SESSION_BYTES:
errors.append(self._import_error(index, session_id, "session exceeds the import size limit"))
continue
total_bytes += session_bytes
if total_bytes > self._IMPORT_MAX_TOTAL_BYTES:
errors.append(self._import_error(index, session_id, "import exceeds the total size limit"))
continue
try:
clean_session = dict(raw)
clean_session["id"] = session_id
clean_session["model_config"] = self._import_json_object_or_none(
clean_session.get("model_config"), "model_config"
)
clean_session["parent_session_id"] = self._import_text_or_none(
clean_session.get("parent_session_id"), "parent_session_id"
)
for field in session_text_fields:
clean_session[field] = self._import_text_or_none(
clean_session.get(field), field
)
clean_messages: List[Dict[str, Any]] = []
for message_index, message in enumerate(messages):
clean_message = dict(message)
role = clean_message.get("role")
if not isinstance(role, str) or not role:
raise ValueError(f"messages[{message_index}].role must be a non-empty string")
for field in message_text_fields:
clean_message[field] = self._import_text_or_none(
clean_message.get(field), field
)
clean_message["token_count"] = self._import_int_or_none(
clean_message.get("token_count"), "token_count"
)
clean_messages.append(clean_message)
except ValueError as exc:
errors.append(self._import_error(index, session_id, str(exc)))
continue
total_messages += len(clean_messages)
if total_messages > self._IMPORT_MAX_TOTAL_MESSAGES:
errors.append(self._import_error(index, session_id, "messages exceeds the total import limit"))
continue
seen_ids.add(session_id)
normalized.append(
{"index": index, "session": clean_session, "messages": clean_messages}
)
raise ValueError(f"sessions must contain at most {self._IMPORT_MAX_SESSIONS} entries")
normalized, errors = self._validate_import_payload(sessions)
if errors:
return {"ok": False, "imported": 0, "skipped": 0, "detached": 0, "errors": errors}
@@ -517,147 +555,21 @@ class SessionPortabilityMixin:
imported_ids: List[str] = []
skipped_ids: List[str] = []
parent_updates: List[tuple[str, str]] = []
detached = 0
for item in normalized:
raw = item["session"]
messages = item["messages"]
session_id = str(raw.get("id") or "").strip()
exists = conn.execute(
"SELECT 1 FROM sessions WHERE id = ? LIMIT 1",
(session_id,),
).fetchone()
if exists:
if conn.execute("SELECT 1 FROM sessions WHERE id = ? LIMIT 1", (session_id,)).fetchone():
skipped_ids.append(session_id)
continue
started_at = self._float_or_none(raw.get("started_at"))
if started_at is None:
started_at = time.time()
archived = 1 if raw.get("archived") else 0
system_prompt_hash = self._store_system_prompt(
conn, raw.get("system_prompt")
)
conn.execute(
"""INSERT INTO sessions (
id, source, user_id, model, model_config, system_prompt,
system_prompt_hash,
parent_session_id, started_at, ended_at, end_reason,
message_count, tool_call_count, input_tokens, output_tokens,
cache_read_tokens, cache_write_tokens, reasoning_tokens,
cwd, git_branch, git_repo_root,
billing_provider, billing_base_url, billing_mode,
estimated_cost_usd, actual_cost_usd, cost_status, cost_source,
pricing_version, title, api_call_count, archived
)
VALUES (
:id, :source, :user_id, :model, :model_config,
NULL, :system_prompt_hash, NULL, :started_at, :ended_at,
:end_reason, 0, 0, :input_tokens, :output_tokens,
:cache_read_tokens, :cache_write_tokens,
:reasoning_tokens, :cwd, :git_branch, :git_repo_root,
:billing_provider, :billing_base_url, :billing_mode,
:estimated_cost_usd, :actual_cost_usd, :cost_status,
:cost_source, :pricing_version, :title,
:api_call_count, :archived
)""",
{
"id": session_id,
"source": str(raw.get("source") or "import"),
"user_id": raw.get("user_id"),
"model": raw.get("model"),
"model_config": raw.get("model_config"),
"system_prompt_hash": system_prompt_hash,
"started_at": started_at,
"ended_at": self._float_or_none(raw.get("ended_at")),
"end_reason": raw.get("end_reason"),
"input_tokens": self._int_or_default(raw.get("input_tokens")),
"output_tokens": self._int_or_default(raw.get("output_tokens")),
"cache_read_tokens": self._int_or_default(raw.get("cache_read_tokens")),
"cache_write_tokens": self._int_or_default(raw.get("cache_write_tokens")),
"reasoning_tokens": self._int_or_default(raw.get("reasoning_tokens")),
"cwd": raw.get("cwd"),
"git_branch": raw.get("git_branch"),
"git_repo_root": raw.get("git_repo_root"),
"billing_provider": raw.get("billing_provider"),
"billing_base_url": raw.get("billing_base_url"),
"billing_mode": raw.get("billing_mode"),
"estimated_cost_usd": self._float_or_none(raw.get("estimated_cost_usd")),
"actual_cost_usd": self._float_or_none(raw.get("actual_cost_usd")),
"cost_status": raw.get("cost_status"),
"cost_source": raw.get("cost_source"),
"pricing_version": raw.get("pricing_version"),
"title": raw.get("title"),
"api_call_count": self._int_or_default(raw.get("api_call_count")),
"archived": archived,
},
)
sanitized_messages: List[Dict[str, Any]] = []
for msg in messages:
clean = dict(msg)
for key in ("reasoning_details", "codex_reasoning_items", "codex_message_items"):
clean[key] = self._reasoning_json_value(clean.get(key))
sanitized_messages.append(clean)
total_messages, total_tool_calls = self._insert_message_rows(
conn, session_id, sanitized_messages
)
conn.execute(
"UPDATE sessions SET message_count = ?, tool_call_count = ? WHERE id = ?",
(total_messages, total_tool_calls, session_id),
)
self._import_session_row(conn, raw, item["messages"], session_id)
parent_id = str(raw.get("parent_session_id") or "").strip()
if parent_id:
parent_updates.append((session_id, parent_id))
imported_ids.append(session_id)
parent_by_child = dict(parent_updates)
def _would_create_cycle(session_id: str, parent_id: str) -> bool:
seen = {session_id}
current = parent_id
while current:
if current in seen:
return True
seen.add(current)
if current in parent_by_child:
current = parent_by_child[current]
continue
row = conn.execute(
"SELECT parent_session_id FROM sessions WHERE id = ? LIMIT 1",
(current,),
).fetchone()
if row is None:
return False
current = row["parent_session_id"]
return False
for session_id, parent_id in parent_updates:
parent_exists = conn.execute(
"SELECT 1 FROM sessions WHERE id = ? LIMIT 1",
(parent_id,),
).fetchone()
if parent_exists and not _would_create_cycle(session_id, parent_id):
conn.execute(
"UPDATE sessions SET parent_session_id = ? WHERE id = ?",
(parent_id, session_id),
)
else:
# Drop only the closing edge; later entries can still attach
# to this now-root session.
parent_by_child.pop(session_id, None)
detached += 1
detached = self._attach_import_parents(conn, parent_updates)
return {
"ok": True,
"imported": len(imported_ids),
"skipped": len(skipped_ids),
"detached": detached,
"imported_ids": imported_ids,
"skipped_ids": skipped_ids,
"ok": True, "imported": len(imported_ids), "skipped": len(skipped_ids),
"detached": detached, "imported_ids": imported_ids, "skipped_ids": skipped_ids,
"errors": [],
}
+35 -53
View File
@@ -1,10 +1,8 @@
"""Process-wide shared SessionDB registry.
A gateway process opens state.db from many call sites (runner, SessionStore,
per-agent recall, cron, per-message helpers). Each bare ``SessionDB()`` mints
its own writer connection, lock, close-time WAL checkpoint and token-writer
thread; N independent writers on one WAL file rely only on SQLite's write lock
plus busy_timeout, and one connection's close-time checkpoint can race another's
A gateway process opens state.db from many call sites; each bare ``SessionDB()``
mints its own writer connection, lock, close-time WAL checkpoint and token
writer thread, and one connection's close-time checkpoint can race another's
growth (lost/reordered-page-write corruption). This module owns that boundary:
one shared ``SessionDB`` per resolved path per process, refcounted, with
generation-aware retirement when the file is replaced (snapshot restore,
@@ -14,16 +12,14 @@ Lifecycle rules:
- ``acquire(path)`` returns the current generation for *path* and bumps its
refcount. Same path ⇒ same instance ⇒ same writer connection.
- ``close()`` on a shared instance is a NO-OP: the registry, not any caller,
owns the connection lifecycle, so one caller can never tear down a writer
others still hold.
- ``close()`` on a shared instance is a NO-OP: the registry owns the connection
lifecycle, so one caller can never tear down a writer others still hold.
- ``release(db)`` decrements the generation *db was acquired from* (object-
keyed, not pathname-keyed, so an inode replacement cannot strand a
still-owned generation). The final release of a retired generation tears
it down.
keyed, so an inode replacement cannot strand a still-owned generation). The
final release of a retired generation tears it down.
- On inode change the old generation is RETIRED (never lent again) but stays
alive until its holders release. If the replacement open fails the registry
keeps NO path entry (never a closed stale object) so the next acquire retries.
keeps NO path entry, so the next acquire retries.
- All teardown happens OUTSIDE the registry lock: a final release's WAL
checkpoint must never stall acquisition for every state.db.
"""
@@ -56,7 +52,7 @@ class _Generation:
_lock = threading.Lock()
# path → live generation. Retired generations move to _retired (keyed by
# path → live generation; retired generations move to _retired (keyed by
# id(db)) until their last holder releases.
_generations: Dict[Path, _Generation] = {}
_retired: Dict[int, _Generation] = {}
@@ -85,16 +81,20 @@ def _teardown(db: "SessionDB") -> None:
logger.debug("Error closing shared SessionDB", exc_info=True)
def _finish_opening(path: Path, opening: threading.Event) -> None:
"""Drop the per-path construction marker and wake waiters (caller holds _lock)."""
if _opening.get(path) is opening:
_opening.pop(path, None)
opening.set()
def acquire(db_path: Optional[Path] = None) -> "SessionDB":
"""Return the shared SessionDB for *db_path*, incrementing its refcount.
If the file was replaced (different inode) since the generation opened —
``hermes sessions recover``, snapshot restore — that generation is RETIRED
but stays alive for its holders, and a fresh one is opened in its place.
Raises whatever ``SessionDB.__init__`` raises. On a replacement-open
failure the registry holds NO entry for the path, so the next acquire
retries fresh instead of receiving a closed stale object.
If the file was replaced (different inode) since the generation opened,
that generation is RETIRED but stays alive for its holders, and a fresh one
is opened in its place. Raises whatever ``SessionDB.__init__`` raises; on
a replacement-open failure the registry holds NO entry for the path.
"""
from hermes_state import _default_db_path
@@ -109,24 +109,16 @@ def acquire(db_path: Optional[Path] = None) -> "SessionDB":
generation = _generations.get(path)
if generation is not None:
current = _stat_db_file_identity(path)
if (
current is not None
and generation.identity is not None
and current != generation.identity
):
# File replaced: retire, then elect one caller to open
# the replacement below.
if current is not None and generation.identity is not None and current != generation.identity:
# File replaced: retire, then elect one caller to open the replacement.
_retire_generation_locked(path, generation)
else:
generation.refcount += 1
return generation.db
opening = _opening.get(path)
if opening is None:
opening = threading.Event()
_opening[path] = opening
opening = _opening[path] = threading.Event()
break
# Another caller is constructing this path; wait without holding the
# global lock. A failed opener signals too, so a waiter can retry.
opening.wait()
@@ -139,9 +131,7 @@ def acquire(db_path: Optional[Path] = None) -> "SessionDB":
identity = _stat_db_file_identity(path)
except BaseException:
with _lock:
if _opening.get(path) is opening:
_opening.pop(path, None)
opening.set()
_finish_opening(path, opening)
raise
with _lock:
@@ -153,9 +143,7 @@ def acquire(db_path: Optional[Path] = None) -> "SessionDB":
else:
_generations[path] = _Generation(db, identity)
winner = db
if _opening.get(path) is opening:
_opening.pop(path, None)
opening.set()
_finish_opening(path, opening)
if winner is not db:
_teardown(db)
return winner
@@ -178,9 +166,8 @@ def release(db: "SessionDB") -> bool:
Returns ``True`` if *db* was shared; ``False`` if it is not registry-managed
(caller owns close()). The final release tears the generation down OUTSIDE
the registry lock so a close-time WAL checkpoint never stalls acquisition.
Lookup is object-keyed, so holders of an old generation release into its
retired record, not into whatever the path currently names.
the registry lock. Lookup is object-keyed, so holders of an old generation
release into its retired record, not into whatever the path currently names.
"""
if db is None:
return False
@@ -223,7 +210,6 @@ def close_all() -> int:
For gateway shutdown, after all agents and cron jobs finished. Idempotent.
"""
closed = 0
with _lock:
generations = list(_generations.values()) + list(_retired.values())
_generations.clear()
@@ -232,16 +218,15 @@ def close_all() -> int:
generation.retired = True
for generation in generations:
_teardown(generation.db)
closed += 1
return closed
return len(generations)
def live_shared_session_dbs() -> List["SessionDB"]:
"""Snapshot of every live (non-retired) shared SessionDB.
"""Snapshot of every live (non-retired) shared SessionDB (refcounts untouched).
For in-process maintenance (housekeeping deferred-FTS retry). Refcounts
are NOT touched: a concurrent final release may close an instance, in
which case the callee sees ``_conn is None``.
For in-process maintenance (housekeeping deferred-FTS retry). A concurrent
final release may close an instance, in which case the callee sees
``_conn is None``.
"""
with _lock:
return [g.db for g in _generations.values() if not g.retired]
@@ -250,13 +235,10 @@ def live_shared_session_dbs() -> List["SessionDB"]:
def stats() -> Dict[str, int]:
"""Registry census for tests and diagnostics (no locks held long)."""
with _lock:
live = len(_generations)
retired = len(_retired)
refs = sum(g.refcount for g in _generations.values())
return {
"live_generations": live,
"retired_generations": retired,
"total_refcounts": refs,
"live_generations": len(_generations),
"retired_generations": len(_retired),
"total_refcounts": sum(g.refcount for g in _generations.values()),
}
+451 -650
View File
File diff suppressed because it is too large Load Diff
+491 -695
View File
File diff suppressed because it is too large Load Diff
+1183 -1611
View File
File diff suppressed because it is too large Load Diff
+135 -230
View File
@@ -26,28 +26,15 @@ def _normalize_telegram_topic_profile_name(profile_name: Optional[str] = None) -
return name if name else "default"
class SessionTelegramTopicsMixin:
"""Telegram DM topic-mode tables, bindings and lookups."""
def apply_telegram_topic_migration(self) -> None:
"""Create Telegram DM topic-mode tables on explicit /topic opt-in.
Deliberately NOT part of startup reconciliation: operators can upgrade
and keep the old bot behavior until a user runs /topic.
Schema versions: v1 initial; v2 session_id FK ON DELETE CASCADE (pruning
clears bindings); v3 ``profile_name`` on both tables so multiplexed
gateways sharing one state.db isolate topic state per profile.
# (table, column list, DDL body). profile_name leads the PK: a private
# chat_id is the user id, identical across bots sharing one state.db.
_TOPIC_TABLES = (
(
"telegram_dm_topic_mode",
"profile_name, chat_id, user_id, enabled, activated_at, updated_at, "
"has_topics_enabled, allows_users_to_create_topics, "
"capability_checked_at, intro_message_id, pinned_message_id",
"""
# (table, column list, DDL body). profile_name leads the PK: a private
# chat_id is the user id, identical across bots sharing one state.db.
tables = (
(
"telegram_dm_topic_mode",
"profile_name, chat_id, user_id, enabled, activated_at, updated_at, "
"has_topics_enabled, allows_users_to_create_topics, "
"capability_checked_at, intro_message_id, pinned_message_id",
"""
profile_name TEXT NOT NULL DEFAULT 'default',
chat_id TEXT NOT NULL,
user_id TEXT NOT NULL,
@@ -61,12 +48,12 @@ class SessionTelegramTopicsMixin:
pinned_message_id TEXT,
PRIMARY KEY (profile_name, chat_id)
""",
),
(
"telegram_dm_topic_bindings",
"profile_name, chat_id, thread_id, user_id, session_key, "
"session_id, managed_mode, linked_at, updated_at",
"""
),
(
"telegram_dm_topic_bindings",
"profile_name, chat_id, thread_id, user_id, session_key, "
"session_id, managed_mode, linked_at, updated_at",
"""
profile_name TEXT NOT NULL DEFAULT 'default',
chat_id TEXT NOT NULL,
thread_id TEXT NOT NULL,
@@ -78,11 +65,75 @@ class SessionTelegramTopicsMixin:
updated_at REAL NOT NULL,
PRIMARY KEY (profile_name, chat_id, thread_id)
""",
),
)
),
)
# Shared SELECT for the unlinked-session listing; the profile/bindings clauses
# are spliced in only when the bindings table exists.
_UNLINKED_SELECT_HEAD = f"""
SELECT s.*,
COALESCE(sp.prompt, s.system_prompt)
AS _system_prompt_resolved,
COALESCE(
(SELECT {_PREVIEW_RAW_SELECT}
FROM messages m
WHERE m.session_id = s.id AND m.role = 'user' AND m.content IS NOT NULL
AND {_PREVIEW_ELIGIBLE_SQL}
ORDER BY m.timestamp, m.id LIMIT 1),
''
) AS _preview_raw,
{_sql_session_last_active("s")} AS last_active
FROM sessions s
LEFT JOIN system_prompts sp
ON sp.hash = s.system_prompt_hash
WHERE s.source = 'telegram'
AND s.user_id = ?
"""
_UNLINKED_SELECT_TAIL = """ ORDER BY last_active DESC, s.started_at DESC
LIMIT ?
"""
# sessions.profile_name is NULL/empty for legacy rows → treat as default.
_UNLINKED_SCOPE_CLAUSES = """ AND COALESCE(NULLIF(TRIM(s.profile_name), ''), 'default') = ?
AND NOT EXISTS (
SELECT 1 FROM telegram_dm_topic_bindings b
WHERE b.session_id = s.id
)
"""
class SessionTelegramTopicsMixin:
"""Telegram DM topic-mode tables, bindings and lookups.
Read paths are read-only and tolerate absent tables (nobody ran ``/topic``)
by returning their empty value; only ``enable``/``bind`` run the migration.
"""
def _topic_read_one(self, sql: str, params, default=None):
"""``fetchone`` that treats an unmigrated table as *default*."""
try:
return self._read_one(sql, params)
except sqlite3.OperationalError:
return default
def _topic_read_all(self, sql: str, params) -> list:
"""``fetchall`` that treats an unmigrated table as no rows."""
try:
return self._read_all(sql, params)
except sqlite3.OperationalError:
return []
def apply_telegram_topic_migration(self) -> None:
"""Create Telegram DM topic-mode tables on explicit /topic opt-in.
Deliberately NOT part of startup reconciliation: operators can upgrade
and keep the old bot behavior until a user runs /topic.
Schema versions: v1 initial; v2 session_id FK ON DELETE CASCADE (pruning
clears bindings); v3 ``profile_name`` on both tables so multiplexed
gateways sharing one state.db isolate topic state per profile.
"""
def _do(conn):
for table, columns, ddl in tables:
for table, columns, ddl in _TOPIC_TABLES:
conn.execute(f"CREATE TABLE IF NOT EXISTS {table} ({ddl})")
have = {row[1] for row in conn.execute(f"PRAGMA table_info('{table}')")}
if "profile_name" in have:
@@ -100,7 +151,6 @@ class SessionTelegramTopicsMixin:
ALTER TABLE {table}_new RENAME TO {table};
"""
)
# Indexes after any rebuild: the user index needs profile_name.
conn.executescript(
"""
@@ -111,7 +161,6 @@ class SessionTelegramTopicsMixin:
ON telegram_dm_topic_bindings(profile_name, user_id, chat_id);
"""
)
conn.execute(
"INSERT INTO state_meta (key, value) VALUES (?, ?) "
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
@@ -120,11 +169,7 @@ class SessionTelegramTopicsMixin:
self._execute_write(_do)
def enable_telegram_topic_mode(
self,
*,
chat_id: str,
user_id: str,
profile_name: str = "default",
self, *, chat_id: str, user_id: str, profile_name: str = "default",
has_topics_enabled: Optional[bool] = None,
allows_users_to_create_topics: Optional[bool] = None,
) -> None:
@@ -139,9 +184,7 @@ class SessionTelegramTopicsMixin:
profile_name = _normalize_telegram_topic_profile_name(profile_name)
def _to_int(value: Optional[bool]) -> Optional[int]:
if value is None:
return None
return 1 if value else 0
return None if value is None else (1 if value else 0)
self._write_sql(
"""
@@ -158,24 +201,12 @@ class SessionTelegramTopicsMixin:
allows_users_to_create_topics = excluded.allows_users_to_create_topics,
capability_checked_at = excluded.capability_checked_at
""",
(
profile_name,
str(chat_id),
str(user_id),
now,
now,
_to_int(has_topics_enabled),
_to_int(allows_users_to_create_topics),
now,
),
(profile_name, str(chat_id), str(user_id), now, now,
_to_int(has_topics_enabled), _to_int(allows_users_to_create_topics), now),
)
def disable_telegram_topic_mode(
self,
*,
chat_id: str,
profile_name: str = "default",
clear_bindings: bool = True,
self, *, chat_id: str, profile_name: str = "default", clear_bindings: bool = True
) -> None:
"""Disable Telegram DM topic mode for one private chat.
@@ -202,110 +233,67 @@ class SessionTelegramTopicsMixin:
self._execute_write(_do)
def is_telegram_topic_mode_enabled(
self,
*,
chat_id: str,
user_id: str,
profile_name: str = "default",
self, *, chat_id: str, user_id: str, profile_name: str = "default"
) -> bool:
"""Return whether Telegram DM topic mode is enabled for this chat/user."""
profile_name = _normalize_telegram_topic_profile_name(profile_name)
with self._read_ctx() as conn:
try:
row = conn.execute(
"""
row = self._topic_read_one(
"""
SELECT enabled FROM telegram_dm_topic_mode
WHERE profile_name = ? AND chat_id = ? AND user_id = ?
""",
(profile_name, str(chat_id), str(user_id)),
).fetchone()
except sqlite3.OperationalError:
return False
if row is None:
return False
enabled = row[0]
return bool(enabled)
(profile_name, str(chat_id), str(user_id)),
)
return bool(row[0]) if row is not None else False
def get_telegram_topic_binding(
self,
*,
chat_id: str,
thread_id: str,
profile_name: str = "default",
self, *, chat_id: str, thread_id: str, profile_name: str = "default"
) -> Optional[Dict[str, Any]]:
"""Return the session binding for a Telegram DM topic, if present."""
profile_name = _normalize_telegram_topic_profile_name(profile_name)
with self._read_ctx() as conn:
try:
row = conn.execute(
"""
row = self._topic_read_one(
"""
SELECT * FROM telegram_dm_topic_bindings
WHERE profile_name = ? AND chat_id = ? AND thread_id = ?
""",
(profile_name, str(chat_id), str(thread_id)),
).fetchone()
except sqlite3.OperationalError:
return None
(profile_name, str(chat_id), str(thread_id)),
)
return dict(row) if row else None
def list_telegram_topic_bindings_for_chat(
self,
*,
chat_id: str,
profile_name: str = "default",
self, *, chat_id: str, profile_name: str = "default"
) -> List[Dict[str, Any]]:
"""All bindings for one chat, newest first. Read-only: [] when the
table is absent (never triggers the migration)."""
"""All bindings for one chat, newest first ([] when the table is absent)."""
profile_name = _normalize_telegram_topic_profile_name(profile_name)
with self._read_ctx() as conn:
try:
rows = conn.execute(
"SELECT * FROM telegram_dm_topic_bindings "
"WHERE profile_name = ? AND chat_id = ? "
"ORDER BY updated_at DESC",
(profile_name, str(chat_id)),
).fetchall()
except sqlite3.OperationalError:
return []
rows = self._topic_read_all(
"SELECT * FROM telegram_dm_topic_bindings "
"WHERE profile_name = ? AND chat_id = ? "
"ORDER BY updated_at DESC",
(profile_name, str(chat_id)),
)
return [dict(row) for row in rows]
def get_telegram_topic_binding_by_session(
self,
*,
session_id: str,
) -> Optional[Dict[str, Any]]:
"""Reverse lookup via the UNIQUE INDEX on session_id; None when
unbound or the table is absent."""
with self._read_ctx() as conn:
try:
row = conn.execute(
"""
def get_telegram_topic_binding_by_session(self, *, session_id: str) -> Optional[Dict[str, Any]]:
"""Reverse lookup via the UNIQUE INDEX on session_id; None when unbound."""
row = self._topic_read_one(
"""
SELECT * FROM telegram_dm_topic_bindings
WHERE session_id = ?
""",
(str(session_id),),
).fetchone()
except sqlite3.OperationalError:
return None
(str(session_id),),
)
return dict(row) if row else None
def delete_telegram_topic_binding(
self,
*,
chat_id: str,
thread_id: str,
profile_name: str = "default",
self, *, chat_id: str, thread_id: str, profile_name: str = "default"
) -> int:
"""Remove the binding row for one (chat, thread) pair.
Called when the Bot API confirms a topic was deleted externally
(``Thread not found`` after the same-thread retry failed); otherwise
``gateway.run._recover_telegram_topic_thread_id`` keeps redirecting
inbound messages to the dead topic.
If this removes the chat's *last* binding, ``telegram_dm_topic_mode``
is flipped to ``enabled = 0`` in the same transaction; otherwise the
chat stays in topic mode with zero lanes and a user who disabled topics
(``Thread not found`` after the same-thread retry failed); otherwise ``gateway.run._recover_telegram_topic_thread_id`` keeps
redirecting inbound messages to the dead topic. If this removes the
chat's *last* binding, ``telegram_dm_topic_mode`` is flipped to
``enabled = 0`` in the same transaction, or a user who disabled topics
in the Telegram client (not via ``/topic off``) stays stuck.
Returns the number of rows deleted; absent binding or unmigrated tables
@@ -331,8 +319,8 @@ class SessionTelegramTopicsMixin:
return
if not deleted["count"]:
return
# Last binding gone → disable topic mode. Same transaction, so no
# read-after-prune race.
# Last binding gone → disable topic mode in the same transaction, so
# there is no read-after-prune race.
try:
remaining = conn.execute(
"""
@@ -356,15 +344,8 @@ class SessionTelegramTopicsMixin:
return deleted["count"]
def bind_telegram_topic(
self,
*,
chat_id: str,
thread_id: str,
user_id: str,
session_key: str,
session_id: str,
managed_mode: str = "auto",
profile_name: str = "default",
self, *, chat_id: str, thread_id: str, user_id: str, session_key: str,
session_id: str, managed_mode: str = "auto", profile_name: str = "default",
) -> None:
"""Bind one Telegram DM topic thread to one Hermes session.
@@ -373,11 +354,8 @@ class SessionTelegramTopicsMixin:
"""
self.apply_telegram_topic_migration()
now = time.time()
chat_id = str(chat_id)
thread_id = str(thread_id)
user_id = str(user_id)
session_key = str(session_key)
session_id = str(session_id)
chat_id, thread_id, user_id = str(chat_id), str(thread_id), str(user_id)
session_key, session_id = str(session_key), str(session_id)
profile_name = _normalize_telegram_topic_profile_name(profile_name)
def _do(conn):
@@ -390,19 +368,13 @@ class SessionTelegramTopicsMixin:
(session_id,),
).fetchone()
if existing_session is not None:
if isinstance(existing_session, sqlite3.Row):
linked_profile = existing_session["profile_name"]
linked_chat = existing_session["chat_id"]
linked_thread = existing_session["thread_id"]
else:
linked_profile, linked_chat, linked_thread = existing_session
linked_profile, linked_chat, linked_thread = existing_session
if (
str(linked_profile) != profile_name
or str(linked_chat) != chat_id
or str(linked_thread) != thread_id
):
raise ValueError("session is already linked to another Telegram topic")
conn.execute(
"""
INSERT INTO telegram_dm_topic_bindings (
@@ -416,111 +388,44 @@ class SessionTelegramTopicsMixin:
managed_mode = excluded.managed_mode,
updated_at = excluded.updated_at
""",
(
profile_name,
chat_id,
thread_id,
user_id,
session_key,
session_id,
managed_mode,
now,
now,
),
(profile_name, chat_id, thread_id, user_id, session_key, session_id,
managed_mode, now, now),
)
self._execute_write(_do)
def is_telegram_session_linked_to_topic(self, *, session_id: str) -> bool:
"""True if the session is bound to any Telegram DM topic. Read-only:
absent tables (nobody ran ``/topic``) mean unbound → False."""
with self._read_ctx() as conn:
try:
row = conn.execute(
"""
"""True if the session is bound to any Telegram DM topic (absent tables → False)."""
row = self._topic_read_one(
"""
SELECT 1 FROM telegram_dm_topic_bindings
WHERE session_id = ?
LIMIT 1
""",
(str(session_id),),
).fetchone()
except sqlite3.OperationalError:
return False
(str(session_id),),
)
return row is not None
def list_unlinked_telegram_sessions_for_user(
self,
*,
chat_id: str,
user_id: str,
profile_name: str = "default",
limit: int = 10,
self, *, chat_id: str, user_id: str, profile_name: str = "default", limit: int = 10
) -> List[Dict[str, Any]]:
"""This user's Telegram sessions not bound to a topic.
Read-only: if the bindings table is absent, every session is unlinked
and a simpler query is used. Scoped by ``profile_name`` so multiplexed
profiles do not surface each other's sessions.
and the profile-unscoped query is used. Scoped by ``profile_name`` so
multiplexed profiles do not surface each other's sessions.
"""
profile_name = _normalize_telegram_topic_profile_name(profile_name)
# sessions.profile_name is NULL/empty for legacy rows → treat as default.
profile_clause = "AND COALESCE(NULLIF(TRIM(s.profile_name), ''), 'default') = ?"
with self._read_ctx() as conn:
try:
rows = conn.execute(
f"""
SELECT s.*,
COALESCE(sp.prompt, s.system_prompt)
AS _system_prompt_resolved,
COALESCE(
(SELECT {_PREVIEW_RAW_SELECT}
FROM messages m
WHERE m.session_id = s.id AND m.role = 'user' AND m.content IS NOT NULL
AND {_PREVIEW_ELIGIBLE_SQL}
ORDER BY m.timestamp, m.id LIMIT 1),
''
) AS _preview_raw,
{_sql_session_last_active("s")} AS last_active
FROM sessions s
LEFT JOIN system_prompts sp
ON sp.hash = s.system_prompt_hash
WHERE s.source = 'telegram'
AND s.user_id = ?
{profile_clause}
AND NOT EXISTS (
SELECT 1 FROM telegram_dm_topic_bindings b
WHERE b.session_id = s.id
)
ORDER BY last_active DESC, s.started_at DESC
LIMIT ?
""",
_UNLINKED_SELECT_HEAD + _UNLINKED_SCOPE_CLAUSES + _UNLINKED_SELECT_TAIL,
(str(user_id), profile_name, int(limit)),
).fetchall()
except sqlite3.OperationalError:
rows = conn.execute(
f"""
SELECT s.*,
COALESCE(sp.prompt, s.system_prompt)
AS _system_prompt_resolved,
COALESCE(
(SELECT {_PREVIEW_RAW_SELECT}
FROM messages m
WHERE m.session_id = s.id AND m.role = 'user' AND m.content IS NOT NULL
AND {_PREVIEW_ELIGIBLE_SQL}
ORDER BY m.timestamp, m.id LIMIT 1),
''
) AS _preview_raw,
{_sql_session_last_active("s")} AS last_active
FROM sessions s
LEFT JOIN system_prompts sp
ON sp.hash = s.system_prompt_hash
WHERE s.source = 'telegram'
AND s.user_id = ?
ORDER BY last_active DESC, s.started_at DESC
LIMIT ?
""",
_UNLINKED_SELECT_HEAD + _UNLINKED_SELECT_TAIL,
(str(user_id), int(limit)),
).fetchall()
sessions: List[Dict[str, Any]] = []
for row in rows:
session = self._session_row_dict(row)
+80 -169
View File
@@ -13,66 +13,44 @@ from hermes_state_common import _COMPRESSION_CHILD_SQL, escape_like as _escape_l
# caplog tests pin the "hermes_state" logger name.
logger = logging.getLogger("hermes_state")
# ASCII controls (keeping \t \n \r for the whitespace collapse), then zero-width,
# bidi override, object-replacement and interlinear-annotation code points.
_TITLE_CONTROL_RE = re.compile(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]')
_TITLE_INVISIBLE_RE = re.compile(r'[\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff\ufffc\ufff9-\ufffb]')
_NUMBERED_TITLE_RE = re.compile(r'^(.*?) #(\d+)$')
class SessionTitlesMixin:
"""Sanitizing, ranking auto/user titles, lineage-aware lookups."""
@classmethod
def _title_rank(cls, source: Optional[str]) -> int:
"""Rank a stored title_source.
NULL (pre-provenance rows) is indistinguishable from a manual ``/title``
of that era, so it ranks as ``user``: auto-titling only ever fills
genuinely empty legacy titles.
"""
"""Rank a stored title_source. NULL (pre-provenance rows) is indistinguishable
from a manual ``/title`` of that era, so it ranks as ``user``."""
if source is None:
return cls._TITLE_SOURCE_RANK[cls.TITLE_SOURCE_USER]
return cls._TITLE_SOURCE_RANK.get(str(source), 0)
@staticmethod
def sanitize_title(title: Optional[str]) -> Optional[str]:
"""Strip control/zero-width/bidi chars, collapse whitespace, normalize
empty to None. Raises ValueError if longer than MAX_TITLE_LENGTH
after cleaning."""
"""Strip control/zero-width/bidi chars (and lone surrogates sqlite3 cannot
bind), collapse whitespace, normalize empty to None. Raises ValueError if
longer than MAX_TITLE_LENGTH after cleaning."""
from hermes_state import SessionDB
if not title:
return None
# Lone surrogates cannot be bound by sqlite3 (UnicodeEncodeError).
title = _sanitize_surrogates(title)
# ASCII controls, keeping \t \n \r so the whitespace collapse below
# turns them into spaces.
cleaned = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]', '', title)
# Zero-width, bidi override, object-replacement, interlinear annotation.
cleaned = re.sub(
r'[\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff\ufffc\ufff9-\ufffb]',
'', cleaned,
)
cleaned = _TITLE_INVISIBLE_RE.sub('', _TITLE_CONTROL_RE.sub('', _sanitize_surrogates(title)))
cleaned = re.sub(r'\s+', ' ', cleaned).strip()
if not cleaned:
return None
if len(cleaned) > SessionDB.MAX_TITLE_LENGTH:
raise ValueError(
f"Title too long ({len(cleaned)} chars, max {SessionDB.MAX_TITLE_LENGTH})"
)
raise ValueError(f"Title too long ({len(cleaned)} chars, max {SessionDB.MAX_TITLE_LENGTH})")
return cleaned
def _is_compression_ancestor(
self, conn, *, ancestor_id: str, descendant_id: str
) -> bool:
"""True if *ancestor_id* is a compression predecessor of *descendant_id*.
Uses the canonical continuation edge ``_COMPRESSION_CHILD_SQL`` (parent
ended with ``end_reason = 'compression'`` and child started at/after its
``ended_at``), which excludes delegate/branch children that also carry
``parent_session_id``. One recursive CTE so the edge is defined once.
"""
def _is_compression_ancestor(self, conn, *, ancestor_id: str, descendant_id: str) -> bool:
"""True if *ancestor_id* is a compression predecessor of *descendant_id*, via the
canonical continuation edge ``_COMPRESSION_CHILD_SQL`` (excludes delegate/branch
children that also carry ``parent_session_id``)."""
if not ancestor_id or not descendant_id or ancestor_id == descendant_id:
return False
edge = _COMPRESSION_CHILD_SQL.format(a="child")
@@ -93,23 +71,15 @@ class SessionTitlesMixin:
).fetchone()
return row is not None
def _set_session_title(
self,
session_id: str,
title: str,
*,
source: str,
) -> bool:
def _set_session_title(self, session_id: str, title: str, *, source: str) -> bool:
"""Write a title, enforcing provenance precedence.
A ``user`` write always lands. ``derived``/``llm`` land only when the
row is untitled or holds strictly lower authority, so derived upgrades
to llm exactly once, nothing overwrites a user name, and re-running the
titler on an llm row is a no-op (stops sessions renaming themselves).
No writer may move a hidden canonical Bot Chat off its title.
Read and write are one compare-and-swap in a single transaction, so a
manual ``/title`` racing an in-flight generation is not clobbered.
A ``user`` write always lands. ``derived``/``llm`` land only when the row is
untitled or holds strictly lower authority (derived upgrades to llm exactly once,
nothing overwrites a user name, re-running the titler on an llm row is a no-op).
No writer may move a hidden canonical Bot Chat off its title. Read and write are
one compare-and-swap transaction, so a manual ``/title`` racing an in-flight
generation is not clobbered.
"""
title = self.sanitize_title(title)
is_user = source == self.TITLE_SOURCE_USER
@@ -117,18 +87,14 @@ class SessionTitlesMixin:
def _do(conn):
current = conn.execute(
"SELECT title, title_source, hidden FROM sessions WHERE id = ?",
(session_id,),
"SELECT title, title_source, hidden FROM sessions WHERE id = ?", (session_id,),
).fetchone()
if current is None:
return 0
# The canonical Bot Chat's NAME is its identity: Bot Mode resolves it
# by exact-title lookup on every open, so a rename orphans the whole
# conversation (next open mints an empty replacement and UNIQUE(title)
# blocks renaming back). Refuse here, the single write path every
# surface funnels through. Hidden is the discriminator: canonical
# chats are born hidden; a visible session merely named "Bot Chat"
# stays renameable. Provenance-blind so the auto-titler no-ops too.
# The canonical Bot Chat's NAME is its identity (Bot Mode resolves it by
# exact-title lookup on every open), so a rename orphans the conversation.
# Hidden is the discriminator: canonical chats are born hidden; a visible
# session merely named "Bot Chat" stays renameable. Provenance-blind.
if (
(current["title"] or "") == self.CANONICAL_BOT_CHAT_TITLE
and bool(current["hidden"])
@@ -141,100 +107,64 @@ class SessionTitlesMixin:
"To start fresh, create a new bot instead."
)
return 0
if not is_user and current["title"] is not None:
if self._title_rank(current["title_source"]) >= new_rank:
return 0
if not is_user and current["title"] is not None and self._title_rank(current["title_source"]) >= new_rank:
return 0
if title:
cursor = conn.execute(
"SELECT id FROM sessions WHERE title = ? AND id != ?",
(title, session_id),
)
conflict = cursor.fetchone()
conflict = conn.execute(
"SELECT id FROM sessions WHERE title = ? AND id != ?", (title, session_id),
).fetchone()
if conflict:
conflict_id = conflict["id"]
# If the conflicting holder is a hidden compressed ancestor
# of this continuation, the user cannot free the title, so
# transfer it onto the tip. Uniqueness and lineage are kept.
if self._is_compression_ancestor(
conn, ancestor_id=conflict_id, descendant_id=session_id
):
conn.execute(
"UPDATE sessions SET title = NULL WHERE id = ?",
(conflict_id,),
)
# A hidden compressed ancestor holding the title cannot be freed by
# the user, so transfer it onto the tip (uniqueness + lineage kept).
if self._is_compression_ancestor(conn, ancestor_id=conflict_id, descendant_id=session_id):
conn.execute("UPDATE sessions SET title = NULL WHERE id = ?", (conflict_id,))
else:
raise ValueError(
f"Title '{title}' is already in use by session {conflict_id}"
)
# CAS on the values just read (``IS`` is NULL-safe): a concurrent
# write between the SELECT and here loses instead of being overwritten.
raise ValueError(f"Title '{title}' is already in use by session {conflict_id}")
# CAS on the values just read (``IS`` is NULL-safe): a concurrent write
# between the SELECT and here loses instead of being overwritten.
cursor = conn.execute(
"UPDATE sessions SET title = ?, title_source = ? "
"WHERE id = ? AND title IS ? AND title_source IS ?",
(
title,
source if title else None,
session_id,
current["title"],
current["title_source"],
),
(title, source if title else None, session_id, current["title"], current["title_source"]),
)
return cursor.rowcount
rowcount = self._execute_write(_do)
return rowcount > 0
return self._execute_write(_do) > 0
def set_session_title(self, session_id: str, title: str) -> bool:
"""Set a title on the user's behalf (``user`` provenance; auto-titling
never replaces it). Empty clears the title. Raises ValueError on a
title conflict or validation failure. Automatic callers must use
:meth:`set_auto_title`."""
return self._set_session_title(
session_id, title, source=self.TITLE_SOURCE_USER
)
"""Set a title on the user's behalf (``user`` provenance). Empty clears it.
Raises ValueError on conflict or validation failure."""
return self._set_session_title(session_id, title, source=self.TITLE_SOURCE_USER)
def set_auto_title(self, session_id: str, title: str, *, source: str) -> bool:
"""Set an automatic title; False (untouched) when a higher-authority
title already holds the row."""
"""Set an automatic title; False (untouched) when a higher-authority title
already holds the row."""
if source not in (self.TITLE_SOURCE_DERIVED, self.TITLE_SOURCE_LLM):
raise ValueError(f"invalid automatic title source: {source!r}")
return self._set_session_title(session_id, title, source=source)
def set_auto_title_if_empty(self, session_id: str, title: str) -> bool:
"""Back-compat shim (third-party plugins reference it by name); new
code calls :meth:`set_auto_title` with an explicit source."""
return self.set_auto_title(
session_id, title, source=self.TITLE_SOURCE_LLM
)
"""Back-compat shim (third-party plugins reference it by name)."""
return self.set_auto_title(session_id, title, source=self.TITLE_SOURCE_LLM)
def get_session_title(self, session_id: str) -> Optional[str]:
"""Get the title for a session, or None."""
with self._read_ctx() as conn:
cursor = conn.execute(
"SELECT title FROM sessions WHERE id = ?", (session_id,)
)
row = cursor.fetchone()
row = self._read_one("SELECT title FROM sessions WHERE id = ?", (session_id,))
return row["title"] if row else None
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._read_ctx() as conn:
cursor = conn.execute(
"SELECT title, title_source FROM sessions WHERE id = ?",
(session_id,),
)
row = cursor.fetchone()
row = self._read_one("SELECT title, title_source FROM sessions WHERE id = ?", (session_id,))
if not row or row["title"] is None:
return None
return row["title_source"]
def set_session_title_source(self, session_id: str, source: str) -> bool:
"""Overwrite a title's provenance without touching the text: a title
copied across a compression rotation keeps the original's authority."""
"""Overwrite a title's provenance without touching the text (a title copied
across a compression rotation keeps the original's authority)."""
if source not in self._TITLE_SOURCE_RANK:
raise ValueError(f"invalid title source: {source!r}")
return self._write_rowcount(
"UPDATE sessions SET title_source = ? "
"WHERE id = ? AND title IS NOT NULL",
@@ -243,63 +173,44 @@ class SessionTitlesMixin:
def get_session_by_title(self, title: str) -> Optional[Dict[str, Any]]:
"""Look up a session by exact title. Returns session dict or None."""
with self._read_ctx() as conn:
cursor = conn.execute(
"SELECT s.*, "
"COALESCE(sp.prompt, s.system_prompt) AS _system_prompt_resolved "
"FROM sessions s "
"LEFT JOIN system_prompts sp ON sp.hash = s.system_prompt_hash "
"WHERE s.title = ?",
(title,),
)
row = cursor.fetchone()
row = self._read_one(
"SELECT s.*, "
"COALESCE(sp.prompt, s.system_prompt) AS _system_prompt_resolved "
"FROM sessions s "
"LEFT JOIN system_prompts sp ON sp.hash = s.system_prompt_hash "
"WHERE s.title = ?",
(title,),
)
return self._session_row_dict(row) if row else None
def resolve_session_by_title(self, title: str) -> Optional[str]:
"""Resolve a title to a session ID, preferring the latest "title #N"
continuation over the exact match."""
exact = self.get_session_by_title(title)
# Escape LIKE wildcards so "%"/"_" in titles cannot false-match.
escaped = _escape_like(title)
with self._read_ctx() as conn:
cursor = conn.execute(
"SELECT id, title, started_at FROM sessions "
"WHERE title LIKE ? ESCAPE '\\' ORDER BY started_at DESC",
(f"{escaped} #%",),
)
numbered = cursor.fetchall()
numbered = self._read_all(
"SELECT id, title, started_at FROM sessions "
"WHERE title LIKE ? ESCAPE '\\' ORDER BY started_at DESC",
(f"{_escape_like(title)} #%",),
)
if numbered:
return numbered[0]["id"]
elif exact:
return exact["id"]
return None
return exact["id"] if exact else None
def get_next_title_in_lineage(self, base_title: str) -> str:
"""Next title in a lineage ("my session" → "my session #2"): strip any
" #N" suffix, then increment the highest existing number."""
match = re.match(r'^(.*?) #(\d+)$', base_title)
if match:
base = match.group(1)
else:
base = base_title
escaped = _escape_like(base)
with self._read_ctx() as conn:
cursor = conn.execute(
"SELECT title FROM sessions WHERE title = ? OR title LIKE ? ESCAPE '\\'",
(base, f"{escaped} #%"),
)
existing = [row["title"] for row in cursor.fetchall()]
if not existing:
"""Next title in a lineage ("my session" -> "my session #2"): strip any " #N"
suffix, then increment the highest existing number."""
match = _NUMBERED_TITLE_RE.match(base_title)
base = match.group(1) if match else base_title
rows = self._read_all(
"SELECT title FROM sessions WHERE title = ? OR title LIKE ? ESCAPE '\\'",
(base, f"{_escape_like(base)} #%"),
)
if not rows:
return base
max_num = 1 # The unnumbered original counts as #1
for t in existing:
m = re.match(r'^.* #(\d+)$', t)
max_num = 1 # the unnumbered original counts as #1
for row in rows:
m = re.match(r'^.* #(\d+)$', row["title"])
if m:
max_num = max(max_num, int(m.group(1)))
return f"{base} #{max_num + 1}"
+185 -348
View File
@@ -14,24 +14,79 @@ from typing import Any, Dict, List, Optional, Tuple
# caplog tests pin the "hermes_state" logger name.
logger = logging.getLogger("hermes_state")
_TOKEN_UPDATE_ABSOLUTE_SQL = """UPDATE sessions SET
input_tokens = ?,
output_tokens = ?,
cache_read_tokens = ?,
cache_write_tokens = ?,
reasoning_tokens = ?,
estimated_cost_usd = COALESCE(?, 0),
actual_cost_usd = CASE
WHEN ? IS NULL THEN actual_cost_usd
ELSE ?
END,
cost_status = COALESCE(?, cost_status),
cost_source = COALESCE(?, cost_source),
pricing_version = COALESCE(?, pricing_version),
billing_provider = COALESCE(billing_provider, ?),
billing_base_url = COALESCE(billing_base_url, ?),
billing_mode = COALESCE(billing_mode, ?),
model = COALESCE(model, ?),
api_call_count = ?
WHERE id = ?"""
_TOKEN_UPDATE_DELTA_SQL = """UPDATE sessions SET
input_tokens = input_tokens + ?,
output_tokens = output_tokens + ?,
cache_read_tokens = cache_read_tokens + ?,
cache_write_tokens = cache_write_tokens + ?,
reasoning_tokens = reasoning_tokens + ?,
estimated_cost_usd = COALESCE(estimated_cost_usd, 0) + COALESCE(?, 0),
actual_cost_usd = CASE
WHEN ? IS NULL THEN actual_cost_usd
ELSE COALESCE(actual_cost_usd, 0) + ?
END,
cost_status = COALESCE(?, cost_status),
cost_source = COALESCE(?, cost_source),
pricing_version = COALESCE(?, pricing_version),
billing_provider = COALESCE(billing_provider, ?),
billing_base_url = COALESCE(billing_base_url, ?),
billing_mode = COALESCE(billing_mode, ?),
model = COALESCE(model, ?),
api_call_count = COALESCE(api_call_count, 0) + ?
WHERE id = ?"""
_MODEL_USAGE_UPSERT_SQL = """INSERT INTO session_model_usage (
session_id, model, billing_provider, billing_base_url, billing_mode,
task, api_call_count, input_tokens, output_tokens,
cache_read_tokens, cache_write_tokens, reasoning_tokens,
estimated_cost_usd, actual_cost_usd, cost_status, cost_source,
first_seen, last_seen
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(session_id, model, billing_provider, billing_base_url, billing_mode, task)
DO UPDATE SET
api_call_count = api_call_count + excluded.api_call_count,
input_tokens = input_tokens + excluded.input_tokens,
output_tokens = output_tokens + excluded.output_tokens,
cache_read_tokens = cache_read_tokens + excluded.cache_read_tokens,
cache_write_tokens = cache_write_tokens + excluded.cache_write_tokens,
reasoning_tokens = reasoning_tokens + excluded.reasoning_tokens,
estimated_cost_usd = estimated_cost_usd + excluded.estimated_cost_usd,
actual_cost_usd = actual_cost_usd + excluded.actual_cost_usd,
cost_status = COALESCE(excluded.cost_status, cost_status),
cost_source = COALESCE(excluded.cost_source, cost_source),
last_seen = excluded.last_seen"""
class SessionUsageMixin:
"""Coalesced token writer, per-model usage rows, billing route."""
def update_session_billing_route(
self,
session_id: str,
*,
provider: str,
base_url: str,
billing_mode: Optional[str] = None,
self, session_id: str, *, provider: str, base_url: str, billing_mode: Optional[str] = None,
) -> None:
"""Unconditionally set the billing route (``update_token_counts`` only
COALESCE-fills NULLs) so the dashboard reflects the latest /model switch.
Also nulls ``system_prompt`` so the cached snapshot (stale ``Model:`` /
``Provider:`` header) is rebuilt, like ``update_session_model``.
"""
COALESCE-fills NULLs) so the dashboard reflects the latest /model switch. Also
nulls ``system_prompt`` so the cached snapshot header is rebuilt."""
# Barrier against queued token deltas — see update_session_model.
self.flush_token_counts()
@@ -50,29 +105,20 @@ class SessionUsageMixin:
self._execute_write(_do)
def queue_token_counts(self, session_id: str, **kwargs) -> None:
"""Enqueue a token/cost delta for the background writer.
Same kwargs and semantics as :meth:`update_token_counts`, applied
asynchronously; cheap enough for the turn thread. After close() has
stopped the writer, falls back to the synchronous path and may raise.
"""
"""Enqueue a token/cost delta for the background writer (same kwargs as
:meth:`update_token_counts`). After close() has stopped the writer, falls back
to the synchronous path and may raise."""
with self._token_queue_cond:
thread = self._token_writer_thread
writer_stopped = self._token_writer_stop and (
thread is None or not thread.is_alive()
)
writer_stopped = self._token_writer_stop and (thread is None or not thread.is_alive())
if not writer_stopped:
self._token_queue.append((session_id, kwargs))
if thread is None or not thread.is_alive():
# Daemon so exit never hangs on accounting; the atexit hook
# (registered once per instance) drains leftovers. Checking
# ``not is_alive()`` rather than ``is None`` respawns a writer
# that died from an unexpected escape, otherwise deltas
# would pile up until a reader's flush drained them.
# Daemon so exit never hangs on accounting; the atexit hook drains
# leftovers. ``not is_alive()`` (not ``is None``) respawns a writer
# that died from an unexpected escape.
thread = threading.Thread(
target=self._token_writer_loop,
name="session-db-token-writer",
daemon=True,
target=self._token_writer_loop, name="session-db-token-writer", daemon=True,
)
self._token_writer_thread = thread
thread.start()
@@ -88,18 +134,21 @@ class SessionUsageMixin:
atexit.register(_drain_at_exit)
self._token_queue_cond.notify_all()
if writer_stopped:
# close() ran (a stop-flagged but live writer still accepts; its
# loop drains before exiting). Enqueueing now would drop the delta
# silently — no writer, atexit hook gone — so apply inline and let a
# closed-connection failure raise at the call site.
# close() ran: enqueueing would drop the delta silently, so apply inline.
self.update_token_counts(session_id, **kwargs)
def flush_token_counts(self, timeout: float = 5.0) -> bool:
"""Block until every queued token delta has been applied.
def _apply_claimed_batch(self, batch) -> None:
"""Apply a batch whose ``busy`` flag the caller already claimed, then release."""
try:
self._apply_token_batch(batch)
finally:
with self._token_queue_cond:
self._token_writer_busy = False
self._token_queue_cond.notify_all()
False on timeout (callers then read totals stale by the queued deltas).
Never raises: apply failures are logged by the writer.
"""
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."""
# Lock-free fast path: reads queue-then-busy (see ordering notes below).
if not self._token_queue and not self._token_writer_busy:
return True
@@ -107,20 +156,13 @@ class SessionUsageMixin:
with self._token_queue_cond:
deadline = time.monotonic() + timeout
while self._token_queue or self._token_writer_busy:
# A live writer is authoritative even when stop-flagged: draining
# here would race its in-flight batch, and newer deltas committing
# before older ones breaks last-non-None-wins / first-accounted-
# route / COALESCE-backfill fields. Only a dead writer lets the
# caller take leftovers; re-checked each wakeup because the writer
# can exit mid-wait with deltas enqueued after its final check.
# busy is claimed while draining so a concurrent flush cannot
# report drained or pop a newer delta while this batch is
# unapplied: a claimed busy means "wait", never "drain alongside".
# A live writer is authoritative even when stop-flagged: draining here
# would race its in-flight batch and reorder deltas (breaking last-non-
# None-wins / first-accounted-route / COALESCE-backfill fields). Only a
# dead writer lets the caller take leftovers; a claimed busy means
# "wait", never "drain alongside".
thread = self._token_writer_thread
if (
(thread is None or not thread.is_alive())
and not self._token_writer_busy
):
if (thread is None or not thread.is_alive()) and not self._token_writer_busy:
self._token_writer_busy = True
batch = list(self._token_queue)
self._token_queue.clear()
@@ -130,12 +172,7 @@ class SessionUsageMixin:
return False
self._token_queue_cond.wait(remaining)
if batch:
try:
self._apply_token_batch(batch)
finally:
with self._token_queue_cond:
self._token_writer_busy = False
self._token_queue_cond.notify_all()
self._apply_claimed_batch(batch)
return True
def _token_writer_loop(self) -> None:
@@ -145,62 +182,44 @@ class SessionUsageMixin:
while not self._token_queue and not self._token_writer_stop:
remaining = idle_deadline - time.monotonic()
if remaining <= 0:
# Retire under the same lock queue_token_counts() uses to
# decide to spawn, so no delta strands behind an exiting worker.
# Retire under the same lock queue_token_counts() uses to decide
# to spawn, so no delta strands behind an exiting worker.
self._token_writer_thread = None
return
self._token_queue_cond.wait(remaining)
if not self._token_queue:
self._token_writer_thread = None
return # stop requested and fully drained
# busy BEFORE clearing the queue: flush's lock-free fast path
# reads queue-then-busy and must never see "empty and idle"
# while a popped batch is unapplied.
# busy BEFORE clearing the queue: flush's lock-free fast path must never
# see "empty and idle" while a popped batch is unapplied.
self._token_writer_busy = True
batch = list(self._token_queue)
self._token_queue.clear()
try:
self._apply_token_batch(batch)
finally:
with self._token_queue_cond:
self._token_writer_busy = False
self._token_queue_cond.notify_all()
self._apply_claimed_batch(batch)
def _apply_token_batch(self, batch: List[Tuple[str, Dict[str, Any]]]) -> None:
"""Apply queued deltas in order, coalescing where safe. Never raises."""
try:
coalesced = self._coalesce_token_deltas(batch)
except Exception as exc:
# Coalescing must never kill the writer (callers cannot observe a
# dead one); the merge is only an optimization.
logger.warning(
"async token accounting: coalesce failed, applying raw "
"batch: %s", exc,
)
# Coalescing must never kill the writer; the merge is only an optimization.
logger.warning("async token accounting: coalesce failed, applying raw batch: %s", exc)
coalesced = batch
for session_id, kwargs in coalesced:
try:
self.update_token_counts(session_id, **kwargs)
except Exception as exc:
# Accounting loss is logged, never raised into a turn.
logger.warning(
"async token accounting: apply failed (session=%s): %s",
session_id, exc,
)
logger.warning("async token accounting: apply failed (session=%s): %s", session_id, exc)
def _coalesce_token_deltas(
self, batch: List[Tuple[str, Dict[str, Any]]]
) -> List[Tuple[str, Dict[str, Any]]]:
"""Merge adjacent incremental deltas with an identical route, so
ordering across sessions and /model switches is preserved exactly.
absolute=True deltas never merge."""
def _coalesce_token_deltas(self, batch: List[Tuple[str, Dict[str, Any]]]) -> List[Tuple[str, Dict[str, Any]]]:
"""Merge adjacent incremental deltas with an identical route, so ordering across
sessions and /model switches is preserved exactly. absolute=True never merges."""
groups: List[Tuple[Optional[tuple], str, Dict[str, Any]]] = []
for session_id, kwargs in batch:
key = None
if not kwargs.get("absolute"):
key = (session_id,) + tuple(
kwargs.get(f) for f in self._TOKEN_DELTA_ROUTE_FIELDS
)
key = (session_id,) + tuple(kwargs.get(f) for f in self._TOKEN_DELTA_ROUTE_FIELDS)
if groups and key is not None and groups[-1][0] == key:
merged = groups[-1][2]
for f in self._TOKEN_DELTA_SUM_FIELDS:
@@ -223,18 +242,16 @@ class SessionUsageMixin:
if thread is not None and thread.is_alive():
thread.join(timeout=join_timeout)
if thread.is_alive():
# Writer stuck mid-apply: leave deltas unapplied rather than
# race it and misorder/double-count.
# Writer stuck mid-apply: leave deltas unapplied rather than race it.
logger.warning(
"async token accounting: writer did not stop within %.0fs; "
"%d queued delta(s) not persisted",
join_timeout, len(self._token_queue),
)
return
# Writer gone: apply leftovers synchronously under the same busy
# protocol. Wait out a flush caller-drain that already claimed busy —
# close() nulls the connection right after this returns and must not
# yank it mid-batch.
# Writer gone: apply leftovers synchronously under the same busy protocol. Wait
# out a flush caller-drain that already claimed busy — close() nulls the
# connection right after this returns and must not yank it mid-batch.
with self._token_queue_cond:
deadline = time.monotonic() + join_timeout
while self._token_writer_busy:
@@ -247,19 +264,13 @@ class SessionUsageMixin:
)
return
self._token_queue_cond.wait(remaining)
# busy BEFORE clearing the queue (same ordering as the writer loop),
# or flush's lock-free fast path could see "empty and idle".
# busy BEFORE clearing the queue (same ordering as the writer loop).
batch = list(self._token_queue)
if batch:
self._token_writer_busy = True
self._token_queue.clear()
if batch:
try:
self._apply_token_batch(batch)
finally:
with self._token_queue_cond:
self._token_writer_busy = False
self._token_queue_cond.notify_all()
self._apply_claimed_batch(batch)
def _drain_token_queue_at_exit(self) -> None:
try:
@@ -268,126 +279,50 @@ class SessionUsageMixin:
pass # never fatal at interpreter shutdown
def update_token_counts(
self,
session_id: str,
input_tokens: int = 0,
output_tokens: int = 0,
model: str = None,
cache_read_tokens: int = 0,
cache_write_tokens: int = 0,
reasoning_tokens: int = 0,
estimated_cost_usd: Optional[float] = None,
actual_cost_usd: Optional[float] = None,
cost_status: Optional[str] = None,
cost_source: Optional[str] = None,
pricing_version: Optional[str] = None,
billing_provider: Optional[str] = None,
billing_base_url: Optional[str] = None,
billing_mode: Optional[str] = None,
api_call_count: int = 0,
absolute: bool = False,
self, session_id: str, input_tokens: int = 0, output_tokens: int = 0, model: str = None,
cache_read_tokens: int = 0, cache_write_tokens: int = 0, reasoning_tokens: int = 0,
estimated_cost_usd: Optional[float] = None, actual_cost_usd: Optional[float] = None,
cost_status: Optional[str] = None, cost_source: Optional[str] = None,
pricing_version: Optional[str] = None, billing_provider: Optional[str] = None,
billing_base_url: Optional[str] = None, billing_mode: Optional[str] = None,
api_call_count: int = 0, absolute: bool = False,
) -> None:
"""Update token counters and backfill model if unset.
*absolute*=False increments (per-API-call deltas, CLI path);
*absolute*=True sets directly (gateway path, where the cached agent
holds cumulative totals).
"""
# Ensure the row exists: under concurrent load the initial
# create_session() may have failed on SQLite locking, and the UPDATE
# would silently affect 0 rows.
"""Update token counters and backfill model if unset. *absolute*=False
increments (per-API-call deltas, CLI path); *absolute*=True sets directly
(gateway path, where the cached agent holds cumulative totals)."""
# Ensure the row exists: under concurrent load create_session() may have failed
# on locking, and the UPDATE would silently affect 0 rows.
self._insert_session_row(session_id, "unknown", model=model)
if absolute:
sql = """UPDATE sessions SET
input_tokens = ?,
output_tokens = ?,
cache_read_tokens = ?,
cache_write_tokens = ?,
reasoning_tokens = ?,
estimated_cost_usd = COALESCE(?, 0),
actual_cost_usd = CASE
WHEN ? IS NULL THEN actual_cost_usd
ELSE ?
END,
cost_status = COALESCE(?, cost_status),
cost_source = COALESCE(?, cost_source),
pricing_version = COALESCE(?, pricing_version),
billing_provider = COALESCE(billing_provider, ?),
billing_base_url = COALESCE(billing_base_url, ?),
billing_mode = COALESCE(billing_mode, ?),
model = COALESCE(model, ?),
api_call_count = ?
WHERE id = ?"""
else:
sql = """UPDATE sessions SET
input_tokens = input_tokens + ?,
output_tokens = output_tokens + ?,
cache_read_tokens = cache_read_tokens + ?,
cache_write_tokens = cache_write_tokens + ?,
reasoning_tokens = reasoning_tokens + ?,
estimated_cost_usd = COALESCE(estimated_cost_usd, 0) + COALESCE(?, 0),
actual_cost_usd = CASE
WHEN ? IS NULL THEN actual_cost_usd
ELSE COALESCE(actual_cost_usd, 0) + ?
END,
cost_status = COALESCE(?, cost_status),
cost_source = COALESCE(?, cost_source),
pricing_version = COALESCE(?, pricing_version),
billing_provider = COALESCE(billing_provider, ?),
billing_base_url = COALESCE(billing_base_url, ?),
billing_mode = COALESCE(billing_mode, ?),
model = COALESCE(model, ?),
api_call_count = COALESCE(api_call_count, 0) + ?
WHERE id = ?"""
has_accounted_usage = bool(
sql = _TOKEN_UPDATE_ABSOLUTE_SQL if absolute else _TOKEN_UPDATE_DELTA_SQL
has_usage = bool(
input_tokens or output_tokens or cache_read_tokens
or cache_write_tokens or reasoning_tokens or api_call_count
or estimated_cost_usd or actual_cost_usd
or cache_write_tokens or reasoning_tokens or api_call_count or estimated_cost_usd
)
has_accounted_usage = bool(has_usage or actual_cost_usd)
params = (
input_tokens,
output_tokens,
cache_read_tokens,
cache_write_tokens,
reasoning_tokens,
estimated_cost_usd,
actual_cost_usd,
actual_cost_usd,
cost_status,
cost_source,
pricing_version,
input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, reasoning_tokens,
estimated_cost_usd, actual_cost_usd, actual_cost_usd, cost_status, cost_source, pricing_version,
billing_provider if has_accounted_usage else None,
billing_base_url if has_accounted_usage else None,
billing_mode if has_accounted_usage else None,
model if has_accounted_usage else None,
api_call_count,
session_id,
billing_mode if has_accounted_usage else None, model if has_accounted_usage else None,
api_call_count, session_id,
)
# Per-model attribution: the sessions row keeps one (model, provider)
# pair, so a mid-session /model switch would attribute every token to
# the initial model. Each delta carries the route active at call time
# and is recorded into session_model_usage keyed by it. Only the
# incremental path records here: absolute cumulative updates cannot be
# Per-model attribution: the sessions row keeps one (model, provider) pair, so a
# mid-session /model switch would attribute every token to the initial model.
# Only the incremental path records here — absolute cumulative updates cannot be
# split back into routes; Insights reconciles the residual instead.
record_model_usage = (not absolute) and (
input_tokens or output_tokens or cache_read_tokens
or cache_write_tokens or reasoning_tokens or api_call_count
or estimated_cost_usd
)
record_model_usage = (not absolute) and has_usage
def _do(conn):
row = conn.execute(
"SELECT model, billing_provider, api_call_count FROM sessions WHERE id = ?",
(session_id,),
"SELECT model, billing_provider, api_call_count FROM sessions WHERE id = ?", (session_id,),
).fetchone()
existing_model = row["model"] if row is not None else None
existing_provider = row["billing_provider"] if row is not None else None
existing_api_calls = int((row["api_call_count"] if row is not None else 0) or 0)
# create_session records the requested route before any API call.
# If that fails and fallback succeeds, the first accounted usage is
# the authoritative route; after that keep the row as is (one row
# cannot represent mixed-provider usage).
# create_session records the requested route before any API call. If that
# fails and fallback succeeds, the first accounted usage is the authoritative
# route; after that keep the row as is (one row cannot represent mixed usage).
first_accounted_route = (
existing_api_calls == 0
and has_accounted_usage
@@ -406,146 +341,63 @@ class SessionUsageMixin:
conn.execute(sql, params)
if record_model_usage:
self._record_model_usage(
conn,
session_id,
model=model,
billing_provider=billing_provider,
billing_base_url=billing_base_url,
billing_mode=billing_mode,
input_tokens=input_tokens,
output_tokens=output_tokens,
cache_read_tokens=cache_read_tokens,
cache_write_tokens=cache_write_tokens,
reasoning_tokens=reasoning_tokens,
estimated_cost_usd=estimated_cost_usd,
actual_cost_usd=actual_cost_usd,
cost_status=cost_status,
cost_source=cost_source,
conn, session_id, model=model, billing_provider=billing_provider,
billing_base_url=billing_base_url, billing_mode=billing_mode,
input_tokens=input_tokens, output_tokens=output_tokens,
cache_read_tokens=cache_read_tokens, cache_write_tokens=cache_write_tokens,
reasoning_tokens=reasoning_tokens, estimated_cost_usd=estimated_cost_usd,
actual_cost_usd=actual_cost_usd, cost_status=cost_status, cost_source=cost_source,
api_call_count=api_call_count,
)
self._execute_write(_do)
def _record_model_usage(
self,
conn,
session_id: str,
*,
model: Optional[str],
billing_provider: Optional[str],
billing_base_url: Optional[str],
billing_mode: Optional[str],
input_tokens: int,
output_tokens: int,
cache_read_tokens: int,
cache_write_tokens: int,
reasoning_tokens: int,
estimated_cost_usd: Optional[float],
actual_cost_usd: Optional[float],
cost_status: Optional[str],
cost_source: Optional[str],
api_call_count: int,
task: str = "",
self, conn, session_id: str, *, model: Optional[str], billing_provider: Optional[str],
billing_base_url: Optional[str], billing_mode: Optional[str], input_tokens: int,
output_tokens: int, cache_read_tokens: int, cache_write_tokens: int, reasoning_tokens: int,
estimated_cost_usd: Optional[float], actual_cost_usd: Optional[float],
cost_status: Optional[str], cost_source: Optional[str], api_call_count: int, task: str = "",
) -> None:
"""Accumulate a per-API-call usage delta into session_model_usage.
Runs inside the caller's write transaction, after the ``sessions``
UPDATE, so per-model rows stay consistent with the summary row. A
missing model/provider falls back to the session row (same COALESCE
behaviour as the summary update). ``task`` is ``''`` for the main loop;
auxiliary calls record their task name via :meth:`record_auxiliary_usage`.
"""Accumulate a per-API-call usage delta into session_model_usage, inside the
caller's write txn after the ``sessions`` UPDATE. A missing model/provider falls
back to the session row (same COALESCE behaviour as the summary update) — except
for aux rows (``task`` set), which must NOT inherit the main-loop route (vision
on gemini while the main loop runs anthropic): missing info stays 'unknown'/empty.
"""
row = conn.execute(
"SELECT model, billing_provider, billing_base_url, billing_mode "
"FROM sessions WHERE id = ?",
(session_id,),
).fetchone()
sess_model = row["model"] if row is not None else None
sess_provider = row["billing_provider"] if row is not None else None
sess_base_url = row["billing_base_url"] if row is not None else None
sess_billing_mode = row["billing_mode"] if row is not None else None
# Aux rows must NOT inherit the main-loop route (vision on gemini while
# the main loop runs anthropic); missing info stays 'unknown'/empty.
if task:
eff_model = model or "unknown"
eff_provider = billing_provider or ""
eff_base_url = billing_base_url or ""
eff_billing_mode = billing_mode or ""
else:
eff_model = model or sess_model or "unknown"
eff_provider = billing_provider or sess_provider or ""
eff_base_url = billing_base_url or sess_base_url or ""
eff_billing_mode = billing_mode or sess_billing_mode or ""
sess = dict(row) if (row is not None and not task) else {}
eff_model = model or sess.get("model") or "unknown"
eff_provider = billing_provider or sess.get("billing_provider") or ""
eff_base_url = billing_base_url or sess.get("billing_base_url") or ""
eff_billing_mode = billing_mode or sess.get("billing_mode") or ""
counts = [v or 0 for v in (input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, reasoning_tokens)]
now = time.time()
conn.execute(
"""INSERT INTO session_model_usage (
session_id, model, billing_provider, billing_base_url, billing_mode,
task, api_call_count, input_tokens, output_tokens,
cache_read_tokens, cache_write_tokens, reasoning_tokens,
estimated_cost_usd, actual_cost_usd, cost_status, cost_source,
first_seen, last_seen
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(session_id, model, billing_provider, billing_base_url, billing_mode, task)
DO UPDATE SET
api_call_count = api_call_count + excluded.api_call_count,
input_tokens = input_tokens + excluded.input_tokens,
output_tokens = output_tokens + excluded.output_tokens,
cache_read_tokens = cache_read_tokens + excluded.cache_read_tokens,
cache_write_tokens = cache_write_tokens + excluded.cache_write_tokens,
reasoning_tokens = reasoning_tokens + excluded.reasoning_tokens,
estimated_cost_usd = estimated_cost_usd + excluded.estimated_cost_usd,
actual_cost_usd = actual_cost_usd + excluded.actual_cost_usd,
cost_status = COALESCE(excluded.cost_status, cost_status),
cost_source = COALESCE(excluded.cost_source, cost_source),
last_seen = excluded.last_seen""",
_MODEL_USAGE_UPSERT_SQL,
(
session_id,
eff_model,
eff_provider,
eff_base_url,
eff_billing_mode,
task or "",
api_call_count or 0,
input_tokens or 0,
output_tokens or 0,
cache_read_tokens or 0,
cache_write_tokens or 0,
reasoning_tokens or 0,
float(estimated_cost_usd or 0.0),
float(actual_cost_usd or 0.0),
cost_status,
cost_source,
now,
now,
session_id, eff_model, eff_provider, eff_base_url, eff_billing_mode, task or "",
api_call_count or 0, *counts,
float(estimated_cost_usd or 0.0), float(actual_cost_usd or 0.0),
cost_status, cost_source, now, now,
),
)
def record_auxiliary_usage(
self,
session_id: str,
task: str,
*,
model: Optional[str] = None,
billing_provider: Optional[str] = None,
billing_base_url: Optional[str] = None,
input_tokens: int = 0,
output_tokens: int = 0,
cache_read_tokens: int = 0,
cache_write_tokens: int = 0,
reasoning_tokens: int = 0,
estimated_cost_usd: Optional[float] = None,
api_call_count: int = 1,
self, session_id: str, task: str, *, model: Optional[str] = None,
billing_provider: Optional[str] = None, billing_base_url: Optional[str] = None,
input_tokens: int = 0, output_tokens: int = 0, cache_read_tokens: int = 0,
cache_write_tokens: int = 0, reasoning_tokens: int = 0,
estimated_cost_usd: Optional[float] = None, api_call_count: int = 1,
) -> None:
"""Record an auxiliary LLM call's usage (vision, compression, title
generation, ...) against *session_id*.
Writes a per-(model, provider, task) delta into ``session_model_usage``
WITHOUT touching the ``sessions`` summary row: the gateway overwrites
session counters with absolute main-loop totals, so aux tokens there
would be clobbered or double-counted. Insights read the union.
``api_call_count`` may aggregate N calls (background-review forks).
Best-effort: callers must never fail an aux call over accounting.
"""
"""Record an auxiliary LLM call's usage (vision, compression, title generation,
...) as a per-(model, provider, task) delta in ``session_model_usage`` WITHOUT
touching the ``sessions`` summary row (the gateway overwrites those counters with
absolute main-loop totals). ``api_call_count`` may aggregate N calls. Best-effort:
callers must never fail an aux call over accounting."""
if not session_id or not task:
return
# FK to sessions.id: same INSERT OR IGNORE guard as update_token_counts.
@@ -553,37 +405,23 @@ class SessionUsageMixin:
def _do(conn):
self._record_model_usage(
conn,
session_id,
model=model,
billing_provider=billing_provider,
billing_base_url=billing_base_url,
billing_mode=None,
input_tokens=input_tokens or 0,
output_tokens=output_tokens or 0,
cache_read_tokens=cache_read_tokens or 0,
cache_write_tokens=cache_write_tokens or 0,
reasoning_tokens=reasoning_tokens or 0,
estimated_cost_usd=estimated_cost_usd,
actual_cost_usd=None,
cost_status=None,
cost_source=None,
api_call_count=(
1 if api_call_count is None else int(api_call_count)
),
task=task,
conn, session_id, model=model, billing_provider=billing_provider,
billing_base_url=billing_base_url, billing_mode=None,
input_tokens=input_tokens or 0, output_tokens=output_tokens or 0,
cache_read_tokens=cache_read_tokens or 0, cache_write_tokens=cache_write_tokens or 0,
reasoning_tokens=reasoning_tokens or 0, estimated_cost_usd=estimated_cost_usd,
actual_cost_usd=None, cost_status=None, cost_source=None,
api_call_count=1 if api_call_count is None else int(api_call_count), task=task,
)
self._execute_write(_do)
def usage_totals(self, *, min_message_count: int = 1, include_archived: bool = False) -> Dict[str, float]:
"""Tokens and spend across the whole store (one scan), so the sidebar
total does not shrink with paging. Spend prefers the billed figure over
the estimate, the same precedence a single row renders."""
"""Tokens and spend across the whole store (one scan), so the sidebar total does
not shrink with paging. Spend prefers the billed figure over the estimate."""
where = ["parent_session_id IS NULL", "message_count >= ?"]
params: List[Any] = [min_message_count]
if not include_archived:
where.append("COALESCE(archived, 0) = 0")
row = self._read_one(
f"""
SELECT COALESCE(SUM(COALESCE(input_tokens, 0) + COALESCE(output_tokens, 0)), 0),
@@ -593,5 +431,4 @@ class SessionUsageMixin:
""",
params,
)
return {"tokens": int(row[0] or 0), "cost_usd": float(row[1] or 0.0)}
+139 -269
View File
@@ -30,42 +30,56 @@ logger = logging.getLogger("hermes_state")
# filesystems (NFS, SMB/CIFS, some FUSE, WSL1) don't provide reliably — there
# ``PRAGMA journal_mode=WAL`` raises ``locking protocol`` (SQLITE_PROTOCOL).
# ZFS instead corrupts the -shm file under concurrent connection bursts (COW +
# mmap), presenting as ``disk I/O error``. Propagating either would silently
# break everything backed by state.db/kanban.db, so we fall back to
# ``journal_mode=DELETE`` (pre-WAL default, works on NFS/ZFS): readers block
# during a write, but it works. The WAL-reset-bug gate and the
# never-live-downgrade invariant are documented on apply_wal_with_fallback.
# mmap), presenting as ``disk I/O error``. Either would silently break
# everything backed by state.db/kanban.db, so we fall back to
# ``journal_mode=DELETE`` (works on NFS/ZFS; readers block during a write).
_WAL_INCOMPAT_MARKERS = (
"locking protocol", # SQLITE_PROTOCOL on NFS/SMB
"not authorized", # Some FUSE mounts block WAL pragma outright
"disk i/o error", # ZFS SHM corruption under concurrent connections
)
# SQLite's default is -1 (unlimited), so state.db-wal would keep the high-water
# mark of the largest-ever transaction forever. See _apply_wal_size_limit().
_WAL_SIZE_LIMIT_BYTES = 64 * 1024 * 1024 # 64 MiB
# Dedup sets: kanban_db.connect() runs on every kanban operation, so an
# undeduped fallback log line would repeat per connection and fill errors.log.
# Once-per-process-per-db_label dedup sets: kanban_db.connect() runs on every
# kanban operation, so an undeduped log line would repeat per connection.
# Tests clear these through ``hermes_state.<name>``; ``_warn_once`` resolves
# the set through hermes_state at call time for the same reason.
_wal_fallback_warned_paths: set[str] = set()
_wal_fallback_warned_lock = threading.Lock()
_wal_reset_bug_warned_paths: set[str] = set()
_wal_reset_bug_warned_lock = threading.Lock()
# "configured delete overridden by on-disk WAL" ERROR.
_delete_overridden_warned_paths: set[str] = set()
_delete_overridden_warned_lock = threading.Lock()
# Dedup state for _log_journal_mode_upgrade_once.
_journal_upgrade_warned_paths: set = set()
_journal_upgrade_warned_lock = threading.Lock()
_CANNOT_VERIFY_DELETE_MSG = (
"could not verify journal mode before applying configured "
"journal_mode=delete (database is locked — possible "
"concurrent openers); refusing to downgrade a database "
"this process does not exclusively own"
)
def _warn_once(lock: threading.Lock, set_name: str, key: str) -> bool:
"""True the first time *key* is seen in ``hermes_state.<set_name>``."""
import hermes_state
seen = getattr(hermes_state, set_name)
with lock:
if key in seen:
return False
seen.add(key)
return True
def _mode_from_row(row) -> str:
"""Lower-cased mode from a ``PRAGMA journal_mode`` row, ``""`` if no row."""
return str(row[0]).strip().lower() if row and row[0] is not None else ""
def _on_disk_journal_mode(conn: sqlite3.Connection) -> Optional[str]:
@@ -96,9 +110,7 @@ def _on_disk_journal_mode(conn: sqlite3.Connection) -> Optional[str]:
return None
return str(mode).strip().lower() if mode is not None else None
if last_exc is not None:
logger.debug(
"_on_disk_journal_mode: retries exhausted on disk read (%s)", last_exc
)
logger.debug("_on_disk_journal_mode: retries exhausted on disk read (%s)", last_exc)
return None
@@ -107,15 +119,10 @@ def _apply_wal_size_limit(conn: sqlite3.Connection) -> None:
SQLite's default ``journal_size_limit`` is -1: a checkpointed WAL is reused
in place, never truncated, so ``state.db-wal`` keeps the high-water mark
of the largest transaction ever run. One bulk op strands gigabytes —
``hermes sessions optimize`` on a 3 GB state.db left a 3 GB WAL and filled
the disk, so the maintenance command was self-defeating on the largest
DBs. With a limit, each checkpoint truncates the WAL back to it; 64 MiB is
above normal transaction sizes (steady-state commits never pay a truncate)
while capping slack predictably. kanban_db uses ``wal_autocheckpoint=100``.
Best-effort: never raises — failure only costs disk slack and must not
prevent the database from opening.
of the largest transaction ever run (a 3 GB optimize left a 3 GB WAL).
With a limit, each checkpoint truncates the WAL back to it; 64 MiB is
above normal transaction sizes while capping slack predictably.
Best-effort: failure only costs disk slack and must not prevent opening.
"""
try:
conn.execute(f"PRAGMA journal_size_limit={_WAL_SIZE_LIMIT_BYTES}")
@@ -127,12 +134,11 @@ def _apply_macos_checkpoint_barrier(conn: sqlite3.Connection) -> None:
"""Enable ``PRAGMA checkpoint_fullfsync`` on macOS (no-op elsewhere).
Apple's ``fsync(2)`` guarantees neither data-on-platter nor write ordering,
so WAL's corruption-safety assumption fails on Darwin without ``F_FULLFSYNC``.
A launchd shutdown drops the page cache (power-loss for in-flight pages), so
a checkpoint that "reported" durable can leave a malformed ``state.db``;
a plain in-session kill survives via the page cache. The barrier applies
only at checkpoint boundaries (~+0.1 ms/commit vs ~+4 ms for
``fullfsync=1``). Best-effort: never raises.
so WAL's corruption-safety assumption fails on Darwin without ``F_FULLFSYNC``:
a launchd shutdown drops the page cache and a checkpoint that "reported"
durable can leave a malformed ``state.db``. The barrier applies only at
checkpoint boundaries (~+0.1 ms/commit vs ~+4 ms for ``fullfsync=1``).
Best-effort: never raises.
"""
if sys.platform != "darwin":
return
@@ -145,11 +151,10 @@ def _apply_macos_checkpoint_barrier(conn: sqlite3.Connection) -> None:
def _enforce_macos_synchronous_full(conn: sqlite3.Connection) -> None:
"""Enforce ``PRAGMA synchronous=FULL`` on macOS to prevent btree corruption.
With NORMAL, a WAL checkpoint racing process termination (launchd shutdown)
can leave half-written btree pages (``btreeInitPage error 11``) because
Darwin's ``fsync()`` guarantees neither ordering nor durability. Called
after every successful WAL activation so a prior connection's NORMAL never
sticks. Best-effort: never raises.
With NORMAL, a WAL checkpoint racing process termination can leave
half-written btree pages (``btreeInitPage error 11``). Called after every
successful WAL activation so a prior connection's NORMAL never sticks.
Best-effort: never raises.
"""
if sys.platform != "darwin":
return
@@ -159,9 +164,14 @@ def _enforce_macos_synchronous_full(conn: sqlite3.Connection) -> None:
pass
def is_sqlite_wal_reset_vulnerable(
version_info: Optional[tuple] = None,
) -> bool:
def _apply_wal_companions(conn: sqlite3.Connection) -> None:
"""The settings every WAL activation carries: size limit + macOS barriers."""
_apply_wal_size_limit(conn)
_apply_macos_checkpoint_barrier(conn)
_enforce_macos_synchronous_full(conn)
def is_sqlite_wal_reset_vulnerable(version_info: Optional[tuple] = None) -> bool:
"""True when the linked SQLite has the WAL-reset bug (3.7.0–3.51.2;
fixed 3.51.3+, backports 3.50.7 / 3.44.6). Pre-WAL libraries are safe.
https://sqlite.org/wal.html#walresetbug
@@ -190,8 +200,7 @@ def _database_has_content(conn: sqlite3.Connection) -> bool:
``PRAGMA page_count`` is a lock-free header read. Fail-quiet: any error
answers False, because the only caller gates a warning on this and an
unknown-answer warning would fire on every fresh database — exactly where
there is provably no operator choice being overwritten.
unknown-answer warning would fire on every fresh database.
"""
try:
row = conn.execute("PRAGMA page_count").fetchone()
@@ -222,7 +231,6 @@ def resolve_journal_mode() -> str:
raw = database.get("journal_mode", "wal")
except Exception:
return "wal"
if not isinstance(raw, str):
return "wal"
mode = raw.strip().lower()
@@ -239,43 +247,29 @@ class WalUnsupportedError(sqlite3.OperationalError):
def apply_wal_with_fallback(
conn: sqlite3.Connection,
*,
db_label: str = "state.db",
require_wal: bool = False,
conn: sqlite3.Connection, *, db_label: str = "state.db", require_wal: bool = False
) -> str:
"""Set ``journal_mode=WAL`` on ``conn``, falling back to DELETE on failure.
Returns the mode actually set (``"wal"`` or ``"delete"``). Shared by
:class:`SessionDB` and ``hermes_cli.kanban_db.connect`` for identical
fallback behavior.
:class:`SessionDB` and ``hermes_cli.kanban_db.connect``. On
WAL-incompatible filesystems SQLite either raises ``OperationalError``
("locking protocol" / "disk I/O error") or — macOS NFS / SMB / AgentFS —
silently refuses and leaves the DB in DELETE; either way we log at ERROR
(once per process per ``db_label``) and fall back to DELETE.
``require_wal=True`` raises :class:`WalUnsupportedError` instead.
On WAL-incompatible filesystems (NFS, SMB, some FUSE, ZFS) SQLite either
raises ``OperationalError`` ("locking protocol" / "disk I/O error") or —
macOS NFS / SMB / AgentFS NFS overlay — silently refuses and leaves the DB
in DELETE. Either way we log at ERROR (a write now blocks readers — a real
concurrency loss) and fall back to DELETE so the feature keeps working.
``require_wal=True`` raises :class:`WalUnsupportedError` instead; all
current callers keep the default so NFS-homed installs work.
WAL-reset-bug builds (https://sqlite.org/wal.html#walresetbug, fixed
3.51.3+, backports 3.50.7 / 3.44.6) never enable WAL on fresh / non-WAL
databases; an already-WAL DB keeps WAL with a warning. This gate is
deliberately RETAINED: the attempt to revert it was confounded by a newer
SQLite, and re-measured on the bundled 3.50.4 there is no evidence WAL is
safer.
On SQLite builds with the WAL-reset bug (https://sqlite.org/wal.html#walresetbug,
fixed 3.51.3+, backports 3.50.7 / 3.44.6), refuse to enable WAL on
fresh / non-WAL databases; an already-WAL DB keeps WAL with a warning.
This gate is deliberately RETAINED: an attempt to revert it (theory: DELETE
was "the mode that corrupts") was confounded — its clean WAL result came
from SQLite 3.53.1, which also carries 3.51.0's close()-broken-POSIX-lock
defenses. Re-measured on the bundled 3.50.4 with the lock fix, WAL and
DELETE are both clean, so there is no evidence WAL is safer; keep new
databases out of WAL until a fixed runtime ships.
Invariant on every path (NFS and WAL-reset alike): never downgrade to
DELETE if the on-disk header reports WAL or the mode cannot be read (see
_on_disk_journal_mode). Other gateway/cron/worker connections may hold the
DB open, and a live downgrade destroys their committed-but-uncheckpointed
transactions.
The ERROR is deduplicated per ``db_label``: once per process per DB, so
state.db and kanban.db on one NFS mount each log once.
Invariant on every path: never downgrade to DELETE if the on-disk header
reports WAL or the mode cannot be read — other gateway/cron/worker
connections may hold the DB open, and a live downgrade destroys their
committed-but-uncheckpointed transactions.
"""
from hermes_state import is_sqlite_wal_reset_vulnerable, resolve_journal_mode
configured = resolve_journal_mode()
@@ -285,9 +279,7 @@ def apply_wal_with_fallback(
# accepted DELETE rather than silently returning MEMORY or another mode.
if is_sqlite_wal_reset_vulnerable():
return _apply_delete_for_wal_reset_bug(
conn,
db_label=db_label,
require_delete=configured == "delete",
conn, db_label=db_label, require_delete=configured == "delete"
)
# Read-only probe — no flock, no checkpoint, no WAL/SHM unlink — so
@@ -297,9 +289,7 @@ def apply_wal_with_fallback(
if configured == "delete":
# Never-live-downgrade keeps WAL; tell the operator their delete did not apply.
_log_configured_delete_overridden_once(db_label)
_apply_wal_size_limit(conn)
_apply_macos_checkpoint_barrier(conn)
_enforce_macos_synchronous_full(conn)
_apply_wal_companions(conn)
return "wal"
# Honor the canonical database.journal_mode setting (on-disk WAL DBs were
@@ -307,16 +297,9 @@ def apply_wal_with_fallback(
if configured == "delete":
if current_mode is None:
# Probe failed (locked/busy): another process may hold this DB open
# in WAL, so ownership is not provably exclusive and flipping modes
# could destroy a concurrent writer's committed-but-uncheckpointed
# transactions. Fail loudly — the operator asked for DELETE and we
# cannot verify it.
raise sqlite3.OperationalError(
"could not verify journal mode before applying configured "
"journal_mode=delete (database is locked — possible "
"concurrent openers); refusing to downgrade a database "
"this process does not exclusively own"
)
# in WAL, so ownership is not provably exclusive. Fail loudly — the
# operator asked for DELETE and we cannot verify it.
raise sqlite3.OperationalError(_CANNOT_VERIFY_DELETE_MSG)
actual = _set_journal_mode_no_wait(conn, "DELETE")
if actual != "delete":
raise sqlite3.OperationalError(
@@ -329,31 +312,26 @@ def apply_wal_with_fallback(
# A 0-page DB has no prior choice, and every caller reaches this before
# creating schema, so brand-new databases stay quiet.
_upgrading_existing_db = (
current_mode is not None
and current_mode != "wal"
and _database_has_content(conn)
current_mode is not None and current_mode != "wal" and _database_has_content(conn)
)
def _wal_activated() -> str:
if _upgrading_existing_db:
_log_journal_mode_upgrade_once(db_label, current_mode)
_apply_wal_companions(conn)
return "wal"
try:
# ``PRAGMA journal_mode=WAL`` RETURNS the resulting mode. Filesystems
# that refuse by *raising* SQLITE_PROTOCOL hit the except branch, but
# macOS NFS, SMB/CIFS and the AgentFS NFS overlay refuse WITHOUT raising
# and just return the still-effective mode. Trust the row, not the
# absence of an exception, or we report a false "wal", skip the
# fallback ERROR, and leave the DB silently in DELETE.
row = conn.execute("PRAGMA journal_mode=WAL").fetchone()
mode = str(row[0]).strip().lower() if row and row[0] is not None else ""
# absence of an exception.
mode = _mode_from_row(conn.execute("PRAGMA journal_mode=WAL").fetchone())
if mode == "wal":
if _upgrading_existing_db:
_log_journal_mode_upgrade_once(db_label, current_mode)
_apply_wal_size_limit(conn)
_apply_macos_checkpoint_barrier(conn)
_enforce_macos_synchronous_full(conn)
return "wal"
return _wal_activated()
# Silent refusal: WAL was not honored, but nothing raised.
silent_exc = WalUnsupportedError(
f"journal_mode=WAL refused without raising (still {mode!r})"
)
silent_exc = WalUnsupportedError(f"journal_mode=WAL refused without raising (still {mode!r})")
if require_wal:
raise silent_exc
_log_wal_fallback_once(db_label, silent_exc)
@@ -365,14 +343,11 @@ def apply_wal_with_fallback(
raise
msg = str(exc).lower()
if not any(marker in msg for marker in _WAL_INCOMPAT_MARKERS):
# Unrelated OperationalError — don't silently swallow.
raise
raise # unrelated OperationalError — don't silently swallow
# ``disk i/o error`` is ambiguous: deterministic WAL-incompatibility on
# ZFS / APFS-CoW (SHM corruption under connection bursts), or a one-shot
# transient EIO (page-cache pressure, brief lock contention). Treating
# a transient EIO as a permanent downgrade signal produced mixed-mode
# corruption (process A downgrades to DELETE while siblings set WAL),
# so retry the pragma: transient EIO clears and we return "wal";
# ZFS / APFS-CoW, or a one-shot transient EIO. Treating a transient EIO
# as a permanent downgrade signal produced mixed-mode corruption (process
# A downgrades to DELETE while siblings set WAL), so retry the pragma: transient EIO clears and we return "wal";
# deterministic cases keep failing into the guarded DELETE fallback.
if "disk i/o error" in msg:
for _ in range(2):
@@ -384,20 +359,8 @@ def apply_wal_with_fallback(
raise
exc = retry_exc
continue
mode = (
str(row[0]).strip().lower()
if row and row[0] is not None
else ""
)
if mode == "wal":
# Transient EIO cleared and the switch went through; same
# header rewrite, so same upgrade signal.
if _upgrading_existing_db:
_log_journal_mode_upgrade_once(db_label, current_mode)
_apply_wal_size_limit(conn)
_apply_macos_checkpoint_barrier(conn)
_enforce_macos_synchronous_full(conn)
return "wal"
if _mode_from_row(row) == "wal":
return _wal_activated()
break
# Don't downgrade if another process already set WAL on disk, or if the
# mode cannot be read (probe blocked by a concurrent opener's locks) —
@@ -418,10 +381,9 @@ def _set_journal_mode_no_wait(conn: sqlite3.Connection, mode: str) -> str:
The ONLY place a journal-mode switch may be issued for a non-WAL target.
Forces ``busy_timeout=0`` so SQLite's exclusivity requirement becomes a
concurrent-opener detector: leaving WAL needs exclusive access, so if ANY
other connection (this process or another) holds the DB the pragma fails
immediately with ``database is locked`` instead of waiting out a busy
timeout and sneaking the flip between a concurrent writer's transactions —
exactly how committed-but-uncheckpointed WAL transactions get destroyed.
other connection holds the DB the pragma fails immediately with ``database
is locked`` instead of sneaking the flip between a concurrent writer's
transactions (how committed-but-uncheckpointed WAL transactions die).
Callers must treat a raised ``OperationalError`` as "not exclusively
owned: leave the journal mode alone", never as retryable. Returns SQLite's
@@ -436,8 +398,7 @@ def _set_journal_mode_no_wait(conn: sqlite3.Connection, mode: str) -> str:
previous_timeout = 0
conn.execute("PRAGMA busy_timeout=0")
try:
row = conn.execute(f"PRAGMA journal_mode={mode}").fetchone()
return str(row[0]).strip().lower() if row and row[0] is not None else ""
return _mode_from_row(conn.execute(f"PRAGMA journal_mode={mode}").fetchone())
finally:
try:
conn.execute(f"PRAGMA busy_timeout={previous_timeout}")
@@ -446,24 +407,19 @@ def _set_journal_mode_no_wait(conn: sqlite3.Connection, mode: str) -> str:
def _apply_delete_for_wal_reset_bug(
conn: sqlite3.Connection,
*,
db_label: str,
require_delete: bool = False,
conn: sqlite3.Connection, *, db_label: str, require_delete: bool = False
) -> str:
"""Avoid enabling WAL when the linked SQLite has the WAL-reset bug.
- Already-WAL on disk: leave WAL alone (no live downgrade) and warn.
- Mode unreadable (probe blocked by a concurrent opener's locks): not
provably exclusive — leave the mode alone and warn. Never treat "could
not read the mode" as "not WAL": that confusion once flipped a live WAL
state.db to DELETE under a concurrent writer, destroying its
committed-but-uncheckpointed transactions.
not read the mode" as "not WAL": that once flipped a live WAL state.db to
DELETE under a concurrent writer, destroying its uncheckpointed commits.
- Otherwise: set DELETE (refusing to wait out concurrent openers) and warn.
- For an explicit operator request, verify SQLite accepted DELETE.
"""
current = _on_disk_journal_mode(conn)
if current == "wal":
_log_wal_reset_bug_once(db_label, kept_wal=True)
if require_delete:
@@ -472,24 +428,15 @@ def _apply_delete_for_wal_reset_bug(
_log_configured_delete_overridden_once(db_label)
# No TRUNCATE / journal_mode=DELETE while other processes may still
# hold this WAL DB open; same safety rule as the NFS path.
_apply_wal_size_limit(conn)
_apply_macos_checkpoint_barrier(conn)
_enforce_macos_synchronous_full(conn)
_apply_wal_companions(conn)
return "wal"
if current is None:
# Probe failed — likely another opener's locks, and the DB may be in
# WAL under a live writer. Never flip a mode we cannot even read.
if require_delete:
raise sqlite3.OperationalError(
"could not verify journal mode before applying configured "
"journal_mode=delete (database is locked — possible "
"concurrent openers); refusing to downgrade a database "
"this process does not exclusively own"
)
raise sqlite3.OperationalError(_CANNOT_VERIFY_DELETE_MSG)
_log_wal_reset_bug_once(db_label, kept_wal=True, indeterminate=True)
return "wal"
actual = ""
try:
actual = _set_journal_mode_no_wait(conn, "DELETE")
@@ -528,8 +475,7 @@ def _wal_reset_repair_hint() -> str:
return f"Hermes-managed installs can repair the embedded runtime with `{cmd}`"
if method == "docker":
return f"update the container image with `{cmd}`"
# nix/nixos
return cmd
return cmd # nix/nixos
except Exception:
pass
return (
@@ -538,25 +484,10 @@ def _wal_reset_repair_hint() -> str:
)
# Dedup state for _log_journal_mode_upgrade_once.
_journal_upgrade_warned_paths: set = set()
_journal_upgrade_warned_lock = threading.Lock()
def _log_wal_reset_bug_once(
db_label: str,
*,
kept_wal: bool,
indeterminate: bool = False,
) -> None:
def _log_wal_reset_bug_once(db_label: str, *, kept_wal: bool, indeterminate: bool = False) -> None:
"""Log once per (process, db_label) about the WAL-reset vulnerability path."""
from hermes_state import _wal_reset_bug_warned_paths
with _wal_reset_bug_warned_lock:
if db_label in _wal_reset_bug_warned_paths:
return
_wal_reset_bug_warned_paths.add(db_label)
if not _warn_once(_wal_reset_bug_warned_lock, "_wal_reset_bug_warned_paths", db_label):
return
if indeterminate:
action = (
"journal mode could not be verified or exclusively switched "
@@ -573,18 +504,13 @@ def _log_wal_reset_bug_once(
action = "using journal_mode=DELETE instead of enabling WAL"
# Install-type-aware so the warning never promises a repair path that
# doesn't exist for git/pip/system Python installs.
repair_hint = _wal_reset_repair_hint()
logger.warning(
"%s: linked SQLite %s (interpreter %s) is vulnerable to the WAL-reset "
"corruption bug (https://sqlite.org/wal.html#walresetbug) — %s. "
"Upgrade to SQLite 3.51.3+ (or backports 3.50.7 / 3.44.6); "
"%s. See `hermes doctor`. This warning fires once per "
"process per database.",
db_label,
sqlite3.sqlite_version,
sys.executable,
action,
repair_hint,
db_label, sqlite3.sqlite_version, sys.executable, action, _wal_reset_repair_hint(),
)
@@ -594,20 +520,12 @@ def _log_journal_mode_upgrade_once(db_label: str, previous_mode: str) -> None:
``PRAGMA journal_mode`` is a property of the FILE: switching an existing DB
to WAL rewrites its header and outlives the process. Operators do set
DELETE on the file directly (the documented WAL-reset-bug mitigation), and
nothing told them the next open would silently put WAL back.
WARNING, not ERROR: the reverse move is ERROR in ``_log_wal_fallback_once``
because dropping to DELETE loses concurrency, whereas this direction is
normally desirable (managed_uv repairs DELETE-stuck DBs on update). The
only problem was invisibility, so this names the durable setting without
claiming a degradation. Deduped per process per ``db_label`` because
kanban opens a fresh connection per operation.
nothing told them the next open would silently put WAL back. WARNING, not
ERROR: this direction is normally desirable; only its invisibility was the
problem, so this names the durable setting without claiming a degradation.
"""
from hermes_state import _journal_upgrade_warned_paths
with _journal_upgrade_warned_lock:
if db_label in _journal_upgrade_warned_paths:
return
_journal_upgrade_warned_paths.add(db_label)
if not _warn_once(_journal_upgrade_warned_lock, "_journal_upgrade_warned_paths", db_label):
return
logger.warning(
"%s: on-disk journal_mode was %s and has been switched to WAL. This "
"rewrites the database header and persists after this process exits. "
@@ -616,9 +534,7 @@ def _log_journal_mode_upgrade_once(db_label: str, previous_mode: str) -> None:
"PRAGMA on the file will not survive -- every open re-applies the "
"configured mode. Set `database.journal_mode: delete` in config.yaml "
"to make it stick. This message fires once per process per database.",
db_label,
previous_mode,
previous_mode,
db_label, previous_mode, previous_mode,
)
@@ -627,21 +543,16 @@ def _log_wal_fallback_once(db_label: str, exc: Exception) -> None:
ERROR, not WARNING: silently dropping to DELETE is a real concurrency loss
(under kanban dispatcher + workers a write blocks readers as SQLITE_BUSY).
Deduped because kanban opens a fresh connection per operation.
"""
from hermes_state import _wal_fallback_warned_paths
with _wal_fallback_warned_lock:
if db_label in _wal_fallback_warned_paths:
return
_wal_fallback_warned_paths.add(db_label)
if not _warn_once(_wal_fallback_warned_lock, "_wal_fallback_warned_paths", db_label):
return
logger.error(
"%s: WAL journal_mode unsupported on this filesystem (%s) — "
"falling back to journal_mode=DELETE (slower rollback-journal "
"mode; reduces concurrency but works on NFS/SMB/FUSE/ZFS). See "
"https://www.sqlite.org/wal.html for details. This message "
"fires once per process per database.",
db_label,
exc,
db_label, exc,
)
@@ -649,16 +560,12 @@ def _log_configured_delete_overridden_once(db_label: str) -> None:
"""Log a single ERROR per (process, db_label) when the operator configured
``journal_mode=delete`` but the on-disk DB is already WAL.
Never-live-downgrade keeps WAL (a live downgrade causes mixed-mode
corruption); without this the operator would never learn that
``database.journal_mode: delete`` had no effect and that a one-time
Never-live-downgrade keeps WAL; without this the operator would never learn
that ``database.journal_mode: delete`` had no effect and that a one-time
offline ``PRAGMA journal_mode=DELETE`` (no open connections) is required.
"""
from hermes_state import _delete_overridden_warned_paths
with _delete_overridden_warned_lock:
if db_label in _delete_overridden_warned_paths:
return
_delete_overridden_warned_paths.add(db_label)
if not _warn_once(_delete_overridden_warned_lock, "_delete_overridden_warned_paths", db_label):
return
logger.error(
"%s: database.journal_mode=delete is configured but the on-disk "
"database is already WAL; keeping WAL (a live downgrade under open "
@@ -675,17 +582,8 @@ def _log_configured_delete_overridden_once(db_label: str) -> None:
# ---------------------------------------------------------------------------
# Operators write synchronous as a name; mapped here rather than passed through
# so a typo becomes a warning instead of a silently different durability level.
_SYNCHRONOUS_LEVELS: Dict[str, int] = {
"OFF": 0,
"NORMAL": 1,
"FULL": 2,
"EXTRA": 3,
}
_SYNCHRONOUS_LEVELS: Dict[str, int] = {"OFF": 0, "NORMAL": 1, "FULL": 2, "EXTRA": 3}
_SYNCHRONOUS_NAMES: Dict[int, str] = {v: k for k, v in _SYNCHRONOUS_LEVELS.items()}
_SYNCHRONOUS_FULL = 2
@@ -715,30 +613,23 @@ def resolve_synchronous_level(raw_value: Any) -> Optional[int]:
return value if value in _SYNCHRONOUS_NAMES else None
def _apply_synchronous_pragma(
conn: sqlite3.Connection,
raw_value: Any,
*,
db_label: str,
) -> None:
def _apply_synchronous_pragma(conn: sqlite3.Connection, raw_value: Any, *, db_label: str) -> None:
"""Set ``PRAGMA synchronous`` from config, never below FULL on macOS.
Kept out of the integer loop in :func:`apply_database_pragmas`: this PRAGMA
decides whether a commit is on the platter, so an unrecognised value must
not fall through to "SQLite default" the way a bad ``cache_size`` can.
Darwin floor: :func:`_enforce_macos_synchronous_full` runs during
``apply_wal_with_fallback()`` and this runs after it, so a configured
``NORMAL`` would otherwise silently undo the macOS btree protection.
Raising the level on macOS is allowed; lowering it is refused out loud.
Darwin floor: :func:`_enforce_macos_synchronous_full` runs during WAL
activation and this runs after it, so a configured ``NORMAL`` would
otherwise silently undo the macOS btree protection. Raising the level on
macOS is allowed; lowering it is refused out loud.
"""
level = resolve_synchronous_level(raw_value)
if level is None:
logger.warning(
"%s: ignoring unrecognized database.synchronous=%r "
"(expected OFF, NORMAL, FULL, EXTRA, or 0-3)",
db_label,
raw_value,
db_label, raw_value,
)
return
if sys.platform == "darwin" and level < _SYNCHRONOUS_FULL:
@@ -747,8 +638,7 @@ def _apply_synchronous_pragma(
"Darwin's fsync() does not guarantee write ordering, so a lower "
"level readmits the half-written btree pages FULL exists to "
"prevent.",
db_label,
_SYNCHRONOUS_NAMES[level],
db_label, _SYNCHRONOUS_NAMES[level],
)
return
try:
@@ -757,27 +647,22 @@ def _apply_synchronous_pragma(
pass
def apply_database_pragmas(
conn: sqlite3.Connection,
*,
db_label: str = "state.db",
) -> None:
def apply_database_pragmas(conn: sqlite3.Connection, *, db_label: str = "state.db") -> None:
"""Apply optional performance and WAL-sizing PRAGMAs from ``config.yaml``.
Journal mode is NOT handled here — ``database.journal_mode`` is owned by
:func:`resolve_journal_mode` inside :func:`apply_wal_with_fallback`, under
all the safety guards.
:func:`resolve_journal_mode` inside :func:`apply_wal_with_fallback`.
Keys under ``database:``: ``cache_size`` (negative = KiB, positive =
pages), ``mmap_size`` (bytes, 0 = disabled), ``temp_store`` (0-3),
``wal_autocheckpoint`` (pages), ``journal_size_limit`` (bytes), and
``synchronous`` (``OFF``/``NORMAL``/``FULL``/``EXTRA`` or ``0``-``3``).
Unset ``synchronous`` leaves SQLite's default, a *compile-time* constant
(``SQLITE_DEFAULT_WAL_SYNCHRONOUS``) that differs between bundled, distro
and Homebrew builds; setting it explicitly is the only way to know.
Unset ``synchronous`` leaves SQLite's compile-time default, which differs
between bundled, distro and Homebrew builds.
Best-effort: config load or pragma failures are ignored so DB init never
breaks on a malformed ``database:`` section.
breaks on a malformed ``database:`` section. Applied to ALL connection
types: writer, read_only, WAL per-thread readers.
"""
try:
# Local import avoids a circular import with hermes_cli.config.
@@ -786,36 +671,21 @@ def apply_database_pragmas(
cfg = load_config_readonly()
except Exception:
return
# Applied to ALL connection types: writer, read_only, WAL per-thread readers.
for pragma_name in (
"cache_size",
"mmap_size",
"temp_store",
"wal_autocheckpoint",
"journal_size_limit",
):
for pragma_name in ("cache_size", "mmap_size", "temp_store", "wal_autocheckpoint", "journal_size_limit"):
raw_value = cfg_get(cfg, "database", pragma_name, default=None)
if raw_value is None:
continue
try:
value = int(str(raw_value).strip())
except (TypeError, ValueError):
logger.warning(
"%s: ignoring non-integer database.%s=%r",
db_label,
pragma_name,
raw_value,
)
logger.warning("%s: ignoring non-integer database.%s=%r", db_label, pragma_name, raw_value)
continue
try:
conn.execute(f"PRAGMA {pragma_name}={value}")
except sqlite3.OperationalError:
pass
# Last: the sizing pragmas above cannot change durability, and the macOS
# enforcement ran earlier during WAL activation (see _apply_synchronous_pragma
# for why that ordering needs an explicit floor rather than an override).
# enforcement ran earlier during WAL activation (see _apply_synchronous_pragma).
raw_synchronous = cfg_get(cfg, "database", "synchronous", default=None)
if raw_synchronous is not None:
_apply_synchronous_pragma(conn, raw_synchronous, db_label=db_label)