diff --git a/hermes_state.py b/hermes_state.py index d43979fea2..0ab66773d5 100644 --- a/hermes_state.py +++ b/hermes_state.py @@ -1,17 +1,8 @@ #!/usr/bin/env python3 -""" -SQLite State Store for Hermes Agent. - -Provides persistent session storage with FTS5 full-text search, replacing -the per-session JSONL file approach. Stores session metadata, full message -history, and model configuration for CLI and gateway sessions. - -Key design decisions: -- WAL mode for concurrent readers + one writer (gateway multi-platform) -- FTS5 virtual table for fast text search across all session messages -- Compression-triggered session splitting via parent_session_id chains -- Batch runner and RL trajectories are NOT stored here (separate systems) -- Session source tagging ('cli', 'telegram', 'discord', etc.) for filtering +"""SQLite state store for Hermes Agent: session metadata, message history, model +config, FTS5 search. WAL mode (concurrent readers + one writer); compression +splits sessions via parent_session_id chains; sessions are source-tagged +('cli', 'telegram', ...). Batch-runner / RL trajectories live elsewhere. """ import asyncio @@ -36,12 +27,9 @@ from pathlib import Path from agent.session_activity import ActivityProvenance from agent.message_sanitization import _sanitize_surrogates -# Intrinsic persistence marker stamped on message dicts that are known-durable -# (#92231). One shared constant with agent.context_compressor (this module -# already imports agent.* at module level, and context_compressor is a -# transitive dependency via hermes_state_common). run_agent keeps its own -# predating copy — hermes_state cannot import run_agent (circular) — guarded -# by test_marker_constant_in_sync. +# Known-durable message marker, shared with agent.context_compressor. run_agent +# keeps its own copy (cannot import hermes_state: circular), guarded by +# test_marker_constant_in_sync. from agent.context_compressor import ( # noqa: F401 (re-exported; tests import it from here) _DB_PERSISTED_MARKER as _DB_PERSISTED_MARKER_KEY, ) @@ -49,155 +37,59 @@ from hermes_constants import get_hermes_home from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, TypeVar, cast from hermes_state_common import ( # noqa: F401 (re-exported for back-compat) - AUTO_VACUUM_MIN_FREELIST_RATIO, - _BRANCH_CHILD_SQL, - _COMPRESSION_CHILD_SQL, - _FTS_CJK_TRIGGERS, - _FTS_TRIGGERS, - _LISTABLE_CHILD_SQL, - _PREVIEW_ELIGIBLE_SQL, - _PREVIEW_RAW_SELECT, - _RECOVERABLE_END_REASONS, - _RECOVERABLE_END_REASONS_SQL, - is_automatic_end_reason, - _RESET_END_REASONS, - _RESET_END_REASONS_SQL, - _ephemeral_child_sql, - _legacy_reset_child_sql, - _shape_preview, - _sql_session_last_active, - _sql_session_last_active_by_id, - escape_like as _escape_like, - DEFERRED_INDEX_SQL, - FTS_CJK_STALE_KEY, - FTS_REBUILD_DEFERRAL_KEY, - FTS_SQL, - FTS_STALE_KEY, - FTS_STORAGE_VERSION, - FTS_TRIGRAM_SQL, - LEGACY_FTS_SQL, - LEGACY_FTS_TRIGRAM_SQL, - MAX_FTS5_QUERY_CHARS, - SCHEMA_SQL, - SCHEMA_VERSION, - _PREVIEW_CONTENT_SQL, - _PREVIEW_HEAD_CHARS, - _PREVIEW_MAX_CHARS, - _PREVIEW_SCAFFOLD_WINDOW, - _PREVIEW_SCAFFOLDED_SQL, - _acquire_db_flock, - _clear_lock_holder_record, - _describe_lock_holder, - _read_lock_holder_record, - is_advisory_lock_contention, - stat_db_file_identity as _stat_db_file_identity, + AUTO_VACUUM_MIN_FREELIST_RATIO, _BRANCH_CHILD_SQL, _COMPRESSION_CHILD_SQL, _FTS_CJK_TRIGGERS, + _FTS_TRIGGERS, _LISTABLE_CHILD_SQL, _PREVIEW_ELIGIBLE_SQL, _PREVIEW_RAW_SELECT, + _RECOVERABLE_END_REASONS, _RECOVERABLE_END_REASONS_SQL, is_automatic_end_reason, + _RESET_END_REASONS, _RESET_END_REASONS_SQL, _ephemeral_child_sql, _legacy_reset_child_sql, + _shape_preview, _sql_session_last_active, _sql_session_last_active_by_id, + escape_like as _escape_like, DEFERRED_INDEX_SQL, FTS_CJK_STALE_KEY, FTS_REBUILD_DEFERRAL_KEY, + FTS_SQL, FTS_STALE_KEY, FTS_STORAGE_VERSION, FTS_TRIGRAM_SQL, LEGACY_FTS_SQL, + LEGACY_FTS_TRIGRAM_SQL, MAX_FTS5_QUERY_CHARS, SCHEMA_SQL, SCHEMA_VERSION, _PREVIEW_CONTENT_SQL, + _PREVIEW_HEAD_CHARS, _PREVIEW_MAX_CHARS, _PREVIEW_SCAFFOLD_WINDOW, _PREVIEW_SCAFFOLDED_SQL, + _acquire_db_flock, _clear_lock_holder_record, _describe_lock_holder, _read_lock_holder_record, + is_advisory_lock_contention, stat_db_file_identity as _stat_db_file_identity, ) from hermes_state_portability import SessionPortabilityMixin from hermes_state_telegram import SessionTelegramTopicsMixin, _normalize_telegram_topic_profile_name # noqa: F401 (re-exported for back-compat) from hermes_state_schema import SessionSchemaMixin from hermes_state_dbfile import ( # noqa: F401 (re-exported; tests patch hermes_state.) - _HEADER_PROBE_FDS, - _HEADER_PROBE_LOCK, - _HERMES_CMDLINE_MARKERS, - _RETIRED_HEADER_PROBE_FDS, - _canonical_sqlite_path, - _concrete_state_db_holder_pids, - _connect_tracked_db, - _is_inactive_orphan_desktop_holder, - _looks_like_hermes, - _pread_db_header, - _read_proc_cmdline, - _read_sqlite_application_id, - _stat_sqlite_sidecar_identity, - _watched_sqlite_sidecar_paths, - collect_state_db_stats, - count_db_holders, - is_zeroed_state_db, - iter_deleted_sqlite_sidecar_holders, - quarantine_cross_process_lock, - quarantine_zeroed_state_db, + _HEADER_PROBE_FDS, _HEADER_PROBE_LOCK, _HERMES_CMDLINE_MARKERS, _RETIRED_HEADER_PROBE_FDS, + _canonical_sqlite_path, _concrete_state_db_holder_pids, _connect_tracked_db, + _is_inactive_orphan_desktop_holder, _looks_like_hermes, _pread_db_header, _read_proc_cmdline, + _read_sqlite_application_id, _stat_sqlite_sidecar_identity, _watched_sqlite_sidecar_paths, + collect_state_db_stats, count_db_holders, is_zeroed_state_db, + iter_deleted_sqlite_sidecar_holders, quarantine_cross_process_lock, quarantine_zeroed_state_db, refuse_deleted_wal_generation, ) from hermes_state_messages import SessionMessagesMixin from hermes_state_wal import ( # noqa: F401 (re-exported; tests patch hermes_state.) - WalUnsupportedError, - _SYNCHRONOUS_FULL, - _SYNCHRONOUS_LEVELS, - _SYNCHRONOUS_NAMES, - _WAL_INCOMPAT_MARKERS, - _WAL_SIZE_LIMIT_BYTES, - _apply_delete_for_wal_reset_bug, - _apply_macos_checkpoint_barrier, - _apply_synchronous_pragma, - _apply_wal_size_limit, - _database_has_content, - _delete_overridden_warned_lock, - _delete_overridden_warned_paths, - _enforce_macos_synchronous_full, - _journal_upgrade_warned_lock, - _journal_upgrade_warned_paths, - _log_configured_delete_overridden_once, - _log_journal_mode_upgrade_once, - _log_wal_fallback_once, - _log_wal_reset_bug_once, - _on_disk_journal_mode, - _set_journal_mode_no_wait, - _wal_fallback_warned_lock, - _wal_fallback_warned_paths, - _wal_reset_bug_warned_lock, - _wal_reset_bug_warned_paths, - _wal_reset_repair_hint, - apply_database_pragmas, - apply_wal_with_fallback, - is_sqlite_wal_reset_vulnerable, - resolve_journal_mode, - resolve_synchronous_level, - sqlite_source_id, + WalUnsupportedError, _SYNCHRONOUS_FULL, _SYNCHRONOUS_LEVELS, _SYNCHRONOUS_NAMES, + _WAL_INCOMPAT_MARKERS, _WAL_SIZE_LIMIT_BYTES, _apply_delete_for_wal_reset_bug, + _apply_macos_checkpoint_barrier, _apply_synchronous_pragma, _apply_wal_size_limit, + _database_has_content, _delete_overridden_warned_lock, _delete_overridden_warned_paths, + _enforce_macos_synchronous_full, _journal_upgrade_warned_lock, _journal_upgrade_warned_paths, + _log_configured_delete_overridden_once, _log_journal_mode_upgrade_once, _log_wal_fallback_once, + _log_wal_reset_bug_once, _on_disk_journal_mode, _set_journal_mode_no_wait, + _wal_fallback_warned_lock, _wal_fallback_warned_paths, _wal_reset_bug_warned_lock, + _wal_reset_bug_warned_paths, _wal_reset_repair_hint, apply_database_pragmas, + apply_wal_with_fallback, is_sqlite_wal_reset_vulnerable, resolve_journal_mode, + resolve_synchronous_level, sqlite_source_id, ) from hermes_state_repair import ( # noqa: F401 (re-exported; tests patch hermes_state.) - _DB_SIDECAR_SUFFIXES, - _FINGERPRINT_SAMPLE_BYTES, - _FINGERPRINT_VOLATILE_HEADER_RANGES, - _MAX_MALFORMED_BACKUPS, - _MAX_PERSISTENT_REPAIR_ATTEMPTS, - _REPAIR_BACKUP_FREE_FRACTION, - _REPAIR_BACKUP_MIN_FREE_BYTES, - _REPAIR_LOCK_POLL_SECONDS, - _REPAIR_SNAPSHOT_MIN_THROUGHPUT_BYTES_PER_SECOND, - _backup_content_identity, - _backup_db_file, - _bump_schema_cookie, - _claim_repair_attempt, - _connect_repair_durable, - _copy_database_snapshot, - _cross_process_repair_lock, - _db_fingerprint, - _db_opens_cleanly, - _exclusive_repair_db_guard, - _existing_malformed_backups, - _live_writer_holds_db, - _mask_volatile_header, - _persistent_repair_attempts_exhausted, - _persistent_repair_exhausted_error, - _probe_journal_mode_for_repair, - _prune_malformed_backups, - _read_repair_ledger, - _reapply_durability_barriers, - _record_repair_outcome, - _release_auto_maintenance_lock, - _repair_backup_headroom_bytes, - _repair_failure_consumes_attempt, - _repair_ledger_path, - _repair_scratch_space_error, - _repair_snapshot_timeout_seconds, - _repair_state_db_schema_locked, - _restore_journal_mode_after_repair, - _run_repair_strategies, - _try_acquire_auto_maintenance_lock, - _unlink_db_triple, - apply_durability_barriers, - preflight_db_writability, - repair_state_db_schema, + _DB_SIDECAR_SUFFIXES, _FINGERPRINT_SAMPLE_BYTES, _FINGERPRINT_VOLATILE_HEADER_RANGES, + _MAX_MALFORMED_BACKUPS, _MAX_PERSISTENT_REPAIR_ATTEMPTS, _REPAIR_BACKUP_FREE_FRACTION, + _REPAIR_BACKUP_MIN_FREE_BYTES, _REPAIR_LOCK_POLL_SECONDS, + _REPAIR_SNAPSHOT_MIN_THROUGHPUT_BYTES_PER_SECOND, _backup_content_identity, _backup_db_file, + _bump_schema_cookie, _claim_repair_attempt, _connect_repair_durable, _copy_database_snapshot, + _cross_process_repair_lock, _db_fingerprint, _db_opens_cleanly, _exclusive_repair_db_guard, + _existing_malformed_backups, _live_writer_holds_db, _mask_volatile_header, + _persistent_repair_attempts_exhausted, _persistent_repair_exhausted_error, + _probe_journal_mode_for_repair, _prune_malformed_backups, _read_repair_ledger, + _reapply_durability_barriers, _record_repair_outcome, _release_auto_maintenance_lock, + _repair_backup_headroom_bytes, _repair_failure_consumes_attempt, _repair_ledger_path, + _repair_scratch_space_error, _repair_snapshot_timeout_seconds, _repair_state_db_schema_locked, + _restore_journal_mode_after_repair, _run_repair_strategies, _try_acquire_auto_maintenance_lock, + _unlink_db_triple, apply_durability_barriers, preflight_db_writability, repair_state_db_schema, ) from hermes_state_titles import SessionTitlesMixin from hermes_state_usage import SessionUsageMixin @@ -218,18 +110,11 @@ MAX_SAFE_EXPORT_MESSAGES = 20_000 def _configured_transcript_limit(key: str, fallback: int) -> int: - """Resolve a transcript safety limit from config at call time. - - Reads ``sessions.`` from config.yaml lazily (avoiding a circular - import at module load) and falls back to the module constant when the - config subsystem is unavailable (scaffold installs, stripped test - environments). A value of 0 disables the guard entirely. No caching: - ``load_config_readonly`` is already mtime-cached, and resolving fresh - keeps tests that monkeypatch config or the module constants working. - """ + """``sessions.`` from config.yaml (lazy import: circular at load), else + *fallback*. 0 disables the guard. Not cached: load_config_readonly is + mtime-cached already, and fresh resolution keeps monkeypatching tests working.""" try: from hermes_cli.config import load_config_readonly - sessions_cfg = load_config_readonly().get("sessions") or {} value = sessions_cfg.get(key) if value is None: @@ -242,23 +127,17 @@ def _configured_transcript_limit(key: str, fallback: int) -> int: def resolved_max_resume_messages() -> int: """Config-resolved resume guard limit (0 disables the guard).""" - return _configured_transcript_limit( - "max_resume_messages", MAX_SAFE_RESUME_MESSAGES - ) + return _configured_transcript_limit("max_resume_messages", MAX_SAFE_RESUME_MESSAGES) def resolved_max_export_messages() -> int: """Config-resolved in-memory export guard limit (0 disables the guard).""" - return _configured_transcript_limit( - "max_export_messages", MAX_SAFE_EXPORT_MESSAGES - ) + return _configured_transcript_limit("max_export_messages", MAX_SAFE_EXPORT_MESSAGES) class SessionResumeTooLargeError(ValueError): def __init__( - self, - message_count: int, - limit: int = MAX_SAFE_RESUME_MESSAGES, + self, message_count: int, limit: int = MAX_SAFE_RESUME_MESSAGES, scope: str = "across its lineage", ): self.message_count = message_count @@ -271,12 +150,7 @@ class SessionResumeTooLargeError(ValueError): class SessionExportTooLargeError(ValueError): - def __init__( - self, - session_id: str, - message_count: int, - limit: int = MAX_SAFE_EXPORT_MESSAGES, - ): + def __init__(self, session_id: str, message_count: int, limit: int = MAX_SAFE_EXPORT_MESSAGES): self.session_id = session_id self.message_count = message_count self.limit = limit @@ -294,16 +168,12 @@ def _system_prompt_hash(system_prompt: str) -> str: def _compression_lock_holder_process_is_dead(holder: str) -> bool: - """Return True only when a structured lock holder's local PID is gone. + """True only when a ``pid=`` lock holder's local PID is provably gone. - Compression locks are stored in a host-local SQLite database and holder - IDs created by ``conversation_compression`` start with ``pid=``. A - process killed during gateway shutdown cannot release its lease, so waiting - for the full TTL makes every new turn repeatedly attempt compaction. Reclaim - only when the kernel proves that PID no longer exists; legacy/unstructured - holders, same-process holders, permission errors, and any probe doubt - remain protected until normal TTL expiry (conservative: PID reuse must - never steal a live lease, and a wrongly-kept lease self-heals via TTL). + A process killed mid-compression cannot release its lease and every new + turn would re-attempt compaction until TTL expiry. Reclaim only on kernel + proof; unstructured/same-process holders and any probe doubt stay protected + (PID reuse must never steal a live lease; a wrongly-kept lease self-heals via TTL). """ match = _COMPRESSION_LOCK_HOLDER_PID_RE.search(holder or "") if match is None: @@ -312,24 +182,18 @@ def _compression_lock_holder_process_is_dead(holder: str) -> bool: pid = int(match.group(1)) except (TypeError, ValueError): return False - if pid <= 0: - return False - if pid == os.getpid(): - # Same-process holder (e.g. another thread's live lease): never - # self-reclaim — the lease refresher and release path own it. + # Same-process holder (another thread's live lease): never self-reclaim — + # the lease refresher and release path own it. + if pid <= 0 or pid == os.getpid(): return False if psutil is not None: try: - # psutil is the canonical cross-platform liveness answer - # (CONTRIBUTING.md "Critical rules" #1). pid_exists() reports - # recycled PIDs as alive — conservative, the TTL still applies. + # Canonical cross-platform liveness answer; recycled PIDs read as alive (conservative). return not psutil.pid_exists(pid) except Exception: return False # any doubt → keep the lease until TTL expiry - # Scaffold-phase fallback only (psutil missing), and POSIX-only: stdlib - # os.kill(pid, 0) is NOT a no-op probe on Windows (bpo-14484 — sig=0 maps - # to CTRL_C_EVENT and can kill the target's console group). Without psutil - # a Windows host stays TTL-only; the lease TTL remains the recovery path. + # psutil-less fallback is POSIX-only: os.kill(pid, 0) is NOT a no-op probe on + # Windows (sig=0 maps to CTRL_C_EVENT and can kill the target's console group). if os.name == "nt": return False try: @@ -342,59 +206,51 @@ def _compression_lock_holder_process_is_dead(holder: str) -> bool: def _scrub_surrogates(value: Any) -> Any: - """Replace lone surrogates when *value* is text; pass anything else through. - - sqlite3 encodes bound ``str`` parameters as UTF-8 and raises - ``UnicodeEncodeError`` on lone surrogates (U+D800..U+DFFF), so a single - such code point anywhere in a message aborts the whole write. No-op for - well-formed text. - """ + """Replace lone surrogates in text (sqlite3 raises UnicodeEncodeError on them, + aborting the whole write); pass anything else through.""" return _sanitize_surrogates(value) if isinstance(value, str) else value def workspace_key(row: Dict[str, Any]) -> Optional[str]: - """A session's workspace grouping key: its git repo root when known, else - its cwd. - - Branch is deliberately excluded so checking out a new branch doesn't - fragment a workspace's session history. Returns None for cwd-less (unbound) - sessions. Both fields are already recorded on ``sessions`` — this just picks - the coarser identity for grouping/filtering. - """ - root = (row.get("git_repo_root") or "").strip() - if root: - return root - - cwd = (row.get("cwd") or "").strip() - return cwd or None + """Workspace grouping key: git repo root when known, else cwd, else None. + Branch is deliberately excluded so a checkout doesn't fragment history.""" + return (row.get("git_repo_root") or "").strip() or (row.get("cwd") or "").strip() or None def _delegate_from_json(col: str = "model_config") -> str: return f"json_extract(COALESCE({col}, '{{}}'), '$._delegate_from')" -# Sentinel returned by SessionDB._merge_model_config_json when the session row -# doesn't exist and on_missing="skip" — distinguishes "no row" from the legal -# None result ("merged config is empty → store NULL"). +# _merge_model_config_json's "no such row" result — distinct from the legal None +# ("merged config is empty → store NULL"). _MODEL_CONFIG_ROW_MISSING = object() -# Billing-bucket classes that aren't a routable provider identity on their -# own — used by session_gateway_runtime's billing_provider fallback and by -# tui_gateway.server._stored_session_runtime_overrides. A session that -# persisted only one of these (never ran /model) must fall back to the -# ambient config default rather than restore a bare bucket. Shared here so -# both consumers stay in sync (previously duplicated as a set in -# tui_gateway/server.py). + +def _parse_model_config(raw: Any) -> Dict[str, Any]: + """Tolerant ``model_config`` decode: JSON text or dict -> dict copy; anything else -> {}.""" + if isinstance(raw, str) and raw.strip(): + try: + parsed = json.loads(raw) + except (json.JSONDecodeError, TypeError): + return {} + return parsed if isinstance(parsed, dict) else {} + if isinstance(raw, dict): + return dict(raw) + return {} + +# Billing buckets that aren't a routable provider identity. A session that +# persisted only one of these (never ran /model) falls back to the config +# default rather than restoring a bare bucket. Shared by session_gateway_runtime +# and tui_gateway.server so the two consumers cannot drift. _BARE_BILLING_PROVIDERS = frozenset({"auto", "custom"}) def _cwd_prefix_clause(cwd_prefix: str) -> Tuple[str, List[str]]: prefix = cwd_prefix.rstrip("/\\") or cwd_prefix - # ``_`` and ``%`` are LIKE wildcards but ordinary characters in a path - # (``my_project``), so an unescaped prefix also matches sibling directories. - # Escape the needle and pair it with ESCAPE; the literal separator - # backslash in the Windows pattern needs escaping for the same reason. The - # ``=`` arm is an exact compare and keeps the raw prefix. + # ``_``/``%`` are LIKE wildcards but ordinary path characters (``my_project``): + # unescaped, a prefix also matches sibling directories. The ``=`` arm is an + # exact compare and keeps the raw prefix; the Windows separator backslash + # in the LIKE pattern needs escaping too. esc = _escape_like(prefix) return ( "(s.cwd = ? OR s.cwd LIKE ? ESCAPE '\\' OR s.cwd LIKE ? ESCAPE '\\')", @@ -403,15 +259,9 @@ def _cwd_prefix_clause(cwd_prefix: str) -> Tuple[str, List[str]]: def _workspace_key_clause(key: str) -> Tuple[str, List[str]]: - """Match sessions whose ``workspace_key(row)`` equals ``key``. - - Mirrors :func:`workspace_key`: a session belongs to workspace ``key`` - when its recorded ``git_repo_root`` equals ``key``, or — for rows that - predate per-session git metadata — when its ``cwd`` is at or under - ``key`` (so a session started in ``repo/src`` still groups with ``repo``). - Used by ``hermes -c``/``--resume`` to continue the most recent session in - the *current* workspace rather than the global MRU. - """ + """WHERE for ``workspace_key(row) == key``: git_repo_root equals ``key``, or + (rows predating per-session git metadata) cwd is at/under ``key``. Used by + ``hermes -c``/``--resume`` to pick the current workspace's MRU, not the global one.""" prefix = key.rstrip("/\\") or key cwd_clause, cwd_params = _cwd_prefix_clause(prefix) return ( @@ -420,23 +270,68 @@ def _workspace_key_clause(key: str) -> Tuple[str, List[str]]: ) -def _collect_delegate_child_ids(conn, parent_ids: List[str]) -> List[str]: - """Delegate-subagent ids to cascade-delete with *parent_ids*. +# First user message of a session, shaped by _shape_preview() in Python. The +# indentation is part of the list_sessions_rich SQL text. +_PREVIEW_COL_SQL = f"""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""" - Only rows carrying the ``_delegate_from`` marker (set at creation, and - backfilled by the v16 migration) — generic untagged children keep the - orphan-don't-delete contract. Walks marker chains recursively so an - orchestrator subagent's own delegate children go too (FK safety). - """ + +def _session_filter_where( + *, exclude_children: bool = False, source: str = None, sources: List[str] = None, + session_key: str = None, exclude_sources: List[str] = None, cwd_prefix: str = None, + min_message_count: int = 0, archived_only: bool = False, include_archived: bool = False, +) -> Tuple[List[str], List[Any]]: + """Shared ``sessions s`` WHERE builder so session counts line up with the + listed rows. ``exclude_children`` hides sub-agent runs and compression + continuations but keeps branch/reset children: ``_LISTABLE_CHILD_SQL`` uses + the stable ``_branched_from`` marker (survives a re-ended parent) OR'd with + the legacy parent-ended-'branched' heuristic for pre-marker rows. Clause + order is part of the SQL text contract.""" + where: List[str] = [] + params: List[Any] = [] + if exclude_children: + where.append(_LISTABLE_CHILD_SQL) + where.append(f"{_delegate_from_json('s.model_config')} IS NULL") + include_sources = [source] if source else list(sources or []) + if include_sources: + where.append(f"s.source IN ({','.join('?' for _ in include_sources)})") + params.extend(include_sources) + if session_key: + where.append("s.session_key = ?") + params.append(session_key) + if exclude_sources: + where.append(f"s.source NOT IN ({','.join('?' for _ in exclude_sources)})") + params.extend(exclude_sources) + if cwd_prefix: + clause, clause_params = _cwd_prefix_clause(cwd_prefix) + where.append(clause) + params.extend(clause_params) + if min_message_count > 0: + where.append("s.message_count >= ?") + params.append(min_message_count) + if archived_only: + where.append("s.archived = 1") + elif not include_archived: + where.append("s.archived = 0") + return where, params + + +def _collect_delegate_child_ids(conn, parent_ids: List[str]) -> List[str]: + """Delegate-subagent ids (``_delegate_from`` marker) to cascade-delete with + *parent_ids*; untagged children keep the orphan-don't-delete contract. + Walks marker chains recursively so an orchestrator's own delegates go too.""" df = _delegate_from_json() seeds = {sid for sid in parent_ids if sid} - # Seed the visited set with the parents themselves. A delegation marker - # chain can loop back onto a parent — a cycle, or a parent that is also - # another parent's delegate child when several ids are deleted at once — - # and without this guard that parent would be collected as one of its own - # descendants and cascade-deleted along with all of its messages. Callers - # delete the parents separately, so parents must never appear in the - # returned child set. (#49148) + # Seed visited with the parents: a marker chain can loop back onto a parent + # (cycle, or a parent that is another parent's delegate child in one batch) + # and it would be collected as its own descendant and cascade-deleted. + # Callers delete parents separately; never return them as children. found: set[str] = set(seeds) frontier = list(seeds) while frontier: @@ -448,7 +343,6 @@ def _collect_delegate_child_ids(conn, parent_ids: List[str]) -> List[str]: ) frontier = [row["id"] for row in cursor.fetchall() if row["id"] not in found] found.update(frontier) - # Return only the discovered children — never the parents themselves. return [sid for sid in found if sid not in seeds] @@ -459,9 +353,7 @@ def _delete_delegate_children(conn, parent_ids: List[str]) -> List[str]: conn.execute(f"DELETE FROM messages WHERE session_id IN ({ph})", ids) # FK safety: orphan any untagged stragglers pointing at a doomed row. conn.execute( - f"UPDATE sessions SET parent_session_id = NULL " - f"WHERE parent_session_id IN ({ph})", - ids, + f"UPDATE sessions SET parent_session_id = NULL WHERE parent_session_id IN ({ph})", ids, ) conn.execute(f"DELETE FROM sessions WHERE id IN ({ph})", ids) return ids @@ -470,106 +362,79 @@ T = TypeVar("T") DEFAULT_DB_PATH = get_hermes_home() / "state.db" -# How long SessionDB stops attempting read-only opens after one fails, before -# probing again. Long enough that a genuinely unreadable file isn't retried per -# query; short enough that transient fd pressure doesn't strand the read pool. +# Back off from read-only opens for this long after one fails: long enough +# that an unreadable file isn't retried per query, short enough that transient +# fd pressure doesn't strand the read pool. _READ_OPEN_RETRY_SECONDS = 60.0 -# Transient SQLITE_IOERR retry budget for READ-ONLY opens (#100436). A WAL -# database being actively written (checkpoint, WAL reset/truncate, frame -# flush) can surface "disk I/O error" to a concurrent ``mode=ro`` reader in -# a millisecond-wide transition window: the read-only connection cannot -# perform the WAL recovery a read through a stale or mid-update -shm file -# needs, because recovery requires writing the -shm index, which mode=ro -# refuses. The window closes on its own (the writer finishes the transition), -# so a bounded number of short retries makes the open succeed instead of -# 500-ing the whole /api/sessions poll (or any other read-only opener). -# Deliberately NOT attempted on writable opens: a writer owns the -# transition, so an IOERR there means a real storage/fd problem. +# Transient SQLITE_IOERR retry budget for READ-ONLY opens. A WAL writer's +# checkpoint / reset / frame flush can surface "disk I/O error" to a concurrent +# mode=ro reader for a millisecond-wide window (ro cannot do the -shm recovery +# the read needs). NOT attempted on writable opens: a writer owns the +# transition, so an IOERR there is a real storage/fd problem. _READ_ONLY_IOERR_RETRY_ATTEMPTS = 3 _READ_ONLY_IOERR_RETRY_BACKOFF_S = 0.05 -# Hard ceiling on read-only connections ALIVE at once against one database -# FILE — pooled idle ones and checked-out ones together, summed over every -# SessionDB in this process that points at that file. See _PathReadBudget. -# -# Deliberately one constant for both the pool's maxsize and the permit count, -# because bounding only the pool bounds the wrong thing. A LifoQueue caps how -# many connections are *returned*; it says nothing about how many are *open*. -# With an open-on-miss checkout, N readers arriving on an empty pool all miss, -# all open, and peak at N — the surplus is closed on release, so nothing -# accumulates forever, but EMFILE is a peak-instant condition and the burst -# that empties the pool is exactly the burst that exhausts the fd table. -# -# So a connection holds a permit for its whole lifetime: acquired in -# _get_read_conn() before the open, released in _close_read_conn() after the -# close. Once permits are gone the read path degrades to the locked writer -# connection instead of opening more descriptors — slower under load, which is -# the correct trade against a process-wide wedge the supervisor cannot see. +# Ceiling on read-only connections ALIVE at once against one database FILE +# (idle pooled + checked out, summed over every SessionDB on that file). One +# constant for both the pool maxsize and the permit count: a LifoQueue only caps +# how many are *returned*; with open-on-miss, N readers hitting an empty pool +# all open and peak at N, and EMFILE is a peak-instant condition. So a +# connection holds a permit for its whole lifetime (_get_read_conn -> +# _close_read_conn); once permits are gone reads degrade to the locked writer +# connection — slower, but not a process-wide wedge the supervisor can't see. _READ_POOL_MAX = 8 -# Hard ceiling on read-only connections ALIVE at once in this PROCESS, across -# every state.db it has open. -# -# _READ_POOL_MAX bounds one file. A multiplexed gateway serves N profiles from -# one process and each profile has its OWN state.db, so a per-file ceiling -# still lets the descriptor cost grow with the profile count — the same shape -# as the per-instance bug, one level out (#98573). -# -# Three profiles' worth. Past it, readers on the (N+1)th file degrade to their -# writer connection instead of opening descriptors, which is the same trade -# _READ_POOL_MAX makes and for the same reason: a slow read path is -# recoverable, a process-wide EMFILE is not. +# Ceiling on read-only connections ALIVE in this PROCESS across every state.db +# (a multiplexed gateway opens one per profile, so a per-file cap still scales +# with profile count). Three profiles' worth; past it readers degrade to the +# writer connection for the same reason as _READ_POOL_MAX. _READ_POOL_PROCESS_MAX = 24 -# Warn when one process accumulates more than this many SessionDB handles on a -# single file. Not a limit — writer connections cannot be rationed the way read -# connections can — a diagnostic for the duplicate-handle class of bug. +# Warn past this many SessionDB handles on one file in one process. Diagnostic +# only: writer connections cannot be rationed the way read connections can. _HANDLES_PER_PATH_WARN = 4 -# Descriptors kept in reserve for everything that is NOT this module: httpx -# sockets, terminal subprocess pipes, log files. -# -# The ceilings above bound Hermes's SQLite descriptors, which is only ever part -# of the fd table. The #98573 report is exactly that case: ~20 state.db -# descriptors were not the whole 256, they were the share that pushed httpx and -# terminal pipes over, and the EMFILE surfaced in tools/terminal_tool.py rather -# than here. So the read pool also yields when the PROCESS is close to its -# limit, whatever is consuming it. +# Descriptors kept in reserve for everything that is NOT this module (httpx +# sockets, terminal pipes, log files): SQLite's share is only part of the fd +# table, and the EMFILE it pushes over surfaces elsewhere (terminal_tool). _FD_HEADROOM_RESERVE = 64 -# The fd count is a directory listing; cache it briefly so a burst of reads -# does not turn one syscall per query. Stale by at most this long, which can -# let through at most the ceiling's worth of opens — already bounded above. +# The fd count is a directory listing; cache it briefly so a read burst isn't a +# syscall per query. Staleness lets through at most the ceiling's worth of opens. _FD_USAGE_CACHE_SECONDS = 0.25 _process_read_permits = threading.BoundedSemaphore(_READ_POOL_PROCESS_MAX) -# Count of read opens refused because the process was low on descriptors. The -# only externally visible signal that the guard is firing; guarded by -# _read_budgets_lock. +# Read opens refused for low descriptor headroom — the only visible signal the +# guard fires. Guarded by _read_budgets_lock. _read_open_denied_fd_headroom = 0 _fd_usage_lock = threading.Lock() _fd_usage_cache: "tuple[float, Optional[int]]" = (0.0, None) -def _open_fd_count() -> Optional[int]: - """Descriptors open in THIS process, or None when it cannot be measured. +def _proc_fd_targets(pid: int) -> Iterator[str]: + """readlink() of every entry in /proc//fd (unreadable links skipped). + Raises OSError when the fd directory itself cannot be listed.""" + fd_dir = f"/proc/{pid}/fd" + for fd in os.listdir(fd_dir): + try: + yield os.readlink(f"{fd_dir}/{fd}") + except OSError: + continue - ``/proc/self/fd`` on Linux, ``/dev/fd`` on macOS and the BSDs. Windows has - neither, and no RLIMIT_NOFILE to compare against, so the guard is inert - there — which is correct: the CRT limit is thousands of handles, not 256. - """ + +def _open_fd_count() -> Optional[int]: + """Open descriptors in THIS process; None when unmeasurable (Windows: no fd + dir and no RLIMIT_NOFILE, correctly inert — its limit is thousands); -1 when + the probe itself hit EMFILE/ENFILE (that IS the answer: no headroom).""" for fd_dir in ("/proc/self/fd", "/dev/fd"): try: return len(os.listdir(fd_dir)) except OSError as exc: if exc.errno in (errno.EMFILE, errno.ENFILE): - # The probe itself could not get a descriptor. That IS the - # answer: there is no headroom. return -1 - continue return None @@ -589,18 +454,13 @@ def _fd_soft_limit() -> Optional[int]: def _fd_headroom_ok() -> bool: - """Whether the process can spare a descriptor for a new read connection. - - Fails OPEN when the platform cannot be measured (Windows, no fd directory, - unlimited RLIMIT_NOFILE): an unmeasurable platform is not a tight one, and - refusing every read there would be a self-inflicted convoy. Fails CLOSED - only on evidence — a measured shortfall, or a probe that could not get a - descriptor of its own. - """ + """Can the process spare a descriptor for a new read connection? + Fails OPEN when unmeasurable (refusing every read there would be a + self-inflicted convoy); fails CLOSED only on evidence (measured shortfall, + or a probe that couldn't get a descriptor itself).""" soft = _fd_soft_limit() if soft is None: return True - global _fd_usage_cache now = time.monotonic() with _fd_usage_lock: @@ -610,59 +470,30 @@ def _fd_headroom_ok() -> bool: cached = _open_fd_count() with _fd_usage_lock: _fd_usage_cache = (now, cached) - if cached is None: return True - if cached < 0: - return False - return (soft - cached) > _FD_HEADROOM_RESERVE + return cached >= 0 and (soft - cached) > _FD_HEADROOM_RESERVE def _reclaim_idle_read_conn_anywhere() -> bool: - """Close one idle read connection on ANY path in this process. - - The process ceiling is shared across files, so the connection that has to - go to make room may belong to a different database entirely — a profile - that has been quiet for an hour should not hold descriptors the profile - being served right now needs. - """ + """Close one idle read connection on ANY path: the process ceiling is shared + across files, so a quiet profile must not hold descriptors a busy one needs.""" with _read_budgets_lock: budgets = list(_read_budgets.values()) - for budget in budgets: - if budget.reclaim_idle(): - return True - return False + return any(budget.reclaim_idle() for budget in budgets) class _PathReadBudget: - """The read-connection permits for ONE database file, shared process-wide. - - ``_READ_POOL_MAX`` used to be enforced by a ``BoundedSemaphore`` owned by - each SessionDB, which bounded the wrong noun: the descriptors are spent on - a *file*, so N SessionDB objects on one state.db each got their own - allowance and peak scaled as ``N x (1 + _READ_POOL_MAX)``. A long-lived - gateway holds at least two (``SessionStore`` and ``GatewayRunner`` open - independent handles per profile path) and the count grows with the profile - count, which is how a healthy process walked into EMFILE — #98573. - - Holding the permits here instead makes the ceiling mean what its docstring - always claimed: read connections ALIVE at once against this path. - - One consequence has to be handled rather than documented away. A pooled - idle connection keeps its permit, so the first instance to warm up would - otherwise pin all eight and every later instance — a cron job's transient - handle, a second profile's store — would be permanently demoted to the - locked writer connection. That is why a permit miss first reclaims an - IDLE connection from a peer instance on the same path: idle descriptors - are transferable, in-use ones are not. - """ + """Read-connection permits for ONE database file, shared process-wide: + per-instance semaphores let N SessionDBs on one file peak at N x (1 + MAX) + and walk into EMFILE. An idle pooled connection keeps its permit, so a + permit miss first reclaims an IDLE connection from a peer on the same path + (idle descriptors are transferable, in-use ones are not).""" def __init__(self) -> None: self.permits = threading.BoundedSemaphore(_READ_POOL_MAX) self._lock = threading.Lock() - # Weak so a SessionDB that is dropped without close() cannot pin its - # peers' budget object; __del__ still runs close() and returns the - # permits. + # Weak: a SessionDB dropped without close() must not pin peers' budget. self._members: "weakref.WeakSet[SessionDB]" = weakref.WeakSet() self._duplicate_handles_warned = False @@ -670,38 +501,26 @@ class _PathReadBudget: with self._lock: self._members.add(db) handles = len(self._members) - warn = ( - handles > _HANDLES_PER_PATH_WARN - and not self._duplicate_handles_warned - ) + warn = (handles > _HANDLES_PER_PATH_WARN and not self._duplicate_handles_warned) if warn: self._duplicate_handles_warned = True if warn: - # The read connections are capped; the WRITER connection each - # handle holds is not, and cannot be — a SessionDB without one - # cannot write. The only real bound on writers is not opening - # redundant handles in the first place (which is what - # GatewayRunner borrowing SessionStore's handle does, #98573), so - # the next duplicate should be visible before it becomes an - # incident rather than inferred from an lsof after one. + # Writer connections cannot be capped (a SessionDB without one cannot + # write); the only bound is not opening redundant handles. Make the + # next duplicate visible before it becomes an incident. logger.warning( "%d live SessionDB handles on %s in this process; each holds " "its own writer connection (read connections are capped at %d " - "for the file). A long-lived process should share one handle " - "per path.", + "for the file). A long-lived process should share one handle per path.", handles, db.db_path, _READ_POOL_MAX, ) def acquire(self, requester: "SessionDB") -> bool: - """Take a permit for a new read connection, or refuse. - - Three gates, broadest first: the process's descriptor headroom, the - process-wide read ceiling, then this file's ceiling. Refusing means - the caller serves the read from the locked writer connection — slower, - never an error. - """ + """Take a permit for a new read connection, or refuse (caller then reads + via the locked writer connection — slower, never an error). Gates, + broadest first: fd headroom, process-wide ceiling, this file's ceiling.""" if not _fd_headroom_ok(): global _read_open_denied_fd_headroom with _read_budgets_lock: @@ -720,43 +539,28 @@ class _PathReadBudget: _process_read_permits.release() def _acquire_process_permit(self) -> bool: - if _process_read_permits.acquire(blocking=False): - return True - if not _reclaim_idle_read_conn_anywhere(): - return False - # Another thread may take the freed permit first; that is a legitimate + # Another thread may take a freed permit first; that is a legitimate # loss, and the caller degrades to the writer lock rather than looping. - return _process_read_permits.acquire(blocking=False) + return _process_read_permits.acquire(blocking=False) or ( + _reclaim_idle_read_conn_anywhere() and _process_read_permits.acquire(blocking=False) + ) def _acquire_path_permit(self, requester: "SessionDB") -> bool: - if self.permits.acquire(blocking=False): - return True - if not self.reclaim_idle(exclude=requester): - return False - return self.permits.acquire(blocking=False) + return self.permits.acquire(blocking=False) or ( + self.reclaim_idle(exclude=requester) and self.permits.acquire(blocking=False) + ) def reclaim_idle(self, exclude: "Optional[SessionDB]" = None) -> bool: - """Close one idle pooled connection held by a member. True if one went. - - Closing it runs release(), which returns both the path permit and the - process permit, so this is the single reclaim primitive both ceilings - use. - """ + """Close one idle pooled connection held by a member; True if one went. + Its release() returns both permits, so both ceilings reclaim through here.""" with self._lock: members = [db for db in self._members if db is not exclude] - for member in members: - if member._evict_one_idle_read_conn(): - return True - return False + return any(member._evict_one_idle_read_conn() for member in members) -# canonical db path -> the permits for that file. Weak values: the budget -# lives exactly as long as some SessionDB on that path holds a strong -# reference to it, so a test that churns tmp_path databases does not grow -# this map for the life of the process. -_read_budgets: "weakref.WeakValueDictionary[str, _PathReadBudget]" = ( - weakref.WeakValueDictionary() -) +# canonical db path -> permits for that file. Weak values: the budget lives as +# long as some SessionDB on the path holds it, so tmp_path churn can't grow this. +_read_budgets: "weakref.WeakValueDictionary[str, _PathReadBudget]" = (weakref.WeakValueDictionary()) _read_budgets_lock = threading.Lock() @@ -778,26 +582,16 @@ def _read_budget_for(db_path) -> _PathReadBudget: return budget -# Import-time snapshot used by _default_db_path() to detect a deliberately +# Import-time snapshot so _default_db_path() can detect a deliberately # re-pointed DEFAULT_DB_PATH (tests monkeypatch the constant directly). _IMPORT_DEFAULT_DB_PATH = DEFAULT_DB_PATH def _default_db_path() -> Path: - """Resolve the default state DB path at call time. - - ``DEFAULT_DB_PATH`` is computed when this module is first imported, which - freezes the developer's real ``~/.hermes`` even when a test fixture later - redirects ``HERMES_HOME`` — importing this module during collection was - enough to point every default ``SessionDB()`` at the real state.db. - - Precedence: - - 1. A deliberately re-pointed ``DEFAULT_DB_PATH`` (differs from the - import-time snapshot — the established test escape hatch) wins. - 2. Otherwise resolve ``get_hermes_home()`` fresh so a runtime - ``HERMES_HOME`` redirect takes effect regardless of import order. - """ + """Default state DB path at CALL time. A re-pointed ``DEFAULT_DB_PATH`` (the + test escape hatch) wins; otherwise ``get_hermes_home()`` is resolved fresh so + a runtime HERMES_HOME redirect works regardless of import order (the frozen + import-time value pointed every default SessionDB() at the real state.db).""" if DEFAULT_DB_PATH != _IMPORT_DEFAULT_DB_PATH: return DEFAULT_DB_PATH return get_hermes_home() / "state.db" @@ -806,54 +600,33 @@ def _default_db_path() -> Path: # --------------------------------------------------------------------------- # Live-DB test-isolation guard # --------------------------------------------------------------------------- -# Forensic evidence (Aug 2026, live developer machine): the production -# ~/.hermes/state.db accumulated pytest fixture rows — sessions with -# chat_id='chat-1'/'123'/'wx-chat' and gateway_routing scopes literally under -# /tmp/pytest-of-*/ — and a pytest-spawned process flipped the journal mode -# out from under the WAL-mode gateway writer, destroying committed -# transcripts ("Persisted transcript lagged live cached history ... possible -# FTS write corruption"). The hermetic conftest redirects HERMES_HOME per -# test, but any escape (a session-scoped fixture running before the autouse -# fixture, a subprocess child launched without HERMES_HOME, a stale worktree -# without the re-pin, or a developer shell that exports HERMES_HOME to the -# real home so the conftest session sandbox is skipped) silently fell -# through to the real database. -# -# This guard is the single choke point: EVERY ``SessionDB`` construction -# resolves its path here, so under pytest a resolution that lands on a -# production state.db fails hard instead of corrupting live data. It is -# env-based (``PYTEST_CURRENT_TEST`` / ``PYTEST_VERSION`` are set by pytest -# and inherited by subprocess children), so it also protects children that -# never import the test conftest. +# Field evidence: pytest fixture rows landed in the production state.db and a +# pytest-spawned child flipped the journal mode under the live WAL writer, +# destroying committed transcripts. The hermetic conftest redirects HERMES_HOME +# per test, but any escape (fixture ordering, a child spawned without +# HERMES_HOME, a shell exporting the real home) fell through silently. EVERY +# SessionDB construction resolves its path here, so under pytest a production +# state.db fails hard. Env-based, so subprocess children are protected too. -#: Escape hatch for the rare legitimate case (a test that genuinely needs -#: the real DB). The in-tree conftest sets this for tests marked -#: ``@pytest.mark.live_system_guard_bypass``; scripts may set it explicitly. +#: Escape hatch for tests that genuinely need the real DB (conftest sets it for +#: ``@pytest.mark.live_system_guard_bypass``); scripts may set it explicitly. _STATE_DB_GUARD_BYPASS = False -#: Env-carried twin of ``_STATE_DB_GUARD_BYPASS``. A module global cannot -#: cross a process boundary, so a test that deliberately points a *child* at -#: the live DB has no way to opt out once ancestry arms the guard there. -#: Export this in the child's env instead. +#: Env twin of ``_STATE_DB_GUARD_BYPASS`` for child processes (a module global +#: cannot cross a process boundary, and ancestry arms the guard there). _STATE_DB_GUARD_BYPASS_ENV = "HERMES_STATE_DB_GUARD_BYPASS" -#: Additional production roots to refuse (beyond the platform default -#: ``~/.hermes``). The test conftest injects the pre-sandbox production -#: root here so custom-``HERMES_HOME`` deployments are covered too. +#: Extra production roots to refuse; conftest injects the pre-sandbox root so +#: custom-HERMES_HOME deployments are covered too. _STATE_DB_GUARD_EXTRA_DENY_ROOTS: Tuple[Path, ...] = () def _real_platform_state_root() -> Optional[Path]: - """Resolve the REAL platform-default Hermes root for the guard. - - Deliberately avoids ``Path.home()`` / ``hermes_constants``: tests - routinely monkeypatch ``Path.home`` to a tempdir, and ``hermes_state`` - is often imported lazily *while* such a patch is active — resolving - through the patched callable would misidentify the test's own hermetic - home as "production" (false positive) or, worse, miss the real one - (false negative). ``os.path.expanduser`` reads the HOME environment - variable / passwd entry, which the hermetic conftest never rewrites. - """ + """The REAL platform-default Hermes root. Avoids ``Path.home()`` / + ``hermes_constants``: tests monkeypatch Path.home to a tempdir while this + module is imported lazily, which would misidentify the hermetic home as + production or miss the real one. ``expanduser`` reads HOME/passwd, which the + conftest never rewrites.""" try: if sys.platform == "win32": base = os.environ.get("LOCALAPPDATA", "").strip() @@ -869,15 +642,10 @@ def _real_platform_state_root() -> Optional[Path]: return None -#: Env marker exported by the hermetic test conftest at the same moment it -#: redirects ``HERMES_HOME`` to the per-session tmp isolation root. Its -#: value is that isolation root. Unlike ``PYTEST_*`` (owned by pytest, and -#: routinely scrubbed by tests that rebuild a child environment), this marker -#: is OURS: it declares "this process tree is running under Hermes test -#: isolation", and it inherits into subprocess children by default — so a -#: child that received the patched ``HERMES_HOME`` also received the marker, -#: and a child that resolves a production DB while carrying it is, by -#: definition, an isolation escape (#82770). +#: Exported by the hermetic conftest alongside the HERMES_HOME redirect (value: +#: the isolation root). Unlike PYTEST_* (scrubbed by tests that rebuild a child +#: env) it is OURS and inherits by default, so a child carrying it that resolves +#: a production DB is by definition an isolation escape. _TEST_ISOLATION_MARKER_ENV = "HERMES_TEST_ISOLATION" @@ -890,37 +658,28 @@ def _running_under_pytest() -> bool: ) -#: Names that identify a pytest launcher in a process command line. Matched -#: against the *basename* of each argv token so ``/tmp/pytest-of-dev/...`` -#: paths — which do show up in real argv — cannot false-positive. -_PYTEST_LAUNCHER_NAMES = frozenset( - {"pytest", "py.test", "pytest.exe", "py.test.exe"} -) +#: pytest launcher names, matched against each argv token's *basename* so +#: ``/tmp/pytest-of-dev/...`` paths cannot false-positive. +_PYTEST_LAUNCHER_NAMES = frozenset({"pytest", "py.test", "pytest.exe", "py.test.exe"}) -#: Memoised ancestry answer. The process tree above us does not change in a -#: way that matters here, and the walk must not cost anything on the hot path. +#: Memoised ancestry answer: the tree above us doesn't change; keep the hot path free. _PYTEST_ANCESTOR: Optional[bool] = None def _process_looks_like_pytest(proc: Any) -> bool: - """True when *proc*'s command line is a pytest invocation. - - Covers both ``pytest ...`` (launcher on argv[0]) and ``python -m pytest`` - (launcher as a bare ``pytest`` token). A process whose command line we - cannot read is treated as "not pytest": guessing the other way would - refuse production opens for unrelated reasons. - """ + """True when *proc*'s command line is a pytest invocation (``pytest ...`` or + ``python -m pytest``). Unreadable cmdline => not pytest: guessing the other + way would refuse production opens for unrelated reasons.""" try: cmdline = proc.cmdline() or [] except Exception: return False for arg in cmdline: try: - token = str(arg).strip('"').strip("'") # Split on both separators on every host: os.path.basename is # POSIX-only under Linux and would leave a Windows-style path # intact, making the matcher's answer depend on the platform. - name = token.replace("\\", "/").rsplit("/", 1)[-1].lower() + name = str(arg).strip('"').strip("'").replace("\\", "/").rsplit("/", 1)[-1].lower() except Exception: continue if name in _PYTEST_LAUNCHER_NAMES: @@ -929,28 +688,17 @@ def _process_looks_like_pytest(proc: Any) -> bool: def _has_pytest_ancestor() -> bool: - """True when some ancestor process of this one is a pytest run. - - ``_running_under_pytest`` reads ``PYTEST_*`` env vars, which a child - spawned with a rebuilt environment loses at the same moment it loses the - ``HERMES_HOME`` redirect: that child aims at the production DB *and* - disarms the guard in one step (#82770). Ancestry is the one test-context - signal that survives an env rebuild, so it backs the env check up. - - Fails open (``False``) when ``psutil`` is unavailable or the walk errors — - that restores the previous env-only behaviour rather than blocking real - user runs on a psutil hiccup. - """ + """True when an ancestor process is a pytest run. A child spawned with a + rebuilt env loses PYTEST_* and the HERMES_HOME redirect together — aiming at + production AND disarming the guard in one step; ancestry survives that. + Fails open without psutil / on walk errors (never block real user runs).""" global _PYTEST_ANCESTOR if _PYTEST_ANCESTOR is not None: return _PYTEST_ANCESTOR found = False if psutil is not None: try: - for parent in psutil.Process().parents(): - if _process_looks_like_pytest(parent): - found = True - break + found = any(_process_looks_like_pytest(p) for p in psutil.Process().parents()) except Exception: found = False _PYTEST_ANCESTOR = found @@ -958,16 +706,9 @@ def _has_pytest_ancestor() -> bool: def _in_test_context() -> bool: - """True when this process is a test run, by environment or by ancestry. - - Order matters for cost: the env probe is two dict lookups and covers the - common in-process case, so the ancestry walk only runs for processes the - environment claims are ordinary user runs — and its answer is memoised, - so a real ``hermes`` invocation pays for at most one walk. - """ - if _running_under_pytest(): - return True - return _has_pytest_ancestor() + """Test run by environment or ancestry. Env first (two dict lookups); the + memoised ancestry walk runs at most once per real ``hermes`` invocation.""" + return _running_under_pytest() or _has_pytest_ancestor() def _production_state_roots() -> List[Path]: @@ -984,36 +725,22 @@ def _production_state_roots() -> List[Path]: def _is_production_state_db(resolved: Path, root: Path) -> bool: - """True when *resolved* is a DB file of the real Hermes home *root*. - - Matches files directly in the root (``/state.db``) and profile - homes (``/profiles//state.db``). Deliberately does NOT - match deeper scratch paths (e.g. repo worktrees that happen to live - under ``~/.hermes/hermes-agent/...``) so hermetic tests using unusual - tempdirs cannot false-positive. - """ + """*resolved* is ``/state.db`` or ``/profiles//state.db``. + Deeper scratch paths (repo worktrees under ~/.hermes/hermes-agent/...) are + deliberately NOT matched so hermetic tests cannot false-positive.""" if resolved.parent == root: return True try: - rel = resolved.relative_to(root) + parts = resolved.relative_to(root).parts except ValueError: return False - parts = rel.parts return len(parts) == 3 and parts[0] == "profiles" def _ensure_test_isolation(db_path: Path) -> None: - """Fail hard when a pytest-context process resolves a production DB. - - Raises ``RuntimeError`` before any connection, mkdir, journal-mode - pragma, or byte probe can touch the live database. No-op outside - pytest and for hermetic (tmp ``HERMES_HOME``) paths. - - "pytest context" means environment *or* process ancestry — see - :func:`_in_test_context`. Env alone is not enough: a child spawned with - a rebuilt environment loses ``PYTEST_*`` and ``HERMES_HOME`` together, - which is precisely the state in which it writes to production (#82770). - """ + """Raise RuntimeError before any connection/mkdir/pragma/byte probe when a + pytest-context process (env OR ancestry, see :func:`_in_test_context`) + resolves a production DB. No-op outside pytest and for hermetic paths.""" if _STATE_DB_GUARD_BYPASS or os.environ.get(_STATE_DB_GUARD_BYPASS_ENV): return if not _in_test_context(): @@ -1029,55 +756,36 @@ def _ensure_test_isolation(db_path: Path) -> None: f"state.db at {resolved} (under real Hermes root {root}). " "Tests must run against a temporary HERMES_HOME — pass an " "explicit tmp db_path or let the hermetic conftest redirect " - "HERMES_HOME. If this test genuinely needs the live " - "database, mark it with " + "HERMES_HOME. If this test genuinely needs the live database, mark it with " "@pytest.mark.live_system_guard_bypass — or, for a spawned " f"child process, export {_STATE_DB_GUARD_BYPASS_ENV}=1 in " "its environment." ) -# Last SessionDB() init error, per-process. Surfaced in /resume and -# related slash-command error strings so users know WHY the DB is -# unavailable instead of getting a bare "Session database not available." -# Only SessionDB.__init__ writes to this; kanban_db.connect() failures -# do not update it (by design — kanban failures are reported via their -# own caller's error handling, not via /resume-style slash commands). +# Last SessionDB() init error, per-process; surfaced by /resume-style slash +# commands so users know WHY. Only SessionDB.__init__ writes it (kanban_db +# failures are reported via their own callers, by design). _last_init_error: Optional[str] = None _last_init_error_lock = threading.Lock() def _set_last_init_error(msg: Optional[str]) -> None: - """Record (or clear) the most recent state.db init failure. - - Thread-safe via _last_init_error_lock. Callers pass a message to - record a failure or None to clear. SessionDB.__init__ only calls - this to SET on failure — it deliberately does NOT clear on success, - because in a multi-threaded caller (e.g. gateway / web_server per- - request SessionDB() instantiation), a concurrent successful open - racing past a different thread's failure would erase the cause - string that thread's /resume handler is about to format. Explicit - clears (e.g. test fixtures) are still supported by passing None. - """ + """Record (or clear with None) the most recent state.db init failure. + __init__ only SETs on failure and never clears on success: a concurrent + successful open would erase the cause another thread's /resume is about to format.""" global _last_init_error with _last_init_error_lock: _last_init_error = msg def get_last_init_error() -> Optional[str]: - """Return the most recent state.db init failure, if any. - - Slash-command handlers (``/resume``, ``/title``, ``/history``, ``/branch``) - call this to surface the underlying cause in their error messages when - ``_session_db is None``. Returns ``None`` if SessionDB initialized - successfully (or hasn't been attempted). - """ + """Most recent state.db init failure (None if none/never attempted).""" return _last_init_error -# Distinctive opening shared by both background-review harness prompts -# (_SKILL_REVIEW_PROMPT and _MEMORY_REVIEW_PROMPT in agent/background_review.py). -# Matched case-sensitively against the leading content of a user/system message. +# Openings of the background-review harness prompts (agent/background_review.py), +# matched case-sensitively against leading user/system content. _REVIEW_HARNESS_PREFIXES = ( "Review the conversation above and update the skill library", "Review the conversation above and consider saving to memory", @@ -1085,34 +793,17 @@ _REVIEW_HARNESS_PREFIXES = ( def _is_background_review_harness_message(msg: Dict[str, Any]) -> bool: - """True when ``msg`` is a persisted background-review harness prompt. - - These are user/system turns the forked skill/memory review agent wrote into - a real session in older builds (before the ``_persist_disabled`` isolation - fix). They instruct the agent to act as the curator under a hard tool - restriction, so replaying them as live history hijacks the session. - """ - if not isinstance(msg, dict): - return False - if msg.get("role") not in {"user", "system"}: + """Persisted background-review harness prompt (older builds wrote the forked + curator's turns into real sessions; replaying them hijacks the session).""" + if not isinstance(msg, dict) or msg.get("role") not in {"user", "system"}: return False content = msg.get("content") - if not isinstance(content, str): - return False - head = content.lstrip() - return any(head.startswith(p) for p in _REVIEW_HARNESS_PREFIXES) + return isinstance(content, str) and content.lstrip().startswith(_REVIEW_HARNESS_PREFIXES) -def _strip_background_review_harness( - messages: List[Dict[str, Any]], -) -> List[Dict[str, Any]]: - """Drop background-review harness messages and the curator-mode assistant - reply that immediately followed each one. - - Walk the list once; when a harness user/system message is found, skip it and - also skip the next message if it is the assistant turn that answered it. - Everything else passes through untouched and in order. - """ +def _strip_background_review_harness(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + """Drop harness messages and the curator-mode assistant reply that + immediately followed each; everything else passes through in order.""" if not messages: return messages out: List[Dict[str, Any]] = [] @@ -1124,8 +815,7 @@ def _strip_background_review_harness( if skip_next_assistant: skip_next_assistant = False if isinstance(msg, dict) and msg.get("role") == "assistant": - # The curator-mode reply to the harness prompt — drop it. - continue + continue # the curator-mode reply to the harness prompt out.append(msg) return out @@ -1135,44 +825,23 @@ _STALE_TOOL_CALL_MARKER_RE = re.compile(r"^\[[A-Za-z_][A-Za-z0-9_.-]*\]$") def _is_stale_tool_call_marker_message(msg: Dict[str, Any]) -> bool: - """True when ``msg`` is a persisted assistant turn whose content is a bare - bracketed marker (e.g. ``[memory]``) left over from a tool-call turn. - - Before the #78148 fix in ``agent.conversation_loop``, a local tool-call - template could emit a bare marker as assistant content alongside a real - tool call. The loop cached that marker as a fallback and later replayed - it as the "final response", persisting it into the session. Sessions - written before the fix can still carry these rows. - """ - if not isinstance(msg, dict): - return False - if msg.get("role") != "assistant": - return False - if not msg.get("tool_calls"): + """Assistant tool-call turn whose content is a bare ``[marker]`` — an older + conversation_loop cached a local template's marker and persisted it as the + "final response"; sessions written before the fix still carry these rows.""" + if not isinstance(msg, dict) or msg.get("role") != "assistant" or not msg.get("tool_calls"): return False content = msg.get("content") - if not isinstance(content, str): - return False - return bool(_STALE_TOOL_CALL_MARKER_RE.fullmatch(content.strip())) + return isinstance(content, str) and bool(_STALE_TOOL_CALL_MARKER_RE.fullmatch(content.strip())) -def _strip_stale_tool_call_markers( - messages: List[Dict[str, Any]], -) -> List[Dict[str, Any]]: - """Clear bare protocol-marker content persisted before the #78148 fix. - - Replaying "[memory]" as if the model had actually answered teaches the - model, by example, to keep emitting the same marker in later turns — the - exact symptom the issue reported. Only the stray ``content`` field is - blanked; the tool call and its result are left untouched so provider - tool_call/tool_result pairing stays intact. Sessions with no affected - rows pass through unchanged. - """ +def _strip_stale_tool_call_markers(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + """Blank stale ``[marker]`` assistant content: replaying it teaches the model + to keep emitting the marker. Only ``content`` is blanked; tool_call/result + pairing stays intact.""" repaired = 0 - for msg in messages: - if _is_stale_tool_call_marker_message(msg): - msg["content"] = "" - repaired += 1 + for msg in filter(_is_stale_tool_call_marker_message, messages): + msg["content"] = "" + repaired += 1 if repaired: logger.info( "Cleared %d stale tool-call marker message(s) while restoring session (#78148)", @@ -1182,19 +851,8 @@ def _strip_stale_tool_call_markers( def format_session_db_unavailable(prefix: str = "Session database not available") -> str: - """Format a user-facing 'session DB unavailable' message with cause. - - When ``SessionDB()`` init fails, callers set ``_session_db = None`` and - several slash commands (/resume, /title, /history, /branch) previously - responded with a bare ``"Session database not available."`` — no - indication of WHY. This helper includes the captured cause (typically - ``"locking protocol"`` from NFS/SMB) and points users at the known - culprit so they can fix it themselves. - - Example output: - Session database not available: locking protocol (state.db may be - on NFS/SMB — see https://www.sqlite.org/wal.html). - """ + """User-facing "session DB unavailable" message with the captured init cause + (e.g. "locking protocol" from NFS/SMB, with a WAL-docs hint).""" cause = get_last_init_error() if not cause: return f"{prefix}." @@ -1205,113 +863,74 @@ def format_session_db_unavailable(prefix: str = "Session database not available" # --------------------------------------------------------------------------- -# Malformed-schema recovery -# --------------------------------------------------------------------------- -# A distinct, nastier failure class than a malformed FTS *inverted index*: -# the ``sqlite_master`` schema table itself becomes inconsistent — most -# commonly a DUPLICATE object definition, e.g. two ``CREATE VIRTUAL TABLE -# messages_fts`` rows. SQLite parses the entire schema while preparing the -# FIRST statement on a connection, so on this class *every* statement raises -# before it runs — including ``PRAGMA journal_mode`` (which is why this trips -# in ``apply_wal_with_fallback`` during ``SessionDB.__init__``, long before -# ``_init_schema`` is reached) and even ``PRAGMA integrity_check`` and a plain -# ``DROP TABLE``. The only operations that still work are -# ``PRAGMA writable_schema=ON`` plus direct ``sqlite_master`` surgery. -# -# Symptom users hit (Desktop/Dashboard show "no sessions" while 200+ JSON -# files sit on disk): -# sqlite3.DatabaseError: malformed database schema (messages_fts) - -# table messages_fts already exists -# -# The canonical ``sessions`` / ``messages`` data is intact in these cases — -# only the derived schema is broken — so recovery preserves all transcripts -# and merely rebuilds the FTS layer. +# Malformed-schema recovery: ``sqlite_master`` itself is inconsistent (typically +# a DUPLICATE ``CREATE VIRTUAL TABLE messages_fts`` row). SQLite parses the +# whole schema while preparing the FIRST statement, so EVERY statement raises — +# including ``PRAGMA journal_mode`` (it trips in apply_wal_with_fallback during +# __init__, before _init_schema) and plain ``DROP TABLE``; only +# ``PRAGMA writable_schema=ON`` + sqlite_master surgery still work. Canonical +# sessions/messages are intact; recovery rebuilds only the FTS layer. _MALFORMED_SCHEMA_MARKERS = ("malformed database schema",) -_MALFORMED_DB_MARKERS = ( - *_MALFORMED_SCHEMA_MARKERS, - "database disk image is malformed", -) +_MALFORMED_DB_MARKERS = (*_MALFORMED_SCHEMA_MARKERS, "database disk image is malformed") -# Process-global guard so auto-repair is attempted at most once per DB path -# per process (prevents repair loops and serialises concurrent web_server / -# gateway opens against the same malformed file). +# Auto-repair at most once per DB path per process (no repair loops; serialises +# concurrent web_server / gateway opens on the same malformed file). _repair_attempted_paths: set[str] = set() _repair_attempt_lock = threading.Lock() def is_malformed_db_error(exc: BaseException) -> bool: - """True for explicit malformed-schema or generic corrupt-image errors. - - This broad classifier is for diagnostics and explicit offline recovery - dispatch. Runtime repair must use :func:`is_malformed_schema_error`, since - a generic corrupt-image error does not identify the damaged object. - """ - if not isinstance(exc, sqlite3.DatabaseError): - return False - return any(marker in str(exc).lower() for marker in _MALFORMED_DB_MARKERS) - - -# SQLITE_IOERR, matched as a plain substring so wrapped error strings still -# classify. Shared by the read-only open retry and the write-path BEGIN retry. -_DISK_IO_ERROR_MARKER = "disk i/o error" - -# Broader set for HTTP classification: a read that failed for one of these -# reasons found the store BUSY, not gone. Callers map it to 503 (retry, the -# list was not cleared) instead of 500. Corruption is deliberately absent — -# a malformed store must surface, not be retried into a timeout. -_TRANSIENT_SQLITE_MARKERS = ( - _DISK_IO_ERROR_MARKER, - "database is locked", - "database table is locked", - "busy", -) - - -def is_transient_sqlite_error(exc: BaseException) -> bool: - """True when a SQLite failure means "busy right now", not "damaged". - - One predicate so the read paths cannot drift apart on what counts as - recoverable: the read-only open retry, and the HTTP 503-vs-500 split on - the session-list endpoints, classify the same way. - """ - if not isinstance(exc, sqlite3.OperationalError): - return False - message = str(exc).lower() - return any(marker in message for marker in _TRANSIENT_SQLITE_MARKERS) - - -def _is_transient_read_only_ioerr(exc: sqlite3.OperationalError, *, attempt: int) -> bool: - """True when a read-only open should be retried rather than raised. - - A ``mode=ro`` connection cannot perform WAL recovery (recovery needs to - write the -shm index, which read-only mode refuses), so a concurrent WAL - checkpoint / reset / frame-flush can surface ``SQLITE_IOERR`` ("disk I/O - error") to a reader on an otherwise healthy database (#100436). The - transition is millisecond-scale, so a bounded number of short retries - clears it without changing classification for genuine storage failures — - a persistent IOERR still exhausts the budget and propagates. - """ - return ( - attempt < _READ_ONLY_IOERR_RETRY_ATTEMPTS - and _DISK_IO_ERROR_MARKER in str(exc).lower() + """Malformed-schema OR generic corrupt-image error. Diagnostics / offline + recovery only — runtime repair must use :func:`is_malformed_schema_error`.""" + return isinstance(exc, sqlite3.DatabaseError) and any( + marker in str(exc).lower() for marker in _MALFORMED_DB_MARKERS ) +# SQLITE_IOERR as a substring (wrapped strings still classify); shared by the +# read-only open retry and the write-path BEGIN retry. +_DISK_IO_ERROR_MARKER = "disk i/o error" + +# "Store BUSY, not gone" — HTTP callers map these to 503 instead of 500. +# Corruption deliberately absent: a malformed store must surface, not be +# retried into a timeout. +_TRANSIENT_SQLITE_MARKERS = ( + _DISK_IO_ERROR_MARKER, "database is locked", "database table is locked", "busy", +) + + +def _is_no_more_rows(exc: sqlite3.Error) -> bool: + """Transient engine error on contended WAL appends; the identical write succeeds + standalone, so it retries like locked/busy. Message-scoped because some builds + raise it as InterfaceError (outside DatabaseError).""" + return "no more rows available" in str(exc).lower() + + +def is_transient_sqlite_error(exc: BaseException) -> bool: + """"Busy right now", not "damaged". One predicate so the read-only open + retry and the HTTP 503-vs-500 split cannot drift apart.""" + return isinstance(exc, sqlite3.OperationalError) and any( + marker in str(exc).lower() for marker in _TRANSIENT_SQLITE_MARKERS + ) + + +def _is_transient_read_only_ioerr(exc: sqlite3.OperationalError, *, attempt: int) -> bool: + """Retry a read-only open? See _READ_ONLY_IOERR_RETRY_ATTEMPTS: a + persistent IOERR still exhausts the budget and propagates.""" + return attempt < _READ_ONLY_IOERR_RETRY_ATTEMPTS and _DISK_IO_ERROR_MARKER in str(exc).lower() + + def is_malformed_schema_error(exc: BaseException) -> bool: - """True only when SQLite explicitly reports malformed schema text. - - A generic ``database disk image is malformed`` error is SQLITE_CORRUPT - and may come from any B-tree or freelist page. It does not prove that - canonical rows are intact, so runtime schema/FTS repair must fail closed. - """ - if not isinstance(exc, sqlite3.DatabaseError): - return False - return any(marker in str(exc).lower() for marker in _MALFORMED_SCHEMA_MARKERS) + """Only SQLite's explicit malformed-schema text. A generic "disk image is + malformed" (SQLITE_CORRUPT) may be any B-tree/freelist page and does not + prove canonical rows intact, so runtime repair must fail closed on it.""" + return isinstance(exc, sqlite3.DatabaseError) and any( + marker in str(exc).lower() for marker in _MALFORMED_SCHEMA_MARKERS + ) -# Markers that mean the host filesystem cannot accept another write. Kept as -# plain substrings so OSError, sqlite3.OperationalError, and wrapped RPC -# error strings all match the same helper. +# "Filesystem cannot accept another write" substrings (OSError, sqlite3, and +# wrapped RPC strings all match the same helper). _DISK_FULL_MARKERS = ( "no space left on device", "not enough space", @@ -1323,45 +942,26 @@ _DISK_FULL_MARKERS = ( def is_disk_full_error(exc: BaseException | str | None) -> bool: - """True when *exc* (or a stringified error) is a disk-full / ENOSPC failure. - - Covers: - * ``OSError`` with ``errno.ENOSPC`` - * SQLite ``OperationalError: database or disk is full`` (SQLITE_FULL) - * Plain English / errno strings that survive RPC wrapping - """ + """Disk-full / ENOSPC: OSError(ENOSPC), SQLITE_FULL, or matching strings.""" if exc is None: return False if isinstance(exc, OSError) and getattr(exc, "errno", None) == errno.ENOSPC: return True - text = exc if isinstance(exc, str) else str(exc) - lowered = text.lower() + lowered = (exc if isinstance(exc, str) else str(exc)).lower() return any(marker in lowered for marker in _DISK_FULL_MARKERS) -# Every cause bucket classify_persistence_error can return. Consumers that -# enumerate causes (e.g. the cron scheduler's explainer-variant suppression) -# must iterate this tuple instead of hardcoding the list, so adding a bucket -# can never silently desynchronize them. +# Every classify_persistence_error bucket; consumers enumerate this tuple so a +# new bucket can never silently desynchronize them. PERSISTENCE_ERROR_CAUSES = ( - "locked", - "compression", - "compression_closed", - "turn_lease", - "corrupt", - "replaced", - "disk", + "locked", "compression", "compression_closed", "turn_lease", "corrupt", "replaced", "disk", "unknown", ) -# Markers that mean the database FILE itself is structurally damaged. Kept -# as plain substrings so sqlite3.DatabaseError, wrapped RPC strings, and -# logged message text all match the same helper. NOTE: "database disk image -# is malformed" contains the word "disk", so this check MUST run before the -# disk-full/readonly bucket in classify_persistence_error — otherwise real -# B-tree corruption gets reported to the user as "free some disk space" -# (the misdiagnosis documented on #77386). +# "Database FILE structurally damaged" substrings. NOTE: "database disk image is +# malformed" contains "disk", so this check MUST run before the disk bucket in +# classify_persistence_error or B-tree corruption reads as "free some disk space". _DB_CORRUPTION_MARKERS = ( "malformed", # "database disk image is malformed" (SQLITE_CORRUPT) "file is not a database", # SQLITE_NOTADB (also connection-level poisoning) @@ -1371,53 +971,22 @@ _DB_CORRUPTION_MARKERS = ( def classify_persistence_error(exc_or_str) -> str: - """Classify a session-persistence failure into a coarse cause bucket. - - Fast-failing a turn on a SessionDB write error is deliberate (the - transcript would otherwise be lost on restart), but the *guidance* the - user gets must match the cause: sustained SQLite write-lock contention - ("database is locked" on a shared state.db) needs "storage was busy, - send it again", while a full disk or read-only database needs the - disk-space/permissions advice. Returns one of PERSISTENCE_ERROR_CAUSES: - - * ``"locked"`` — SQLite lock/busy contention (another process holds the - database write lock); transient, retry-later guidance applies. - * ``"compression"`` — a live compression lease refused the transcript - write; the database itself is healthy and unlocked. - * ``"compression_closed"`` — the write targeted a session already - rotated (closed) by compression and no live continuation was adopted; - the store is healthy — the client must refresh/adopt the new session - id, so disk-space advice would be a misdiagnosis. - * ``"turn_lease"`` — a presented session-turn-lease holder no longer - owns the conversation (expired, released, or reclaimed); fail-fast - fencing, not a storage fault. - * ``"corrupt"`` — the database file itself is structurally damaged - (``database disk image is malformed`` / SQLITE_NOTADB). Distinct from - ``"disk"``: freeing space cannot help, the user needs the repair path - (``hermes doctor`` / automatic schema surgery). - * ``"replaced"`` — the ``state.db`` path no longer names the file this - process opened (out-of-band ``cp``/``mv``/restore). In-file FTS repair - cannot help; writes to the live handle must stop. - * ``"disk"`` — disk full / read-only / permission-shaped failures - (delegates the disk-full patterns to :func:`is_disk_full_error` so the - two classifiers can never drift apart — e.g. ENOSPC). - * ``"unknown"`` — anything else (or no visible exception at all). - """ + """Coarse cause bucket (PERSISTENCE_ERROR_CAUSES) so the user's guidance + matches: "locked" = busy, retry; "disk" = full/read-only/permissions; + "compression" = a live lease refused the write; "compression_closed" = adopt + the rotated session id; "turn_lease" = fencing, not storage; "corrupt" = + file damage (repair path, not disk space); "replaced" = stop writing.""" if exc_or_str is None: return "unknown" - # A refused write during a live compression lease is contention, not - # storage damage — but its message ("is being compressed by another - # writer" / "Compression lease lost") contains neither "locked" nor - # "busy", so it must be matched by type and by phrase (for strings that - # survived RPC wrapping). + # Lease refusals contain neither "locked" nor "busy": match by type, then by + # phrase for strings that survived RPC wrapping. if isinstance(exc_or_str, SessionTurnLeaseLostError): return "turn_lease" if isinstance(exc_or_str, CompressionSessionClosedError): return "compression_closed" if isinstance(exc_or_str, CompressionSessionBusyError): return "compression" - if isinstance(exc_or_str, StateDbReplacedError): - # Includes DeletedWalGenerationError (subclass). + if isinstance(exc_or_str, StateDbReplacedError): # incl. DeletedWalGenerationError return "replaced" if isinstance(exc_or_str, StateDbCorruptError): return "corrupt" @@ -1432,95 +1001,49 @@ def classify_persistence_error(exc_or_str) -> str: return "replaced" if "deleted state.db-wal" in text or "deleted state.db-shm" in text: return "replaced" - # Structural corruption BEFORE the lock and disk buckets: "database disk - # image is malformed" contains "disk" (and some wrapped corruption - # strings mention "locked" recovery attempts), so later buckets would - # steal it and misdiagnose damage as space/contention. + # Corruption BEFORE the lock/disk buckets: "disk image is malformed" + # contains "disk" and some wrapped strings mention "locked" recovery. if any(marker in text for marker in _DB_CORRUPTION_MARKERS): return "corrupt" - if ( - "locked" in text - or "busy" in text - ): + if "locked" in text or "busy" in text: return "locked" - if ( - is_disk_full_error(exc_or_str) - or "disk" in text - or "readonly" in text - or "read-only" in text - ): + if is_disk_full_error(exc_or_str) or "disk" in text or "readonly" in text or "read-only" in text: return "disk" return "unknown" -# Cross-process serialisation for the schema-surgery paths below. The -# ``_repair_attempt_lock`` above is a ``threading.Lock`` — it only covers -# threads inside ONE interpreter, yet a normal Hermes host runs several -# independent processes against the same ``state.db``: the gateway service, -# the Desktop app's own ``hermes serve`` backend, interactive CLI sessions, -# and the TUI slash worker. Two of those hitting a malformed DB at once each -# ran the full ``writable_schema`` surgery + ``VACUUM`` on their own private -# connection, with nothing serialising them. -# -# The timeout is sized for the slowest legitimate holder — a ``VACUUM`` over a -# multi-GB DB in strategy 2. Waiting that long is not a new stall: before this -# lock the losing caller spent the same minutes running its own surgery, it -# just did so on top of the winner's. +# Cross-process schema-surgery lock: ``_repair_attempt_lock`` covers one +# interpreter only, while gateway, Desktop backend, CLI and TUI worker share the +# file and each used to run surgery + VACUUM on top of the winner's. Timeout +# sized for the slowest legitimate holder (VACUUM over a multi-GB DB). _REPAIR_LOCK_TIMEOUT_SECONDS = 120.0 _IS_WINDOWS = sys.platform == "win32" -# ── Repair-loop bounding + dead-backup hygiene (#86747) ───────────────────── -# -# ``_claim_repair_attempt`` above is an in-memory set: it bounds the loop -# only WITHIN one process. A corruption class the strategies cannot heal -# (b-tree page damage) failed repair on EVERY process start, and each pass -# took a fresh ~900MB forensic backup — 105 attempts / 89GB of identical -# dead copies in the reporting install. Two persistent bounds fix the class: -# -# * a sidecar attempt ledger (``.repair-attempts.json``) that refuses -# further surgery after ``_MAX_PERSISTENT_REPAIR_ATTEMPTS`` failures on -# the SAME damaged file (fingerprint = size + a bounded content sample; any -# successful repair or replacement changes it and resets the count); -# * backup dedupe + a retention cap in ``_backup_db_file`` — an identical -# damaged file is never copied twice, and only the newest -# ``_MAX_MALFORMED_BACKUPS`` forensic copies are kept. - +# Repair-loop bounding (hermes_state_repair): unhealable b-tree damage failed +# repair on every start, each pass taking a fresh ~900MB backup (89GB of +# identical copies). A sidecar attempt ledger (fingerprint = size + content +# sample) refuses surgery after _MAX_PERSISTENT_REPAIR_ATTEMPTS, and backups are +# deduped and capped at _MAX_MALFORMED_BACKUPS. # ── CJK-bigram FTS index (replaces the trigram index when available) ──── +# Trigram needs >=3 chars per term, so 1-2 char CJK terms fell through to a +# LIKE table scan (3-6s CPU per query on multi-GB installs). ``cjk_unicode61`` +# (native/fts5_cjk/, loadable) re-emits CJK runs as overlapping bigrams; FTS5 +# phrase semantics then give exact substring matching down to 2 chars. # -# The trigram tokenizer needs >=3 chars per query term, so 1-2 char CJK -# terms (ubiquitous in Korean/Chinese: 일본, 구글, 项目, ...) fall through -# to a LIKE full-table scan — measured 3-6s CPU per query on multi-GB -# installs and the dominant base cost of session_search on CJK workloads. +# Same v23 discipline as the trigram table: external-content over a +# tool-row-excluding view, triggers gated on a DEDICATED marker pair +# (fts_cjk_rebuild_high_water / _progress) so a cjk-only backfill never gates +# the complete messages_fts triggers. The table exists ONLY when the tokenizer +# loads (~/.hermes/lib/libfts5_cjk.so); a process that cannot load it drops the +# cjk triggers (writes keep working; the index goes stale until the next +# optimize-storage on a capable host). # -# ``cjk_unicode61`` (native/fts5_cjk/, a ~250-line loadable FTS5 tokenizer -# with no dependencies) wraps unicode61: maximal CJK runs are re-emitted as -# overlapping character bigrams (Lucene CJKAnalyzer semantics), everything -# else passes through unchanged. FTS5 phrase semantics turn a query term's -# consecutive bigrams into exact substring matching down to 2 chars at -# index speed. Contributed by Soju06 (PR #65544). -# -# Same v23 storage discipline as the trigram table it replaces: -# external-content over a tool-row-excluding view (zero inline text -# copies; tool rows stay searchable via ``messages_fts``), triggers gated -# on a DEDICATED marker pair (``fts_cjk_rebuild_high_water`` / -# ``fts_cjk_rebuild_progress``) so a cjk-only backfill — e.g. the -# trigram→cjk upgrade on an already-optimized DB — never gates the -# complete ``messages_fts`` index's triggers. -# -# The table exists ONLY when the loadable tokenizer is available -# (``~/.hermes/lib/libfts5_cjk.so``, built by ``native/fts5_cjk/build.sh``). -# A process that cannot load it self-heals by dropping the cjk triggers -# (message writes keep working; the index goes stale and is rebuilt by the -# next ``hermes sessions optimize-storage`` on a capable host). -# -# Split DDL: the table/view part is safe to ensure any time; the triggers -# are created ONLY while the index is complete-or-marker-gated. A stale -# index (trigger gap of unknown extent) must keep its triggers DROPPED — -# an external-content 'delete' op for a rowid the index never held is the -# canonical FTS5 index-corruption hazard the v23 marker gating exists to -# prevent. +# Split DDL: the table/view is safe to ensure any time; triggers are created +# ONLY while the index is complete-or-marker-gated. A stale index must keep its +# triggers DROPPED — an external-content 'delete' for a rowid the index never +# held is the canonical FTS5 corruption hazard the marker gating prevents. FTS_CJK_TABLE_SQL = """ CREATE VIEW IF NOT EXISTS messages_fts_cjk_src AS SELECT id, role, content, tool_name, tool_calls @@ -1590,19 +1113,13 @@ def fts5_cjk_so_path() -> Path: def _cjk_fts_config_enabled() -> bool: """config.yaml ``sessions.cjk_fts`` (default on), via its env bridge.""" - return os.getenv("HERMES_CJK_FTS", "1").strip().lower() not in ( - "0", "false", "off", "no", - ) + return os.getenv("HERMES_CJK_FTS", "1").strip().lower() not in ("0", "false", "off", "no") def load_fts5_cjk_extension(conn: sqlite3.Connection) -> bool: - """Best-effort load of the cjk_unicode61 tokenizer into ``conn``. - - Returns False (never raises) when the .so is absent, the feature is - disabled via ``sessions.cjk_fts``, or this Python build has extension - loading compiled out — every caller treats False as "behave exactly as - before the cjk index existed". - """ + """Best-effort load of the cjk_unicode61 tokenizer. False (never raises) + when the .so is absent, ``sessions.cjk_fts`` is off, or extension loading + is compiled out — callers then behave as before the cjk index existed.""" if not _cjk_fts_config_enabled(): return False path = fts5_cjk_so_path() @@ -1636,66 +1153,40 @@ class CompressionSessionBusyError(RuntimeError): class SessionCompressionInProgressError(CompressionSessionBusyError): - """A concurrent writer collided with a *live* compression lock. - - Split out from :class:`CompressionSessionBusyError` because the two - conditions that class covers need opposite handling. This one is - transient: a healthy compressor holds the session for a few seconds and - the lock row carries its own ``expires_at``, so the write can simply wait - (see ``_execute_write``'s patience loop). The other case, a compressor - discovering its own lease is gone, is permanent and must fail fast rather - than spin out the whole patience budget. - - Subclassing keeps every existing ``except CompressionSessionBusyError`` - handler working unchanged. - """ + """A concurrent writer collided with a *live* compression lock — transient + (the compressor publishes in seconds; ``_execute_write`` waits), unlike the + parent class's other case (a compressor whose own lease is gone: permanent, + fail fast). Subclassing keeps every existing handler working.""" class SessionTurnLeaseLostError(RuntimeError): """A transcript write presented a turn-lease holder that no longer owns it. - - Fail-fast fencing: do not retry inside ``_execute_write``. The caller - either still thinks it owns the conversation after expiry/reclaim, or - the lease row is gone. A later writer may already be persisting a - newer turn; landing this write would interleave a stale reply. - """ + Fail-fast fencing (no ``_execute_write`` retry): a later writer may already + be persisting a newer turn, and landing this one would interleave a stale reply.""" class StateDbReplacedError(RuntimeError): - """The state.db path no longer names the file this SessionDB opened. - - Raised when an out-of-band ``cp``/``mv``/restore replaces the database - under a live gateway. In-place FTS repair and fail-open trigger - dropping cannot fix a generation mismatch; they amplify it. - """ + """The state.db path no longer names the file this SessionDB opened + (out-of-band cp/mv/restore). In-place FTS repair and fail-open trigger + dropping cannot fix a generation mismatch; they amplify it.""" class DeletedWalGenerationError(StateDbReplacedError): - """A live process holds a deleted state.db-wal / -shm generation. - - Opening or writing through this handle would mint a second WAL inode - (or keep committing on the orphan) — the split-brain that produces - intermittent SQLITE_CORRUPT / SQLITE_IOERR. Stop the writers; do not - unlink the WAL yourself. ``database.journal_mode: delete`` is operator - containment, not a default change. - - Subclasses :class:`StateDbReplacedError` so every downstream consumer - that already stops SQLite writes and diverts pending transcripts on a - replaced store (gateway retry queue, run_agent flush) handles the split - WAL generation identically — the correct response is the same: stop - writing, preserve the transcript tail on disk. - """ + """A live process holds a deleted state.db-wal / -shm generation. Opening or + writing through this handle would mint a second WAL inode (split-brain -> + intermittent SQLITE_CORRUPT / IOERR). Stop the writers; never unlink the WAL + yourself. Subclasses StateDbReplacedError so every consumer that diverts + transcripts on a replaced store handles this identically.""" -# SQLite header: 4-byte big-endian application_id at offset 68. Distinct from -# inode: ``cp`` onto the same path keeps st_ino and truncates+rewrites. +# SQLite header application_id (offset 68). Distinct from inode: ``cp`` onto the +# same path keeps st_ino and truncates+rewrites. _STATE_DB_APPLICATION_ID_OFFSET = 68 _STATE_DB_GENERATION_KEY = "db_file_generation" _STATE_DB_REPLACED_MSG = ( "FATAL: state.db was replaced underneath the gateway; refusing further " "writes to this file. Divert transcripts to sessions/.jsonl (and the " - "gateway pending_messages spool) and restore or reopen after operator " - "intervention." + "gateway pending_messages spool) and restore or reopen after operator intervention." ) _DELETED_WAL_GENERATION_MSG = ( "FATAL: a live process holds a deleted state.db-wal or state.db-shm " @@ -1708,32 +1199,13 @@ _DELETED_WAL_GENERATION_MSG = ( class StateDbCorruptError(sqlite3.DatabaseError): - """A live SessionDB observed structural (non-FTS) corruption and is quarantined. - - Raised once a write on this handle reports bare ``SQLITE_CORRUPT`` / - ``SQLITE_NOTADB`` that is neither FTS-scoped (``_is_fts_write_corruption_error``) - nor a replaced-file case (``StateDbReplacedError``). Subclasses - ``sqlite3.DatabaseError`` so every existing ``except sqlite3.Error`` - degrade path keeps working; ``sqlite_errorcode``/``sqlite_errorname`` - are copied from the originating error. - - The quarantine is sticky for the life of the handle: later writes fail - fast, the handle never reopens after ``close()``, and ``close()`` skips - its own WAL checkpoint. Field evidence (the #90837 lost/reordered-page - signature, the #90950 page-1 clobber): a handle that kept writing for ~50 - minutes after the first structural error checkpointed 15 pages under the - wrong page numbers on shutdown, turning a still-readable file into - ``file is not a database``. Stopping the writes is what prevents that; - skipping the explicit checkpoint is the second line of defence. SQLite - still runs its own last-connection checkpoint inside ``close()`` (and - deletes the ``-wal`` sidecar) unless ``SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE`` - is set — Python exposes it via ``Connection.setconfig()`` on 3.12+, so - quarantine disables the close-time checkpoint there and the WAL survives - on disk for forensics; on 3.11 the internal checkpoint is unavoidable - (post-quarantine it can only carry pre-corruption committed frames, since - no further writes are accepted). The - recovery boundary is a process restart on a repaired or restored file. - """ + """A live SessionDB observed structural (non-FTS, non-replaced) corruption and + is quarantined: sticky for the handle's life — writes fail fast, no reopen, + no close-time checkpoint (a handle that kept writing after the first error + checkpointed 15 pages under wrong page numbers and turned a readable file + into "file is not a database"; SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE on 3.12+ + also stops SQLite's own). Subclasses sqlite3.DatabaseError so every degrade + path keeps working. Recovery boundary: restart on a repaired/restored file.""" _STATE_DB_CORRUPT_MSG = ( @@ -1747,12 +1219,8 @@ _STATE_DB_CORRUPT_MSG = ( def divert_session_transcript_jsonl(session_id: str, messages) -> "Optional[Path]": - """Append pending messages as JSON lines under HERMES_HOME/sessions. - - Used when state.db is replaced under a live process so the current - turn is not only in RAM. Returns the jsonl path, or None when there - is nothing to write. - """ + """Append pending messages to HERMES_HOME/sessions/.jsonl (state.db was + replaced under a live process). Returns the path, or None if nothing to write.""" sid = str(session_id or "").strip() if not sid or not messages: return None @@ -1768,79 +1236,47 @@ def divert_session_transcript_jsonl(session_id: str, messages) -> "Optional[Path return path -# ── Process-wide shared SessionDB registry (#90837) ── -# -# The registry itself lives in hermes_state_registry.py — a bounded -# module owning acquisition, generation identity, refcounting, -# retirement, and teardown. These re-exports keep the historical -# import path (``from hermes_state import get_shared_session_db``) -# working for every call site and test that imports from here. -# -# Routing rules (see hermes_state_registry for the full lifecycle): -# - Long-lived in-process callers (gateway, tui_gateway, cron, -# in-process tools) share ONE writer connection per resolved path -# via get_shared_session_db(). -# - CLI one-shots, recovery flows, and read-only cross-profile opens -# keep using SessionDB() directly with their own close(). - +# ── Process-wide shared SessionDB registry ── +# Lives in hermes_state_registry.py; re-exported here for the historical import +# path. Long-lived in-process callers (gateway, tui_gateway, cron, in-process +# tools) share ONE writer connection per resolved path via +# get_shared_session_db(); CLI one-shots, recovery flows and read-only +# cross-profile opens use SessionDB() directly with their own close(). from hermes_state_registry import ( # noqa: F401 (re-export) - close_shared_session_dbs, - get_shared_session_db, - release_or_close, - release_shared_session_db, + close_shared_session_dbs, get_shared_session_db, release_or_close, release_shared_session_db, ) - -# ── Read-only health/stats probes (hermes doctor, dashboards) ────────── - - -# Lifecycle statuses surfaced by session pickers. Classification looks ONLY at -# a session's final message row — role, whether it carries tool_calls, and its -# finish_reason — so it stays O(1) per session (see -# SessionDB.session_lifecycle_statuses). +# Lifecycle statuses surfaced by session pickers; classified from the final +# message row ONLY (role, tool_calls, finish_reason) so it stays O(1) per session. SESSION_STATUS_COMPLETE = "complete" SESSION_STATUS_INTERRUPTED = "interrupted" SESSION_STATUS_ERROR = "error" SESSION_STATUS_EMPTY = "empty" -# finish_reason values that mark the turn as having ended in a provider or -# agent error (vs. a normal 'stop'/'length'/'tool_calls' completion). +# finish_reason values meaning the turn ended in a provider/agent error. _ERROR_FINISH_REASONS = frozenset({"error", "agent_error", "content_filter"}) def classify_session_status( - role: Optional[str], - has_tool_calls: bool, - finish_reason: Optional[str], + role: Optional[str], has_tool_calls: bool, finish_reason: Optional[str], ) -> str: - """Classify a session's lifecycle from the shape of its final message. - - - assistant with a normal finish → ``complete`` - - assistant that still has pending tool_calls (no tool result row ever - followed, or it would be the last row instead) → ``interrupted`` - - user or tool as the last row → ``interrupted`` (the agent never got to - answer / never consumed the tool result) - - an error finish_reason on the last row → ``error`` - - anything unrecognized → ``complete`` (benign default; pickers must not - alarm on unknown shapes) - """ + """Lifecycle from the final message: error finish → ``error``; assistant + with pending tool_calls (result never landed), or a trailing user/tool row → + ``interrupted``; normal assistant finish or unknown shape → ``complete`` + (benign default; pickers must not alarm on unknown shapes).""" if (finish_reason or "").strip().lower() in _ERROR_FINISH_REASONS: return SESSION_STATUS_ERROR r = (role or "").strip().lower() if r == "assistant": - # The last row being an assistant message WITH tool_calls means the - # matching tool result never landed — an interrupted tool turn. return SESSION_STATUS_INTERRUPTED if has_tool_calls else SESSION_STATUS_COMPLETE if r in {"user", "tool"}: return SESSION_STATUS_INTERRUPTED return SESSION_STATUS_COMPLETE -# Parent→child ``profile_name`` inheritance fence (#88381). ``agent::...`` -# gateway keys encode the profile namespace; a keyless row (CLI / subagent -# lineage) carries none and inherits freely. Two keyed rows must agree on -# ``agent::`` — a default child (``agent:main:``) forked from a sibling -# profile's row must not be durably mislabelled as that profile's. +# Parent→child profile_name inheritance fence: keyless rows (CLI / subagent) +# inherit freely; two ``agent::...`` keyed rows must agree on the namespace +# so a default child forked from a sibling profile's row isn't mislabelled. _SAME_KEY_NAMESPACE_SQL = ( "p.session_key IS NULL OR sessions.session_key IS NULL" " OR substr(p.session_key, 1, instr(substr(p.session_key, 7), ':') + 6)" @@ -1849,116 +1285,62 @@ _SAME_KEY_NAMESPACE_SQL = ( class SessionDB( - SessionSearchMixin, - SessionSchemaMixin, - SessionPortabilityMixin, - SessionTelegramTopicsMixin, - SessionCompressionMixin, - SessionGatewayMixin, - SessionMaintenanceMixin, - SessionUsageMixin, - SessionTitlesMixin, - SessionMessagesMixin, + SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin, SessionTelegramTopicsMixin, + SessionCompressionMixin, SessionGatewayMixin, SessionMaintenanceMixin, SessionUsageMixin, + SessionTitlesMixin, SessionMessagesMixin, ): - """ - SQLite-backed session storage with FTS5 search. + """SQLite-backed session storage with FTS5 search. Thread-safe for the gateway + pattern (many reader threads, one writer via WAL); each method opens its own cursor.""" - Thread-safe for the common gateway pattern (multiple reader threads, - single writer via WAL mode). Each method opens its own cursor. - """ - - # Only these state-owned producers participate in automatic stale-open - # reconciliation. Messaging-platform and UI/desktop sources have separate - # lifecycle owners; unknown/future sources fail closed (#60609). + # Only these state-owned producers join automatic stale-open reconciliation; + # messaging/UI sources have their own lifecycle owners; unknown sources fail closed. _AUTO_PRUNE_STALE_OPEN_SOURCES: Tuple[str, ...] = ( - "cli", - "cron", - "kanban", - "acp", - "api_server", - "subagent", - "tool", + "cli", "cron", "kanban", "acp", "api_server", "subagent", "tool", ) # ── Write-contention tuning ── - # With multiple hermes processes (gateway + CLI sessions + worktree agents) - # all sharing one state.db, WAL write-lock contention causes visible TUI - # freezes. SQLite's built-in busy handler uses a deterministic sleep - # schedule that causes convoy effects under high concurrency. - # - # Instead, we keep the SQLite timeout short (1s) and handle retries at the - # application level with random jitter, which naturally staggers competing - # writers and avoids the convoy. - # - # Patience is TIME-based, not attempt-based. A shared state.db is - # legitimately held for multi-second stretches by sibling Hermes - # processes: a TRUNCATE checkpoint at close on a large WAL, VACUUM after - # an auto-prune, offline recovery, or an older still-running process - # whose FTS maintenance predates the bounded-merge protocol (every - # `hermes update` leaves mixed-version processes sharing the DB until - # the old ones exit). An attempt-counted budget (~15s incidental worst - # case) silently loses that race and surfaces as - # session_persistence_failed — a destroyed turn — even though the store - # is healthy and merely busy (#74478). - # - # Two budgets: routine writes give up after _WRITE_PATIENCE_S so - # background/UI callers don't stall excessively, while transcript - # writes (append_message / session-row creation — the ones whose - # failure aborts the user's turn) ride out anything shorter than - # _TRANSCRIPT_WRITE_PATIENCE_S. Jitter stays small for the first - # _WRITE_RETRY_SLOW_AFTER_S (fast reclaim on millisecond contention), - # then backs off so a long hold isn't hammered with BEGIN IMMEDIATE - # attempts. + # SQLite's deterministic busy handler convoys under many hermes processes, + # so the SQLite timeout stays short (1s) and retries use random jitter. + # Patience is TIME-based: a sibling legitimately holds the lock for seconds + # (TRUNCATE checkpoint at close, VACUUM after auto-prune, recovery, an older + # process's unbounded FTS optimize); an attempt-counted budget lost that race + # and destroyed the turn as session_persistence_failed on a healthy store. + # Routine writes give up after _WRITE_PATIENCE_S; transcript writes (whose + # failure aborts the user's turn) get _TRANSCRIPT_WRITE_PATIENCE_S. Jitter + # stays small for _WRITE_RETRY_SLOW_AFTER_S, then backs off. _WRITE_PATIENCE_S = 20.0 _TRANSCRIPT_WRITE_PATIENCE_S = 60.0 - # Observation-only activity heartbeat/label writes (#76354 review S1): - # these run on (or adjacent to) the response-critical path and must never - # wait out the full routine patience under contention. Sub-second budget; - # a skipped write is retried naturally at the next heartbeat window. + # Observation-only activity heartbeat/label writes sit on the response- + # critical path: sub-second budget; a skipped write retries next window. _ACTIVITY_WRITE_PATIENCE_S = 0.5 - # A live compression lock gets its own, much shorter budget than the write - # lock. Compression publishes in a couple of seconds, so a brief wait saves - # the overwhelming majority of concurrent turns (#75083). It deliberately - # stays short: the lease is a correctness boundary, not just a busy signal - # (see test_compression_lease_blocks_non_owner_but_allows_owner_flush), so - # a writer that is still locked out after this budget must still be - # refused rather than allowed to land a stale turn in a session whose - # compression is genuinely long-running or wedged. + # A live compression lock gets a short budget: compression publishes in a + # couple of seconds, so a brief wait saves most concurrent turns — but the + # lease is a correctness boundary, so a writer still locked out afterwards + # must be refused rather than land a stale turn in a wedged compression. _COMPRESSION_BUSY_WAIT_S = 5.0 _WRITE_RETRY_MIN_S = 0.020 # 20ms _WRITE_RETRY_MAX_S = 0.150 # 150ms _WRITE_RETRY_SLOW_AFTER_S = 2.0 _WRITE_RETRY_SLOW_MIN_S = 0.250 # 250ms _WRITE_RETRY_SLOW_MAX_S = 1.000 # 1s - # Attempt a WAL checkpoint every N successful writes (PASSIVE mode). + # PASSIVE WAL checkpoint every N successful writes. _CHECKPOINT_EVERY_N_WRITES = 50 - # Retain the existing coarse 1000-write maintenance cadence, but replace - # the unbounded FTS5 ``'optimize'`` (measured holding the write lock for - # 9-18 s per index on a 10 GB production DB — longer than a competing - # writer's full retry patience, surfacing as "database is locked" / - # session_persistence_failed) with bounded ``'merge'`` commands. A - # positive merge rank is an approximate output-page budget, so each - # command holds the write lock for milliseconds; up to - # ``_FTS_MERGE_COMMANDS_PER_PASS`` commands run per index per cadence, - # stopping early on the documented no-progress signal. ``usermerge`` is - # lowered to 2 so positive merges act on any level with >= 2 segments — - # without that, levels below the default threshold of 4 are skipped and - # a fragmented index never converges (SQLite FTS5 §6.8-6.9). + # Bounded FTS ``'merge'`` (milliseconds of lock each) instead of ``'optimize'`` + # (9-18s per index on a 10GB DB — longer than a writer's patience); up to + # _FTS_MERGE_COMMANDS_PER_PASS per index, stopping on no-progress. usermerge + # is lowered to 2 so levels with >= 2 segments merge (default 4 never converges). _FTS_MERGE_EVERY_N_WRITES = 1000 _FTS_MERGE_MAX_PAGES_PER_INDEX = 500 _FTS_MERGE_COMMANDS_PER_PASS = 4 - # Session imports intentionally use a lower cap than exports: import holds - # one BEGIN IMMEDIATE transaction, so bounded batches avoid starving live - # gateway/CLI writers. The dashboard accepts one exported JSON/JSONL file - # at a time, so these still cover normal history restores. + # Imports cap lower than exports: an import holds one BEGIN IMMEDIATE, so + # bounded batches avoid starving live writers (one dashboard file at a time). _IMPORT_MAX_SESSIONS = 500 _IMPORT_MAX_MESSAGES_PER_SESSION = 10_000 _IMPORT_MAX_TOTAL_MESSAGES = 50_000 _IMPORT_MAX_SESSION_BYTES = 5 * 1024 * 1024 _IMPORT_MAX_TOTAL_BYTES = 25 * 1024 * 1024 - # Demand-started accounting workers retire after an idle window so their - # bound targets do not keep abandoned SessionDB instances (and SQLite - # descriptors) alive forever. A later enqueue starts a fresh worker. + # Accounting workers retire when idle so a bound-method target can't keep an + # abandoned SessionDB (and its descriptors) alive; a later enqueue restarts one. _TOKEN_WRITER_IDLE_SECONDS = 30.0 @staticmethod @@ -1975,11 +1357,8 @@ class SessionDB( @staticmethod def _delete_unreferenced_system_prompts(conn) -> None: conn.execute( - "DELETE FROM system_prompts " - "WHERE NOT EXISTS (" - "SELECT 1 FROM sessions " - "WHERE sessions.system_prompt_hash = system_prompts.hash" - ")" + "DELETE FROM system_prompts WHERE NOT EXISTS (" + "SELECT 1 FROM sessions WHERE sessions.system_prompt_hash = system_prompts.hash)" ) @staticmethod @@ -2003,330 +1382,89 @@ class SessionDB( def __init__(self, db_path: Path = None, read_only: bool = False): self.db_path = db_path or _default_db_path() - # Fail hard (before any connection/pragma/mkdir) if a pytest-context - # process resolved the developer's production state.db — see the - # live-DB test-isolation guard block near _default_db_path(). - _ensure_test_isolation(self.db_path) + _ensure_test_isolation(self.db_path) # before any connection/pragma/mkdir self.read_only = read_only - self._lock = threading.Lock() - # Read-path split (WAL only): recall/browse queries borrow a - # read-only connection from a bounded pool so they never queue - # behind writer flushes on self._lock. See _read_ctx(). - # - # The pool is BOUNDED because the previous per-thread - # (threading.local + strong set) scheme pinned one connection per - # (SessionDB x thread) for the life of the process. Starlette - # dispatches sync routes on anyio worker threads, so a SessionDB - # that is never closed accumulated a connection — and two fds, the - # database and its -wal — for every worker thread that ever read, - # until the process hit the 256 soft RLIMIT_NOFILE a service manager - # hands it and every request failed with EMFILE while the process - # stayed alive, so the supervisor's restart-on-exit never fired. - # Same bug class as the closing(...) fix in gateway/readiness.py - # (#69678 / #69567). - self._read_pool: "queue.LifoQueue[sqlite3.Connection]" = queue.LifoQueue( - maxsize=_READ_POOL_MAX - ) - # One permit per live read connection, held from before the open in - # _get_read_conn() until after the close in _close_read_conn(). This - # is what bounds PEAK descriptors; _read_pool alone bounds only the - # idle set. See _READ_POOL_MAX. Acquired non-blocking on purpose: a - # reader that cannot get a permit must degrade to the writer lock, not - # queue here — blocking would convert fd exhaustion into a stall, which - # is the same outage with a different stack trace. - # - # Permits are shared per DATABASE PATH, not per instance: the - # descriptors they ration belong to the file, and one process holds - # several SessionDB objects on the same state.db (#98573). See - # _PathReadBudget. + # Read-path split (WAL only): reads borrow a read-only connection from a + # BOUNDED pool so they never queue behind writer flushes on self._lock + # (see _read_ctx). The old per-thread scheme pinned one connection (two + # fds) per SessionDB x anyio worker thread for the process lifetime until + # a 256 RLIMIT_NOFILE service hit EMFILE while staying alive, so the + # supervisor's restart-on-exit never fired. + self._read_pool: "queue.LifoQueue[sqlite3.Connection]" = queue.LifoQueue(maxsize=_READ_POOL_MAX) + # Permits bound PEAK descriptors (the pool bounds only the idle set) and + # are shared per DATABASE PATH (see _PathReadBudget). Acquired + # non-blocking on purpose: a reader without a permit degrades to the + # writer lock — blocking would turn fd exhaustion into a stall. self._read_budget = _read_budget_for(self.db_path) self._read_budget.register(self) - # Bound to the semaphore itself so every release site - # (_close_read_conn and the _get_read_conn failure paths) is unchanged. + # Bound to the semaphore itself so every release site is unchanged. self._read_permits = self._read_budget.permits - # Count of reads that found no permit and fell back to the locked - # writer connection. Not load-bearing; it is the only externally - # visible signal that the ceiling is actually being reached, so a - # too-small _READ_POOL_MAX is diagnosable from a running process - # instead of inferred from latency. + # Reads that fell back to the writer connection — the only visible + # signal that the ceiling is being reached (diagnostic, not load-bearing). self._read_permit_exhausted = 0 self._read_conns_lock = threading.Lock() - # Set when close() begins. _read_ctx checks this under the lock - # before returning a connection to the pool, so a reader still in - # flight during the drain closes its own connection instead of - # re-populating a pool nobody will drain again. + # Set when close() begins; a reader still in flight then closes its own + # connection instead of re-populating a pool nobody will drain again. self._read_conns_closed = False - # "read-only opens are failing against this file" backoff stamp. - # Instance-wide rather than per-thread: with a shared pool the open - # is no longer a per-thread event, and retrying a known-bad open on - # every query is a syscall storm for no benefit. The locked writer - # connection still serves reads while the backoff holds. - # Deliberately a TIMESTAMP, not a sticky bool: the likeliest trigger - # is transient fd pressure (EMFILE) — the very condition this pool - # exists to prevent — and a permanent flag would demote every reader - # on this instance to the writer lock for the life of the process. - # The gateway shares one SessionDB across every agent, so that turns - # a momentary blip into a permanent global convoy. Expires after - # _READ_OPEN_RETRY_SECONDS so the read path self-heals. + # "read-only opens are failing" backoff stamp — a TIMESTAMP, not a sticky + # bool: the likeliest trigger is transient EMFILE, and a permanent flag + # would demote every reader (the gateway shares one SessionDB across all + # agents) to the writer lock forever. Expires after _READ_OPEN_RETRY_SECONDS. self._read_open_failed_at = 0.0 self._wal_active = False self._write_count = 0 - # File identity of the state.db this instance opened. Compared on - # every write (and before FTS fail-open / reopen-after-close) so an - # out-of-band replace cannot limp through in-place surgery. - # Inode catches mv/new-file; application_id catches cp onto the - # same path (same inode, truncate+rewrite). + # File identity of the opened state.db, compared on every write (and + # before FTS fail-open / reopen) so an out-of-band replace cannot limp + # through in-place surgery. Inode catches mv/new-file; application_id + # catches cp onto the same path (same inode, truncate+rewrite). self._db_file_identity: Optional[tuple] = None self._db_file_application_id: int = 0 self._db_file_generation_token: str = "" - self._db_replaced = False - # Sticky: set once a write on THIS handle reports bare SQLITE_CORRUPT / - # NOTADB that is not FTS-scoped and not a replaced-file case. Never - # cleared; the recovery boundary is a process restart on a repaired or - # restored file (see StateDbCorruptError). + self._db_sidecar_identity: Dict[str, tuple] = {} + self._db_replaced = self._db_wal_generation_lost = False + # Sticky quarantine (see StateDbCorruptError); never cleared. self._db_corrupt = False self._db_corrupt_reason = "" - self._db_sidecar_identity: Dict[str, tuple] = {} - self._db_wal_generation_lost = False - # One-shot guard for the usermerge-floor config write on the - # incremental FTS merge cadence (see _merge_fts_incrementally). - self._fts_usermerge_floor_applied = False - self._fts_enabled = False - self._fts_stale = False - self._trigram_available = False - # CJK-bigram index (cjk_unicode61 loadable tokenizer). _fts_cjk_loaded: - # extension present on the writer connection; _fts_cjk_available: the - # messages_fts_cjk table is queryable AND not marked stale. Set during - # _init_schema / _probe_fts_cjk. - self._fts_cjk_loaded = False - self._fts_cjk_available = False - self._fts_unavailable_warned = False + self._fts_usermerge_floor_applied = False # one-shot usermerge-floor write guard + self._fts_enabled = self._fts_stale = self._trigram_available = False + # _fts_cjk_loaded: tokenizer extension present on the writer connection; + # _fts_cjk_available: messages_fts_cjk is queryable AND not marked stale. + self._fts_cjk_loaded = self._fts_cjk_available = self._fts_unavailable_warned = False self._conn = None - # Async token accounting (see queue_token_counts). The condition - # guards queue + writer state; it is distinct from self._lock so - # enqueue/flush bookkeeping never contends with SQLite writes. + # Async token accounting (queue_token_counts). Distinct from self._lock + # so enqueue/flush bookkeeping never contends with SQLite writes. self._token_queue: deque = deque() self._token_queue_cond = threading.Condition(threading.Lock()) self._token_writer_thread: Optional[threading.Thread] = None - self._token_writer_stop = False - self._token_writer_busy = False + self._token_writer_stop = self._token_writer_busy = False self._token_atexit_hook: Optional[Callable[[], None]] = None - # Set True when this instance is opened via get_shared_session_db(). - # Makes close() a no-op so the registry (not individual callers) - # controls the connection lifecycle (#90837). + # Opened via get_shared_session_db(): close() releases a refcount instead. self._shared_registry_owned = False initialization_complete = False try: if read_only: - # Read-only attach for cross-profile aggregation: SELECT-only, - # so we skip schema init entirely (no DDL, no FTS probe, no - # column reconcile). Crucially this takes NO write lock, so - # polling another profile's live DB on every sidebar refresh - # never contends with that profile's running backend. The DB - # must already exist + be initialised (callers guard on - # db_path.exists()); a SELECT against an empty file raises and - # the caller degrades per-profile. - open_attempt = 0 - while True: - try: - self._conn = _connect_tracked_db( - f"file:{self.db_path}?mode=ro", - tracking_path=self.db_path, - uri=True, - check_same_thread=False, - timeout=1.0, - isolation_level=None, - ) - self._conn.row_factory = sqlite3.Row - # FTS capability flags normally come from writable schema - # initialisation. Probe existing virtual tables with - # SELECTs only so read-only search keeps its FTS and - # trigram paths. Close the connection on ANY probe - # failure (e.g. malformed schema raises DatabaseError, - # not the OperationalError the probe handles). The - # constructor's outer finally also covers failures - # before this probe and BaseException paths, so a - # leaked tracked connection cannot block - # _backup_db_file's raw-copy for the rest of the - # process — the writable heal that follows would then - # repair WITHOUT its forensic backup. - try: - apply_database_pragmas(self._conn, db_label="state.db") - cursor = self._conn.cursor() - self._fts_enabled = ( - self._fts_table_probe(cursor, "messages_fts") - is True - ) - if self._fts_enabled: - self._trigram_available = ( - self._fts_table_probe( - cursor, - "messages_fts_trigram", - ) - is True - ) - except BaseException: - conn, self._conn = self._conn, None - try: - conn.close() - except Exception: - pass - raise - break - except sqlite3.OperationalError as ioerr: - # A WAL checkpoint / reset / frame-flush in flight on - # the writer side can surface SQLITE_IOERR to a - # concurrent mode=ro reader (it cannot perform the - # recovery the read needs — recovery writes the -shm - # index, which mode=ro refuses). The transition closes - # in milliseconds, so retry a bounded number of times - # before classifying the store as failed (#100436). - if not _is_transient_read_only_ioerr( - ioerr, attempt=open_attempt - ): - raise - open_attempt += 1 - time.sleep(_READ_ONLY_IOERR_RETRY_BACKOFF_S) + self._open_read_only() self._record_db_file_identity() initialization_complete = True return - self.db_path.parent.mkdir(parents=True, exist_ok=True) - - # Read-only file/sidecar preflight (port of kilocode#12508): - # repair-or-refuse BEFORE the first connection so users get an - # actionable message instead of an opaque "attempt to write a - # readonly database" from deep inside _init_schema. + # Read-only file/sidecar preflight: repair-or-refuse BEFORE the first + # connection, for an actionable message instead of an opaque "attempt + # to write a readonly database" from deep inside _init_schema. if not read_only: preflight_db_writability(self.db_path, db_label="state.db") - - # #68474 / #97568: Serialize startup across zero-byte check, quarantine, - # connect, and schema commit so concurrent openers don't race on an - # absent-path -> connect -> schema-commit window. - needs_startup_guard = ( - not read_only - and ( - not self.db_path.exists() - or is_zeroed_state_db(self.db_path) - ) + # Serialize zero-byte check, quarantine, connect and schema commit so + # concurrent openers don't race the absent-path -> schema-commit window. + needs_startup_guard = not read_only and ( + not self.db_path.exists() or is_zeroed_state_db(self.db_path) ) - - def _handle_quarantine_if_zeroed(already_locked: bool = False): - if ( - self.db_path.exists() - and is_zeroed_state_db(self.db_path) - ): - try: - zsize = self.db_path.stat().st_size - except OSError: - zsize = -1 - qpath = quarantine_zeroed_state_db( - self.db_path, already_locked=already_locked - ) - snaps = self.db_path.parent / "state-snapshots" - msg = ( - f"state.db looks ZEROED ({zsize} bytes, no SQLite header). " - f"Preserved at {qpath or '(quarantine failed — file left in place)'}. " - f"Restore from {snaps} via `hermes snapshot list` / " - f"`hermes snapshot restore ` if available. " - "Opening a fresh empty database so the agent can start." - ) - logger.error(msg) - _set_last_init_error(msg) - # If quarantine failed, do not open the zeroed file (would fail - # opaquely or risk further damage). Raise with the clear message. - if qpath is None and self.db_path.exists() and is_zeroed_state_db(self.db_path): - raise sqlite3.DatabaseError(msg) - - def _connect_and_init(): - # Refuse before sqlite3.connect (under the startup lock) so we - # cannot mint a replacement WAL while a live writer still - # holds a deleted sidecar inode. - refuse_deleted_wal_generation(self.db_path) - self._conn = _connect_tracked_db( - str(self.db_path), - check_same_thread=False, - # Short timeout — application-level retry with random - # jitter handles contention instead of sitting in - # SQLite's internal busy handler for up to 30s. - timeout=1.0, - # auto-starts transactions on DML, which conflicts with - # our explicit BEGIN IMMEDIATE. None = we manage - # transactions ourselves. - isolation_level=None, - ) - self._conn.row_factory = sqlite3.Row - self._wal_active = ( - apply_wal_with_fallback(self._conn, db_label="state.db") == "wal" - ) - apply_database_pragmas(self._conn, db_label="state.db") - self._conn.execute("PRAGMA foreign_keys=ON") - self._fts_cjk_loaded = load_fts5_cjk_extension(self._conn) - self._init_schema() - - def _connect_and_init_with_lock_patience(): - # Lock contention during open: _init_schema's DDL/reconcile - # statements run on a 1s-timeout connection with no retry, so - # a sibling process holding the write lock (VACUUM, TRUNCATE - # checkpoint at close, a long FTS pass from an older - # still-running install) used to fail the ENTIRE open — - # callers then disable persistence for the whole run - # ("Failed to initialize SessionDB ... database is locked", - # #74478). The store is healthy; wait it out with the same - # jittered patience the write path uses. Non-lock errors - # (including the malformed class) propagate immediately. - deadline = time.monotonic() + self._WRITE_PATIENCE_S - while True: - try: - _connect_and_init() - return - except sqlite3.OperationalError as exc: - err = str(exc).lower() - if "locked" not in err and "busy" not in err: - raise - try: - if self._conn is not None: - self._conn.close() - except Exception: - pass - now = time.monotonic() - if now >= deadline: - raise - time.sleep( - min( - random.uniform( - self._WRITE_RETRY_SLOW_MIN_S, - self._WRITE_RETRY_SLOW_MAX_S, - ), - max(deadline - now, 0.001), - ) - ) - - def _open_with_optional_startup_guard(): - if needs_startup_guard: - with quarantine_cross_process_lock(self.db_path) as lock_acquired: - if not lock_acquired: - logger.warning( - "startup quarantine lock for %s not acquired within 5s; proceeding", - self.db_path, - ) - _handle_quarantine_if_zeroed(already_locked=lock_acquired) - _connect_and_init_with_lock_patience() - else: - _handle_quarantine_if_zeroed(already_locked=False) - _connect_and_init_with_lock_patience() - try: - _open_with_optional_startup_guard() + self._open_with_optional_startup_guard(needs_startup_guard) except sqlite3.DatabaseError as exc: - # The malformed-schema class (e.g. a duplicate sqlite_master - # row for messages_fts) fails on the very first statement — - # before _init_schema can run — so it can't be caught at the - # FTS-rebuild layer. Recover by repairing sqlite_master in - # place (backup first; canonical sessions/messages preserved), - # then reopen once. This is what lets Desktop/Dashboard - # self-heal instead of silently showing "no sessions". + # Malformed schema fails on the very first statement (before + # _init_schema), so it can't be caught at the FTS-rebuild layer: + # repair sqlite_master in place (backup first) and reopen once. if not is_malformed_schema_error(exc) or not _claim_repair_attempt(self.db_path): raise logger.error( @@ -2341,31 +1479,17 @@ class SessionDB( report = repair_state_db_schema(self.db_path) if not report.get("repaired"): raise - _connect_and_init_with_lock_patience() - - # NOTE: the v23 FTS optimization is OPT-IN (`hermes db optimize`), - # never auto-started on open. Legacy installs keep their working - # v22 inline FTS untouched here; only the explicit foreground - # command demotes + rebuilds. This avoids a background worker - # racing session lifecycle and the surprise disk/latency cost on - # an unattended open. (An interrupted optimize resumes when the - # user re-runs the command.) + self._connect_and_init_with_lock_patience() + # The v23 FTS optimization is OPT-IN (`hermes db optimize`), never + # auto-started on open: no background worker racing session + # lifecycle, no surprise disk/latency cost on an unattended open. self._ensure_db_file_generation() self._record_db_file_identity() initialization_complete = True except Exception as exc: - # Capture the cause so /resume and friends can surface WHY the - # session DB is unavailable instead of a bare "Session database - # not available." Callers that catch this exception keep their - # existing ``self._session_db = None`` degradation path. - # - # Note: we deliberately do NOT clear _last_init_error on the - # success path (no else branch). In multi-threaded callers - # (gateway, web_server per-request SessionDB()), a concurrent - # successful open racing past this failure would erase the - # cause that another thread's /resume is about to format. - # Tests that need to reset the state can call - # ``hermes_state._set_last_init_error(None)`` explicitly. + # Surface WHY via /resume and friends; deliberately never cleared on + # success (see _set_last_init_error). Callers keep their + # ``self._session_db = None`` degradation path. _set_last_init_error(f"{type(exc).__name__}: {exc}") raise finally: @@ -2373,23 +1497,145 @@ class SessionDB( conn, self._conn = self._conn, None self._close_connection_quietly(conn) + def _open_read_only(self) -> None: + """Read-only attach for cross-profile aggregation: no schema init, NO + write lock (sidebar polling never contends with that profile's backend); + the DB must already exist. FTS flags are probed with SELECTs only, and + the connection is closed on ANY probe failure (malformed schema raises + DatabaseError) so a leaked tracked connection cannot block the forensic + backup the writable heal takes next.""" + open_attempt = 0 + while True: + try: + self._conn = conn = _connect_tracked_db( + f"file:{self.db_path}?mode=ro", tracking_path=self.db_path, uri=True, + check_same_thread=False, timeout=1.0, isolation_level=None, + ) + conn.row_factory = sqlite3.Row + try: + apply_database_pragmas(conn, db_label="state.db") + cursor = conn.cursor() + self._fts_enabled = self._fts_table_probe(cursor, "messages_fts") is True + if self._fts_enabled: + self._trigram_available = ( + self._fts_table_probe(cursor, "messages_fts_trigram") is True + ) + except BaseException: + self._conn = None + try: + conn.close() + except Exception: + pass + raise + return + except sqlite3.OperationalError as ioerr: + # A WAL checkpoint / reset / frame-flush in flight on the writer + # side can surface SQLITE_IOERR to a concurrent mode=ro reader + # (it cannot perform the -shm recovery the read needs). The + # transition closes in milliseconds; retry a bounded number of + # times before classifying the store as failed. + if not _is_transient_read_only_ioerr(ioerr, attempt=open_attempt): + raise + open_attempt += 1 + time.sleep(_READ_ONLY_IOERR_RETRY_BACKOFF_S) + + def _handle_quarantine_if_zeroed(self, already_locked: bool = False) -> None: + """Quarantine a zero-byte/headerless state.db so a fresh one can open. + + If quarantine failed, do not open the zeroed file (it would fail + opaquely or risk further damage) — raise with the clear message. + """ + if not (self.db_path.exists() and is_zeroed_state_db(self.db_path)): + return + try: + zsize = self.db_path.stat().st_size + except OSError: + zsize = -1 + qpath = quarantine_zeroed_state_db(self.db_path, already_locked=already_locked) + msg = ( + f"state.db looks ZEROED ({zsize} bytes, no SQLite header). " + f"Preserved at {qpath or '(quarantine failed — file left in place)'}. " + f"Restore from {self.db_path.parent / 'state-snapshots'} via `hermes snapshot list` / " + f"`hermes snapshot restore ` if available. " + "Opening a fresh empty database so the agent can start." + ) + logger.error(msg) + _set_last_init_error(msg) + if qpath is None and self.db_path.exists() and is_zeroed_state_db(self.db_path): + raise sqlite3.DatabaseError(msg) + + def _connect_and_init(self) -> None: + # Refuse before sqlite3.connect (under the startup lock) so we cannot + # mint a replacement WAL while a live writer still holds a deleted + # sidecar inode. + refuse_deleted_wal_generation(self.db_path) + self._conn = _connect_tracked_db( + str(self.db_path), + check_same_thread=False, + # Short timeout — application-level jittered retry handles + # contention instead of SQLite's internal busy handler (up to 30s). + timeout=1.0, + # None = we manage transactions ourselves (explicit BEGIN IMMEDIATE). + isolation_level=None, + ) + self._conn.row_factory = sqlite3.Row + self._wal_active = apply_wal_with_fallback(self._conn, db_label="state.db") == "wal" + apply_database_pragmas(self._conn, db_label="state.db") + self._conn.execute("PRAGMA foreign_keys=ON") + self._fts_cjk_loaded = load_fts5_cjk_extension(self._conn) + self._init_schema() + + def _connect_and_init_with_lock_patience(self) -> None: + """Open + init, waiting out a sibling's write lock with jittered patience: + _init_schema's DDL runs on a 1s-timeout connection, so a sibling's VACUUM + or checkpoint used to fail the ENTIRE open and callers disabled + persistence for the whole run. Non-lock errors propagate immediately.""" + deadline = time.monotonic() + self._WRITE_PATIENCE_S + while True: + try: + self._connect_and_init() + return + except sqlite3.OperationalError as exc: + err = str(exc).lower() + if "locked" not in err and "busy" not in err: + raise + try: + if self._conn is not None: + self._conn.close() + except Exception: + pass + now = time.monotonic() + if now >= deadline: + raise + time.sleep(min( + random.uniform(self._WRITE_RETRY_SLOW_MIN_S, self._WRITE_RETRY_SLOW_MAX_S), + max(deadline - now, 0.001), + )) + + def _open_with_optional_startup_guard(self, needs_startup_guard: bool) -> None: + if needs_startup_guard: + with quarantine_cross_process_lock(self.db_path) as lock_acquired: + if not lock_acquired: + logger.warning( + "startup quarantine lock for %s not acquired within 5s; proceeding", + self.db_path, + ) + self._handle_quarantine_if_zeroed(already_locked=lock_acquired) + self._connect_and_init_with_lock_patience() + else: + self._handle_quarantine_if_zeroed(already_locked=False) + self._connect_and_init_with_lock_patience() + # ── Read-path split ── def _get_read_conn(self) -> Optional[sqlite3.Connection]: - """Open a fresh read-only connection, or None when unavailable. + """Open a fresh read-only connection, or None when unavailable (callers + return it to self._read_pool; this opens, it does not track). - Callers must return the connection to self._read_pool (see - _read_ctx); this opens, it does not track. - - Only used under WAL: WAL readers see a consistent snapshot and never - block on (or get blocked by) the writer, so recall/browse queries can - skip self._lock entirely. Under DELETE journal mode (NFS fallback) a - reader can hit SQLITE_BUSY storms during writes, so we keep the - legacy locked single-connection path there. - - Fresh read transactions begin per statement (autocommit), so each - query observes everything committed so far — read-your-writes holds - for the flush-then-search patterns in a turn. + WAL only: WAL readers never block on the writer, so reads skip + self._lock; under DELETE journal mode (NFS fallback) readers hit + SQLITE_BUSY storms, so the legacy locked path stays. Autocommit reads + see everything committed so far (read-your-writes for flush-then-search). """ if not self._wal_active or self.read_only: return None @@ -2402,9 +1648,7 @@ class SessionDB( < _READ_OPEN_RETRY_SECONDS ): return None - # Take the descriptor permit BEFORE the open, so concurrent openers - # race for permits rather than for file descriptors. Non-blocking: - # losing the race means "use the writer connection", not "wait". + # Permit BEFORE the open: openers race for permits, not descriptors. if not self._read_budget.acquire(self): with self._read_conns_lock: self._read_permit_exhausted += 1 @@ -2415,69 +1659,46 @@ class SessionDB( self.db_path, ) return None - # Bound before the try: the except handlers close it if the open - # half-succeeded, and an unbound name there would raise NameError over - # the top of the real failure. - conn = None + conn = None # bound before the try so the handlers can close a half-open one try: conn = _connect_tracked_db( f"file:{self.db_path}?mode=ro", tracking_path=self.db_path, uri=True, - # Pooled connections are borrowed by whichever thread runs - # the next read, and sqlite3 otherwise refuses cross-thread - # use ("SQLite objects created in a thread can only be used - # in that same thread") — including on close(), which is how - # the old per-thread connections became unclosable and leaked - # their fds. Exclusive ownership is enforced by the pool - # checkout/return, not by sqlite3. Matches the writer opens. + # Pooled connections are borrowed by whichever thread reads next + # (sqlite3 otherwise refuses cross-thread use, including close() + # — how the old per-thread connections leaked their fds). + # Exclusive ownership is enforced by pool checkout, not sqlite3. check_same_thread=False, timeout=5.0, isolation_level=None, ) conn.row_factory = sqlite3.Row apply_database_pragmas(conn, db_label="state.db") - # Load the CJK tokenizer extension on this connection so - # messages_fts_cjk queries work on the read path. The .so - # registers the tokenizer in the connection's in-memory - # registry, not the database file, so mode=ro is fine. + # The tokenizer registers in the connection's in-memory registry, + # not the file, so mode=ro is fine. if self._fts_cjk_loaded: load_fts5_cjk_extension(conn) except sqlite3.Error: - # A partially-constructed connection — _connect_tracked_db - # succeeded, the CJK extension load did not — must be closed here. - # Dropping it on the floor still open leaves a live descriptor the - # tracking registry still counts: the same leak shape this pool - # exists to fix, one level further down. + # A half-open connection (open ok, extension load failed) is a live + # tracked descriptor — the leak shape this pool exists to fix. self._discard_partial_read_conn(conn) - # Back off from retrying the open on every query; the locked - # writer connection still serves reads until the stamp expires. with self._read_conns_lock: self._read_open_failed_at = time.monotonic() logger.debug("read-only connection open failed for %s", self.db_path, exc_info=True) self._read_budget.release() return None except BaseException: - # Anything else (a non-sqlite3 extension-load failure, MemoryError, - # KeyboardInterrupt landing between open and return) must not - # strand the permit: a stranded permit is not a transient error, it - # permanently shrinks the read path by one slot for the life of the - # process. + # A stranded permit permanently shrinks the read path by one slot. self._discard_partial_read_conn(conn) self._read_budget.release() raise return conn def _evict_one_idle_read_conn(self) -> bool: - """Close one connection sitting idle in this instance's pool. - - Called by _PathReadBudget when a peer SessionDB on the same file wants - a permit this instance is holding but not using. Only the idle set is - reachable from here — a checked-out connection is not in the queue — - so this can never pull a connection out from under a live reader. - - Returns whether a connection (and therefore a permit) was released. - """ + """Close one idle pooled connection (a peer on the same file wants its + permit). Only the idle set is reachable — never pulls a connection out + from under a live reader. Returns whether a permit was released.""" try: conn = self._read_pool.get_nowait() except queue.Empty: @@ -2486,37 +1707,23 @@ class SessionDB( return True def _discard_partial_read_conn(self, conn) -> None: - """Close a connection that failed between open and hand-off. - - Separate from _close_read_conn because that one releases a permit and - this runs on paths that release their own. - """ + """Close a connection that failed between open and hand-off; unlike + _close_read_conn this does NOT release a permit (callers release their own).""" if conn is None: return try: conn.close() except Exception as exc: - logger.warning( - "partially-opened read conn close failed for %s: %s", self.db_path, exc - ) + logger.warning("partially-opened read conn close failed for %s: %s", self.db_path, exc) def _close_read_conn(self, conn) -> None: - """Close a pooled read connection and release its descriptor permit. + """Close a pooled read connection and release its permit. - This was a bare ``except Exception: pass``, which silently swallowed - the sqlite3.ProgrammingError raised when close() ran on a thread - other than the one that opened the connection — the exact signature - of the fd leak this pool fixes. A close that fails leaks a tracked - fd, so it must not be invisible. - - The permit is released even when close() raises: the descriptor is - already lost at that point, and withholding the permit too would turn - one leaked fd into a permanently narrower read path — failing twice for - one fault. The warning is the signal that matters. - - Pairs with _get_read_conn(). Calling this on a connection that did not - come from there over-releases the BoundedSemaphore, which raises - ValueError rather than silently widening the ceiling. + A failing close leaks a tracked fd, so it is logged, never swallowed. + The permit is released even then: withholding it would turn one leaked + fd into a permanently narrower read path. Pairs with _get_read_conn(); + over-releasing the BoundedSemaphore raises ValueError rather than + silently widening the ceiling. """ try: conn.close() @@ -2526,19 +1733,10 @@ class SessionDB( self._read_budget.release() def _checkout_read_conn(self) -> Optional[sqlite3.Connection]: - """Borrow a read connection from the pool, opening one on a miss. - - The single acquisition seam for the read path: the WAL/read_only gate, - the pool checkout and the open-on-miss all live here, so there is - exactly one place to exercise (and one place for a caller to bypass by - accident). Returns None when the read path is unavailable and the - caller must fall back to the locked writer connection. - - A pool hit costs no permit — the connection it hands back is already - holding one. Only the miss path can open, and only _get_read_conn() can - take a permit, so peak live connections is bounded by _READ_POOL_MAX no - matter how many threads miss simultaneously. - """ + """Borrow a read connection, opening on a miss; None when the read path + is unavailable. The single acquisition seam: a pool hit costs no permit + (the connection already holds one), only _get_read_conn() takes one, so + peak live connections stay bounded however many threads miss at once.""" if not self._wal_active or self.read_only: return None try: @@ -2548,22 +1746,11 @@ class SessionDB( @contextmanager def _read_ctx(self) -> Iterator[sqlite3.Connection]: - """Yield a connection for read-only statements. - - WAL: a read-only connection borrowed from a bounded pool with NO - lock — recall queries never convoy behind writer flushes (the - gateway shares one SessionDB across every agent, so this lock was a - global choke point). The connection is checked out for the duration - of the block, so no two threads ever touch it concurrently. - Non-WAL, read-conn failure, or _READ_POOL_MAX already reached: the - shared writer connection under self._lock, byte-for-byte the legacy - behavior. - - That last case is the deliberate degradation. Past the ceiling readers - convoy on the writer lock instead of opening descriptors — measurably - slower under a burst, and the alternative is EMFILE, which takes the - whole process down in a way a restart-on-exit supervisor cannot see. - """ + """Yield a connection for read-only statements: a pooled read-only + connection with NO lock under WAL (the writer lock was a global choke + point), checked out for the block; otherwise (non-WAL, open failure, + ceiling reached) the writer connection under self._lock — the deliberate + degradation: slower than EMFILE, which the supervisor cannot see.""" conn = self._checkout_read_conn() if conn is not None: try: @@ -2578,65 +1765,32 @@ class SessionDB( except queue.Full: pass if not returned: - # close() has already drained the pool, so this connection - # is surplus. Close it here — dropping it on the floor is - # what leaked the fd. - # - # queue.Full is now unreachable in practice (permits and - # maxsize are both _READ_POOL_MAX, so there can never be a - # ninth connection to return), but the branch stays: it is - # load-bearing if those two ever drift apart, and a leak is - # the failure mode it prevents. + # close() drained the pool: this connection is surplus. + # queue.Full is unreachable while permits == maxsize, but the + # branch is load-bearing if they ever drift apart (a leak). self._close_read_conn(conn) return with self._lock: - if self._conn is None: - # close() ran while a reader was still unwinding (#94736 - # class) — reopen instead of yielding None to a .execute. + if self._conn is None: # close() raced a still-unwinding reader self._reopen_after_close_locked(context="read") yield cast(sqlite3.Connection, self._conn) def _reopen_after_close_locked(self, context: str = "write") -> None: - """Reopen the writer connection after ``close()`` raced a live caller. - - The #94736 failure shape: a teardown owner (cron ``run_job``'s - ``finally``, a delegate timeout owner abandoning its worker, agent - ``close()``) calls ``SessionDB.close()`` — which sets ``_conn = None`` - — while a still-unwinding worker thread has one more transcript flush - to land. The next ``_execute_write`` then died on - ``'NoneType' object has no attribute 'execute'``, the conversation - loop force-ended the turn as ``session_persistence_failed``, and the - in-flight tail of the subagent/cron session was silently dropped - (delivered as ``last_status: ok``). - - The transcript append is THE critical write — losing it destroys the - turn — so at this shared persistence boundary we self-heal: reopen a - connection to the same database file and let the write land. The - reopen is loud (WARNING names the race) and bounded (only fires when - ``_conn`` is ``None``, i.e. after an explicit ``close()`` — the - constructor never leaves a live instance with a ``None`` handle). - ``__del__`` delegates to ``close()``, so the reopened connection is - still released at GC/exit time. - - Caller must hold ``self._lock``. Raises ``sqlite3.OperationalError`` - with an explicit cause when the reopen itself fails, so the surfaced - persistence error names the teardown race instead of the opaque - ``NoneType`` attribute error. - """ + """Reopen the writer after ``close()`` raced a live caller (a teardown + owner set ``_conn = None`` while a worker still had a transcript flush + to land; the turn's tail was silently dropped). Loud (WARNING) and + bounded (only after an explicit close()); ``__del__`` still releases it. + Caller holds ``self._lock``. A failed reopen names the race in its error.""" if self.read_only: raise sqlite3.ProgrammingError( f"SessionDB for {self.db_path} was closed (read-only handle); " f"cannot serve a {context} after close()" ) - # A reopen resolves the PATH again — if the file at that path is no - # longer the one this instance originally opened (out-of-band - # restore/cp/mv), reconnecting would write into the new generation - # through stale WAL/shm assumptions (#89332). Refuse instead. + # A reopen resolves the PATH again: a replaced file would be written + # through stale WAL/shm assumptions; a quarantined handle must never + # hand a fresh connection (and its close-time checkpoint) to a damaged file. if self._db_replaced or self._db_file_was_replaced(): self._halt_db_replaced() - # A quarantined handle must never come back: reopening would hand a - # fresh connection (and its own close-time checkpoint) to a file we - # already know is structurally damaged. if self._db_corrupt: raise self._corrupt_error( f"state.db connection for {self.db_path} is quarantined after " @@ -2653,94 +1807,57 @@ class SessionDB( ) try: conn = _connect_tracked_db( - str(self.db_path), - check_same_thread=False, - timeout=1.0, - isolation_level=None, + str(self.db_path), check_same_thread=False, timeout=1.0, isolation_level=None, ) except Exception as exc: raise sqlite3.OperationalError( f"state.db connection was closed while a {context} was still " f"in flight (a session-teardown path called close() before " - f"this worker finished — #94736) and the automatic reopen " - f"failed: {exc}" + f"this worker finished — #94736) and the automatic reopen failed: {exc}" ) from exc try: conn.row_factory = sqlite3.Row - self._wal_active = ( - apply_wal_with_fallback(conn, db_label="state.db") == "wal" - ) + self._wal_active = (apply_wal_with_fallback(conn, db_label="state.db") == "wal") apply_database_pragmas(conn, db_label="state.db") conn.execute("PRAGMA foreign_keys=ON") self._fts_cjk_loaded = load_fts5_cjk_extension(conn) except Exception as exc: self._close_connection_quietly(conn) raise sqlite3.OperationalError( - f"state.db reopen after close() succeeded but connection " - f"setup failed: {exc}" + f"state.db reopen after close() succeeded but connection setup failed: {exc}" ) from exc - # Schema was initialised by this instance's original open; the file - # cannot have lost it, so no _init_schema here (no DDL races with - # sibling processes during teardown). + # Schema was initialised by the original open; no _init_schema here (no + # DDL races with siblings during teardown). self._conn = conn # ── Core write helper ── @staticmethod def _is_fts5_unavailable_error(exc: sqlite3.OperationalError) -> bool: + # Builds with FTS5 but without the optional trigram tokenizer raise + # "no such tokenizer: trigram" instead of "no such module"; the loadable + # cjk_unicode61 tokenizer shows the same capability-error shape. Scoped + # to those two tokenizers so unrelated tokenizer errors aren't masked. err = str(exc).lower() - if "no such module" in err and "fts5" in err: - return True - # SQLite builds that have FTS5 but lack the optional trigram tokenizer - # raise "no such tokenizer: trigram" instead of "no such module". - # Scope to trigram specifically to avoid masking unrelated tokenizer errors. - if "no such tokenizer: trigram" in err: - return True - # The cjk_unicode61 tokenizer is a loadable extension — a process - # that couldn't load it sees the same capability-error shape. - if "no such tokenizer: cjk_unicode61" in err: - return True - return False + return ("no such module" in err and "fts5" in err) or SessionDB._is_trigram_unavailable_error(exc) @staticmethod def _is_trigram_unavailable_error(exc: sqlite3.OperationalError) -> bool: - """True when only an optional tokenizer is missing (FTS5 itself works). - - Covers the built-in trigram tokenizer (needs SQLite >= 3.34) and the - loadable cjk_unicode61 tokenizer — both mean "this one index can't be - served here", never "disable FTS". - """ + """Only an optional tokenizer is missing (trigram needs SQLite >= 3.34; + cjk_unicode61 is loadable): "this one index can't be served", never "disable FTS".""" err = str(exc).lower() - return ( - "no such tokenizer: trigram" in err - or "no such tokenizer: cjk_unicode61" in err - ) + return ("no such tokenizer: trigram" in err or "no such tokenizer: cjk_unicode61" in err) @staticmethod def _db_has_legacy_inline_fts(cursor: sqlite3.Cursor) -> bool: - """True when messages_fts exists in ANY pre-v23 shape. - - v23's messages_fts is external-content over THREE real columns - (content, tool_name, tool_calls). Every pre-v23 shape lacks the - tool_name/tool_calls columns — whether the old inline single-column - form (v11..v22) or the even older external-content single-column form - (v10-era, pre-#16751). We therefore detect "needs optimize" as "the - stored CREATE lacks the tool_name column", which is the precise v23 - marker and correctly catches BOTH legacy variants. - - Returns False when messages_fts doesn't exist yet (fresh DB mid-init): - the post-migration FTS setup block will create it in the v23 shape. - """ + """messages_fts exists in ANY pre-v23 shape. v23 is external-content over + content/tool_name/tool_calls; every legacy shape (inline single-column + v11..v22, or the v10-era external single-column) lacks tool_name, so + "stored CREATE lacks tool_name" catches both. False when absent (fresh DB).""" row = cursor.execute( - "SELECT sql FROM sqlite_master " - "WHERE type = 'table' AND name = 'messages_fts'" + "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'messages_fts'" ).fetchone() - if row is None: - return False - sql = row[0] or "" - # The v23 table declares tool_name/tool_calls columns. Their absence - # means a legacy shape that doesn't index tool metadata → optimize. - return "tool_name" not in sql + return row is not None and "tool_name" not in (row[0] or "") def _warn_trigram_unavailable(self, exc: sqlite3.OperationalError) -> None: """Log once that the trigram tokenizer is missing; base FTS5 stays enabled.""" @@ -2764,55 +1881,32 @@ class SessionDB( logger.warning( "SQLite FTS5 unavailable for %s; full-text session search " "disabled. Run `hermes update` to rebuild the venv with a " - "current Python (managed uv guarantees FTS5). " - "(underlying error: %s)", + "current Python (managed uv guarantees FTS5). (underlying error: %s)", self.db_path, exc, ) def _ensure_fts_cjk_schema(self, cursor) -> None: - """Create / repair / self-heal the CJK-bigram index surface. - - ``cursor`` may be a Cursor or a Connection (both expose execute / - executescript). Called only for v23-shape DBs with the base FTS - surface healthy. Sets ``self._fts_cjk_available``. Never raises; - every failure mode degrades to "no cjk index" (trigram/LIKE routing - keeps working). - - Cases: - tokenizer loaded, table absent → create. Empty DB: index is - complete by construction (triggers cover everything). Populated - DB: set the cjk backfill markers so the id-gated triggers stay - correct and `optimize-storage` can backfill; the index is NOT - served until the backfill completes. - tokenizer loaded, table present → ensure triggers (recreates any - dropped by a tokenizer-less process), honour the stale - breadcrumb (serve only when absent and no backfill pending). - tokenizer NOT loaded, table present with live triggers → drop the - cjk triggers so message INSERTs don't fail at trigger time, - and leave the stale breadcrumb (#self-heal). The table itself - stays for a later capable open to rebuild. - """ + """Create / repair / self-heal the CJK-bigram index (see the module + comment). Sets ``_fts_cjk_available``; never raises. Loaded + absent → + create (a populated DB gets the backfill markers and is NOT served until + optimize-storage backfills); loaded + present → ensure triggers, honour + the stale breadcrumb; NOT loaded + live triggers → drop them so INSERTs + don't fail at trigger time and leave the breadcrumb.""" try: cjk_present = bool(cursor.execute( - "SELECT 1 FROM sqlite_master WHERE type = 'table' " - "AND name = 'messages_fts_cjk'" + "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'messages_fts_cjk'" ).fetchone()) - if not self._fts_cjk_loaded: if cjk_present: - live = [ - r[0] for r in cursor.execute( - "SELECT name FROM sqlite_master WHERE type = 'trigger' " - f"AND name IN ({','.join('?' for _ in _FTS_CJK_TRIGGERS)})", - _FTS_CJK_TRIGGERS, - ).fetchall() - ] + live = [r[0] for r in cursor.execute( + "SELECT name FROM sqlite_master WHERE type = 'trigger' " + f"AND name IN ({','.join('?' for _ in _FTS_CJK_TRIGGERS)})", + _FTS_CJK_TRIGGERS, + ).fetchall()] if live: - # Self-heal: this process cannot tokenize, so every - # message INSERT would die inside the cjk trigger. - # Breadcrumb FIRST (crash between the two statements is - # merely conservative), then drop. + # Breadcrumb FIRST (a crash between the two statements + # is merely conservative), then drop. logger.warning( "messages_fts_cjk triggers present but the " "cjk_unicode61 tokenizer is unavailable (%s) — " @@ -2832,68 +1926,43 @@ class SessionDB( self._fts_cjk_available = False return except sqlite3.OperationalError: - # Mirror the tokenizer-loaded except below: the presence check - # and self-heal above run before the loaded/not-loaded branch is - # even known to be safe, so they need the same never-raises - # guarantee the docstring promises for the rest of the method. logger.warning( "messages_fts_cjk presence check failed; CJK search stays on " "trigram/LIKE", exc_info=True, ) self._fts_cjk_available = False return - try: cursor.executescript(FTS_CJK_TABLE_SQL) if not cjk_present: - # Freshly created. An empty DB's index is complete by - # construction (triggers will cover every future row); a - # populated DB (e.g. a v23 install predating the cjk index) - # gets the dedicated marker pair so the id-gated triggers - # keep NEW rows indexed while old rows await the - # `optimize-storage` backfill. Either way any old stale - # breadcrumb refers to a table that no longer exists. - cursor.execute( - "DELETE FROM state_meta WHERE key = ?", - (FTS_CJK_STALE_KEY,), - ) - n_msgs = cursor.execute( - "SELECT COUNT(*) FROM messages WHERE role <> 'tool'" - ).fetchone()[0] - if n_msgs > 0: - hw = cursor.execute( - "SELECT COALESCE(MAX(id), 0) FROM messages" - ).fetchone()[0] + # Any old stale breadcrumb refers to a table that no longer exists. + cursor.execute("DELETE FROM state_meta WHERE key = ?", (FTS_CJK_STALE_KEY,)) + # Empty DB: index complete by construction (triggers cover everything), + # no markers. Populated DB: the marker pair keeps the id-gated triggers + # correct while old rows await optimize-storage; the index is NOT + # served until that backfill completes. + if cursor.execute("SELECT COUNT(*) FROM messages WHERE role <> 'tool'").fetchone()[0] > 0: + hw = cursor.execute("SELECT COALESCE(MAX(id), 0) FROM messages").fetchone()[0] for k, v in ( - ("fts_cjk_rebuild_high_water", str(hw)), - ("fts_cjk_rebuild_progress", "0"), + ("fts_cjk_rebuild_high_water", str(hw)), ("fts_cjk_rebuild_progress", "0"), ): cursor.execute( "INSERT INTO state_meta (key, value) VALUES (?, ?) " "ON CONFLICT(key) DO UPDATE SET value = excluded.value", (k, v), ) - stale = cursor.execute( - "SELECT 1 FROM state_meta WHERE key = ?", - (FTS_CJK_STALE_KEY,), - ).fetchone() - if stale: - # A tokenizer-less process dropped the triggers at some - # unknown point — the index has a gap of unknown extent. - # Do NOT reinstall triggers (an external-content 'delete' - # for an unindexed rowid corrupts the index); the next - # `optimize-storage` run rebuilds from scratch. + if cursor.execute("SELECT 1 FROM state_meta WHERE key = ?", (FTS_CJK_STALE_KEY,)).fetchone(): + # Gap of unknown extent: do NOT reinstall triggers (an + # external-content 'delete' for an unindexed rowid corrupts the + # index); the next optimize-storage rebuilds from scratch. self._fts_cjk_available = False return cursor.executescript(FTS_CJK_TRIGGER_SQL) backfill_pending = cursor.execute( - "SELECT 1 FROM state_meta " - "WHERE key = 'fts_cjk_rebuild_high_water' LIMIT 1" + "SELECT 1 FROM state_meta WHERE key = 'fts_cjk_rebuild_high_water' LIMIT 1" ).fetchone() self._fts_cjk_available = not backfill_pending - except sqlite3.OperationalError: - # Includes "no such tokenizer: cjk_unicode61" if the extension - # loaded but registration failed — degrade to trigram/LIKE. + except sqlite3.OperationalError: # incl. "no such tokenizer" after a failed registration logger.warning( "messages_fts_cjk ensure failed; CJK search stays on " "trigram/LIKE", exc_info=True, @@ -2908,27 +1977,18 @@ class SessionDB( except sqlite3.OperationalError: pass - def _ensure_fts_schema( - self, - cursor: sqlite3.Cursor, - table_name: str, - ddl: str, - ) -> bool: + def _ensure_fts_schema(self, cursor: sqlite3.Cursor, table_name: str, ddl: str) -> bool: status = self._fts_table_probe(cursor, table_name) if status is None: return False try: - # Run even when the virtual table exists so any dropped or missing - # triggers are recreated after a previous no-FTS5 runtime disabled - # them to keep message writes working. + # Run even when the table exists: recreates triggers a no-FTS5 runtime dropped. cursor.executescript(ddl) return True except sqlite3.OperationalError as exc: if not self._is_fts5_unavailable_error(exc): raise - # Only disable FTS entirely when the whole FTS5 module is missing. - # A missing specific tokenizer (e.g. trigram) means only that - # particular table cannot be created — the base FTS5 table is fine. + # A missing tokenizer disables only that table; the base FTS5 table is fine. if self._is_trigram_unavailable_error(exc): self._warn_trigram_unavailable(exc) else: @@ -2936,67 +1996,35 @@ class SessionDB( return False def _execute_write( - self, - fn: Callable[[sqlite3.Connection], T], - patience_s: Optional[float] = None, + self, fn: Callable[[sqlite3.Connection], T], patience_s: Optional[float] = None, ) -> T: - """Execute a write transaction with BEGIN IMMEDIATE and jitter retry. + """Run *fn(conn)* inside BEGIN IMMEDIATE with jittered lock retry; commit + is handled here (callers must not commit). Returns *fn*'s result. - *fn* receives the connection and should perform INSERT/UPDATE/DELETE - statements. The caller must NOT call ``commit()`` — that's handled - here after *fn* returns. - - BEGIN IMMEDIATE acquires the WAL write lock at transaction start - (not at commit time), so lock contention surfaces immediately. - On ``database is locked``, we release the Python lock, sleep a - random jitter, and retry — breaking the convoy pattern that - SQLite's built-in deterministic backoff creates. - - *patience_s* is the total time budget for lock retries (default - ``_WRITE_PATIENCE_S``). Transcript-critical writes pass - ``_TRANSCRIPT_WRITE_PATIENCE_S`` so a sibling process holding the - lock for a legitimate long operation (VACUUM, TRUNCATE checkpoint, - pre-bounded-merge FTS optimize from an older still-running - install) exhausts routine writers' patience without destroying a - user turn. Jitter starts small (20-150ms) for fast reclaim on - millisecond contention and backs off to 250ms-1s once the lock has - been held longer than ``_WRITE_RETRY_SLOW_AFTER_S``. - - Returns whatever *fn* returns. + BEGIN IMMEDIATE takes the WAL write lock up front so contention surfaces + immediately; on locked/busy the Python lock is released, a random jitter + slept, and the WHOLE callback retried (see the class tuning comment for + the two patience budgets and the jitter schedule). *fn* must therefore + stay idempotent under retry. """ if patience_s is None: patience_s = self._WRITE_PATIENCE_S deadline = time.monotonic() + patience_s - # Set on the first compression-busy collision so the short wait is + # Set on the first compression-busy collision: the short wait is # measured from then, not from the start of the write. compression_deadline: Optional[float] = None - # One retry for SQLITE_IOERR raised by BEGIN IMMEDIATE itself. The - # callback has not run at that point, so there is no durable effect - # to replay and the retry is exactly-once safe (#99502's contract). - # Once the callback starts, an IOERR leaves the write's settlement - # unknown and must propagate — this helper owns non-idempotent - # transcript/counter mutations, not just idempotent UPSERTs. + # One retry for SQLITE_IOERR raised by BEGIN IMMEDIATE itself: the + # callback has not run, so nothing is replayed (exactly-once safe). Once + # it has started, an IOERR leaves settlement unknown and must propagate — + # this helper owns non-idempotent transcript/counter mutations. ioerr_begin_retried = False - - # Transient engine-level error observed on contended WAL appends - # (dual gateway/agent writers; FTS5 trigram sync holds the write - # lock). The identical write succeeds standalone, so it is - # retryable like locked/busy. The exception CLASS varies with the - # SQLite build — some surface it as InterfaceError, which lives - # OUTSIDE DatabaseError and escaped the retry net entirely on - # attempt 0 — so the check is message-scoped, not class-scoped. - def _is_no_more_rows(exc: sqlite3.Error) -> bool: - return "no more rows available" in str(exc).lower() - while True: self._raise_if_db_corrupt() self._raise_if_db_replaced() fn_started = False try: with self._lock: - if self._conn is None: - # close() ran while this writer was still unwinding - # (#94736) — reopen instead of dying on None.execute. + if self._conn is None: # close() raced this writer self._reopen_after_close_locked(context="write") self._conn.execute("BEGIN IMMEDIATE") try: @@ -3017,17 +2045,9 @@ class SessionDB( self._try_incremental_merge_fts() return result except SessionCompressionInProgressError: - # A live foreign compression lock is transient: the compressor - # publishes in a couple of seconds. Without any wait, a steer - # that lands mid-compression aborts the user's turn as - # session_persistence_failed and sends the operator hunting - # disk space that was never the problem (#75083). - # - # The budget is _COMPRESSION_BUSY_WAIT_S, not the write-lock - # patience: the lease is a correctness boundary, so a writer - # still locked out after a short wait must be refused rather - # than left to land a stale turn once a long-running or wedged - # compression finally lets go. + # Transient (see _COMPRESSION_BUSY_WAIT_S): without a wait, a + # steer landing mid-compression aborts the turn and sends the + # operator hunting disk space that was never the problem. if compression_deadline is None: compression_deadline = min( time.monotonic() + self._COMPRESSION_BUSY_WAIT_S, deadline @@ -3042,8 +2062,7 @@ class SessionDB( if "locked" in err_msg or "busy" in err_msg: if self._sleep_before_write_retry(deadline, patience_s): continue - # Patience exhausted — say what actually happened so the - # surfaced error doesn't read as disk/permission damage. + # Say what actually happened, not disk/permission damage. raise sqlite3.OperationalError( f"database is locked (another Hermes process held the " f"state.db write lock for over {patience_s:.0f}s — " @@ -3059,83 +2078,58 @@ class SessionDB( and not ioerr_begin_retried and self._sleep_before_write_retry(deadline, patience_s) ): - # BEGIN IMMEDIATE itself hit a transient WAL-transition - # IOERR. Nothing has been mutated, so retrying on the SAME - # connection replays nothing. Never close()+reopen to - # "heal" it: close() cancels this process's POSIX locks on - # the file for every sibling connection (howtocorrupt §2.2). + # Retry on the SAME connection. Never close()+reopen to + # "heal": close() cancels this process's POSIX locks on the + # file for every sibling connection (howtocorrupt §2.2). ioerr_begin_retried = True continue - # Non-lock error, the callback already ran (settlement is - # unknown — do not replay), or patience exhausted. - raise + raise # non-lock error, callback already ran, or patience exhausted except sqlite3.DatabaseError as exc: if _is_no_more_rows(exc) and self._sleep_before_write_retry(deadline, patience_s): continue - # An out-of-band replace of state.db (restore/cp/mv under a - # live process) surfaces as this same corruption error class. - # In-file repair on a NEW file generation amplifies the - # damage (#89332) — halt writes on this handle instead. + # An out-of-band replace surfaces as this same corruption class; + # in-file repair on a NEW generation amplifies the damage. if ( "not a database" in str(exc).lower() or is_malformed_db_error(exc) or self._is_fts_write_corruption_error(exc) ): self._raise_if_db_replaced() - # Corrupt FTS shadow tables make every write raise the - # malformed/corrupt error class through the FTS sync triggers - # while the canonical messages table is intact. Never run a - # full-message FTS5 rebuild from this live persistence path: - # on a multi-gigabyte state.db that can hold the writer lock - # for minutes. Atomically detach the derived indexes instead, - # then retry the canonical write. The existing stale-open and - # explicit repair paths retain rebuild ownership. + # Corrupt FTS shadow tables fail every write via the sync + # triggers while canonical rows are intact. Never rebuild FTS + # from this live path (minutes of writer lock on a multi-GB DB): + # detach the derived indexes atomically and retry the write. if self._enter_fts_fail_open(exc): continue - # Bare SQLITE_CORRUPT / NOTADB that survived the replaced-file - # check and the FTS-scoped fail-open is structural damage: - # quarantine the handle (see StateDbCorruptError). + # What survives both checks is structural damage: quarantine. if self._is_structural_corruption_error(exc): self._halt_db_corrupt(exc) raise except sqlite3.Error as exc: - # Catch-all for builds that surface 'no more rows available' - # as InterfaceError (a sibling of DatabaseError, not a - # subclass) or another sqlite3.Error class outside the two - # handlers above. Message-scoped: anything else propagates - # untouched. + # Builds raising 'no more rows' as InterfaceError (sibling of + # DatabaseError); anything else propagates untouched. if _is_no_more_rows(exc) and self._sleep_before_write_retry(deadline, patience_s): continue raise def _write_sql( - self, - sql: str, - params: Any = (), - *, - many: bool = False, - patience_s: Optional[float] = None, + self, sql: str, params: Any = (), *, many: bool = False, patience_s: Optional[float] = None, ) -> None: """Run one INSERT/UPDATE/DELETE through ``_execute_write``.""" def _do(conn): (conn.executemany if many else conn.execute)(sql, params) - self._execute_write(_do, patience_s=patience_s) def _write_rowcount( self, sql: str, params: Any = (), *, patience_s: Optional[float] = None ) -> int: - """Run one UPDATE/DELETE through ``_execute_write``; return rows changed. - - Falls back to ``SELECT changes()`` when the driver reports an unknown - rowcount (None / negative). - """ + """Run one UPDATE/DELETE through ``_execute_write``; return rows changed + (``SELECT changes()`` when the driver reports None / negative).""" def _do(conn): rowcount = conn.execute(sql, params).rowcount if rowcount is None or rowcount < 0: rowcount = conn.execute("SELECT changes()").fetchone()[0] return rowcount - return self._execute_write(_do, patience_s=patience_s) def _read_one(self, sql: str, params: Any = ()) -> Optional[sqlite3.Row]: @@ -3150,11 +2144,8 @@ class SessionDB( def _ensure_db_file_generation(self) -> None: """Mint a once-per-file generation stamp (state_meta + application_id). - - First opener wins via INSERT OR IGNORE. application_id is written - only when still 0 so racers converge on the same header value. - PASSIVE checkpoint only — never TRUNCATE (#45383). - """ + First opener wins (INSERT OR IGNORE); application_id is written only while + 0 so racers converge. PASSIVE checkpoint only — never TRUNCATE.""" if self.read_only or self._conn is None: return token = uuid.uuid4().hex @@ -3165,22 +2156,16 @@ class SessionDB( (_STATE_DB_GENERATION_KEY, token), ) row = self._conn.execute( - "SELECT value FROM state_meta WHERE key = ?", - (_STATE_DB_GENERATION_KEY,), + "SELECT value FROM state_meta WHERE key = ?", (_STATE_DB_GENERATION_KEY,), ).fetchone() if row and row[0]: token = str(row[0]) self._db_file_generation_token = token - current = 0 pragma_row = self._conn.execute("PRAGMA application_id").fetchone() - if pragma_row: - current = int(pragma_row[0] or 0) + current = int(pragma_row[0] or 0) if pragma_row else 0 if current == 0: - app_id = int(token[:8], 16) & 0x7FFFFFFF - if app_id == 0: - app_id = 1 - self._conn.execute(f"PRAGMA application_id={app_id}") - current = app_id + current = (int(token[:8], 16) & 0x7FFFFFFF) or 1 + self._conn.execute(f"PRAGMA application_id={current}") self._db_file_application_id = current try: self._conn.execute("PRAGMA wal_checkpoint(PASSIVE)") @@ -3199,10 +2184,10 @@ class SessionDB( elif self._conn is not None and not self._db_file_application_id: try: pragma_row = self._read_one("PRAGMA application_id") - if pragma_row and pragma_row[0]: - self._db_file_application_id = int(pragma_row[0]) except sqlite3.Error: - pass + pragma_row = None + if pragma_row and pragma_row[0]: + self._db_file_application_id = int(pragma_row[0]) def _db_file_was_replaced(self) -> bool: """True when the path no longer names the file this instance opened.""" @@ -3214,8 +2199,8 @@ class SessionDB( recorded_app = int(self._db_file_application_id or 0) if recorded_app: disk_app = _read_sqlite_application_id(self.db_path) - # Header 0 means the WAL has not been checkpointed yet — not a - # replace. A copied Hermes DB that minted its own id is nonzero. + # Header 0 = WAL not yet checkpointed, not a replace; any real + # replacement (a copied Hermes DB minted its own id) is nonzero. if disk_app and disk_app != recorded_app: return True return False @@ -3227,50 +2212,31 @@ class SessionDB( raise StateDbReplacedError(_STATE_DB_REPLACED_MSG) def _wal_generation_was_lost(self) -> bool: - """True when the WAL/SHM generation this instance opened is gone. + """True when the WAL/SHM generation this handle opened is gone. - Steady state (a sidecar generation is recorded): pure stat — a - recorded inode that is missing or replaced by a new file at the same - path means the generation split. No /proc walk on healthy writes. - - Empty-identity state (fresh DB whose WAL appears only after open, or - identity cleared by a clean ``close()``): fall back to a - ``/proc/self/fd`` deleted-fd probe, and adopt the current sidecars as - this handle's generation once the probe comes back clean. The full - ``/proc/*/fd`` walk is reserved for - :func:`refuse_deleted_wal_generation` on open, where we must see - *foreign* deleted holders before ``sqlite3.connect`` mints a new WAL. + Recorded generation: pure stat (missing/replaced inode = split); no + /proc walk on healthy writes. Empty identity (fresh DB whose WAL appears + after open, or cleared by a clean close()): probe /proc/self/fd for + deleted sidecars and adopt the current ones once clean. The full + /proc/*/fd walk is reserved for refuse_deleted_wal_generation on open. """ recorded = self._db_sidecar_identity or {} base = os.fspath(self.db_path) if recorded: - for suffix, recorded_ident in recorded.items(): - current = _stat_db_file_identity(Path(base + suffix)) - if current is None or current != recorded_ident: - return True - return False - if not self._wal_active: - # No WAL on this handle (journal_mode=delete/truncate fallback): - # there is no sidecar generation to lose, and probing every write - # would put a /proc walk on the hot path of exactly the - # delete-mode deployments the field report used as containment. + return any( + _stat_db_file_identity(Path(base + suffix)) != ident for suffix, ident in recorded.items() + ) + if not self._wal_active: # no sidecar generation to lose; keep /proc off the hot path return False if sys.platform.startswith("linux"): watched = _watched_sqlite_sidecar_paths(self.db_path) - fd_dir = f"/proc/{os.getpid()}/fd" try: - for fd in os.listdir(fd_dir): - try: - target = os.readlink(f"{fd_dir}/{fd}") - except OSError: - continue + for target in _proc_fd_targets(os.getpid()): if " (deleted)" in target and _canonical_sqlite_path(target) in watched: return True except OSError: return False - # Probe clean (or unavailable on this platform): adopt whatever - # sidecar generation exists now so subsequent writes use the cheap - # stat check. + # Probe clean (or unavailable): adopt the current sidecar generation. current_identity = _stat_sqlite_sidecar_identity(self.db_path) if current_identity: self._db_sidecar_identity = current_identity @@ -3282,32 +2248,30 @@ class SessionDB( logger.error(_DELETED_WAL_GENERATION_MSG) raise DeletedWalGenerationError(_DELETED_WAL_GENERATION_MSG) + def _halt_if_db_generation_changed(self) -> None: + """Halt (logging) when the file or its WAL generation is no longer ours.""" + if self._db_replaced or self._db_file_was_replaced(): + self._halt_db_replaced() + if self._db_wal_generation_lost or self._wal_generation_was_lost(): + self._halt_deleted_wal_generation() + def _raise_if_db_replaced(self) -> None: if self._db_replaced: raise StateDbReplacedError(_STATE_DB_REPLACED_MSG) if self._db_wal_generation_lost: raise DeletedWalGenerationError(_DELETED_WAL_GENERATION_MSG) - if self._db_file_was_replaced(): - self._halt_db_replaced() - if self._wal_generation_was_lost(): - self._halt_deleted_wal_generation() + self._halt_if_db_generation_changed() @classmethod def _is_structural_corruption_error(cls, exc: BaseException) -> bool: - """Bare SQLITE_CORRUPT/NOTADB with no FTS provenance. - - ``_is_fts_write_corruption_error`` is the positive FTS classifier; - everything else in the ``corrupt`` bucket of - ``classify_persistence_error`` is damage to a canonical B-tree, the - schema, or the freelist — never repairable from the live write path. - """ - if not isinstance(exc, sqlite3.DatabaseError): - return False - if isinstance(exc, StateDbCorruptError): - return False - if cls._is_fts_write_corruption_error(exc): - return False - return classify_persistence_error(exc) == "corrupt" + """Bare SQLITE_CORRUPT/NOTADB with no FTS provenance: canonical B-tree / + schema / freelist damage, never repairable from the live write path.""" + return ( + isinstance(exc, sqlite3.DatabaseError) + and not isinstance(exc, StateDbCorruptError) + and not cls._is_fts_write_corruption_error(exc) + and classify_persistence_error(exc) == "corrupt" + ) def _corrupt_error(self, prefix: str = "") -> "StateDbCorruptError": """Build the quarantine error for this handle (message assembled once).""" @@ -3324,136 +2288,90 @@ class SessionDB( "state.db %s reported structural corruption outside the FTS " "indexes (%s); quarantining this handle: no further writes, no " "automatic reopen, no explicit WAL checkpoint at close. Stop the " - "gateway and run `hermes sessions recover --source %s " - "--inspect-only`.", + "gateway and run `hermes sessions recover --source %s --inspect-only`.", self.db_path, exc, self.db_path, ) err = self._corrupt_error() for attr in ("sqlite_errorcode", "sqlite_errorname"): - value = getattr(exc, attr, None) - if value is not None: - setattr(err, attr, value) + if getattr(exc, attr, None) is not None: + setattr(err, attr, getattr(exc, attr)) raise err from exc def _disable_close_time_checkpoint(self) -> None: - """Best-effort: stop SQLite's own last-connection checkpoint on close. - - Skipping our explicit ``PRAGMA wal_checkpoint(PASSIVE)`` in - ``close()`` is not enough on its own: ``sqlite3.Connection.close()`` - still runs SQLite's internal last-connection PASSIVE checkpoint and - unlinks the ``-wal``/``-shm`` sidecars. On the field incident's file - that close-time checkpoint is exactly what wrote 15 pages under the - wrong page numbers. Python 3.12+ exposes the switch as - ``Connection.setconfig(SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE)``; on 3.11 - neither the constant nor ``setconfig`` exists, so the internal - checkpoint remains (it can only carry pre-quarantine committed - frames — no further writes are accepted on this handle). - """ + """Best-effort SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE (Python 3.12+): skipping + our explicit checkpoint isn't enough, sqlite3's close() still runs the + internal last-connection checkpoint that wrote the incident's 15 pages + under wrong page numbers. See StateDbCorruptError.""" flag = getattr(sqlite3, "SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE", None) - if flag is None: - return conn = self._conn setconfig = getattr(conn, "setconfig", None) - if conn is None or setconfig is None: + if flag is None or conn is None or setconfig is None: + # <3.12 has no setconfig: the residual close checkpoint is tolerable — it + # can only carry pre-quarantine committed frames; this handle accepts no + # further writes. return try: setconfig(flag, True) except Exception: logger.debug( - "Could not disable SQLite's close-time checkpoint on the " - "quarantined handle for %s", - self.db_path, - exc_info=True, + "Could not disable SQLite's close-time checkpoint on the quarantined handle for %s", + self.db_path, exc_info=True, ) def _raise_if_db_corrupt(self) -> None: if self._db_corrupt: raise self._corrupt_error() - def _sleep_before_write_retry( - self, deadline: float, patience_s: float - ) -> bool: - """Sleep one jitter interval if the patience budget still allows it. - - Returns True when the caller should retry, False when *deadline* has - passed and the error should propagate. Jitter stays small for the - first ``_WRITE_RETRY_SLOW_AFTER_S`` (fast reclaim on millisecond - contention) and backs off after that, and never overshoots the - deadline by a full slow-jitter. - """ + def _sleep_before_write_retry(self, deadline: float, patience_s: float) -> bool: + """Sleep one jitter interval if the budget allows; True = retry, False = + deadline passed. Small jitter for the first _WRITE_RETRY_SLOW_AFTER_S, + then backs off; never overshoots the deadline by a full slow-jitter.""" now = time.monotonic() if now >= deadline: return False - elapsed = now - (deadline - patience_s) - if elapsed >= self._WRITE_RETRY_SLOW_AFTER_S: - jitter = random.uniform( - self._WRITE_RETRY_SLOW_MIN_S, - self._WRITE_RETRY_SLOW_MAX_S, - ) - else: - jitter = random.uniform( - self._WRITE_RETRY_MIN_S, - self._WRITE_RETRY_MAX_S, - ) + slow = now - (deadline - patience_s) >= self._WRITE_RETRY_SLOW_AFTER_S + jitter = ( + random.uniform(self._WRITE_RETRY_SLOW_MIN_S, self._WRITE_RETRY_SLOW_MAX_S) if slow + else random.uniform(self._WRITE_RETRY_MIN_S, self._WRITE_RETRY_MAX_S) + ) time.sleep(min(jitter, max(deadline - now, 0.001))) return True @staticmethod def _is_fts_write_corruption_error(exc: sqlite3.DatabaseError) -> bool: - """Return true only when SQLite identifies corruption as FTS-scoped. - - Newer SQLite builds include ``fts5`` in the error text. Older builds - may emit only ``database disk image is malformed`` while exposing the - extended ``SQLITE_CORRUPT_VTAB`` result code. A bare - ``SQLITE_CORRUPT``/malformed-image error is structural and must not - trigger live FTS maintenance: it does not prove that canonical B-trees - are intact. - """ - corrupt_vtab = getattr(sqlite3, "SQLITE_CORRUPT_VTAB", 267) + """Corruption SQLite identifies as FTS-scoped: SQLITE_CORRUPT_VTAB, or + (older builds) an ``fts5:`` message. A bare malformed-image error is + structural and must not trigger live FTS maintenance.""" error_code = getattr(exc, "sqlite_errorcode", None) if error_code is not None: - return error_code == corrupt_vtab + return error_code == getattr(sqlite3, "SQLITE_CORRUPT_VTAB", 267) msg = str(exc).lower() return msg.startswith("fts5:") and "corrupt structure" in msg def _foreign_state_db_holders(self) -> List[Tuple[int, str]]: - """Return foreign processes holding this DB or its WAL sidecars. - - Automatic FTS repair is structural maintenance, not an ordinary WAL - write. It must not run while another process remains attached: a - sidecar reset under that holder can leave the two processes writing - through different WAL inodes. - - A scan failure is represented as an unknown holder. Skipping optional - automatic maintenance is safer than assuming quiescence; canonical - writes continue through the stale-FTS fail-open path. + """Foreign processes holding this DB or its WAL sidecars. Automatic FTS + repair is structural maintenance and must not run while another process + is attached (a sidecar reset under it splits the WAL inodes). A scan + failure is reported as an unknown holder: skipping optional maintenance + beats assuming quiescence. """ - # The split-brain mechanism requires POSIX unlink semantics: Windows - # refuses to replace SQLite sidecars while another process has them - # open. Avoid psutil.open_files() there; querying arbitrary Windows - # processes can block for minutes on device-backed handles. + # Split-brain needs POSIX unlink semantics (Windows refuses to replace + # open sidecars); psutil.open_files() there can block for minutes. if _IS_WINDOWS: return [] if psutil is None: return [(-1, "open-file scan unavailable")] - db_path = os.path.abspath(os.fspath(self.db_path)) watched = { - _canonical_sqlite_path(db_path), - _canonical_sqlite_path(db_path + "-wal"), + _canonical_sqlite_path(db_path), _canonical_sqlite_path(db_path + "-wal"), _canonical_sqlite_path(db_path + "-shm"), } holders: List[Tuple[int, str]] = [] - - # On Linux, read /proc//fd symlinks directly. psutil's - # open_files() filters through isfile_strict(), which stats the - # literal path — for an unlinked WAL sidecar the kernel returns - # "/path/state.db-wal (deleted)" and stat fails, so the entry is - # silently dropped and the split-brain holder is never seen. - # /proc readlinks preserve the "(deleted)" suffix so _canonical can - # strip it and match. + # Linux: read /proc//fd directly. psutil.open_files() stats the + # literal path, so an unlinked "state.db-wal (deleted)" entry is silently + # dropped and the split-brain holder never seen; readlink keeps the suffix. if sys.platform.startswith("linux"): try: own_pid = os.getpid() @@ -3463,78 +2381,55 @@ class SessionDB( pid = int(pid_str) if pid == own_pid: continue - fd_dir = f"/proc/{pid}/fd" try: - fds = os.listdir(fd_dir) + targets = list(_proc_fd_targets(pid)) except OSError: - # Cannot read this process's fd table (different - # user, e.g. root gateway vs user desktop). - # /proc//cmdline is world-readable by default, - # so check whether this is a Hermes process — - # only flag uninspectable holders that look like - # another Hermes instance, not every system daemon. + # Unreadable fd table (other user: root gateway vs user + # desktop). cmdline is world-readable: flag only + # uninspectable holders that look like Hermes. cmdline = _read_proc_cmdline(pid) if cmdline is not None and _looks_like_hermes(cmdline): holders.append((pid, f"uninspectable holder: {cmdline[:80]}")) continue - for fd in fds: - try: - target = os.readlink(f"{fd_dir}/{fd}") - except OSError: - continue - if _canonical_sqlite_path(target) in watched: - holders.append((pid, target)) + holders.extend((pid, t) for t in targets if _canonical_sqlite_path(t) in watched) except Exception as exc: - logger.warning( - "Could not prove state.db has no foreign holders; " - "deferring automatic FTS maintenance: %s", - exc, - ) - return holders or [(-1, f"open-file scan failed: {exc}")] + return self._foreign_holder_scan_failed(holders, exc) return holders - - # macOS / BSD: use psutil.open_files(). macOS does not use the - # "(deleted)" suffix convention, so psutil's filtering is safe here. + # macOS / BSD: psutil.open_files(). macOS does not use the "(deleted)" + # suffix convention, so psutil's filtering is safe here. psutil's + # as_dict() converts AccessDenied to None -> empty iteration; acceptable + # on macOS (the root-gateway/user-desktop topology is Linux-specific). try: for process in psutil.process_iter(["pid", "open_files"]): - info = process.info - pid = int(info["pid"]) + pid = int(process.info["pid"]) if pid == os.getpid(): continue - # psutil's as_dict() converts AccessDenied to None, which - # or-() turns into an empty iteration. On macOS this is - # acceptable: the gateway/desktop topology from the issue is - # Linux-specific (systemd units running as root). - for opened in info.get("open_files") or (): + for opened in process.info.get("open_files") or (): path = getattr(opened, "path", "") if path and _canonical_sqlite_path(path) in watched: holders.append((pid, path)) except Exception as exc: - logger.warning( - "Could not prove state.db has no foreign holders; " - "deferring automatic FTS maintenance: %s", - exc, - ) - return holders or [(-1, f"open-file scan failed: {exc}")] + return self._foreign_holder_scan_failed(holders, exc) return holders + @staticmethod + def _foreign_holder_scan_failed(holders: List[Tuple[int, str]], exc: Exception) -> List[Tuple[int, str]]: + logger.warning( + "Could not prove state.db has no foreign holders; " + "deferring automatic FTS maintenance: %s", + exc, + ) + return holders or [(-1, f"open-file scan failed: {exc}")] def _enter_fts_fail_open(self, exc: sqlite3.DatabaseError) -> bool: - """Detach corrupt FTS indexes so canonical writes can continue. - - The stale breadcrumb and trigger removal commit atomically. Its - ordering is load-bearing: after triggers are absent, new canonical - rows create an index gap of unknown extent, so another process must - never reinstall the triggers without first rebuilding every row. - """ + """Detach corrupt FTS indexes so canonical writes can continue. Stale + breadcrumb + trigger drop commit atomically: once triggers are absent + the index has a gap of unknown extent, so no process may reinstall them + without rebuilding every row.""" if not self._fts_enabled or not self._is_fts_write_corruption_error(exc): return False self._raise_if_db_corrupt() - if self._db_replaced or self._db_file_was_replaced(): - self._halt_db_replaced() - if self._db_wal_generation_lost or self._wal_generation_was_lost(): - self._halt_deleted_wal_generation() - + self._halt_if_db_generation_changed() try: with self._lock: self._conn.execute("BEGIN IMMEDIATE") @@ -3563,12 +2458,10 @@ class SessionDB( raise except sqlite3.Error as detach_exc: logger.error( - "Could not detach corrupt FTS indexes; canonical write still " - "cannot proceed: %s", + "Could not detach corrupt FTS indexes; canonical write still cannot proceed: %s", detach_exc, ) return False - self._fts_stale = True self._fts_enabled = False self._trigram_available = False @@ -3582,164 +2475,83 @@ class SessionDB( return True def _try_wal_checkpoint(self) -> None: - """Best-effort PASSIVE WAL checkpoint. Never raises. - - Flushes committed WAL frames back into the main DB file without - requiring an exclusive lock. PASSIVE is safe for frequent - periodic use because it does not block concurrent writers and - cannot corrupt B-tree pages under I/O pressure. - - PASSIVE does not truncate the WAL file — it stays at its - high-water mark. Explicit checkpoints on the shared ``state.db`` no - longer truncate the WAL; it is bounded by ``journal_size_limit`` and - the writer's natural post-checkpoint reset rather than by a TRUNCATE - at every close or maintenance command. - - Previous TRUNCATE strategy caused B-tree corruption on large - databases (65K+ pages) due to the exclusive-lock I/O pressure - from checkpointing thousands of frames at once (issue #45383). - """ + """Best-effort PASSIVE WAL checkpoint; never raises. PASSIVE never blocks + writers and leaves the WAL at its high-water mark (bounded by + journal_size_limit); the old TRUNCATE strategy corrupted B-trees on + 65K+ page databases under exclusive-lock I/O pressure.""" if self._db_corrupt: return # quarantined: never checkpoint over a damaged image try: with self._lock: - result = self._conn.execute( - "PRAGMA wal_checkpoint(PASSIVE)" - ).fetchone() + result = self._conn.execute("PRAGMA wal_checkpoint(PASSIVE)").fetchone() if result and result[1] > 0: - logger.debug( - "WAL checkpoint: %d/%d pages checkpointed", - result[2], result[1], - ) + logger.debug("WAL checkpoint: %d/%d pages checkpointed", result[2], result[1]) except Exception as exc: logger.warning("WAL checkpoint (PASSIVE) failed: %s", exc) def __enter__(self) -> "SessionDB": - """Enter a scope that closes this handle on the way out. - - Ownership of a SessionDB should be released explicitly. - Historically an instance with a started token writer pinned ITSELF - (bound-method writer target plus a strong ``atexit`` drain hook), so - ``__del__`` never ran for exactly the instances that leaked - descriptors (#88033). The writer now retires after an idle window - and the atexit hook holds only a weak reference, so abandoned - handles are eventually collectible — but "eventually, after the - idle window and a GC cycle" is not a release policy. Call sites - owning a handle are still expected to close it deterministically - (see the ownership comments in ``run_agent.py`` and - ``tui_gateway/methods_session.py``). - - This makes the correct usage the easy one, so an owning scope can be - exception-safe by construction rather than by remembering a - ``try/finally``: - - with SessionDB(path) as db: - db.append_message(...) - - Purely additive: it changes nothing for callers that already call - ``close()`` directly, and ``close()`` stays idempotent, so a scope - that closes early still exits cleanly. - """ + """``with SessionDB(path) as db:`` closes the handle on exit. Owners must + release deterministically: a started token writer used to pin the + instance (bound-method target + strong atexit hook) so __del__ never ran + for exactly the handles that leaked descriptors; the writer now retires + when idle and the hook is weak, but "eventually after a GC cycle" is not + a release policy. close() stays idempotent.""" return self def __exit__(self, exc_type, exc, tb) -> bool: - """Close the handle, then let any exception propagate. - - Returns False (never suppressing), so ``with`` here only manages the - descriptor lifetime and never swallows a caller's error. - """ + """Close the handle; never suppress the caller's exception.""" self.close() return False def close(self): - """Close the database connection. - - Drains queued token deltas first (the background writer needs the - connection). Writable connections then attempt a PASSIVE WAL - checkpoint (NOT TRUNCATE: transient per-cron-run connections close - many times an hour, and a TRUNCATE fires a full WAL reset that - races the gateway's live writer and tears B-tree pages — issue - #45383). Read-only connections never request a checkpoint. - - When this instance is shared (opened via ``get_shared_session_db``), - ``close()`` RELEASES one refcount instead of tearing down the - connection: the registry owns the lifecycle and only closes on the - final release (#90837). This prevents one caller's close from - tearing down the writer connection that other callers in the same - process are still using — while still letting legacy ``close()`` - call sites return their reference instead of leaking it. - """ + """Close the connection: drain queued token deltas (the writer needs the + connection), then a PASSIVE checkpoint on writable handles (NOT + TRUNCATE: per-cron-run connections close many times an hour and a full + WAL reset races the gateway's live writer, tearing B-tree pages). + A registry-shared instance RELEASES one refcount instead, so one + caller's close cannot tear down a connection others still use.""" if getattr(self, "_shared_registry_owned", False): from hermes_state_registry import release - release(self) return self._stop_token_writer() hook, self._token_atexit_hook = self._token_atexit_hook, None if hook is not None: atexit.unregister(hook) - # Drain the read-only connection pool. Setting the closed flag - # under the lock first means a reader still in flight closes its own - # connection on release instead of re-populating a pool that has - # already been drained. + # Closed flag first (under the lock): an in-flight reader then closes its + # own connection instead of re-populating the drained pool. with self._read_conns_lock: self._read_conns_closed = True - while True: - try: - conn = self._read_pool.get_nowait() - except queue.Empty: - break - self._close_read_conn(conn) + while self._evict_one_idle_read_conn(): + pass with self._lock: if self._conn: - if self._db_corrupt: - # Quarantined handle (see StateDbCorruptError): no explicit - # checkpoint over a damaged page image. + if self._db_corrupt: # quarantined: no checkpoint over a damaged image logger.warning( "Skipping the close-time WAL checkpoint for %s: this " "handle observed structural corruption (%s). Take a " "snapshot of state.db, -wal and -shm before restarting, " - "then run `hermes sessions recover --source %s " - "--inspect-only`.", + "then run `hermes sessions recover --source %s --inspect-only`.", self.db_path, self._db_corrupt_reason, self.db_path, ) - elif not self.read_only: - # PASSIVE, not TRUNCATE. Every cron run_agent opens+closes a - # transient SessionDB, so a TRUNCATE here fires a full WAL - # reset many times/hour, racing the gateway's long-lived - # writer on large WAL databases and tearing hot B-tree - # pages -- the #45383 corruption this class's own periodic - # checkpoint was already made PASSIVE to avoid. TRUNCATE - # belongs only on a sole-opener/quiescent connection. + elif not self.read_only: # PASSIVE, not TRUNCATE (see docstring) try: self._conn.execute("PRAGMA wal_checkpoint(PASSIVE)") except Exception as exc: - logger.debug( - "WAL checkpoint (PASSIVE) at close failed: %s", - exc, - ) + logger.debug("WAL checkpoint (PASSIVE) at close failed: %s", exc) conn, self._conn = self._conn, None self._close_connection_quietly(conn) - # A clean close of the last connection lets SQLite unlink the - # WAL/SHM sidecars — a legitimate end of this handle's sidecar - # generation, not a split (#94736 late writes must still - # self-heal). Drop the recorded generation so a teardown-race - # reopen re-adopts whatever exists then instead of halting. + # A clean last close lets SQLite unlink the sidecars — a + # legitimate end of this generation, not a split. Drop it so a + # teardown-race reopen re-adopts what exists instead of halting. self._db_sidecar_identity = {} def __del__(self) -> None: - """Safety net: close the connection if the caller forgot. - - The async accounting worker retires when idle and its atexit hook - holds only a weak reference, so neither can pin an otherwise orphaned - instance. During interpreter teardown the order of module cleanup is - undefined, so every attribute access remains guarded. - - Delegates to ``close()`` so the read pool, token writer, and atexit - hook are all cleaned up — not just the writer connection. - """ + """Safety net: close() if the caller forgot (read pool, token writer and + atexit hook too). Attribute access stays guarded: module teardown order + is undefined.""" if self.__dict__.get("_conn") is None: return try: @@ -3748,69 +2560,28 @@ class SessionDB( pass # ── Chunked FTS rebuild engine (v23 opt-in optimize) ── - # - # `optimize_fts_storage()` (the `hermes sessions optimize-storage` - # command) drops the legacy inline FTS indexes and backfills the new - # external-content ones. A single blocking rebuild measured ~16 minutes - # of held write lock on a real 25 GB DB, so the backfill runs in small - # chunks, each in its own short write transaction: - # - concurrent readers/writers are never starved (WAL stays small, - # each chunk checkpoints via the normal _execute_write cadence); - # - an interrupted run (Ctrl-C, crash) resumes from - # fts_rebuild_progress when the command is re-run; - # - multiple processes sharing the DB don't double-run it — each chunk - # claims work by compare-and-swap on fts_rebuild_progress, so even a - # concurrent second runner just interleaves chunks safely. - # - # THROTTLING (the part that keeps a live gateway sharing the DB - # responsive): a greedy chunk loop re-acquires BEGIN IMMEDIATE nearly - # back-to-back and can starve another process's writer into exhausting - # its lock retries (an early 5000-row/50ms version owned the write lock - # ~85% of the time and visibly froze concurrent CLI sessions on a large - # install). Two layers prevent that: - # 1. Small chunks (500 rows) — a foreground write queues behind a - # chunk for at most ~tens of ms. - # 2. Inter-chunk pause — the loop sleeps max(_FTS_REBUILD_MIN_PAUSE, - # chunk cost x _FTS_REBUILD_DUTY_FACTOR) between chunks, capping - # this process's share of DB bandwidth so concurrent writers always - # find open windows. This works cross-process (unlike any - # same-process activity stamp) because it bounds our own duty - # cycle unconditionally. - + # One blocking rebuild held the write lock ~16 minutes on a 25 GB DB, so the + # backfill runs in small chunks, each its own short transaction (resumable + # from fts_rebuild_progress; concurrent runners claim chunks by CAS). + # THROTTLING: a greedy loop owned the lock ~85% of the time and starved + # other processes' writers; 500-row chunks plus a pause of max(MIN_PAUSE, + # chunk cost x DUTY_FACTOR) cap our duty cycle unconditionally (works + # cross-process, unlike any same-process activity stamp). _FTS_REBUILD_CHUNK_ROWS = 500 _FTS_REBUILD_DUTY_FACTOR = 4.0 # sleep >= 4x chunk cost (≤20% duty) _FTS_REBUILD_MIN_PAUSE = 0.2 # seconds — floor between chunks - # Demoted v22 FTS shadow tables awaiting teardown (see the v23 migration: - # DROP of a multi-GB FTS vtable blocks for minutes, so the migration - # demotes the vtable definitions out of sqlite_master and renames the - # orphaned shadow tables — now plain tables — to fts_v22_trash_*; the - # worker empties them in bounded chunks, then drops them cheaply). + # Demoted v22 FTS shadow tables awaiting teardown: DROP of a multi-GB vtable + # blocks for minutes, so the v23 migration demotes the vtable definitions + # out of sqlite_master and renames the orphaned shadow tables (now plain + # tables) to fts_v22_trash_*; the worker empties them in chunks, then drops. _FTS_TRASH_PREFIX = "fts_v22_trash_" - # ── CJK-bigram index backfill (dedicated marker pair) ── - # - # Same chunk engine as the main deferred rebuild, but on the - # ``fts_cjk_rebuild_*`` markers so a cjk-only backfill (the common case: - # an already-optimized v23 DB gaining the cjk index) never gates the - # complete ``messages_fts`` / trigram triggers. - - # ── Opt-in v23 FTS storage optimization (`hermes sessions optimize-storage`) ── - # - # This is the ONLY path that migrates an existing legacy (v22 inline) DB - # to the v23 external-content schema. It is deliberately foreground and - # user-invoked, never automatic, because it is disk-heavy and long. It - # runs the throttled/resumable chunk engine above to completion - # synchronously — demote → new schema → chunked backfill → chunked - # teardown — with progress callbacks, a disk preflight in the CLI - # wrapper, a VACUUM at the end, and a defensive schema_version bump. - def _has_fts_trash(self, conn) -> bool: """True when demoted v22 shadow tables are still awaiting teardown. Caller must hold ``self._lock`` (or pass a migration-time cursor).""" return bool(conn.execute( - "SELECT 1 FROM sqlite_master WHERE type = 'table' " - "AND name LIKE ? ESCAPE '\\' LIMIT 1", + "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name LIKE ? ESCAPE '\\' LIMIT 1", (self._FTS_TRASH_PREFIX.replace("_", "\\_") + "%",), ).fetchone()) @@ -3821,88 +2592,99 @@ class SessionDB( _PROFILE_DIR_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$") def _own_profile_name(self) -> Optional[str]: - """The profile that owns THIS store, derived from ``db_path`` alone. - - Every profile-tree ``state.db`` belongs to exactly one profile - (``/state.db`` → ``default``, - ``/profiles//state.db`` → ````), so the derivation - is a single match, never a guess — the same contract - :meth:`backfill_null_session_profiles` and the web listing's - ``row_profile`` stamp rely on. Path-based (not - ``get_active_profile_name()``) on purpose: a gateway serving a - NON-launch profile opens that profile's store directly, and the row - must be stamped with the store's owner, not the serving process's - launch profile. Returns ``None`` for stores outside the profile tree - (explicit ``db_path`` in tests, ad-hoc copies) — those rows keep the - legacy NULL rather than a fabricated owner. - """ + """The profile owning THIS store, from ``db_path`` alone (``/state.db`` + → default, ``/profiles//state.db`` → name). Path-based, not + get_active_profile_name(): a gateway serving a NON-launch profile opens + that profile's store and rows must carry the store's owner. None outside + the profile tree — keep NULL rather than a fabricated owner.""" try: from hermes_constants import get_default_hermes_root - root = get_default_hermes_root().resolve() parent = Path(self.db_path).resolve().parent if parent == root: return "default" - if parent.parent == root / "profiles" and self._PROFILE_DIR_RE.match( - parent.name - ): + if parent.parent == root / "profiles" and self._PROFILE_DIR_RE.match(parent.name): return parent.name except Exception: logger.debug("own-profile derivation failed", exc_info=True) return None + @staticmethod + def _inherit_parent_session_metadata(conn, session_id: str) -> None: + """NULL-fill a child's cwd/git/profile from its parent (child creators + didn't propagate them, so lineages dropped out of the project sidebar); + profile_name only within the same ``agent::`` namespace. The second + UPDATE inherits gateway routing columns ONLY for compression forks: a + crash before the gateway re-records the peer would otherwise strand the + child unroutable, while delegate children are spawned under a live + parent and must NOT inherit routing keys (peer recovery could repoint + gateway traffic into a subagent's session).""" + conn.execute( + f"""UPDATE sessions + SET cwd = COALESCE(sessions.cwd, + (SELECT p.cwd FROM sessions p + WHERE p.id = sessions.parent_session_id)), + git_repo_root = COALESCE(sessions.git_repo_root, + (SELECT p.git_repo_root FROM sessions p + WHERE p.id = sessions.parent_session_id)), + git_branch = COALESCE(sessions.git_branch, + (SELECT p.git_branch FROM sessions p + WHERE p.id = sessions.parent_session_id)), + profile_name = COALESCE(sessions.profile_name, + (SELECT p.profile_name FROM sessions p + WHERE p.id = sessions.parent_session_id + AND ({_SAME_KEY_NAMESPACE_SQL}))) + WHERE id = ? AND parent_session_id IS NOT NULL""", + (session_id,), + ) + conn.execute( + """UPDATE sessions + SET user_id = COALESCE(sessions.user_id, + (SELECT p.user_id FROM sessions p + WHERE p.id = sessions.parent_session_id)), + session_key = COALESCE(sessions.session_key, + (SELECT p.session_key FROM sessions p + WHERE p.id = sessions.parent_session_id)), + chat_id = COALESCE(sessions.chat_id, + (SELECT p.chat_id FROM sessions p + WHERE p.id = sessions.parent_session_id)), + chat_type = COALESCE(sessions.chat_type, + (SELECT p.chat_type FROM sessions p + WHERE p.id = sessions.parent_session_id)), + thread_id = COALESCE(sessions.thread_id, + (SELECT p.thread_id FROM sessions p + WHERE p.id = sessions.parent_session_id)), + display_name = COALESCE(sessions.display_name, + (SELECT p.display_name FROM sessions p + WHERE p.id = sessions.parent_session_id)), + origin_json = COALESCE(sessions.origin_json, + (SELECT p.origin_json FROM sessions p + WHERE p.id = sessions.parent_session_id)) + WHERE id = ? AND parent_session_id IS NOT NULL + AND EXISTS ( + SELECT 1 FROM sessions p + WHERE p.id = sessions.parent_session_id + AND p.end_reason = 'compression' + )""", + (session_id,), + ) + def _insert_session_row( - self, - session_id: str, - source: str, - model: str = None, - model_config: Dict[str, Any] = None, - system_prompt: str = None, - user_id: str = None, - session_key: Optional[str] = None, - chat_id: str = None, - chat_type: str = None, - thread_id: str = None, - parent_session_id: str = None, - cwd: str = None, - profile_name: Optional[str] = None, - git_repo_root: str = None, - origin_json: str = None, - display_name: str = None, + self, session_id: str, source: str, model: str = None, model_config: Dict[str, Any] = None, + system_prompt: str = None, user_id: str = None, session_key: Optional[str] = None, + chat_id: str = None, chat_type: str = None, thread_id: str = None, + parent_session_id: str = None, cwd: str = None, profile_name: Optional[str] = None, + git_repo_root: str = None, origin_json: str = None, display_name: str = None, ) -> None: - """Insert a session row, enriching NULL metadata on conflict. - - The gateway creates a bare row (source + user_id) before the agent - exists and the agent's later ``create_session`` carries the real - model/model_config/system_prompt; ``INSERT OR IGNORE`` dropped that - enrichment, so the upsert ``COALESCE``-fills columns that are still - NULL and never overwrites what an earlier writer set (a later bare - source="unknown" call cannot clobber a real source/model). - - ``chat_id``/``thread_id`` record the messaging origin so gateway - ``/resume`` can prove an inactive row belongs to the caller's - chat/thread (IDOR scoping). - - With ``parent_session_id`` (compression fork, delegate spawn, branch), - NULL ``cwd``/``git_repo_root``/``git_branch``/``profile_name`` are - backfilled from the parent — child creators historically did not - propagate them, so lineages dropped out of the project sidebar or were - aggregated as "default" on every fork. NULL-fill only. Compression - forks (parent ``end_reason='compression'``) also inherit the gateway - origin columns (user_id/session_key/chat_id/chat_type/thread_id/ - display_name/origin_json) so a crash before the gateway re-records the - peer cannot strand the child without a routing mapping. - - With no ``profile_name`` the row is stamped with THIS store's own - profile (:meth:`_own_profile_name`): every state.db belongs to exactly - one profile (the contract :meth:`backfill_null_session_profiles` - relies on), and profile-keyed consumers treat NULL as unowned, hiding - the session from the sidebar. Stores outside the profile tree derive - nothing and keep NULL — never guess. - """ + """Upsert a session row, COALESCE-filling NULL columns and never + overwriting what an earlier writer set (the gateway creates a bare row + before the agent's create_session carries the real model/prompt; a later + bare source="unknown" cannot clobber it). chat_id/thread_id scope gateway + /resume (IDOR). Children backfill from the parent + (:meth:`_inherit_parent_session_metadata`); a missing profile_name is + stamped with THIS store's own profile (NULL reads as unowned).""" if not (profile_name or "").strip(): profile_name = self._own_profile_name() - def _do(conn): system_prompt_hash = self._store_system_prompt(conn, system_prompt) conn.execute( @@ -3955,91 +2737,17 @@ class SessionDB( origin_json = COALESCE(sessions.origin_json, excluded.origin_json), display_name = COALESCE(sessions.display_name, excluded.display_name)""", ( - session_id, - source, - user_id, - session_key, - chat_id, - chat_type, - thread_id, - model, - json.dumps(model_config) if model_config else None, - system_prompt_hash, - parent_session_id, - cwd, - profile_name, - git_repo_root, - origin_json, - display_name, + session_id, source, user_id, session_key, chat_id, chat_type, thread_id, model, + json.dumps(model_config) if model_config else None, system_prompt_hash, + parent_session_id, cwd, profile_name, git_repo_root, origin_json, display_name, time.time(), ), ) if system_prompt_hash is not None: self._delete_unreferenced_system_prompts(conn) if parent_session_id: - conn.execute( - f"""UPDATE sessions - SET cwd = COALESCE(sessions.cwd, - (SELECT p.cwd FROM sessions p - WHERE p.id = sessions.parent_session_id)), - git_repo_root = COALESCE(sessions.git_repo_root, - (SELECT p.git_repo_root FROM sessions p - WHERE p.id = sessions.parent_session_id)), - git_branch = COALESCE(sessions.git_branch, - (SELECT p.git_branch FROM sessions p - WHERE p.id = sessions.parent_session_id)), - profile_name = COALESCE(sessions.profile_name, - (SELECT p.profile_name FROM sessions p - WHERE p.id = sessions.parent_session_id - AND ({_SAME_KEY_NAMESPACE_SQL}))) - WHERE id = ? AND parent_session_id IS NOT NULL""", - (session_id,), - ) - # Belt-and-suspenders for gateway routing metadata (#59527): - # the gateway re-records the peer on the child after rotation - # (d5b4879d4), but a hard crash between child creation and that - # write leaves the child row without origin columns, so - # ``find_latest_gateway_session_for_peer`` can't recover the - # mapping on restart. Inherit them from the parent at creation - # time — but ONLY for compression forks (parent already ended - # with end_reason='compression'). Delegate/subagent children - # are spawned while the parent is still live and must NOT - # inherit routing keys, or peer recovery could repoint gateway - # traffic into a subagent's session. - conn.execute( - """UPDATE sessions - SET user_id = COALESCE(sessions.user_id, - (SELECT p.user_id FROM sessions p - WHERE p.id = sessions.parent_session_id)), - session_key = COALESCE(sessions.session_key, - (SELECT p.session_key FROM sessions p - WHERE p.id = sessions.parent_session_id)), - chat_id = COALESCE(sessions.chat_id, - (SELECT p.chat_id FROM sessions p - WHERE p.id = sessions.parent_session_id)), - chat_type = COALESCE(sessions.chat_type, - (SELECT p.chat_type FROM sessions p - WHERE p.id = sessions.parent_session_id)), - thread_id = COALESCE(sessions.thread_id, - (SELECT p.thread_id FROM sessions p - WHERE p.id = sessions.parent_session_id)), - display_name = COALESCE(sessions.display_name, - (SELECT p.display_name FROM sessions p - WHERE p.id = sessions.parent_session_id)), - origin_json = COALESCE(sessions.origin_json, - (SELECT p.origin_json FROM sessions p - WHERE p.id = sessions.parent_session_id)) - WHERE id = ? AND parent_session_id IS NOT NULL - AND EXISTS ( - SELECT 1 FROM sessions p - WHERE p.id = sessions.parent_session_id - AND p.end_reason = 'compression' - )""", - (session_id,), - ) - # Session-row creation is transcript-critical: if it fails, the - # first flush of a new session fails and the turn is aborted as - # session_persistence_failed. Ride out long sibling holds. + self._inherit_parent_session_metadata(conn, session_id) + # Transcript-critical: a failed row creation aborts the turn. Ride out long holds. self._execute_write(_do, patience_s=self._TRANSCRIPT_WRITE_PATIENCE_S) def create_session(self, session_id: str, source: str, **kwargs) -> str: @@ -4047,40 +2755,25 @@ class SessionDB( self._insert_session_row(session_id, source, **kwargs) return session_id - def set_expiry_finalized(self, session_id: str, finalized: bool = True) -> None: - """Mark a gateway session's expiry-finalization flag in state.db. - - Mirrors ``SessionEntry.expiry_finalized`` (sessions.json) so the flag - survives even if the JSON index is pruned or lost (#9006). - """ + """Mirror ``SessionEntry.expiry_finalized`` so it survives a lost sessions.json.""" if not session_id: return - self._write_sql( "UPDATE sessions SET expiry_finalized = ? WHERE id = ?", (1 if finalized else 0, session_id), ) - # ── Gateway routing index (replaces sessions.json, #9006 follow-up) ──── - + # ── Gateway routing index (replaces sessions.json) ──── def find_session_by_origin( - self, - *, - platform: str, - chat_id: str, - thread_id: Optional[str] = None, + self, *, platform: str, chat_id: str, thread_id: Optional[str] = None, user_id: Optional[str] = None, ) -> Optional[str]: - """Find the most recent live session_id for a platform + chat origin. - - Equivalent of gateway/mirror's sessions.json scan: matches on - source + chat_id (+ thread_id when provided). When ``user_id`` is - provided, exact sender matches are preferred; if multiple distinct - users share the chat and none matches, returns None rather than - contaminating another participant's session. - """ + """Most recent live session_id for source + chat_id (+ thread_id). With + ``user_id``, exact sender matches win; if several distinct users share + the chat and none matches, None rather than contaminating another + participant's session.""" if not platform or chat_id in (None, ""): return None query = """ @@ -4095,8 +2788,7 @@ class SessionDB( query += " AND COALESCE(thread_id, '') = ?" params.append(str(thread_id)) query += " ORDER BY started_at DESC" - with self._read_ctx() as conn: - rows = [dict(r) for r in conn.execute(query, params).fetchall()] + rows = [dict(r) for r in self._read_all(query, params)] if not rows: return None if user_id: @@ -4106,88 +2798,59 @@ class SessionDB( if len(rows) > 1: return None elif len(rows) > 1: - distinct_users = { - str(r.get("user_id") or "").strip() - for r in rows - if str(r.get("user_id") or "").strip() - } + distinct_users = {u for u in (str(r.get("user_id") or "").strip() for r in rows) if u} if len(distinct_users) > 1: return None return str(rows[0]["id"]) - - # ── Orphaned gateway-session repair (#82616) ────────────────────────── - # A write-path failure (corrupt FTS, crash between routing publication - # and row creation) can leave the live conversation in a session row - # that never received its identity columns. Both queries above require - # those columns, so the row holding the real transcript is invisible to - # recovery: the chat resolves to the last keyed row instead — days older - # — and the conversation time-travels. Hardening the write side cannot - # reach a row that is *already* damaged; these two methods are the - # offline repair path behind ``hermes sessions repair-routing``. - - # Widest plausible gap between a keyed predecessor going quiet and its - # unkeyed successor being minted. The reported incident gap was ~60s; - # 15 minutes stays generous without spanning unrelated conversations. + # ── Orphaned gateway-session repair (``hermes sessions repair-routing``) ── + # A write-path failure between routing publication and row creation leaves + # the live transcript in a row without identity columns, invisible to + # recovery (the chat resolves to a days-older keyed row). Widest plausible + # gap between a keyed predecessor going quiet and its unkeyed successor: + # the reported incident was ~60s; 15 minutes stays generous without + # spanning unrelated conversations. _ORPHAN_ADOPTION_MAX_GAP_S = 900.0 - - # Children that carry a ``parent_session_id`` but are NOT compression - # continuations: branches, delegate/subagent runs, and tool sessions. - # A marker only disqualifies a child when it points at the parent being - # queried — compression continuations inherit the rotated agent's - # ``model_config`` verbatim (``publish_compression_child`` callers pass - # ``agent._session_init_model_config``), so a delegate subagent's - # continuation carries ``_delegate_from=``. - # Matching markers by mere presence misclassified those real - # continuations as delegate children (fail-open for orphan reopen, - # fail-closed for adoption). Bind the parent id for both markers. + # Children with a ``parent_session_id`` that are NOT compression + # continuations (branches, delegate runs, tool sessions). Markers are bound + # to the queried parent id: compression continuations inherit the rotated + # agent's model_config verbatim, so a delegate's continuation carries + # ``_delegate_from=`` and presence-matching + # misclassified real continuations as delegate children. _NON_CONTINUATION_CHILD_FILTER_SQL = ( " AND COALESCE(json_extract(COALESCE({alias}model_config, '{{}}')," " '$._branched_from'), '') != ?\n" " AND COALESCE(json_extract(COALESCE({alias}model_config, '{{}}')," - " '$._delegate_from'), '') != ?\n" - " AND COALESCE({alias}source, '') != 'tool'\n" + " '$._delegate_from'), '') != ?\n AND COALESCE({alias}source, '') != 'tool'\n" ) - def end_session(self, session_id: str, end_reason: str) -> None: - """Mark a session as ended. - - No-ops when the session is already ended. The first end_reason wins: - compression-split sessions must keep their ``end_reason = 'compression'`` - record even if a later stale ``end_session()`` call (e.g. from a - desynced CLI session_id after ``/resume`` or ``/branch``) targets them - with a different reason. Use ``reopen_session()`` first if you - intentionally need to re-end a closed session with a new reason. - """ + """Mark a session ended. The first end_reason wins (no-op when already + ended): a compression split must keep ``'compression'`` even if a stale + desynced-CLI end_session() targets it later. reopen_session() first to + deliberately re-end with a new reason.""" def _do(conn): changed = conn.execute( "UPDATE sessions SET ended_at = ?, end_reason = ? " "WHERE id = ? AND ended_at IS NULL", (time.time(), end_reason, session_id), ).rowcount - # Only a boundary this call actually wrote advances the generation: - # the first end_reason wins, so a no-op must not rotate the peer. + # Only a boundary this call wrote advances the generation (a no-op must not rotate the peer). if changed: self._bump_conversation_generation(conn, session_id, end_reason) self._execute_write(_do) def reopen_session(self, session_id: str) -> None: - """Clear ended_at/end_reason so a session can be resumed. - - Before clearing a reset boundary, stabilize markerless legacy reset - children that still depend on the parent's mutable end_reason. - """ + """Clear ended_at/end_reason so a session can be resumed. First stamp + markerless legacy reset children that depend on the parent's mutable + end_reason (WHERE shared with the listing predicate via + _legacy_reset_child_sql so the two cannot drift).""" def _do(conn): placeholders = ",".join("?" for _ in _RESET_END_REASONS) - # WHERE shape shared with _RESET_CHILD_SQL's fallback arm via - # _legacy_reset_child_sql so the stamping and the listing - # predicate cannot drift. conn.execute( "UPDATE sessions AS child SET model_config = json_set(" - "COALESCE(child.model_config, '{}'), '$._reset_from', " - "child.parent_session_id) " + "COALESCE(child.model_config, '{}'), '$._reset_from', child.parent_session_id) " "WHERE child.parent_session_id = ? " "AND json_extract(COALESCE(child.model_config, '{}'), " " '$._reset_from') IS NULL " @@ -4200,40 +2863,16 @@ class SessionDB( ) self._execute_write(_do) - def promote_to_session_reset( - self, session_id: str, reason: str = "session_reset" - ) -> bool: - """Durably mark a session as ended by an intentional reset boundary. - - Promotes *only* live rows (``ended_at IS NULL``) or rows carrying an - accidental end_reason that the recovery query - (``find_latest_gateway_session_for_peer``) treats as recoverable: - ``agent_close`` (older gateway cleanup bug) and ``ws_orphan_reap`` - (mistaken TUI reaper). Explicit conversation boundaries such as - ``compression``, ``session_reset``, ``session_switch``, etc. are - preserved — the first writer wins for those, and a later expiry - finalization must not silently overwrite them. - - Plain ``end_session()`` is NOT sufficient for reset boundaries: it - no-ops on an already-ended row, so a row that agent cleanup already - closed as ``agent_close`` would stay recoverable and stale-route - recovery would resurrect the reset session with its full history - (#61220, #61993, #63539). - - Keep this promotion set in sync with the recoverable set in - ``find_latest_gateway_session_for_peer`` — any reason recovery would - reopen must be promotable here. - - ``reason`` lets reset paths keep their auditable specific reasons - (``idle``, ``daily``, ``suspended``, ``resume_pending_expired``). - - Returns ``True`` when the row was promoted, ``False`` when skipped - (already has a different explicit end_reason, or row not found). - """ + def promote_to_session_reset(self, session_id: str, reason: str = "session_reset") -> bool: + """Durably mark an intentional reset boundary on live rows or rows with a + *recoverable* accidental end_reason; explicit boundaries are preserved + (first writer wins). Plain end_session() no-ops on an ended row, so an + ``agent_close`` row would stay recoverable and stale-route recovery would + resurrect the reset session. Keep in sync with + find_latest_gateway_session_for_peer. True when promoted.""" if not session_id: return False now = time.time() - def _do(conn): cursor = conn.execute( "UPDATE sessions SET ended_at = ?, end_reason = ? " @@ -4241,71 +2880,39 @@ class SessionDB( f"OR end_reason IN ({_RECOVERABLE_END_REASONS_SQL}))", (now, reason, session_id), ) - # /new and the policy auto-resets promote rather than end_session, - # so the generation has to advance here too — in the same - # transaction as the boundary, and only when one was written. + # /new and policy auto-resets promote rather than end_session, so the + # generation advances here too — same transaction, only when written. if cursor.rowcount: self._bump_conversation_generation(conn, session_id, reason) return cursor.rowcount - try: - rows = self._execute_write(_do) - return bool(rows) + return bool(self._execute_write(_do)) except Exception: return False def update_session_cwd( - self, - session_id: str, - cwd: str, - git_branch: Optional[str] = None, - git_repo_root: Optional[str] = None, - replace_git_meta: bool = False, + self, session_id: str, cwd: str, git_branch: Optional[str] = None, + git_repo_root: Optional[str] = None, replace_git_meta: bool = False, ) -> Optional[int]: """Persist the authoritative cwd and claim a Git metadata generation. - - ``git_branch`` records the git branch checked out in ``cwd`` at the time - the session started/resumed. The sidebar groups main-checkout sessions - by this so feature-branch work doesn't pile under a single "main" row - (the main checkout's *current* branch is transient and would - misattribute past sessions). - - ``git_repo_root`` records the git repo this cwd belongs to — the - authoritative project key. Resolving it here, at the lowest level, means - every surface reads the same membership instead of re-probing git in the - GUI over a partial page. Each field is only written when non-empty so a - probe failure never clobbers a previously-captured value. - - ``replace_git_meta`` inverts that non-empty rule: a deliberate workspace - MOVE (re-homing a session into another project) must overwrite the old - repo identity even when the new cwd resolves to none — keeping the stale - root would leave the session grouped under the project it just left. - - Every call increments ``git_metadata_generation`` in the same write - transaction. Async Git probes must publish through - :meth:`publish_session_git_metadata` with the returned generation, so - an older worker cannot overwrite a newer cwd claim even after an - A -> B -> A transition or from another process sharing this database. - Metadata from a different cwd is cleared atomically with the move. - """ + git fields are written only when non-empty (a probe failure never + clobbers a captured value) except under ``replace_git_meta`` (a + workspace MOVE must overwrite the old repo identity even when the new + cwd has none). Each call bumps ``git_metadata_generation``; async probes + publish via :meth:`publish_session_git_metadata` with that generation so + an older worker cannot overwrite a newer claim (A -> B -> A).""" if not session_id or not cwd: return None - branch = (git_branch or "").strip() repo_root = (git_repo_root or "").strip() - def _do(conn): current = conn.execute( "SELECT cwd FROM sessions WHERE id = ?", (session_id,) ).fetchone() if current is None: return None - current_cwd = current[0] - sets = [ - "cwd = ?", - "git_metadata_generation = COALESCE(git_metadata_generation, 0) + 1", - ] + sets = ["cwd = ?", "git_metadata_generation = COALESCE(git_metadata_generation, 0) + 1"] params: List[Any] = [cwd] if current_cwd != cwd or replace_git_meta: sets.extend(("git_branch = ?", "git_repo_root = ?")) @@ -4317,26 +2924,15 @@ class SessionDB( sets.append("git_repo_root = ?") params.append(repo_root) params.append(session_id) - conn.execute( - f"UPDATE sessions SET {', '.join(sets)} WHERE id = ?", params - ) + conn.execute(f"UPDATE sessions SET {', '.join(sets)} WHERE id = ?", params) row = conn.execute( - "SELECT git_metadata_generation FROM sessions WHERE id = ?", - (session_id,), + "SELECT git_metadata_generation FROM sessions WHERE id = ?", (session_id,), ).fetchone() - if row is None: - return None - value = row[0] - return int(value) - + return None if row is None else int(row[0]) return self._execute_write(_do) def publish_session_git_metadata( - self, - session_id: str, - cwd: str, - generation: int, - git_branch: Optional[str] = None, + self, session_id: str, cwd: str, generation: int, git_branch: Optional[str] = None, git_repo_root: Optional[str] = None, ) -> bool: """Publish async Git enrichment only while its cwd claim is current.""" @@ -4348,12 +2944,10 @@ class SessionDB( or generation < 1 ): return False - branch = (git_branch or "").strip() repo_root = (git_repo_root or "").strip() if not branch and not repo_root: return False - sets: List[str] = [] params: List[Any] = [] if branch: @@ -4363,125 +2957,58 @@ class SessionDB( sets.append("git_repo_root = ?") params.append(repo_root) params.extend((session_id, cwd, generation)) - return self._write_rowcount( f"UPDATE sessions SET {', '.join(sets)} " - "WHERE id = ? AND cwd = ? " - "AND git_metadata_generation = ?", + "WHERE id = ? AND cwd = ? AND git_metadata_generation = ?", params, ) == 1 def backfill_repo_roots(self, cwd_to_root: Dict[str, str]) -> None: - """Persist resolved git repo roots for cwds that don't have one yet. - - Backfills history so projects light up for sessions created before the - column existed, without clobbering an already-recorded root. Only - non-empty roots are written (a non-git cwd stays NULL). - """ + """Backfill git repo roots for cwds without one (pre-column sessions); + never clobbers a recorded root; empty roots are skipped.""" pairs = [(root, cwd) for cwd, root in cwd_to_root.items() if root and cwd] - if not pairs: - return - - def _do(conn): - for root, cwd in pairs: - conn.execute( - "UPDATE sessions SET git_repo_root = ? " - "WHERE cwd = ? AND COALESCE(git_repo_root, '') = ''", - (root, cwd), - ) - - self._execute_write(_do) - - - # ────────────────────────────────────────────────────────────────────── - # Compression locks - # ────────────────────────────────────────────────────────────────────── - # Atomic per-session locks that prevent two compression paths from - # racing on the same session_id and producing orphan child sessions. - # - # The race: ``conversation_compression.py`` rotates ``agent.session_id`` - # as a side effect of a successful compression (end old session, create - # new). That mutation is local to the AIAgent instance — but ``state.db`` - # is shared across all instances. Two AIAgents that share the same - # ``session_id`` at the moment they both decide to compress (most - # commonly the parent turn's agent + a background-review fork started - # right after the turn ended) each end the parent and create their own - # NEW session, parented to the same old id. The gateway SessionEntry - # only catches one rotation; the other child silently accumulates - # writes — Damien's "parent → two orphan children" repro shape. - # - # The lock is keyed by ``session_id`` and is held for the duration of - # the compress() call plus the rotation. ``holder`` identifies the - # current owner (pid:tid:nonce) for diagnostics; the lock is recovered - # via ``expires_at`` if the holder process crashed without releasing. + if pairs: + self._write_sql( + "UPDATE sessions SET git_repo_root = ? " + "WHERE cwd = ? AND COALESCE(git_repo_root, '') = ''", + pairs, many=True, + ) + # Compression locks (atomic per-session, keyed by session_id, recovered via + # expires_at) live in SessionCompressionMixin; they stop two AIAgents that + # share a session_id from both rotating it into two orphan children. def touch_session_activity( - self, - session_id: str, - ts: Optional[float] = None, - *, - description: Optional[str] = None, + self, session_id: str, ts: Optional[float] = None, *, description: Optional[str] = None, provenance: Optional[ActivityProvenance] = None, ) -> None: - """Stamp durable mid-turn session activity (observation-only). - - Called (rate-limited) from ``AIAgent._touch_activity`` so gateway/CLI - surfaces and stall consumers observe API/tool/compaction activity - even when no new message row has been written yet (#72016 / #72039). - - Never moves ``last_activity_at`` backwards. When the timestamp - advances, bounded ``last_activity_description`` / - ``last_activity_provenance`` are written with it. No-ops when - ``session_id`` is empty or the row does not exist. - """ + """Stamp durable mid-turn activity (observation-only; rate-limited by + AIAgent._touch_activity) so surfaces see API/tool/compaction activity + before any message row lands. Never moves ``last_activity_at`` backwards.""" if not session_id: return from agent.session_activity import ( - bound_activity_description, - normalize_activity_provenance, + bound_activity_description, normalize_activity_provenance, ) - when = float(ts if ts is not None else time.time()) desc = bound_activity_description(description) prov = normalize_activity_provenance(provenance).value - - # Observation-only write: never let it ride the full routine - # write-patience budget (#76354 review S1). Under contention a - # heartbeat that waits ~20s would delay the response-critical path - # it is merely observing; give up after a sub-second budget instead - # (the next due window retries naturally). self._write_sql( - "UPDATE sessions SET " - "last_activity_at = ?, " - "last_activity_description = ?, " - "last_activity_provenance = ? " + "UPDATE sessions SET last_activity_at = ?, " + "last_activity_description = ?, last_activity_provenance = ? " "WHERE id = ? AND (last_activity_at IS NULL OR last_activity_at < ?)", (when, desc, prov, session_id, when), patience_s=self._ACTIVITY_WRITE_PATIENCE_S, ) def clear_session_activity_labels(self, session_id: str) -> None: - """Clear mid-turn activity labels after a turn ends. - - Keeps ``last_activity_at`` intact so idle / watchdog clocks stay - continuous. Description and provenance are observation labels for - *what was happening at* that timestamp during an active turn; once - the turn is idle they must not keep advertising "compressing" / - "executing tool" (#72039). - - Response-critical-path contract (#76354 review S1): runs in the - turn's ``finally``; a no-op clear (labels already empty) skips the - write transaction entirely, and a real clear uses the same short - sub-second busy budget as :meth:`touch_session_activity` instead of - the full routine write patience. - """ + """Clear activity labels after a turn (keep ``last_activity_at`` so idle / + watchdog clocks stay continuous; an idle turn must not keep advertising + "compressing"). Runs in the turn's finally: a no-op clear skips the + write transaction, a real one uses the short activity budget.""" if not session_id: return from agent.session_activity import ActivityProvenance - - # No-op fast path: skip the transaction when there is nothing to - # clear. Read-only, no write lock. try: row = self._read_one( "SELECT last_activity_description, last_activity_provenance " @@ -4490,32 +3017,21 @@ class SessionDB( ) except sqlite3.Error: row = None - if row is not None: - desc = row[0] - prov = row[1] - if not desc and ( - not prov or prov == ActivityProvenance.UNKNOWN.value - ): - return - + if row is not None and not row[0] and (not row[1] or row[1] == ActivityProvenance.UNKNOWN.value): + return self._write_sql( - "UPDATE sessions SET " - "last_activity_description = ?, " - "last_activity_provenance = ? " - "WHERE id = ?", + "UPDATE sessions SET last_activity_description = ?, " + "last_activity_provenance = ? WHERE id = ?", ("", ActivityProvenance.UNKNOWN.value, session_id), patience_s=self._ACTIVITY_WRITE_PATIENCE_S, ) def get_session_activity(self, session_id: str) -> Optional[Dict[str, Any]]: """Return the durable activity snapshot for *session_id*, or None.""" - if not session_id: - return None - row = self.get_session(session_id) + row = self.get_session(session_id) if session_id else None if not row: return None from agent.session_activity import build_activity_snapshot - return build_activity_snapshot( last_activity_at=row.get("last_activity_at"), last_activity_description=row.get("last_activity_description"), @@ -4523,148 +3039,97 @@ class SessionDB( ) def update_session_meta( - self, - session_id: str, - model_config_json: str, - model: Optional[str] = None, + self, session_id: str, model_config_json: str, model: Optional[str] = None, ) -> None: - """Update model_config and optionally model for an existing session. - - Uses COALESCE so that passing model=None leaves the stored model - column unchanged. Routes through _execute_write for the standard - BEGIN IMMEDIATE + jitter-retry + lock guarantee. - """ - # Barrier against queued token deltas — see update_session_model. - self.flush_token_counts() - + """Update model_config and (COALESCE) optionally model.""" + self.flush_token_counts() # barrier against queued token deltas — see update_session_model self._write_sql( "UPDATE sessions SET model_config = ?, model = COALESCE(?, model) WHERE id = ?", (model_config_json, model, session_id), ) - def update_system_prompt( - self, session_id: str, system_prompt: Optional[str] - ) -> None: + def update_system_prompt(self, session_id: str, system_prompt: Optional[str]) -> None: """Store the full assembled system prompt snapshot.""" def _do(conn): system_prompt_hash = self._store_system_prompt(conn, system_prompt) conn.execute( - "UPDATE sessions " - "SET system_prompt_hash = ?, system_prompt = NULL WHERE id = ?", + "UPDATE sessions SET system_prompt_hash = ?, system_prompt = NULL WHERE id = ?", (system_prompt_hash, session_id), ) self._delete_unreferenced_system_prompts(conn) self._execute_write(_do) - def update_session_tool_names( - self, session_id: str, tool_names: Optional[List[str]] - ) -> None: - """Persist the session's resolved ``tools[]`` name order (JSON array). - - Read back by ``tools.mcp_tool.restore_agent_tool_prefix`` when a fresh - ``AIAgent`` is rebuilt for an existing session (gateway agent-cache - eviction) so a flipped ``check_fn`` verdict can't fork the cached tool - prefix. ``None`` clears the pin. - """ + def update_session_tool_names(self, session_id: str, tool_names: Optional[List[str]]) -> None: + """Persist the resolved ``tools[]`` name order so a rebuilt AIAgent + (agent-cache eviction) can't fork the cached tool prefix on a flipped + check_fn verdict. ``None`` clears the pin.""" payload = json.dumps(list(tool_names)) if tool_names is not None else None - - self._write_sql( - "UPDATE sessions SET tool_names = ? WHERE id = ?", - (payload, session_id), - ) + self._write_sql("UPDATE sessions SET tool_names = ? WHERE id = ?", (payload, session_id)) def update_session_model( self, session_id: str, model: str, provider: Optional[str] = None ) -> None: - """Update the model for a session after a mid-session switch. - - Unlike ``update_token_counts`` which uses ``COALESCE(model, ?)`` - (only filling in NULL), this unconditionally sets the model column - so that the dashboard reflects the user's latest /model choice. - Also nulls ``system_prompt`` so stale ``Model:`` / ``Provider:`` - footer metadata is rebuilt on the next turn. A successful /model - switch explicitly replaces any confirmed Browser runtime lock while - preserving unrelated lineage markers in ``model_config``. - - When *provider* is given, it is merged into ``model_config`` - alongside the model (``$.model`` / ``$.provider``) so a later - resume recombines the persisted model with the provider that - actually serves it instead of the config.yaml primary provider - (#79536). Callers without provider knowledge leave any stored - provider untouched. - """ - # This write bypasses the token queue, so deltas enqueued before the - # switch must land first: a still-queued first delta carries the - # pre-switch route, and applying it after this UPDATE would trip the - # first_accounted_route overwrite in update_token_counts (row sees - # api_call_count == 0 + a route mismatch) and resurrect the old - # model/provider. Flushing here restores the pre-queue ordering. + """Set the model after a mid-session /model switch (unconditionally, + unlike update_token_counts' COALESCE), null system_prompt so stale + Model:/Provider: footers rebuild, and replace any confirmed Browser + runtime lock while keeping lineage markers. *provider* is merged into + model_config so resume recombines the model with the provider that + actually serves it, not the config.yaml primary.""" + # This write bypasses the token queue: a still-queued first delta carries + # the pre-switch route and, applied after this UPDATE, would trip the + # first_accounted_route overwrite and resurrect the old model/provider. self.flush_token_counts() + # browser_model_lock is deleted via a None patch value (same semantics + # as the old json_remove); lineage markers survive the merge. + patch: Dict[str, Any] = {"browser_model_lock": None} + if model: + patch["model"] = model + if provider: + patch["provider"] = provider + self._write_model_config_patch( + session_id, patch, + "UPDATE sessions SET model = ?, model_config = ?, " + "system_prompt = NULL, system_prompt_hash = NULL WHERE id = ?", + lambda merged: (model, merged, session_id), + clear_prompts=True, + ) + def _write_model_config_patch( + self, session_id: str, patch: Dict[str, Any], sql: str, + params: Callable[[Optional[str]], tuple], *, clear_prompts: bool = False, + ) -> None: + """Merge ``patch`` into model_config then run ``sql`` with ``params(merged)``. + + One write transaction; no-op when the row doesn't exist. ``clear_prompts`` + additionally garbage-collects unreferenced system_prompts (for writers + that NULL the row's system_prompt_hash). + """ def _do(conn): - # Use the shared merge discipline so lineage markers like - # _branched_from / _delegate_from survive. browser_model_lock - # is deleted via a None patch value (same semantics as the - # old json_remove). - patch: Dict[str, Any] = {"browser_model_lock": None} - if model: - patch["model"] = model - if provider: - patch["provider"] = provider merged = self._merge_model_config_json(conn, session_id, patch) if merged is _MODEL_CONFIG_ROW_MISSING: return - conn.execute( - "UPDATE sessions SET " - "model = ?, model_config = ?, " - "system_prompt = NULL, system_prompt_hash = NULL " - "WHERE id = ?", - (model, merged, session_id), - ) - self._delete_unreferenced_system_prompts(conn) + conn.execute(sql, params(merged)) + if clear_prompts: + self._delete_unreferenced_system_prompts(conn) self._execute_write(_do) def _merge_model_config_json( - self, - conn, - session_id: str, - patch: Dict[str, Any], - *, - on_missing: str = "skip", + self, conn, session_id: str, patch: Dict[str, Any], *, on_missing: str = "skip", ): - """SELECT + tolerant-parse + merge ``patch`` into a session's model_config. - - Shared by every model_config writer (``update_session_runtime_lock``, - ``set_session_yolo``, ``archive_and_compact``, - ``patch_session_model_config``) so the merge discipline that keeps - lineage markers like ``_branched_from`` / ``_delegate_from`` alive - lives in exactly one place. A ``None`` patch value deletes that key. - Must run inside an open write transaction (callers own the UPDATE). - - Returns the serialized merged JSON — ``None`` when the merged dict is - empty (matching ``create_session``'s NULL convention) — or the - ``_MODEL_CONFIG_ROW_MISSING`` sentinel when the row doesn't exist and - ``on_missing == "skip"``; ``on_missing == "raise"`` raises ValueError. - """ + """SELECT + tolerant-parse + merge ``patch`` into model_config — the one + place the merge discipline keeping ``_branched_from``/``_delegate_from`` + alive lives. ``None`` deletes a key. Runs inside the caller's write + transaction. Returns serialized JSON (``None`` when empty, matching + create_session's NULL) or ``_MODEL_CONFIG_ROW_MISSING`` when the row + doesn't exist (``on_missing="raise"`` raises ValueError instead).""" row = conn.execute( - "SELECT model_config FROM sessions WHERE id = ?", - (session_id,), + "SELECT model_config FROM sessions WHERE id = ?", (session_id,), ).fetchone() if row is None: if on_missing == "raise": raise ValueError(f"Session not found: {session_id}") return _MODEL_CONFIG_ROW_MISSING - raw = row[0] - config: Dict[str, Any] = {} - if isinstance(raw, str) and raw.strip(): - try: - parsed = json.loads(raw) - if isinstance(parsed, dict): - config = parsed - except (json.JSONDecodeError, TypeError): - config = {} - elif isinstance(raw, dict): - config = dict(raw) + config = _parse_model_config(row[0]) for key, value in patch.items(): if value is None: config.pop(key, None) @@ -4672,155 +3137,73 @@ class SessionDB( config[key] = value return json.dumps(config) if config else None - def patch_session_model_config( - self, session_id: str, patch: Dict[str, Any] - ) -> None: - """Merge ``patch`` into a session's model_config JSON atomically. - - A ``None`` patch value removes that key. No-op when the session row - doesn't exist or the patch is empty. This is the standalone setter for - callers that need to update model_config *without* rewriting the - transcript (the transcript-coupled path is ``archive_and_compact``'s - ``model_config_patch``, which shares the same merge helper). - """ + def patch_session_model_config(self, session_id: str, patch: Dict[str, Any]) -> None: + """Merge ``patch`` into model_config atomically (``None`` removes a key); + no-op when the row or patch is empty. The transcript-coupled path is + archive_and_compact's ``model_config_patch``.""" if not session_id or not patch: return + self._write_model_config_patch( + session_id, patch, "UPDATE sessions SET model_config = ? WHERE id = ?", + lambda merged: (merged, session_id), + ) - def _do(conn): - merged = self._merge_model_config_json(conn, session_id, patch) - if merged is _MODEL_CONFIG_ROW_MISSING: - return - conn.execute( - "UPDATE sessions SET model_config = ? WHERE id = ?", - (merged, session_id), - ) - - self._execute_write(_do) - - def get_session_model_config_value( - self, session_id: str, key: str, default: Any = None - ) -> Any: + def get_session_model_config_value(self, session_id: str, key: str, default: Any = None) -> Any: """Read one key out of a session's model_config JSON (tolerant parse).""" session = self.get_session(session_id) or {} - raw = session.get("model_config") - config: Dict[str, Any] = {} - if isinstance(raw, str) and raw.strip(): - try: - parsed = json.loads(raw) - if isinstance(parsed, dict): - config = parsed - except (json.JSONDecodeError, TypeError): - config = {} - elif isinstance(raw, dict): - config = raw - return config.get(key, default) + return _parse_model_config(session.get("model_config")).get(key, default) def update_session_runtime_lock( - self, - session_id: str, - *, - model: Optional[str] = None, - provider: Optional[str] = None, - model_options: Optional[Dict[str, Any]] = None, - route_source: Optional[str] = None, + self, session_id: str, *, model: Optional[str] = None, provider: Optional[str] = None, + model_options: Optional[Dict[str, Any]] = None, route_source: Optional[str] = None, confirmed: bool = False, ) -> None: - """Persist a Browser / API client runtime lock without clobbering lineage markers. - - Merges ``browser_model_lock`` into the existing ``model_config`` JSON so - ``_branched_from`` / ``_delegate_from`` survive. Nulls ``system_prompt`` - so cached ``Model:`` / ``Provider:`` footers cannot lie after a switch. - """ + """Persist a Browser / API-client runtime lock into model_config (lineage + markers survive); null system_prompt so cached footers cannot lie.""" lock = { - "provider": provider or "", - "model": model or "", - "model_options": model_options or {}, - "route_source": route_source or "", - "confirmed": bool(confirmed), + "provider": provider or "", "model": model or "", "model_options": model_options or {}, + "route_source": route_source or "", "confirmed": bool(confirmed), "updated_at": time.time(), } - - def _do(conn): - merged = self._merge_model_config_json( - conn, session_id, {"browser_model_lock": lock} - ) - if merged is _MODEL_CONFIG_ROW_MISSING: - return - conn.execute( - """UPDATE sessions SET + self._write_model_config_patch( + session_id, {"browser_model_lock": lock}, + """UPDATE sessions SET model_config = ?, model = COALESCE(?, model), system_prompt = NULL, system_prompt_hash = NULL WHERE id = ?""", - (merged, model, session_id), - ) - self._delete_unreferenced_system_prompts(conn) - self._execute_write(_do) + lambda merged: (merged, model, session_id), + clear_prompts=True, + ) def set_session_yolo(self, session_id: str, enabled: bool) -> None: - """Persist the per-session YOLO bypass flag into ``model_config``. - - Merges ``yolo_mode`` into the existing ``model_config`` JSON (same - merge discipline as ``update_session_runtime_lock`` so lineage - markers like ``_branched_from`` / ``_delegate_from`` survive). The - CLI resume paths read this flag back so a ``/yolo ON`` toggle — or a - ``--yolo`` launch — survives ``hermes --resume`` into a fresh - process. No-op when the session row doesn't exist yet; the - creation-time ``model_config`` carries the flag for ``--yolo`` - launches. - """ + """Persist the per-session YOLO flag into model_config so ``/yolo`` or + ``--yolo`` survives ``hermes --resume``. No-op when the row doesn't exist + yet (creation-time model_config carries the flag for --yolo launches).""" if not session_id: return - - def _do(conn): - merged = self._merge_model_config_json( - conn, session_id, {"yolo_mode": bool(enabled)} - ) - if merged is _MODEL_CONFIG_ROW_MISSING: - return - conn.execute( - "UPDATE sessions SET model_config = ? WHERE id = ?", - (merged, session_id), - ) - self._execute_write(_do) + self._write_model_config_patch( + session_id, {"yolo_mode": bool(enabled)}, + "UPDATE sessions SET model_config = ? WHERE id = ?", + lambda merged: (merged, session_id), + ) @staticmethod def session_yolo_enabled(session_meta: Optional[Dict[str, Any]]) -> bool: - """Read the persisted YOLO flag off a session row dict. + """Persisted YOLO flag from a session row (JSON string or parsed dict); + False on any parse failure — resume must never enable the bypass by accident.""" + return bool(_parse_model_config((session_meta or {}).get("model_config")).get("yolo_mode")) - Accepts the dict returned by ``get_session`` (``model_config`` is a - JSON string) or an already-parsed dict. Returns False on any parse - failure — resume must never enable the bypass by accident. - """ - raw = (session_meta or {}).get("model_config") - if isinstance(raw, str): - try: - raw = json.loads(raw) - except Exception: - return False - if not isinstance(raw, dict): - return False - return bool(raw.get("yolo_mode")) - - - # ── Async token accounting ── - # update_token_counts() runs a sessions UPDATE (plus a per-model usage - # upsert) inside BEGIN IMMEDIATE; against a cold multi-GB state.db one - # call can stall the turn thread for tens to hundreds of ms, and the - # tool loop pays it after EVERY API call (measured p50 3.3ms / p95 70ms - # per call in production). queue_token_counts() reduces the critical - # path to a deque append: a dedicated single-writer thread applies - # deltas in enqueue order, coalescing consecutive same-route deltas - # into one UPDATE when a backlog forms. Readers that need exact - # mid-turn totals (get_session and friends) call flush_token_counts() - # first — a plain attribute check when nothing is queued. - - # Delta fields summed when coalescing. Route fields must be equal for - # two deltas to merge: model/billing_* feed COALESCE backfill and the - # per-model usage attribution key, and cost_status/cost_source are - # last-non-None-wins — equality makes the merged UPDATE byte-for-byte - # equivalent to applying the deltas sequentially. + # ── Async token accounting (SessionUsageMixin) ── + # update_token_counts() stalls the turn thread for tens-hundreds of ms on a + # cold multi-GB DB after EVERY API call; queue_token_counts() reduces the + # critical path to a deque append, a single-writer thread applies deltas in + # order, coalescing consecutive same-route deltas. Exact readers call + # flush_token_counts() first. Route fields must be equal for two deltas to + # merge (model/billing_* feed COALESCE backfill and the per-model + # attribution key; cost_status/source are last-non-None-wins) so the merged + # UPDATE is byte-for-byte equivalent to applying the deltas sequentially. _TOKEN_DELTA_SUM_FIELDS = ( "input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens", "reasoning_tokens", "api_call_count", @@ -4831,54 +3214,28 @@ class SessionDB( "billing_provider", "billing_base_url", "billing_mode", ) - def ensure_session( - self, - session_id: str, - source: str = "unknown", - model: str = None, - **kwargs, + self, session_id: str, source: str = "unknown", model: str = None, **kwargs, ) -> str: - """Ensure a session row exists (INSERT OR IGNORE). Accepts optional kwargs.""" + """Ensure a session row exists (upsert). Accepts optional kwargs.""" self._insert_session_row(session_id, source, model=model, **kwargs) return session_id - - # ── Cross-backend heartbeat API (#94895) ─────────────────────────── - # Each serve / tui_gateway process registers a heartbeat row at startup - # and refreshes ``last_heartbeat`` periodically. The startup orphan - # sweep reads these rows to avoid reaping sessions owned by another - # still-live backend that just happens to be idle. Backends remove - # their own row on graceful shutdown; a row that survives a crash is - # reclaimed by the staleness sweep once ``last_heartbeat`` ages out. - - def get_session(self, session_id: str) -> Optional[Dict[str, Any]]: - """Get a session by ID.""" - # Cost/usage readers (/status, /usage, gateway endpoints) reach the - # row through here; drain queued token deltas so they see exact - # totals. No-op attribute check when nothing is queued. + """Get a session by ID (drains queued token deltas first so cost readers see exact totals).""" self.flush_token_counts() 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 " + "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.id = ?", (session_id,), ) return self._session_row_dict(row) if row else None - def get_dominant_session_model_route( - self, session_id: str - ) -> Optional[Dict[str, Any]]: - """Return the main-loop model route that served most API calls. - - ``sessions`` is a legacy aggregate row and can hold model/provider fields - written by different route changes. ``session_model_usage`` keeps the - coherent per-call tuple, so persisted status and billing reads should use - its dominant main-loop route when one is available. - """ + def get_dominant_session_model_route(self, session_id: str) -> Optional[Dict[str, Any]]: + """Main-loop model route that served most API calls. ``sessions`` is a + legacy aggregate mixing route changes; ``session_model_usage`` keeps the + coherent per-call tuple, so status/billing reads prefer it.""" self.flush_token_counts() row = self._read_one( """SELECT model, billing_provider, billing_base_url, billing_mode, @@ -4898,74 +3255,41 @@ class SessionDB( return dict(row) if row else None def resolve_session_id(self, session_id_or_prefix: str) -> Optional[str]: - """Resolve an exact or uniquely prefixed session ID to the full ID. - - Returns the exact ID when it exists. Otherwise treats the input as a - prefix and returns the single matching session ID if the prefix is - unambiguous. Returns None for no matches or ambiguous prefixes. - """ + """Exact id, else the single unambiguous prefix match, else None.""" exact = self.get_session(session_id_or_prefix) if exact: return exact["id"] - escaped = _escape_like(session_id_or_prefix) matches = [row["id"] for row in self._read_all( "SELECT id FROM sessions WHERE id LIKE ? ESCAPE '\\' ORDER BY started_at DESC LIMIT 2", (f"{escaped}%",), )] - if len(matches) == 1: - return matches[0] - return None + return matches[0] if len(matches) == 1 else None - # Maximum length for session titles MAX_TITLE_LENGTH = 100 - # Title provenance, lowest to highest authority. An auto-titling write may - # only replace a title of strictly lower authority, so the instant - # ``derived`` title upgrades to the model's ``llm`` title exactly once and - # nothing the agent generates can ever clobber a name the user typed. + # Title provenance, lowest to highest authority: auto-titling may only + # replace a strictly lower-authority title, so ``derived`` upgrades to + # ``llm`` exactly once and nothing generated clobbers a user-typed name. TITLE_SOURCE_DERIVED = "derived" TITLE_SOURCE_LLM = "llm" TITLE_SOURCE_USER = "user" - _TITLE_SOURCE_RANK = { - TITLE_SOURCE_DERIVED: 0, - TITLE_SOURCE_LLM: 1, - TITLE_SOURCE_USER: 2, - } + _TITLE_SOURCE_RANK = {TITLE_SOURCE_DERIVED: 0, TITLE_SOURCE_LLM: 1, TITLE_SOURCE_USER: 2} - # Bot Mode's forever-chat registry: the session titled exactly this, on a - # bot's profile, IS the bot's canonical chat — resolved by exact-title - # lookup on every open (no session-id pointer exists). The title is the - # identity, which is why _set_session_title refuses renames of a hidden - # row holding it (#92473). + # Bot Mode's canonical chat is resolved by exact-title lookup (no session-id + # pointer exists); the title IS the identity, so _set_session_title refuses + # renames of a hidden row holding it. CANONICAL_BOT_CHAT_TITLE = "Bot Chat" - def backfill_null_session_profiles(self, profile_name: str) -> int: - """One-shot owner backfill for legacy pre-ownership session rows. - - Sessions created before the durable-ownership work (#95407 lineage) - carry ``profile_name = NULL``. On single-backend installs that was - harmless, but once a Desktop registers a second connection the - fail-closed owner ladder (which is correct for new sessions) can no - longer route those rows anywhere — every pre-campaign session becomes - unresumable after upgrade (#94724, field report). - - This store belongs to exactly one profile — the profile whose - ``state.db`` this is — so stamping its own name onto rows that never - recorded one is a single-match backfill, not a guess. Rules mirror the - ``create_session`` COALESCE contract: - - * only ``NULL``/empty ``profile_name`` rows are touched — a non-NULL - owner is NEVER overwritten; - * idempotent and one-shot-per-row: a second run matches zero rows. - - Returns the number of rows stamped (0 when nothing was legacy). - """ + """Stamp this store's own profile onto legacy ``profile_name IS NULL`` + rows, which the fail-closed owner ladder cannot route once a Desktop + registers a second connection (pre-ownership sessions became + unresumable). Single-match, not a guess: a store belongs to exactly one + profile. Never overwrites a non-NULL owner; idempotent. Returns rows stamped.""" stamp = (profile_name or "").strip() if not stamp: return 0 - return int(self._write_rowcount( """UPDATE sessions SET profile_name = ? @@ -4974,14 +3298,10 @@ class SessionDB( ) or 0) def _set_lineage_column(self, column: str, session_id: str, value: Any) -> bool: - """Set one ``sessions`` column across a whole compression lineage. - - Walks ancestors and descendants joined by ``end_reason='compression'`` - so the root and every continuation flip as a unit — Desktop projects - compression roots forward to their latest tip, and updating only the - displayed tip would let the untouched root resurrect it on refresh. - Returns True when at least one row changed. - """ + """Set one ``sessions`` column across a whole compression lineage + (ancestors + descendants joined by end_reason='compression'): Desktop + projects roots forward to their tip, and updating only the displayed tip + would let the untouched root resurrect it on refresh. True if any row changed.""" return self._write_rowcount( f""" WITH RECURSIVE @@ -5016,37 +3336,19 @@ class SessionDB( ) > 0 def set_session_archived(self, session_id: str, archived: bool) -> bool: - """Archive or unarchive a session. - - Archived sessions are hidden from the default session list but keep all - their messages — this is a soft hide, not a delete. For compression - chains, archive the whole logical conversation. Desktop lists compression - roots projected forward to their latest continuation; updating only the - displayed tip lets the still-unarchived root resurrect it on refresh. - Returns True when at least one row was updated. - """ + """Soft-hide (or unhide) a session and its whole compression lineage; + messages are kept. True when at least one row changed.""" return self._set_lineage_column('archived', session_id, 1 if archived else 0) - # Accidental end reasons that recovery treats as resumable. Single source - # of truth: hermes_state_common._RECOVERABLE_END_REASONS, interpolated - # into find_latest_gateway_session_for_peer / promote_to_session_reset - # SQL — literals cannot drift (docs/session-lifecycle.md "recoverable - # accidental reasons"). + # Accidental end reasons recovery treats as resumable; the same constant is + # interpolated into the recovery/promotion SQL so literals cannot drift. RECOVERABLE_END_REASONS = _RECOVERABLE_END_REASONS def unarchive_recoverable_session(self, session_id: str) -> bool: - """Un-archive a session that was archived by a recoverable accident. - - Registry-style lookups (Bot Mode's canonical "Bot Chat") use this to - resurrect a row the ws-orphan reaper (``ws_orphan_reap``) or older - agent cleanup (``agent_close``) archived: those ends are accidents, - not user intent, so the identity-scoped canonical chat must survive - them (#92687). Sessions archived with no end_reason or an explicit - boundary reason (user archived deliberately, ``session_reset``, …) - are left untouched — returns ``False`` for those, ``True`` only when - the row was archived for a recoverable reason and is now un-archived - (whole compression lineage, via :meth:`set_session_archived`). - """ + """Un-archive a session archived by a recoverable accident (ws_orphan_reap, + agent_close) — used by registry lookups like Bot Mode's canonical chat. + Deliberate archives (no end_reason, or an explicit boundary) are left + alone. True only when a recoverable row was un-archived (whole lineage).""" if not session_id: return False try: @@ -5055,9 +3357,8 @@ class SessionDB( return False if not row or not row.get("archived"): return False - # A compressed lineage's registry row keeps end_reason='compression'; - # the accidental stamp lives on the live TIP. Judge recoverability at - # the tip (== the row itself when uncompressed). + # The accidental stamp lives on the live TIP (the registry row keeps + # end_reason='compression'); judge recoverability there. tip = row try: tip_id = self.get_compression_tip(session_id) or session_id @@ -5069,198 +3370,162 @@ class SessionDB( return False if not self.set_session_archived(session_id, False): return False - - # Clear the accidental end stamp: the session is live again, and a - # surviving ws_orphan_reap/agent_close reason would make a LATER - # deliberate archive (which never writes end_reason) auto-resurrect - # on the next lookup — permanently overriding user intent. - def _clear_end(conn): - conn.execute( - "UPDATE sessions SET ended_at = NULL, end_reason = NULL WHERE id = ?", - (tip["id"],), - ) - return 1 - - self._execute_write(_clear_end) + # Clear the accidental end stamp, or a LATER deliberate archive (which + # never writes end_reason) would auto-resurrect on the next lookup. + self._write_sql( + "UPDATE sessions SET ended_at = NULL, end_reason = NULL WHERE id = ?", (tip["id"],), + ) return True def set_session_pinned(self, session_id: str, pinned: bool) -> bool: - """Pin or unpin a session (and its whole compression lineage). - - ``pinned`` is a durable "keep" flag: pinned sessions are exempt from - the ``sessions.auto_archive`` stale sweep (see - :meth:`archive_stale_sessions`). Desktop is the current writer — its - sidebar pins mirror here so a backend/other-surface sweep honours - them. Like :meth:`set_session_archived` the whole compression chain is - flipped as a unit, so pinning the surfaced tip protects the root (and - vice-versa) no matter which id the caller holds. Returns True when at - least one row changed. - """ + """Pin/unpin a session and its compression lineage. Pinned sessions are + exempt from the ``sessions.auto_archive`` sweep; Desktop mirrors its + sidebar pins here so backend sweeps honour them.""" return self._set_lineage_column('pinned', session_id, 1 if pinned else 0) def set_session_hidden(self, session_id: str, hidden: bool) -> bool: - """Hide or unhide a session (and its whole compression lineage). - - ``hidden`` is a generic "don't show in the global Sessions sidebar" - flag: a hidden session is dropped from the default - :meth:`list_sessions_rich` listing (which omits ``include_hidden``) but - stays fully resumable by the surface that owns it — useful for plugins - that manage their own sessions (e.g. kanban) and don't want them - cluttering the shared recents list. Like :meth:`set_session_archived` - / :meth:`set_session_pinned` the whole compression chain is flipped as - a unit, so hiding the surfaced tip hides the root (and vice-versa) no - matter which id the caller holds. Returns True when at least one row - changed. - """ + """Hide/unhide a session and its compression lineage from the default + list_sessions_rich listing; it stays resumable by the owning surface + (plugins such as kanban manage their own sessions).""" return self._set_lineage_column('hidden', session_id, 1 if hidden else 0) def set_session_read(self, session_id: str, read: bool = True) -> bool: - """Mark a session read or unread (and its whole compression lineage). - - Read state is a watermark, not a flag: ``last_read_at`` records when - the conversation was last read, and it counts as unread when activity - postdates that watermark (the derived ``unread`` key on - :meth:`list_sessions_rich` rows). New messages therefore flip a read - conversation back to unread without any write on the message path. - Three states: - - * NULL — never tracked (every pre-feature row): treated as read, so - shipping the column doesn't badge a user's entire history at once. - * 0 — explicitly marked unread: any activity postdates it. - * timestamp — read up to that moment. - - Like :meth:`set_session_archived` / :meth:`set_session_pinned`, the - whole compression chain is stamped as a unit, so reading the surfaced - tip clears the root (and vice-versa) no matter which id the caller - holds. Returns True when at least one row changed. - """ + """Mark read/unread across the compression lineage. ``last_read_at`` is a + watermark, not a flag: unread when activity postdates it, so new + messages flip it back without any write on the message path. NULL = + never tracked = read (shipping the column doesn't badge all history); + 0 = explicitly unread; timestamp = read up to then.""" return self._set_lineage_column('last_read_at', session_id, time.time() if read else 0.0) @staticmethod def session_unread(session_row: Dict[str, Any]) -> bool: - """Derive unread from a session row's watermark and activity. - - Shared by ``list_sessions_rich`` and any future surface that holds a - row (or projected row) with ``last_read_at`` and ``last_active``. - NULL watermark = never tracked = read. - """ + """Unread = activity postdates the ``last_read_at`` watermark (NULL = read).""" last_read = session_row.get("last_read_at") if last_read is None: return False last_active = session_row.get("last_active") or session_row.get("started_at") return float(last_active or 0) > float(last_read) - - # Columns excluded from compact_rows projections: only the payload-heavy - # blob no list consumer renders. Everything else — including gateway - # routing fields and desktop sidebar fields like git_branch — stays, and - # the projection is derived from SCHEMA_SQL so columns added later via - # declarative reconciliation are included automatically instead of - # silently dropping out of list rows. + # compact_rows excludes only payload-heavy blobs no list consumer renders; + # the projection derives from SCHEMA_SQL so new columns join automatically. _SESSION_COMPACT_EXCLUDED = frozenset( {"system_prompt", "system_prompt_hash", "git_metadata_generation"} ) _session_compact_cols_sql: Optional[str] = None + @staticmethod + def _chain_search_where(where_sql: str, id_needle: str, search_needle: str) -> Tuple[str, List[Any]]: + """Extend ``where_sql`` with the id_query / search_query filters: a row is + admitted when its own id or any id in its forward compression chain + matches (search also matches titles and a punctuation-stripped form so + ``an94`` finds ``AN-94``). Leading-wildcard LIKE can't use an index but + chain membership keeps it bounded — far cheaper than scanning in Python.""" + params: List[Any] = [] + clauses: List[str] = [] + def _like_pattern(needle: str) -> str: + return f"%{_escape_like(needle)}%" + if id_needle: + clauses.append( + "EXISTS (SELECT 1 FROM chain cq WHERE cq.root_id = s.id" + " AND LOWER(cq.cur_id) LIKE ? ESCAPE '\\')" + ) + params.append(_like_pattern(id_needle)) + if search_needle: + compact_needle = re.sub(r"[\W_]+", "", search_needle) + compact_sql = ( + "REPLACE(REPLACE(REPLACE(REPLACE(LOWER(COALESCE({0}, ''))," + " '-', ''), '_', ''), '.', ''), ' ', '')" + ) + search_clause = ( + "EXISTS (SELECT 1 FROM chain cq JOIN sessions cs ON cs.id = cq.cur_id" + " WHERE cq.root_id = s.id AND (LOWER(COALESCE(cs.title, '')) LIKE ? ESCAPE '\\'" + " OR LOWER(cq.cur_id) LIKE ? ESCAPE '\\'" + ) + params.extend([_like_pattern(search_needle)] * 2) + if compact_needle: + search_clause += f" OR {compact_sql.format('cs.title')} LIKE ? ESCAPE '\\'" + params.append(_like_pattern(compact_needle)) + clauses.append(search_clause + "))") + if not clauses: + return where_sql, params + combined = " AND ".join(clauses) + return (f"{where_sql} AND {combined}" if where_sql else f"WHERE {combined}"), params + + def _project_compression_tips(self, sessions: List[Dict[str, Any]], compact_rows: bool) -> List[Dict[str, Any]]: + """Replace each compression root's surfaced fields with its live tip's + (root ``started_at`` kept for stable ordering); tip rows are fetched in + one batched query. ``_lineage_ids`` carries every id on the chain: a + persisted tile can hold a MIDDLE segment's id, and with only root/tip a + surface cannot prove it names this conversation (one chat open twice).""" + tip_ids_by_root: Dict[str, str] = {} + chain_by_root: Dict[str, List[str]] = {} + for s in sessions: + if s.get("end_reason") != "compression": + continue + chain = self.get_compression_chain(s["id"]) + tip_id = chain[-1] if chain else s["id"] + if tip_id != s["id"]: + tip_ids_by_root[s["id"]] = tip_id + chain_by_root[s["id"]] = chain + tip_rows = ( + self._get_session_rich_rows_batch(set(tip_ids_by_root.values()), compact_rows=compact_rows) + if tip_ids_by_root else {} + ) + projected = [] + for s in sessions: + tip_id = tip_ids_by_root.get(s["id"]) + tip_row = tip_rows.get(tip_id) if tip_id else None + if not tip_row: + projected.append(s) + continue + merged = dict(s) + for key in ( + "id", "ended_at", "end_reason", "message_count", + "tool_call_count", "title", "last_active", "preview", + "model", "system_prompt", "cwd", "git_branch", "git_repo_root", + ): + if key in tip_row: + merged[key] = tip_row[key] + merged["_lineage_root_id"] = s["id"] + merged["_lineage_ids"] = chain_by_root.get(s["id"]) or None + projected.append(merged) + return projected + + @classmethod + def _list_row(cls, row: sqlite3.Row) -> Dict[str, Any]: + """Project a list_sessions_rich row: shape the preview, drop internal ordering columns.""" + s = cls._session_row_dict(row) + s["preview"] = _shape_preview(s.pop("_preview_raw", "")) + s.pop("_effective_last_active", None) + return s def list_sessions_rich( - self, - source: str = None, - sources: List[str] = None, - exclude_sources: List[str] = None, - cwd_prefix: str = None, - limit: int = 20, - offset: int = 0, - include_children: bool = False, - min_message_count: int = 0, - project_compression_tips: bool = True, - order_by_last_active: bool = False, - include_archived: bool = False, - archived_only: bool = False, - id_query: str = None, - search_query: str = None, - compact_rows: bool = False, - include_pinned: bool = False, - session_key: str = None, + self, source: str = None, sources: List[str] = None, exclude_sources: List[str] = None, + cwd_prefix: str = None, limit: int = 20, offset: int = 0, include_children: bool = False, + min_message_count: int = 0, project_compression_tips: bool = True, + order_by_last_active: bool = False, include_archived: bool = False, + archived_only: bool = False, id_query: str = None, search_query: str = None, + compact_rows: bool = False, include_pinned: bool = False, session_key: str = None, include_hidden: bool = False, ) -> List[Dict[str, Any]]: - """List sessions with preview (first user message) and last_active, in one query. - - ``last_active`` = freshest of the activity heartbeat and the latest - message timestamp, else ``started_at``. Implementation-detail children - (subagent runs, compression continuations) are excluded unless - ``include_children``; branch/reset children stay listable. - - ``project_compression_tips`` (default) surfaces each compression chain - as ONE entry showing the live tip's id/message_count/title/last_active; - ``False`` returns raw root rows (admin/debug UIs). - ``order_by_last_active`` sorts by the chain TIP's activity via a - recursive CTE, so LIMIT/OFFSET stay cheap and a recently continued old - conversation lands in the right slot. ``search_query`` (that path - only) substring-matches title/id across the forward chain, plus a - punctuation-stripped variant (``an94`` finds ``AN-94``). - ``compact_rows`` omits the ``system_prompt`` blob from the SELECT so - SQLite never copies tens of KB per row out of the B-tree page. - ``include_pinned`` back-fills pinned conversations the page window left - out (a pin means "always reachable"; the desktop sidebar would - otherwise render an empty Pinned section) — they still obey the - source/archived/min_message_count filters. ``session_key`` restricts to - one gateway conversation scope. - """ - # Rows carry token/cost totals — drain queued deltas first so - # listings (sidebar, /resume, dashboards) show exact counters. - self.flush_token_counts() - where_clauses = [] - params = [] - - if not include_children: - # Show roots and user-visible branch/reset sessions, while still - # hiding sub-agent runs and compression continuations. All four - # carry parent_session_id, so the shared predicate classifies the - # edge from stable markers plus legacy-compatible parent metadata. - # - # Branch sessions are identified two ways, OR'd for robustness: - # 1. A stable ``_branched_from`` marker in model_config, written - # by /branch at creation time. This survives the parent being - # reopened and re-ended with a different end_reason (e.g. - # tui_shutdown overwriting 'branched'), which otherwise hides - # the branch — see issue #20856. - # 2. The legacy heuristic (parent ended with 'branched' before the - # child started), covering branch sessions created before the - # marker existed. - where_clauses.append(_LISTABLE_CHILD_SQL) - where_clauses.append(f"{_delegate_from_json('s.model_config')} IS NULL") - - include_sources = [source] if source else list(sources or []) - if include_sources: - placeholders = ",".join("?" for _ in include_sources) - where_clauses.append(f"s.source IN ({placeholders})") - params.extend(include_sources) - if session_key: - where_clauses.append("s.session_key = ?") - params.append(session_key) - if exclude_sources: - placeholders = ",".join("?" for _ in exclude_sources) - where_clauses.append(f"s.source NOT IN ({placeholders})") - params.extend(exclude_sources) - if cwd_prefix: - clause, clause_params = _cwd_prefix_clause(cwd_prefix) - where_clauses.append(clause) - params.extend(clause_params) - if min_message_count > 0: - where_clauses.append("s.message_count >= ?") - params.append(min_message_count) - if archived_only: - where_clauses.append("s.archived = 1") - elif not include_archived: - where_clauses.append("s.archived = 0") + """List sessions with preview and ``last_active`` in one query. Subagent + runs / compression continuations are hidden unless ``include_children``; + ``project_compression_tips`` shows each chain as its live tip; + ``order_by_last_active`` sorts by the chain TIP via a recursive CTE (the + only path honouring ``id_query`` / ``search_query``); ``compact_rows`` + omits the system_prompt blob; ``include_pinned`` back-fills pins the page + missed ("always reachable"), still obeying the other filters.""" + self.flush_token_counts() # rows carry token/cost totals + where_clauses, params = _session_filter_where( + exclude_children=not include_children, source=source, sources=sources, + session_key=session_key, exclude_sources=exclude_sources, cwd_prefix=cwd_prefix, + min_message_count=min_message_count, archived_only=archived_only, + include_archived=include_archived, + ) if not include_hidden: where_clauses.append("s.hidden = 0") - where_sql = f"WHERE {' AND '.join(where_clauses)}" if where_clauses else "" - # Snapshot the filter params before the query builders below extend - # them with LIMIT/OFFSET — the pinned back-fill reuses the same WHERE. - base_where_params = list(params) + base_where_params = list(params) # pinned back-fill reuses the WHERE before LIMIT/OFFSET prompt_select = ( "" if compact_rows else ", COALESCE(sp.prompt, s.system_prompt) AS _system_prompt_resolved" @@ -5269,79 +3534,17 @@ class SessionDB( "" if compact_rows else "LEFT JOIN system_prompts sp ON sp.hash = s.system_prompt_hash" ) - - # Optional session-id filter, pushed into SQL so callers (Desktop - # session-id search) don't have to fetch every row and filter in - # Python. ``id_query`` is matched as a case-insensitive substring - # against each surfaced row's id AND every id in its forward - # compression chain — so searching a compression *root* id or a *tip* - # id both resolve to the same projected conversation. Only used in the - # order_by_last_active path (which builds the chain CTE); other callers - # pass id_query=None. + _sel = self._compact_session_cols() if compact_rows else "s.*" id_needle = (id_query or "").strip().lower() search_needle = (search_query or "").strip().lower() if order_by_last_active: - # Compute effective_last_active by walking each surfaced session's - # compression-continuation chain forward in SQL and taking the MAX - # timestamp across the chain. This lets us ORDER BY + LIMIT at SQL - # level instead of fetching every row and sorting in Python, while - # still surfacing old compression roots whose live tip is fresh. - # - # The CTE seeds from rows the outer WHERE admits (roots + - # user-visible branch/reset children), then recursively joins through - # compression-continuation edges. Do NOT require - # child.started_at >= parent.ended_at here: real desktop/gateway - # races can insert the continuation row before the parent's - # ended_at is written, while stale websocket siblings may satisfy - # the timestamp test and hijack resume/list projection. - outer_where = where_sql - id_params: List[Any] = [] - filter_clauses: List[str] = [] - - def _like_pattern(needle: str) -> str: - return f"%{_escape_like(needle)}%" - - if id_needle: - # Admit a surfaced row if its own id or any id in its forward - # compression chain matches the needle. LIKE with a leading - # wildcard can't use an index, but the chain membership and - # the small result set keep this bounded — far cheaper than - # fetching every session and scanning in Python. - filter_clauses.append( - "EXISTS (SELECT 1 FROM chain cq" - " WHERE cq.root_id = s.id" - " AND LOWER(cq.cur_id) LIKE ? ESCAPE '\\')" - ) - id_params.append(_like_pattern(id_needle)) - if search_needle: - # Same chain-membership trick as id_query, but matching either - # the title or the id of any session in the chain. The compact - # (punctuation-stripped) variant lets `an94` match `AN-94`. - compact_needle = re.sub(r"[\W_]+", "", search_needle) - compact_sql = ( - "REPLACE(REPLACE(REPLACE(REPLACE(LOWER(COALESCE({0}, ''))," - " '-', ''), '_', ''), '.', ''), ' ', '')" - ) - search_clause = ( - "EXISTS (SELECT 1 FROM chain cq" - " JOIN sessions cs ON cs.id = cq.cur_id" - " WHERE cq.root_id = s.id" - " AND (LOWER(COALESCE(cs.title, '')) LIKE ? ESCAPE '\\'" - " OR LOWER(cq.cur_id) LIKE ? ESCAPE '\\'" - ) - id_params.extend([_like_pattern(search_needle)] * 2) - if compact_needle: - search_clause += ( - f" OR {compact_sql.format('cs.title')} LIKE ? ESCAPE '\\'" - ) - id_params.append(_like_pattern(compact_needle)) - filter_clauses.append(search_clause + "))") - if filter_clauses: - combined = " AND ".join(filter_clauses) - outer_where = ( - f"{where_sql} AND {combined}" if where_sql else f"WHERE {combined}" - ) - _sel = self._compact_session_cols() if compact_rows else "s.*" + # The CTE seeds from rows the outer WHERE admits and walks + # compression-continuation edges forward; MAX over the chain gives + # effective_last_active so ORDER BY + LIMIT happen in SQL. Do NOT + # require child.started_at >= parent.ended_at: races insert the + # continuation before the parent's ended_at is written, while stale + # websocket siblings could pass the timestamp test and hijack projection. + outer_where, id_params = self._chain_search_where(where_sql, id_needle, search_needle) query = f""" WITH RECURSIVE chain(root_id, cur_id) AS ( SELECT s.id, s.id FROM sessions s {where_sql} @@ -5363,14 +3566,7 @@ class SessionDB( GROUP BY root_id ) SELECT {_sel}{prompt_select}, - 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, + {_PREVIEW_COL_SQL}, {_sql_session_last_active("s")} AS last_active, COALESCE(cm.effective_last_active, s.started_at) AS _effective_last_active FROM sessions s @@ -5380,21 +3576,11 @@ class SessionDB( ORDER BY _effective_last_active DESC, s.started_at DESC, s.id DESC LIMIT ? OFFSET ? """ - # WHERE params apply twice (CTE seed + outer select); the id filter - # only applies to the outer select. - params = params + params + id_params + [limit, offset] + params = params + params + id_params + [limit, offset] # WHERE binds twice (seed + outer) else: - _sel = self._compact_session_cols() if compact_rows else "s.*" query = f""" SELECT {_sel}{prompt_select}, - 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, + {_PREVIEW_COL_SQL}, {_sql_session_last_active("s")} AS last_active FROM sessions s {prompt_join} @@ -5403,36 +3589,15 @@ class SessionDB( LIMIT ? OFFSET ? """ params.extend([limit, offset]) - rows = self._read_all(query, params) - sessions = [] - for row in rows: - s = self._session_row_dict(row) - s["preview"] = _shape_preview(s.pop("_preview_raw", "")) - # Drop the internal ordering column so callers see a clean dict. - s.pop("_effective_last_active", None) - sessions.append(s) - - # Back-fill pinned conversations the page missed. A pin outlives - # recency, so this runs BEFORE compression projection below — a - # back-filled root then projects to its live tip exactly like a row - # that had made the page on its own. One extra query, bounded by the - # number of pins (a handful), never N+1 per pin. + sessions = [self._list_row(row) for row in self._read_all(query, params)] + # Pinned back-fill runs BEFORE compression projection so a back-filled + # root projects to its tip like any other row. One query, never N+1. if include_pinned: seen_ids = {s["id"] for s in sessions} - pinned_where = ( - f"{where_sql} AND s.pinned = 1" if where_sql else "WHERE s.pinned = 1" - ) - _sel = self._compact_session_cols() if compact_rows else "s.*" + pinned_where = (f"{where_sql} AND s.pinned = 1" if where_sql else "WHERE s.pinned = 1") pinned_query = f""" SELECT {_sel}{prompt_select}, - 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, + {_PREVIEW_COL_SQL}, COALESCE( (SELECT MAX(m2.timestamp) FROM messages m2 WHERE m2.session_id = s.id), s.started_at @@ -5442,103 +3607,22 @@ class SessionDB( {pinned_where} ORDER BY s.started_at DESC """ - pinned_rows = self._read_all(pinned_query, base_where_params) - for row in pinned_rows: - s = self._session_row_dict(row) - if s["id"] in seen_ids: - continue - s["preview"] = _shape_preview(s.pop("_preview_raw", "")) - seen_ids.add(s["id"]) - sessions.append(s) - - # Project compression roots forward to their tips. Each row whose - # end_reason is 'compression' has a continuation child; replace the - # surfaced fields (id, message_count, title, last_active, ended_at, - # end_reason, preview) with the tip's values so the list entry acts - # as the live conversation. Keep the root's started_at to preserve - # chronological ordering by original conversation start. + for row in self._read_all(pinned_query, base_where_params): + s = self._list_row(row) + if s["id"] not in seen_ids: + seen_ids.add(s["id"]) + sessions.append(s) if project_compression_tips and not include_children: - # get_compression_tip() walks each root's chain individually (it's - # a per-session graph walk, not batchable in one query), but the - # tip *row* fetch afterward was previously one _get_session_rich_row() - # call per compression root. Batch that half instead: resolve - # every tip id first, then fetch all tip rows in a single query. - tip_ids_by_root: Dict[str, str] = {} - chain_by_root: Dict[str, List[str]] = {} - for s in sessions: - if s.get("end_reason") != "compression": - continue - chain = self.get_compression_chain(s["id"]) - tip_id = chain[-1] if chain else s["id"] - if tip_id != s["id"]: - tip_ids_by_root[s["id"]] = tip_id - chain_by_root[s["id"]] = chain - - tip_rows = ( - self._get_session_rich_rows_batch( - set(tip_ids_by_root.values()), compact_rows=compact_rows - ) - if tip_ids_by_root - else {} - ) - - projected = [] - for s in sessions: - tip_id = tip_ids_by_root.get(s["id"]) - tip_row = tip_rows.get(tip_id) if tip_id else None - if not tip_row: - projected.append(s) - continue - # Preserve the root's started_at for stable sort order, but - # surface the tip's identity and activity data. - merged = dict(s) - for key in ( - "id", "ended_at", "end_reason", "message_count", - "tool_call_count", "title", "last_active", "preview", - "model", "system_prompt", "cwd", "git_branch", "git_repo_root", - ): - if key in tip_row: - merged[key] = tip_row[key] - merged["_lineage_root_id"] = s["id"] - # Every id on the chain, intermediates included. Root and tip - # alone are not enough client-side: a persisted tile or route - # can hold a MIDDLE segment's id (it was the tip when opened, - # then rotated again), and with only the root/tip pair such a - # surface can no longer prove it names this conversation — - # which is how one chat ends up open twice after compaction. - merged["_lineage_ids"] = chain_by_root.get(s["id"]) or None - projected.append(merged) - sessions = projected - - # Derive read state per surfaced conversation. ``last_read_at`` is - # lineage-stamped by set_session_read, so a projected row's root - # watermark and its tip's are the same value — comparing it against - # the tip's last_active is correct either way. + sessions = self._project_compression_tips(sessions, compact_rows) + # last_read_at is lineage-stamped, so root and tip watermarks agree. for s in sessions: s["unread"] = self.session_unread(s) - return sessions - def session_lifecycle_statuses( - self, session_ids: List[str] - ) -> Dict[str, str]: - """Classify each session's lifecycle state from its LAST message row. - - Returns ``{session_id: status}`` where status is one of: - - - ``'complete'`` — last message is a normal assistant reply - - ``'interrupted'`` — last message is a user turn, a pending assistant - tool call (no tool result followed), or a tool result the assistant - never responded to - - ``'error'`` — last message carries an error finish_reason - - ``'empty'`` — session has no messages - - Cost-bounded by design: one query that resolves each listed session's - newest message id via ``MAX(id)`` (an index seek on - ``idx_messages_session_id``) and joins back for that single row's - role/tool_calls/finish_reason. Never scans transcripts, so it stays - cheap on large databases regardless of total message volume. - """ + def session_lifecycle_statuses(self, session_ids: List[str]) -> Dict[str, str]: + """``{session_id: status}`` from each session's LAST message row (see + :func:`classify_session_status`; ``'empty'`` when no messages). One query: + MAX(id) per session (index seek) joined back for that row — never scans transcripts.""" ids = [sid for sid in (session_ids or []) if sid] if not ids: return {} @@ -5559,71 +3643,42 @@ class SessionDB( rows = self._read_all(query, ids) for row in rows: statuses[row["session_id"]] = classify_session_status( - role=row["role"], - has_tool_calls=bool(row["has_tool_calls"]), + role=row["role"], has_tool_calls=bool(row["has_tool_calls"]), finish_reason=row["finish_reason"], ) return statuses - # ========================================================================= - # Message storage - # ========================================================================= - - # Sentinel prefix used to distinguish JSON-encoded structured content - # (multimodal messages: lists of parts like text + image_url) from plain - # string content. The NUL byte is not legal in normal text, so this - # cannot collide with real user content. + # ── Message storage constants (SessionMessagesMixin) ── + # Prefix distinguishing JSON-encoded structured content (multimodal parts) + # from plain strings; NUL is not legal in normal text, so it cannot collide. _CONTENT_JSON_PREFIX = "\x00json:" - - - #: Key under which message reactions live inside ``display_metadata``. - #: Reactions share the existing per-message JSON column rather than a side - #: table so they survive rewind/compaction row rewrites with the row itself. + #: Reactions live inside ``display_metadata`` (not a side table) so they + #: survive rewind/compaction row rewrites with the row itself. REACTIONS_METADATA_KEY = "reactions" - - - # Columns every conversation projection decodes. Shared by - # get_messages_as_conversation and get_resume_conversations so a single - # SELECT can feed both the model-fed and display views. ``active`` rides - # along so a display read can split the compaction-archived rows from the - # live set (and feed _dedupe_display_generations) without a second query. + # Columns every conversation projection decodes (model-fed and display + # views share one SELECT); ``active`` rides along so a display read can + # split compaction-archived rows from the live set without a second query. _CONVERSATION_ROW_COLUMNS = ( "id, role, content, tool_call_id, tool_calls, tool_name, effect_disposition, " "finish_reason, reasoning, reasoning_content, reasoning_details, " "codex_reasoning_items, codex_message_items, platform_message_id, observed, " - "_compressed_summary, timestamp, active, " - "api_content, display_kind, display_metadata" + "_compressed_summary, timestamp, active, api_content, display_kind, display_metadata" ) - - def assert_export_safe( - self, - session_id: str, - max_messages: Optional[int] = None, - ) -> int: - """Return active row count or reject an unsafe in-memory export. - - Exporting one session does not include compression ancestors, so this - guard deliberately counts only the requested segment. The limited - subquery stops as soon as it proves the transcript exceeds the bound. - - ``max_messages=None`` resolves the limit from config - (``sessions.max_export_messages``); 0 disables the guard and returns - the active row count without raising. - """ + def assert_export_safe(self, session_id: str, max_messages: Optional[int] = None) -> int: + """Active row count of this segment (compression ancestors excluded), or + raise SessionExportTooLargeError. The LIMITed subquery stops once it + proves the bound is exceeded. ``None`` resolves ``sessions.max_export_messages``; + 0 disables the guard (returns 0 without counting).""" if max_messages is None: max_messages = resolved_max_export_messages() if max_messages < 0: raise ValueError("max_messages must be non-negative") if max_messages == 0: - # Guard disabled by config — skip the COUNT; live callers use - # this for its raise side effect only (and skip calling it - # entirely when the limit is 0). return 0 row = self._read_one( "SELECT COUNT(*) FROM (" - "SELECT 1 FROM messages WHERE session_id = ? AND active = 1 LIMIT ?" - ")", + "SELECT 1 FROM messages WHERE session_id = ? AND active = 1 LIMIT ?)", (session_id, max_messages + 1), ) message_count = int(row[0] if row else 0) @@ -5631,38 +3686,19 @@ class SessionDB( raise SessionExportTooLargeError(session_id, message_count, max_messages) return message_count - def _is_explicit_branch_session(self, session_id: str) -> bool: - """Return whether *session_id* is a copied user-facing branch. - - Branches and compression continuations both use ``parent_session_id``, - but they have different history semantics: a branch owns a copied - transcript, while a compression continuation needs its ended parent's - archived rows for display. The durable ``_branched_from`` marker is the - existing discriminator written by all branch creation paths. - """ + """Copied user-facing branch (``_branched_from`` marker)? Branches own a + copied transcript; compression continuations need the parent's archived rows.""" if not session_id: return False - row = self._read_one( - "SELECT model_config FROM sessions WHERE id = ?", - (session_id,), - ) + row = self._read_one("SELECT model_config FROM sessions WHERE id = ?", (session_id,)) if row is None: return False - raw_config = row["model_config"] if hasattr(row, "keys") else row[0] - if not raw_config: - return False - try: - config = json.loads(raw_config) if isinstance(raw_config, str) else raw_config - except (json.JSONDecodeError, TypeError): - return False - return isinstance(config, dict) and bool(config.get("_branched_from")) - + return bool(_parse_model_config(row[0]).get("_branched_from")) def _session_lineage_root_to_tip(self, session_id: str) -> List[str]: if not session_id: return [session_id] - chain = [] current = session_id seen = set() @@ -5673,48 +3709,23 @@ class SessionDB( seen.add(current) chain.append(current) row = conn.execute( - "SELECT parent_session_id FROM sessions WHERE id = ?", - (current,), + "SELECT parent_session_id FROM sessions WHERE id = ?", (current,), ).fetchone() if row is None: break - current = row["parent_session_id"] if hasattr(row, "keys") else row[0] + current = row[0] return list(reversed(chain)) or [session_id] - - # ========================================================================= - # Rewind (soft-delete) — see /rewind slash command + issue #21910 - # ========================================================================= - - - # ========================================================================= - # Search - # ========================================================================= - def search_sessions( - self, - source: str = None, - limit: int = 20, - offset: int = 0, - workspace_key: str = None, + self, source: str = None, limit: int = 20, offset: int = 0, workspace_key: str = None, ) -> List[Dict[str, Any]]: - """List sessions, optionally filtered by source. - - Returns rows enriched with a computed ``last_active`` column - (freshest of ``last_activity_at`` and latest message timestamp, - else ``started_at``), ordered by most-recently-used first. - - Pass ``workspace_key`` to scope rows to one workspace - matching - :func:`workspace_key` semantics (git repo root, else cwd). Used by - ``hermes -c``/``--resume`` so the "last" session is the last one in - the *current* workspace, not the global MRU. - """ + """Sessions MRU-first with a computed ``last_active``; ``workspace_key`` + scopes to one workspace (:func:`workspace_key` semantics) so + ``hermes -c``/``--resume`` picks the current workspace's last session.""" select_with_last_active = ( - "SELECT s.*, " - "COALESCE(sp.prompt, s.system_prompt) AS _system_prompt_resolved, " + "SELECT s.*, COALESCE(sp.prompt, s.system_prompt) AS _system_prompt_resolved, " f"{_sql_session_last_active('s')} AS last_active " - "FROM sessions s " - "LEFT JOIN system_prompts sp ON sp.hash = s.system_prompt_hash " + "FROM sessions s LEFT JOIN system_prompts sp ON sp.hash = s.system_prompt_hash " ) where_clauses = [] params: list = [] @@ -5728,290 +3739,134 @@ class SessionDB( where_sql = f" WHERE {' AND '.join(where_clauses)}" if where_clauses else "" params.extend([limit, offset]) return [self._session_row_dict(row) for row in self._read_all( - f"{select_with_last_active}" - f"{where_sql} " + f"{select_with_last_active}{where_sql} " "ORDER BY last_active DESC, s.started_at DESC, s.id DESC LIMIT ? OFFSET ?", params, )] - # ========================================================================= - # Utility - # ========================================================================= - def session_count( - self, - source: str = None, - sources: List[str] = None, - cwd_prefix: str = None, - min_message_count: int = 0, - include_archived: bool = False, - archived_only: bool = False, - exclude_children: bool = False, - exclude_sources: List[str] = None, + self, source: str = None, sources: List[str] = None, cwd_prefix: str = None, + min_message_count: int = 0, include_archived: bool = False, archived_only: bool = False, + exclude_children: bool = False, exclude_sources: List[str] = None, ) -> int: - """Count sessions, optionally filtered by source. - - Pass ``exclude_children=True`` to count only the conversations that - ``list_sessions_rich`` surfaces (root + branch/reset sessions), hiding - sub-agent runs and compression continuations. Use it whenever the count - is paired with a ``list_sessions_rich`` page (e.g. sidebar "load more" - totals) so the total matches the number of listable rows — otherwise the - raw row count is inflated by children and "load more" never settles. - - Pass ``exclude_sources`` to drop whole source classes from the count - (e.g. ``["cron"]`` so the recents "load more" total matches a - cron-excluded ``list_sessions_rich`` page and doesn't keep "load more" - stuck on for buried scheduler sessions). - """ - where_clauses = [] - params = [] - - if exclude_children: - # Mirror list_sessions_rich's child-exclusion clause exactly so the - # count lines up with the rows: roots plus user-visible branch/reset - # children. - where_clauses.append(_LISTABLE_CHILD_SQL) - where_clauses.append(f"{_delegate_from_json('s.model_config')} IS NULL") - include_sources = [source] if source else list(sources or []) - if include_sources: - placeholders = ",".join("?" for _ in include_sources) - where_clauses.append(f"s.source IN ({placeholders})") - params.extend(include_sources) - if exclude_sources: - placeholders = ",".join("?" for _ in exclude_sources) - where_clauses.append(f"s.source NOT IN ({placeholders})") - params.extend(exclude_sources) - if cwd_prefix: - clause, clause_params = _cwd_prefix_clause(cwd_prefix) - where_clauses.append(clause) - params.extend(clause_params) - if min_message_count > 0: - where_clauses.append("s.message_count >= ?") - params.append(min_message_count) - if archived_only: - where_clauses.append("s.archived = 1") - elif not include_archived: - where_clauses.append("s.archived = 0") - + """Count sessions with the same filters as list_sessions_rich, so a + paired "load more" total matches the listable rows (children or a + cron-excluded page would otherwise inflate it and never settle).""" + where_clauses, params = _session_filter_where( + exclude_children=exclude_children, source=source, sources=sources, + exclude_sources=exclude_sources, cwd_prefix=cwd_prefix, + min_message_count=min_message_count, + archived_only=archived_only, include_archived=include_archived, + ) where_sql = f" WHERE {' AND '.join(where_clauses)}" if where_clauses else "" - return self._read_one(f"SELECT COUNT(*) FROM sessions s{where_sql}", params)[0] def session_count_ge(self, n: int = 1) -> bool: - """Check if at least N sessions exist (archived included). - - Short-circuits via LIMIT — much cheaper than ``session_count()``, - which pays a full index scan for its default ``archived = 0`` - filter (measured 543us vs 4us on a 20k-session DB). Archived - sessions count: every caller so far asks "has this install ever - had sessions", and an archived session is still a created one. - Use this instead of ``session_count() >= n`` when the exact count - is irrelevant. - """ + """At least N sessions exist (archived included — "has this install ever + had sessions"). LIMIT short-circuits: 4us vs session_count()'s 543us + index scan on a 20k-session DB.""" rows = self._read_all("SELECT 1 FROM sessions LIMIT ?", (n,)) return len(rows) >= n def session_count_by_source( - self, - *, - include_archived: bool = False, - archived_only: bool = False, + self, *, include_archived: bool = False, archived_only: bool = False, exclude_children: bool = False, ) -> Dict[str, int]: - """Return a ``{source: count}`` dict via a single ``GROUP BY`` query. - - Replaces the O(N) ``list_sessions_rich`` histogram loop with an - aggregate query. When ``exclude_children`` is False the query uses - ``idx_sessions_source``; when True, the child-exclusion predicates - require a full table scan (same as ``session_count`` and - ``list_sessions_rich``). - - ``exclude_children=True`` mirrors ``list_sessions_rich`` visibility - (roots + branch/reset sessions, excluding sub-agent runs, delegates, - and compression continuations) so the source counts match what the - Sessions page actually lists. - """ - where_clauses = [] - params: list = [] - - if exclude_children: - where_clauses.append(_LISTABLE_CHILD_SQL) - where_clauses.append(f"{_delegate_from_json('s.model_config')} IS NULL") - if archived_only: - where_clauses.append("s.archived = 1") - elif not include_archived: - where_clauses.append("s.archived = 0") - + """``{source: count}`` via one GROUP BY (uses idx_sessions_source unless + ``exclude_children``, whose predicates need a table scan like + list_sessions_rich). ``exclude_children`` mirrors listing visibility.""" + where_clauses, params = _session_filter_where( + exclude_children=exclude_children, + archived_only=archived_only, include_archived=include_archived, + ) where_sql = f" WHERE {' AND '.join(where_clauses)}" if where_clauses else "" - with self._read_ctx() as conn: if self._conn is None: raise RuntimeError("SessionDB connection is closed") rows = conn.execute( "SELECT COALESCE(NULLIF(s.source, ''), 'cli') AS source, COUNT(*) AS count " f"FROM sessions s{where_sql} " - "GROUP BY COALESCE(NULLIF(s.source, ''), 'cli') " - "ORDER BY count DESC", + "GROUP BY COALESCE(NULLIF(s.source, ''), 'cli') ORDER BY count DESC", params, ).fetchall() return {str(row["source"]): int(row["count"] or 0) for row in rows} - - # ========================================================================= - # Export and cleanup - # ========================================================================= - - def declared_scope_identity(self, session_id: str) -> Tuple[bool, str]: - """Fork verdict and recorded ``source`` for *session_id*, in ONE read. - - ``agent/prompt_cache_scope.py`` needs both to resolve a host-declared - conversation scope, and both live on the same ``sessions`` row; asking - for them separately read that row twice per resolution (@teknium1 on - #98811). The marker rules stay here, beside - :meth:`is_explicit_fork_child`, instead of being re-implemented by the - caller. - - A missing row is not a fork and has no source, which is the right - answer before ``_ensure_db_session`` persists it. This raises whatever - :meth:`get_session` raises: the caller fails closed on a DB error, and - merging the two reads cannot weaken that, because the fork check was - already the first of the two. - """ + """(is_fork_child, source) for *session_id* in ONE read — prompt_cache_scope + needs both from the same row. A missing row is (False, ""); DB errors + propagate so the caller fails closed.""" session = self.get_session(session_id) if not session: return False, "" - return ( - self._is_explicit_fork_child_row(session), - str(session.get("source") or "").strip(), - ) - + return (self._is_explicit_fork_child_row(session), str(session.get("source") or "").strip()) @staticmethod def _remove_session_files(sessions_dir: Optional[Path], session_id: str) -> None: - """Remove on-disk transcript files for a session. - - Cleans up ``{session_id}.json``, ``{session_id}.jsonl``, and any - ``request_dump_{session_id}_*.json`` files left by the gateway. - Silently skips files that don't exist and swallows OSError so a - filesystem hiccup never blocks a DB operation. - """ + """Remove ``.json``/``.jsonl`` and gateway ``request_dump__*.json``; + OSError is swallowed so a filesystem hiccup never blocks a DB operation.""" if sessions_dir is None: return - for suffix in (".json", ".jsonl"): - p = sessions_dir / f"{session_id}{suffix}" + targets = [sessions_dir / f"{session_id}{suffix}" for suffix in (".json", ".jsonl")] + try: + # request_dump files use session_id as a prefix component + targets.extend(sessions_dir.glob(f"request_dump_{session_id}_*.json")) + except OSError: + pass + for p in targets: try: p.unlink(missing_ok=True) except OSError: pass - # request_dump files use session_id as a prefix component - try: - for p in sessions_dir.glob(f"request_dump_{session_id}_*.json"): - try: - p.unlink(missing_ok=True) - except OSError: - pass - except OSError: - pass def get_session_delete_targets(self, session_id: str) -> List[str]: - """Return every session row that :meth:`delete_session` would remove. - - The requested session is first, followed by its recursively discovered - delegate/subagent children. Branch and compression children are not - included because deletion preserves them by orphaning their parent - reference. - """ + """Rows :meth:`delete_session` would remove: the session, then its + recursive delegate children (branch/compression children are orphaned, not deleted).""" with self._read_ctx() as conn: - exists = conn.execute( - "SELECT 1 FROM sessions WHERE id = ? LIMIT 1", (session_id,) - ).fetchone() - if not exists: + if not conn.execute("SELECT 1 FROM sessions WHERE id = ? LIMIT 1", (session_id,)).fetchone(): return [] - # Use the borrowed read connection, never self._conn: handing the - # shared writer connection to a helper here executes on it without - # self._lock — the same unsynchronized-read class as #99349/#90734. + # The borrowed read connection, never self._conn (unlocked writer use). delegate_ids = _collect_delegate_child_ids(conn, [session_id]) return [session_id, *sorted(delegate_ids)] def delete_session( - self, - session_id: str, - sessions_dir: Optional[Path] = None, + self, session_id: str, sessions_dir: Optional[Path] = None, expected_delete_ids: Optional[List[str]] = None, ) -> bool: - """Delete a session and all its messages. - - Delegate subagent children (``model_config._delegate_from``) are - cascade-deleted with the parent so they never resurface in session - pickers as orphaned rows. Branch / compression children are orphaned - (``parent_session_id → NULL``) so they remain accessible independently. - When *sessions_dir* is provided, also removes on-disk transcript - files (``.json`` / ``.jsonl`` / ``request_dump_*``) for every deleted - session. When *expected_delete_ids* is provided, deletion proceeds only - if the parent plus delegate cascade still matches that exact set. This - lets export-before-delete callers fail closed if a new delegate appears - after they materialize their archive. The delegate tree is re-walked - inside the write transaction on purpose (TOCTOU guard); the cost is - accepted for correctness. Returns True if the session was found and - deleted. - """ + """Delete a session and its messages. Delegate children cascade (they'd + resurface as orphans in pickers); branch/compression children are + orphaned (parent -> NULL). *sessions_dir*: also remove transcript files. + *expected_delete_ids*: proceed only if parent + delegate cascade still + equals that set (export-before-delete fails closed if a new delegate + appeared); the tree is re-walked inside the transaction on purpose (TOCTOU).""" removed_delegate_ids: List[str] = [] - expected_ids = ( - set(expected_delete_ids) if expected_delete_ids is not None else None - ) - + expected_ids = set(expected_delete_ids) if expected_delete_ids is not None else None def _do(conn): - cursor = conn.execute( - "SELECT 1 FROM sessions WHERE id = ? LIMIT 1", (session_id,) - ) - if cursor.fetchone() is None: + if conn.execute("SELECT 1 FROM sessions WHERE id = ? LIMIT 1", (session_id,)).fetchone() is None: + return False + if expected_ids is not None and expected_ids != { + session_id, *_collect_delegate_child_ids(conn, [session_id]) + }: return False - if expected_ids is not None: - actual_ids = { - session_id, - *_collect_delegate_child_ids(conn, [session_id]), - } - if actual_ids != expected_ids: - return False removed_delegate_ids.extend(_delete_delegate_children(conn, [session_id])) - # Orphan remaining child sessions (branches, etc.) so FK is satisfied. - conn.execute( - "UPDATE sessions SET parent_session_id = NULL " - "WHERE parent_session_id = ?", + conn.execute( # orphan remaining children (branches) so FK is satisfied + "UPDATE sessions SET parent_session_id = NULL WHERE parent_session_id = ?", (session_id,), ) conn.execute("DELETE FROM messages WHERE session_id = ?", (session_id,)) conn.execute("DELETE FROM sessions WHERE id = ?", (session_id,)) self._delete_unreferenced_system_prompts(conn) return True - deleted = self._execute_write(_do) if deleted: - for delegate_id in removed_delegate_ids: - self._remove_session_files(sessions_dir, delegate_id) - self._remove_session_files(sessions_dir, session_id) + for sid in removed_delegate_ids + [session_id]: + self._remove_session_files(sessions_dir, sid) return bool(deleted) - def delete_session_if_empty( - self, - session_id: str, - sessions_dir: Optional[Path] = None, - ) -> bool: - """Delete *session_id* only when it never gained resumable content. - - A session is considered empty when it has no messages and no - user-assigned title. Used by CLI exit / session-rotation paths so - immediately-started-and-quit sessions don't pile up in ``/resume`` - and ``hermes sessions list`` output. (Pattern ported from - google-gemini/gemini-cli#27770.) - - The emptiness check and delete run in one transaction, so a message - flushed concurrently by another writer can't be lost. Sessions with - children (delegate subagent runs) are preserved — a parent that - spawned work is not "empty" even if its own transcript never - flushed. Returns True if the session was deleted. - """ + def delete_session_if_empty(self, session_id: str, sessions_dir: Optional[Path] = None) -> bool: + """Delete *session_id* only if it has no messages, no title and no + children (a parent that spawned work is not "empty"), so start-and-quit + sessions don't pile up in /resume. Check and delete share one + transaction so a concurrently flushed message can't be lost.""" def _do(conn): cursor = conn.execute( """ @@ -6031,356 +3886,179 @@ class SessionDB( if cursor.rowcount > 0: self._delete_unreferenced_system_prompts(conn) return cursor.rowcount > 0 - deleted = self._execute_write(_do) if deleted: self._remove_session_files(sessions_dir, session_id) return bool(deleted) - def delete_sessions( - self, - session_ids: List[str], - sessions_dir: Optional[Path] = None, - ) -> int: - """Delete every session in *session_ids* in a single transaction. - - Backs the dashboard's bulk-select-then-delete flow on the - sessions page (``POST /api/sessions/bulk-delete``). Mirrors the - single-session :meth:`delete_session` contract per row: - - * Unknown IDs are silently skipped (no 404) — selection state - in the UI can race against another tab's delete, and we'd - rather succeed-on-the-rest than fail-the-whole-batch. - * Delegate subagent children (``model_config._delegate_from``) are - cascade-deleted with their parent; branch children are orphaned - (``parent_session_id → NULL``) so they stay accessible. - * Messages and the session row both go in one - ``_execute_write`` call so a partial failure can't leave the - DB in a "messages gone but session row still there" state. - * On-disk transcript / ``request_dump_*`` files are cleaned up - outside the DB transaction when *sessions_dir* is provided, - matching :meth:`prune_sessions` and - :meth:`delete_empty_sessions`. - - Returns the count of sessions that actually existed and were - deleted (may be less than ``len(session_ids)`` if some IDs were - already gone). - """ + def delete_sessions(self, session_ids: List[str], sessions_dir: Optional[Path] = None) -> int: + """Bulk delete (dashboard multi-select) with :meth:`delete_session` + semantics per row, in ONE transaction so a partial failure can't leave + "messages gone, row still there". Unknown ids are skipped (UI selection + can race another tab's delete: succeed-on-the-rest). Returns the number + that actually existed and were deleted.""" if not session_ids: return 0 - # Dedup + drop any non-string entries up-front. Avoids - # double-counting in the WHERE-IN list and protects against - # callers that pass a list with stray ``None`` values. unique_ids = list({sid for sid in session_ids if isinstance(sid, str) and sid}) if not unique_ids: return 0 - removed_ids: list[str] = [] removed_delegate_ids: list[str] = [] - def _do(conn): - placeholders = ",".join("?" * len(unique_ids)) - # First, filter to IDs that actually exist — we want to - # return the real deleted count, not the input length. - cursor = conn.execute( - f"SELECT id FROM sessions WHERE id IN ({placeholders})", + # Filter to IDs that actually exist: return the real deleted count. + existing = [row["id"] for row in conn.execute( + f"SELECT id FROM sessions WHERE id IN ({','.join('?' * len(unique_ids))})", unique_ids, - ) - existing = [row["id"] for row in cursor.fetchall()] + ).fetchall()] if not existing: return 0 - existing_placeholders = ",".join("?" * len(existing)) removed_delegate_ids.extend(_delete_delegate_children(conn, existing)) - # Orphan remaining children whose parent is in the kill list so the - # FK constraint stays satisfied. Pin children whose parent - # is itself in the kill list rather than NULL-ing parents - # of survivors — the IN list on ``parent_session_id`` does - # exactly this. - conn.execute( + conn.execute( # orphan children whose parent is in the kill list (FK) f"UPDATE sessions SET parent_session_id = NULL " f"WHERE parent_session_id IN ({existing_placeholders})", existing, ) conn.execute( - f"DELETE FROM messages WHERE session_id IN ({existing_placeholders})", - existing, - ) - conn.execute( - f"DELETE FROM sessions WHERE id IN ({existing_placeholders})", - existing, + f"DELETE FROM messages WHERE session_id IN ({existing_placeholders})", existing, ) + conn.execute(f"DELETE FROM sessions WHERE id IN ({existing_placeholders})", existing) self._delete_unreferenced_system_prompts(conn) removed_ids.extend(existing) return len(existing) - count = self._execute_write(_do) - for sid in removed_delegate_ids: - self._remove_session_files(sessions_dir, sid) - for sid in removed_ids: + for sid in removed_delegate_ids + removed_ids: self._remove_session_files(sessions_dir, sid) return count - #: Shared selector for :meth:`count_empty_sessions` and - #: :meth:`delete_empty_sessions` so the badge and the sweep agree. - #: - #: ``message_count`` tracks live (``active = 1``) rows only; rewind - #: (:meth:`replace_messages` w/ ``archive_dropped``) and in-place - #: compaction (:meth:`archive_and_compact`) reset it to 0 while keeping - #: dropped turns on disk as ``active = 0`` — the only recoverable copy - #: (#70516 / #80763 / #82756). The ``NOT EXISTS`` probe is the authority; - #: ``message_count = 0`` stays as a cheap prefilter. Same shape as every - #: other emptiness guard in this module. (#95868) + #: Shared by count_empty_sessions / delete_empty_sessions so badge and sweep + #: agree. ``message_count`` counts live rows only — rewind and compaction + #: reset it to 0 while keeping dropped turns as ``active = 0`` (the only + #: recoverable copy) — so NOT EXISTS is the authority; message_count = 0 is + #: a cheap prefilter. _EMPTY_SESSION_WHERE = ( - "message_count = 0 " - "AND ended_at IS NOT NULL " - "AND archived = 0 " - "AND NOT EXISTS (" - "SELECT 1 FROM messages WHERE messages.session_id = sessions.id" - ")" + "message_count = 0 AND ended_at IS NOT NULL AND archived = 0 AND NOT EXISTS (" + "SELECT 1 FROM messages WHERE messages.session_id = sessions.id)" ) def count_empty_sessions(self) -> int: - """Return the count of empty, non-active, non-archived sessions. - - "Empty" = the session holds no message rows at all AND has ended - (``ended_at IS NOT NULL``) AND is not archived. The ``ended_at`` - guard matches the safety contract used by :meth:`prune_sessions`: - only ended sessions are candidates for bulk deletion, so a freshly - spawned session whose first message hasn't landed yet — or one - held open by the live agent — is never sniped out from under - the runtime. - - Emptiness is decided by :data:`_EMPTY_SESSION_WHERE` — see that - constant for why the ``NOT EXISTS`` probe is needed instead of - trusting ``message_count`` alone. - - Backs the ``GET /api/sessions/empty/count`` endpoint that lets the - web dashboard hide its "Delete empty" button when there's nothing - to clean up, and pre-populate the confirm dialog with the actual - count. - """ + """Count of empty, ended, non-archived sessions (:data:`_EMPTY_SESSION_WHERE`). + The ended_at guard matches prune_sessions: a fresh session whose first + message hasn't landed is never sniped out from under the runtime.""" return self._read_one(f"SELECT COUNT(*) FROM sessions WHERE {self._EMPTY_SESSION_WHERE}")[0] - def delete_empty_sessions( - self, - sessions_dir: Optional[Path] = None, - ) -> int: - """Delete every empty, ended, non-archived session. - - Mirrors :meth:`prune_sessions`' transactional shape: - - * Selects candidate IDs first (:data:`_EMPTY_SESSION_WHERE`) so we - never touch a live session, one the user deliberately archived, - or one whose transcript survives as soft-archived rows. - * Orphans any child whose parent is in the kill list — children - of an empty parent are kept and re-parented to ``NULL`` rather - than cascade-deleted, matching ``delete_session`` / - ``prune_sessions`` semantics so branch/subagent transcripts - survive an inadvertent parent cleanup. - * Deletes the rows in a single ``_execute_write`` callback so - the operation is atomic — a partial failure (e.g. SIGKILL - mid-loop) doesn't leave the DB in a "messages-deleted but - session-row-still-there" half-state. - * Cleans up on-disk transcript files (``.json`` / ``.jsonl`` / - ``request_dump_*``) outside the DB transaction when - ``sessions_dir`` is provided. Empty sessions don't typically - have transcript files, but the gateway can leave a stub - ``request_dump_*`` if it crashed before the first reply — - so we still sweep, matching ``prune_sessions``. - - Returns the number of sessions deleted. - """ + def delete_empty_sessions(self, sessions_dir: Optional[Path] = None) -> int: + """Delete every empty, ended, non-archived session (:data:`_EMPTY_SESSION_WHERE`) + in one transaction, orphaning (not cascading) children so branch/subagent + transcripts survive. Transcript files are swept too: the gateway can + leave a stub request_dump_* if it crashed before the first reply.""" removed_ids: list[str] = [] - def _do(conn): - cursor = conn.execute( + session_ids = {row["id"] for row in conn.execute( f"SELECT id FROM sessions WHERE {self._EMPTY_SESSION_WHERE}" - ) - session_ids = {row["id"] for row in cursor.fetchall()} - + ).fetchall()} 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})", + f"WHERE parent_session_id IN ({','.join('?' * len(session_ids))})", list(session_ids), ) - for sid in session_ids: - # DELETE FROM messages is paranoia — the selector's - # ``NOT EXISTS`` probe already proved these sessions own no - # message rows — but a row inserted between the SELECT and - # this statement would otherwise be left dangling, so we - # still leave a clean FK state. - conn.execute( - "DELETE FROM messages WHERE session_id = ?", (sid,) - ) + # DELETE FROM messages is paranoia — the selector's NOT EXISTS + # probe proved these own no rows — but a row inserted between + # the SELECT and here would otherwise dangle (clean FK state). + conn.execute("DELETE FROM messages WHERE session_id = ?", (sid,)) conn.execute("DELETE FROM sessions WHERE id = ?", (sid,)) removed_ids.append(sid) self._delete_unreferenced_system_prompts(conn) return len(session_ids) - count = self._execute_write(_do) for sid in removed_ids: self._remove_session_files(sessions_dir, sid) return count - def archive_sessions( - self, - older_than_days: Optional[float] = None, - source: str = None, - **filters, + self, older_than_days: Optional[float] = None, source: str = None, **filters, ) -> int: - """Bulk-archive (soft-hide) every session matching the filters. - - Same filter surface as :meth:`prune_sessions`, but instead of deleting - rows it flips ``archived = 1`` via :meth:`set_session_archived` so - each match's compression lineage is archived as a unit (an unarchived - compression root would otherwise resurrect the conversation in - Desktop's projected list). Nothing is deleted; messages and transcript - files are untouched. Returns the number of sessions matched. - - ``archived`` defaults to ``False`` here (only select rows not yet - archived) so repeat runs are idempotent no-ops. - """ + """Bulk soft-hide with prune_sessions' filter surface, via + set_session_archived so each lineage flips as a unit. ``archived`` + defaults to False so repeat runs are idempotent. Returns matches.""" filters.setdefault("archived", False) - rows = self.list_prune_candidates( - older_than_days=older_than_days, source=source, **filters - ) + rows = self.list_prune_candidates(older_than_days=older_than_days, source=source, **filters) for row in rows: self.set_session_archived(row["id"], True) return len(rows) - - # ── Meta key/value (for scheduler bookkeeping) ── + # ── Meta key/value (scheduler bookkeeping) ── def get_meta(self, key: str) -> Optional[str]: - """Read a value from the state_meta key/value store.""" - # Kept on self._lock (not _read_ctx) because callers like - # fts_rebuild_step read progress before entering a write - # transaction, and the read-only WAL connection sees only - # committed data — a pending write transaction's uncommitted - # meta writes would be invisible. This is a cheap point lookup, - # not the convoy bottleneck the read-path split targets. + """Read state_meta[key]. On self._lock, not _read_ctx: fts_rebuild_step + reads progress before its write transaction, and a read-only WAL + connection would not see uncommitted meta writes.""" with self._lock: row = self._conn.execute( "SELECT value FROM state_meta WHERE key = ?", (key,) ).fetchone() - if row is None: - return None - return row[0] + return None if row is None else row[0] - def set_meta( - self, key: str, value: str, *, cursor: Optional[sqlite3.Cursor] = None - ) -> None: - """Write a value to the state_meta key/value store. - - When ``cursor`` is provided the write is issued on that cursor - inline (used during ``_init_schema``, which already holds an open - transaction — routing through ``_execute_write`` there would nest - BEGIN IMMEDIATE and deadlock). Otherwise a normal write transaction - is used. - """ - if cursor is not None: - cursor.execute( - "INSERT INTO state_meta (key, value) VALUES (?, ?) " - "ON CONFLICT(key) DO UPDATE SET value = excluded.value", - (key, value), - ) - return - - self._write_sql( + def set_meta(self, key: str, value: str, *, cursor: Optional[sqlite3.Cursor] = None) -> None: + """Upsert state_meta[key]. With ``cursor`` the write is inline (_init_schema + already holds a transaction; _execute_write would nest BEGIN IMMEDIATE and deadlock).""" + sql = ( "INSERT INTO state_meta (key, value) VALUES (?, ?) " - "ON CONFLICT(key) DO UPDATE SET value = excluded.value", - (key, value), + "ON CONFLICT(key) DO UPDATE SET value = excluded.value" ) + if cursor is not None: + cursor.execute(sql, (key, value)) + else: + self._write_sql(sql, (key, value)) def retag_kanban_worker_sessions(self, workspaces_root: str) -> int: - """Retag legacy kanban worker rows from ``cli`` to ``kanban``. - - Workers used to spawn without ``HERMES_SESSION_SOURCE``, so their runs - landed as untitled ``cli`` rows and the sidebar rendered one per attempt - labeled with the worker's own prompt. New workers tag themselves; this - reclaims the rows already on disk so they drop out of the session lists - too. Identified by cwd under the board's workspaces root — a path only - the dispatcher ever runs a session in. - - Gated per workspaces root (``state_meta``) so each board reclaims its - own rows exactly once. Returns the number of rows retagged. - """ + """Retag legacy kanban worker rows (spawned without HERMES_SESSION_SOURCE) + from ``cli`` to ``kanban``, identified by cwd under the board's workspaces + root — a path only the dispatcher runs sessions in. Gated once per root + via state_meta. Returns rows retagged.""" prefix = str(workspaces_root).rstrip("/\\") if not prefix: return 0 - gate = f"kanban_worker_source_retagged:{prefix}" if self.get_meta(gate) == "1": return 0 - def _do(conn): cursor = conn.execute( "UPDATE sessions SET source = 'kanban' " "WHERE source = 'cli' AND (cwd = ? OR cwd LIKE ? ESCAPE '\\')", (prefix, _escape_like(prefix) + "/%"), ) - # Read rowcount before set_meta reuses this cursor for its INSERT, - # which would otherwise overwrite it with the meta write's count. + # rowcount BEFORE set_meta reuses this cursor for its INSERT. retagged = cursor.rowcount or 0 self.set_meta(gate, "1", cursor=cursor) return retagged - return self._execute_write(_do) def list_meta_prefix(self, prefix: str) -> List[Tuple[str, str]]: - """Return ``[(key, value), ...]`` for state_meta keys with ``prefix``. - - Used by feature stores that persist one row per session under a - namespaced key (e.g. ``loop:``) and need to enumerate - them across sessions (the gateway's idle /loop wakeup watcher). - ``prefix`` is matched literally — LIKE wildcards in it are escaped. - """ + """``[(key, value), ...]`` for state_meta keys starting with the literal + ``prefix`` (LIKE wildcards escaped) — e.g. ``loop:`` rows.""" if not prefix: return [] escaped = prefix.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") rows = self._read_all( - "SELECT key, value FROM state_meta WHERE key LIKE ? ESCAPE '\\'", - (escaped + "%",), + "SELECT key, value FROM state_meta WHERE key LIKE ? ESCAPE '\\'", (escaped + "%",), ) return [(row[0], row[1]) for row in rows] - - # ── Space reclamation ── - - # FTS5 virtual tables whose b-tree segments we merge on optimize. The - # trigram table is created lazily / may be disabled, and the cjk-bigram - # table only exists (and is only queryable) when the loadable tokenizer - # is present — so we probe each before touching it (see optimize_fts). + # FTS5 tables merged on optimize; trigram may be disabled and cjk exists only + # with the loadable tokenizer, so each is probed before touching (optimize_fts). _FTS_TABLES = ("messages_fts", "messages_fts_trigram", "messages_fts_cjk") - def maybe_auto_archive( - self, - idle_days: float = 3, - min_interval_hours: int = 24, - exclude_pinned: bool = True, + self, idle_days: float = 3, min_interval_hours: int = 24, exclude_pinned: bool = True, ) -> Dict[str, Any]: - """Idempotent auto-archive: soft-hide sessions idle for ``idle_days``. - - Sibling of :meth:`maybe_auto_prune_and_vacuum` but non-destructive — - it archives (hides) rather than deletes, and ages on last activity - (see :meth:`archive_stale_sessions`) rather than creation. Records the - last run in ``state_meta['last_auto_archive']`` so calls within - ``min_interval_hours`` no-op; safe to call opportunistically (startup - hooks, or when the Desktop backend lists sessions). - - Never raises. Returns a dict with: - - ``"skipped"`` (bool) — within min_interval_hours of last run - - ``"archived"`` (int) — sessions archived this run - - ``"error"`` (str, optional) — present only on failure - """ + """Idempotent auto-archive of sessions idle for ``idle_days`` (ages on last + activity, non-destructive). ``state_meta['last_auto_archive']`` gates + runs within ``min_interval_hours``; safe to call opportunistically. + Never raises: {"skipped", "archived", "error"?}.""" result: Dict[str, Any] = {"skipped": False, "archived": 0} try: last_raw = self.get_meta("last_auto_archive") @@ -6392,43 +4070,22 @@ class SessionDB( return result except (TypeError, ValueError): pass # corrupt meta; treat as no prior run - - archived = self.archive_stale_sessions( - idle_days, exclude_pinned=exclude_pinned - ) - result["archived"] = archived - - # Record even a zero-archive run so we don't re-sweep every call - # within the interval window. + archived = result["archived"] = self.archive_stale_sessions(idle_days, exclude_pinned=exclude_pinned) + # Record even a zero-archive run so we don't re-sweep every call. self.set_meta("last_auto_archive", str(now)) - if archived > 0: logger.info( - "state.db auto-archive: archived %d session(s) idle >= %s days", - archived, + "state.db auto-archive: archived %d session(s) idle >= %s days", archived, idle_days, ) except Exception as exc: logger.warning("state.db auto-archive failed: %s", exc) result["error"] = str(exc) - return result - # ── Handoff (cross-platform session transfer) ────────────────────────── - # - # State machine: - # None — no handoff in flight - # "pending" — CLI requested handoff, gateway hasn't picked it up yet - # "running" — gateway is processing (session switch + synthetic turn) - # "completed"— gateway successfully delivered the synthetic turn - # "failed" — gateway hit an error; reason in handoff_error - # - # The CLI writes "pending" then poll-waits for terminal state. The gateway - # watcher transitions pending→running→{completed,failed}. - - class AsyncSessionDB: - """Async door onto SessionDB: offloads each call via asyncio.to_thread so a blocking SQLite call never freezes the event loop. Generic forwarder — the audit confirms no method returns a live cursor/generator.""" + """Async door onto SessionDB: each call is offloaded via asyncio.to_thread so a + blocking SQLite call never freezes the event loop (no method returns a live cursor).""" def __init__(self, db: "SessionDB") -> None: self._db = db @@ -6437,8 +4094,6 @@ class AsyncSessionDB: attr = getattr(self._db, name) if not callable(attr): return attr - async def _offloaded(*args, **kwargs): return await asyncio.to_thread(attr, *args, **kwargs) - return _offloaded diff --git a/hermes_state_common.py b/hermes_state_common.py index 88faf2e3ba..88318404ca 100644 --- a/hermes_state_common.py +++ b/hermes_state_common.py @@ -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. `.fts_rebuild.lock` +# is distinct from `.repair.lock` (schema surgery on an EXCLUSIVE offline +# connection, minutes in VACUUM). Lives here because mixins cannot import # hermes_state (cycle). -# -# `.fts_rebuild.lock` is distinct from `.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: diff --git a/hermes_state_compression.py b/hermes_state_compression.py index cb91823f39..eb9dfb5f49 100644 --- a/hermes_state_compression.py +++ b/hermes_state_compression.py @@ -16,30 +16,29 @@ from hermes_state_common import _sql_session_last_active, is_automatic_end_reaso # Log-record parity with the origin module (caplog tests pin "hermes_state"). logger = logging.getLogger("hermes_state") +_ENDED_ROW_SQL = "SELECT ended_at, end_reason FROM sessions WHERE id = ?" +_LOCK_ROW_SQL = "SELECT holder, expires_at FROM compression_locks WHERE session_id = ?" +_COOLDOWN_ROW_SQL = ( + "SELECT compression_failure_cooldown_until, compression_failure_error FROM sessions WHERE id = ?" +) + + +def _ended_by_compression(row) -> bool: + return row is not None and row["ended_at"] is not None and row["end_reason"] == "compression" + class SessionCompressionMixin: """Compression lineage, cooldown/streak counters, locks and turn leases.""" - def find_live_compression_child( - self, parent_session_id: str - ) -> Optional[Dict[str, Any]]: - """Return the unique live direct child of a compression-ended session. + def find_live_compression_child(self, parent_session_id: str) -> Optional[Dict[str, Any]]: + """The unique live direct child of a compression-ended session, else None. A stale agent whose parent was rotated elsewhere may recover only when the - lineage names exactly one live continuation; more than one fails closed - rather than guessing which transcript owns later messages.""" + lineage names exactly one live continuation; more than one fails closed.""" if not parent_session_id: return None with self._read_ctx() as conn: - parent = conn.execute( - "SELECT ended_at, end_reason FROM sessions WHERE id = ?", - (parent_session_id,), - ).fetchone() - if ( - parent is None - or parent["ended_at"] is None - or parent["end_reason"] != "compression" - ): + if not _ended_by_compression(conn.execute(_ENDED_ROW_SQL, (parent_session_id,)).fetchone()): return None rows = conn.execute( """ @@ -61,28 +60,16 @@ class SessionCompressionMixin: return self._session_row_dict(rows[0]) if len(rows) == 1 else None def reopen_orphaned_compression_session(self, session_id: str) -> bool: - """Reopen a compression parent only when no continuation was published. - - Publication is atomic now, but older builds could leave a closed parent - after an interrupted handoff. Conservative by design: an active lease or - any canonical child means another path owns the lineage — fail closed.""" + """Reopen a compression parent only when no continuation was published (older + builds could leave a closed parent after an interrupted handoff). Conservative: + an active lease or any canonical child means another path owns the lineage.""" if not session_id: return False def _do(conn): - parent = conn.execute( - "SELECT ended_at, end_reason FROM sessions WHERE id = ?", - (session_id,), - ).fetchone() - if ( - parent is None - or parent["ended_at"] is None - or parent["end_reason"] != "compression" - ): + if not _ended_by_compression(conn.execute(_ENDED_ROW_SQL, (session_id,)).fetchone()): return False - - # Any non-branch/non-delegate/non-tool child is a continuation, ended - # or not; reopening past it could give one lineage a second live head. + # Any non-branch/non-delegate/non-tool child is a continuation, ended or not. child = conn.execute( """ SELECT 1 @@ -97,17 +84,11 @@ class SessionCompressionMixin: ).fetchone() if child is not None: return False - - # refresh_compression_lock() lets an owner revive its own expired - # row, so reclaim it inside this write transaction before reopening: - # refresh-first makes the lease active and aborts recovery; - # recovery-first deletes the holder so a later refresh can't resurrect it. + # refresh_compression_lock() lets an owner revive its own expired row, so + # reclaim it inside this write txn: refresh-first makes the lease active and + # aborts recovery; recovery-first deletes the holder so a refresh can't resurrect it. now = time.time() - lock_row = conn.execute( - "SELECT holder, expires_at FROM compression_locks " - "WHERE session_id = ?", - (session_id,), - ).fetchone() + lock_row = conn.execute(_LOCK_ROW_SQL, (session_id,)).fetchone() if lock_row is not None: expires_at = lock_row["expires_at"] if expires_at is None or float(expires_at) >= now: @@ -119,70 +100,89 @@ class SessionCompressionMixin: ) if deleted.rowcount != 1: return False - updated = conn.execute( "UPDATE sessions SET ended_at = NULL, end_reason = NULL " "WHERE id = ? AND ended_at IS NOT NULL " "AND end_reason = 'compression'", (session_id,), ) - # rowcount==1 is guaranteed by the parent SELECT in this same BEGIN - # IMMEDIATE transaction. If a False return is ever added past this - # point, raise instead: _execute_write commits the lease DELETE above unless _do raises. + # rowcount==1 is guaranteed by the parent SELECT in this same txn. A False + # return added past this point must raise instead: the lease DELETE above + # commits unless _do raises. return updated.rowcount == 1 return bool(self._execute_write(_do)) + def _publish_child_session_row(self, conn, parent, *, parent_session_id, child_session_id, source, + model, model_config, system_prompt, cwd, profile_name) -> None: + """INSERT the compression child's ``sessions`` row copied from *parent*.""" + system_prompt_hash = self._store_system_prompt(conn, system_prompt) + conn.execute( + """INSERT INTO sessions ( + id, source, model, model_config, system_prompt, + system_prompt_hash, + parent_session_id, cwd, git_branch, git_repo_root, + profile_name, user_id, session_key, chat_id, chat_type, + thread_id, display_name, origin_json, started_at + ) VALUES (?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", + ( + child_session_id, + source, + model, + json.dumps(model_config) if model_config else None, + system_prompt_hash, + parent_session_id, + cwd or parent["cwd"], + parent["git_branch"], + parent["git_repo_root"], + # Same contract as _insert_session_row's compression-fork backfill: the + # child stays on the parent's profile and keeps gateway routing/origin + # columns; no owner on either side -> this store's profile. + profile_name or parent["profile_name"] or self._own_profile_name(), + parent["user_id"], + parent["session_key"], + parent["chat_id"], + parent["chat_type"], + parent["thread_id"], + parent["display_name"], + parent["origin_json"], + time.time(), + ), + ) + def publish_compression_child( - self, - *, - parent_session_id: str, - child_session_id: str, - source: str, - messages: List[Dict[str, Any]], - model: str = None, - model_config: Dict[str, Any] = None, - system_prompt: str = None, - cwd: str = None, - profile_name: str = None, - compression_lock_holder: str = None, - require_compression_lease: bool = True, - require_lease_refresh: bool = False, - lease_ttl_seconds: float = 300.0, - watermark: Optional[int] = None, - watermark_ceiling: Optional[int] = None, + self, *, parent_session_id: str, child_session_id: str, source: str, + messages: List[Dict[str, Any]], model: str = None, model_config: Dict[str, Any] = None, + system_prompt: str = None, cwd: str = None, profile_name: str = None, + compression_lock_holder: str = None, require_compression_lease: bool = True, + require_lease_refresh: bool = False, lease_ttl_seconds: float = 300.0, + watermark: Optional[int] = None, watermark_ceiling: Optional[int] = None, ) -> None: """Atomically close a parent and publish its durable compression child. - Closure, child row, and handoff commit in one transaction: readers see - the live parent or a complete child, never an ended parent with a - missing/empty child. + Closure, child row, and handoff commit in one transaction: readers see the live + parent or a complete child, never an ended parent with a missing/empty child. - *watermark* (parent's ``get_active_message_watermark`` at compression - start): parent rows with ``id > watermark`` — appends landed during the - slow summary call — are column-cloned into the child AFTER the handoff - so they survive rotation. *watermark_ceiling* bounds the clone: the - rotation path flushes its OWN transcript to the parent just before - publishing and those rows are already in the handoff, so the caller - captures ``MAX(id)`` right BEFORE that flush and only - ``(watermark, watermark_ceiling]`` is foreign tail. ``None`` = unbounded. + *watermark* (parent's ``get_active_message_watermark`` at compression start): + parent rows with ``id > watermark`` — appends landed during the slow summary — + are column-cloned into the child AFTER the handoff. *watermark_ceiling* bounds + the clone: the rotation path flushes its OWN transcript to the parent just + before publishing and those rows are already in the handoff, so only + ``(watermark, watermark_ceiling]`` is foreign tail (``None`` = unbounded). - *require_lease_refresh* + *compression_lock_holder* refreshes the lease - on the same ``conn`` before the expiry check (no TOCTOU window), so a - refresher that died on transient DB errors gets one last chance.""" + *require_lease_refresh* + *compression_lock_holder* refreshes the lease on the + same ``conn`` before the expiry check (no TOCTOU window), so a refresher that + died on transient DB errors gets one last chance.""" from hermes_state import CompressionSessionBusyError + def _do(conn): if require_lease_refresh and compression_lock_holder: conn.execute( "UPDATE compression_locks SET expires_at = ? " "WHERE session_id = ? AND holder = ?", - (time.time() + lease_ttl_seconds, parent_session_id, - compression_lock_holder), + (time.time() + lease_ttl_seconds, parent_session_id, compression_lock_holder), ) - lock_row = conn.execute( - "SELECT holder, expires_at FROM compression_locks WHERE session_id = ?", - (parent_session_id,), - ).fetchone() + lock_row = conn.execute(_LOCK_ROW_SQL, (parent_session_id,)).fetchone() if require_compression_lease and ( lock_row is None or not compression_lock_holder @@ -202,14 +202,11 @@ class SessionCompressionMixin: if parent is None: raise RuntimeError(f"Compression parent not found: {parent_session_id}") if parent["ended_at"] is not None: - # An ended stamp from AUTOMATIC cleanup (tui_shutdown, ws_disconnect, - # orphan reap, idle/LRU evict) is stale by construction — this lease - # holder is still continuing the conversation. Left alone it wedges - # rotation forever (every attempt aborts here; each pre-publish flush - # re-grows the parent until the provider rejects it). Clear it; the - # closure UPDATE below re-stamps end_reason='compression'. Deliberate - # boundaries (compression, session_reset, explicit close) still fail - # closed — another path owns the lineage. + # An AUTOMATIC end stamp (tui_shutdown, ws_disconnect, orphan reap, + # idle/LRU evict) is stale by construction — this lease holder is still + # continuing the conversation, and left alone it wedges rotation forever. + # Clear it; the closure UPDATE below re-stamps end_reason='compression'. + # Deliberate boundaries still fail closed. if is_automatic_end_reason(parent["end_reason"]): conn.execute( "UPDATE sessions SET ended_at = NULL, end_reason = NULL " @@ -217,90 +214,34 @@ class SessionCompressionMixin: (parent_session_id,), ) else: - raise RuntimeError( - f"Compression parent already ended: {parent_session_id}" - ) + raise RuntimeError(f"Compression parent already ended: {parent_session_id}") if not messages: raise RuntimeError("Compression child handoff must not be empty") - system_prompt_hash = self._store_system_prompt(conn, system_prompt) - - conn.execute( - """INSERT INTO sessions ( - id, source, model, model_config, system_prompt, - system_prompt_hash, - parent_session_id, cwd, git_branch, git_repo_root, - profile_name, user_id, session_key, chat_id, chat_type, - thread_id, display_name, origin_json, started_at - ) VALUES (?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", - ( - child_session_id, - source, - model, - json.dumps(model_config) if model_config else None, - system_prompt_hash, - parent_session_id, - cwd or parent["cwd"], - parent["git_branch"], - parent["git_repo_root"], - # Same contract as _insert_session_row's compression-fork backfill: - # child stays on the parent's profile and keeps gateway routing/ - # origin columns so peer recovery works after a boundary crash. No - # owner on either side (legacy NULL parent) → stamp this store's - # profile so the child doesn't extend the unowned lineage. - profile_name - or parent["profile_name"] - or self._own_profile_name(), - parent["user_id"], - parent["session_key"], - parent["chat_id"], - parent["chat_type"], - parent["thread_id"], - parent["display_name"], - parent["origin_json"], - time.time(), - ), - ) - total_messages, total_tool_calls = self._insert_message_rows( - conn, child_session_id, messages + self._publish_child_session_row( + conn, parent, parent_session_id=parent_session_id, child_session_id=child_session_id, + source=source, model=model, model_config=model_config, system_prompt=system_prompt, + cwd=cwd, profile_name=profile_name, ) + total_messages, total_tool_calls = self._insert_message_rows(conn, child_session_id, messages) if watermark is not None: - # Clone the parent's concurrent tail (see docstring) into the - # child after the handoff: column-exact except id/session_id; + # Clone the parent's concurrent tail into the child after the handoff; # originals stay in the closed parent for lineage recovery. _ceiling_clause = "" _params: list = [parent_session_id, int(watermark)] if watermark_ceiling is not None: _ceiling_clause = " AND id <= ?" _params.append(int(watermark_ceiling)) - tail_rows = conn.execute( + tail_ids, tail_tool_calls = self._tail_rows_after_watermark( + conn, "SELECT id, tool_calls FROM messages " "WHERE session_id = ? AND active = 1 AND id > ?" f"{_ceiling_clause} ORDER BY id", _params, - ).fetchall() - if tail_rows: - tail_ids = [int(r["id"]) for r in tail_rows] - placeholders = ",".join("?" for _ in tail_ids) - clone_cols = [ - c for c in self._message_column_names(conn) - if c not in ("id", "session_id", "active", "compacted") - ] - col_list = ", ".join(clone_cols) - conn.execute( - f"INSERT INTO messages ({col_list}, session_id, active, compacted) " - f"SELECT {col_list}, ?, 1, 0 FROM messages " - f"WHERE id IN ({placeholders}) ORDER BY id", - [child_session_id, *tail_ids], - ) + ) + if tail_ids: + self._clone_message_rows(conn, tail_ids, session_id=child_session_id) total_messages += len(tail_ids) - for r in tail_rows: - raw = r["tool_calls"] - if raw: - try: - parsed = json.loads(raw) if isinstance(raw, str) else raw - total_tool_calls += len(parsed) if isinstance(parsed, list) else 0 - except (TypeError, ValueError): - pass + total_tool_calls += tail_tool_calls conn.execute( "UPDATE sessions SET message_count = ?, tool_call_count = ? WHERE id = ?", (total_messages, total_tool_calls, child_session_id), @@ -311,111 +252,66 @@ class SessionCompressionMixin: (time.time(), parent_session_id), ) if updated.rowcount != 1: - raise RuntimeError( - f"Compression parent changed during publication: {parent_session_id}" - ) + raise RuntimeError(f"Compression parent changed during publication: {parent_session_id}") self._execute_write(_do) - def record_compression_failure_cooldown( - self, - session_id: str, - cooldown_until: float, - error: Optional[str] = None, - ) -> None: - """Persist the active compression-failure cooldown for a session.""" + def _write_sql_logged(self, op: str, session_id: str, sql: str, params) -> None: + """``_write_sql`` that logs (never raises) on ``sqlite3.Error``.""" + try: + self._write_sql(sql, params) + except sqlite3.Error as exc: + logger.warning("%s(%s) failed: %s", op, session_id, exc) + + def record_compression_failure_cooldown(self, session_id: str, cooldown_until: float, error: Optional[str] = None) -> None: + """Persist the active compression-failure cooldown. Merge-max with any longer + live deadline so a later shorter write can't reopen the thrash window; error + always takes the latest diagnostic.""" if not session_id: return + self._write_sql_logged( + "record_compression_failure_cooldown", session_id, + "UPDATE sessions SET compression_failure_cooldown_until = CASE " + "WHEN compression_failure_cooldown_until IS NOT NULL " + " AND compression_failure_cooldown_until > ? " + "THEN compression_failure_cooldown_until ELSE ? END, " + "compression_failure_error = ? WHERE id = ?", + (cooldown_until, cooldown_until, error, session_id), + ) - try: - # Merge-max with any longer live deadline so a later shorter write - # can't reopen the thrash window; error always takes the latest diagnostic. - self._write_sql( - "UPDATE sessions SET compression_failure_cooldown_until = CASE " - "WHEN compression_failure_cooldown_until IS NOT NULL " - " AND compression_failure_cooldown_until > ? " - "THEN compression_failure_cooldown_until ELSE ? END, " - "compression_failure_error = ? WHERE id = ?", - (cooldown_until, cooldown_until, error, session_id), - ) - except sqlite3.Error as exc: - logger.warning( - "record_compression_failure_cooldown(%s) failed: %s", - session_id, exc, - ) - - def get_compression_failure_cooldown( - self, - session_id: str, - ) -> Optional[Dict[str, Any]]: - """Return the active compression-failure cooldown for ``session_id``.""" + def get_compression_failure_cooldown(self, session_id: str) -> Optional[Dict[str, Any]]: + """Return the active (unexpired) compression-failure cooldown, or None.""" if not session_id: return None now = time.time() - row = self._read_one( - "SELECT compression_failure_cooldown_until, compression_failure_error " - "FROM sessions WHERE id = ?", - (session_id,), - ) - if row is None: + row = self._read_one(_COOLDOWN_ROW_SQL, (session_id,)) + if row is None or row[0] is None: return None - cooldown_until = row[0] - if cooldown_until is None: - return None - cooldown_until = float(cooldown_until) + cooldown_until = float(row[0]) if cooldown_until <= now: return None - error = row[1] - return { - "cooldown_until": cooldown_until, - "remaining_seconds": cooldown_until - now, - "error": error, - } + return {"cooldown_until": cooldown_until, "remaining_seconds": cooldown_until - now, "error": row[1]} - def get_compression_failure_cooldown_row( - self, - session_id: str, - ) -> Dict[str, Any]: - """Exact stored cooldown columns, no expiry filtering. Compression - cancellation uses this under its session lease so rollback preserves an - expired, partially-null, or absent row exactly instead of coercing it - through the active-cooldown API.""" - if not session_id: - return {"session_exists": False, "cooldown_until": None, "error": None} - row = self._read_one( - "SELECT compression_failure_cooldown_until, compression_failure_error " - "FROM sessions WHERE id = ?", - (session_id,), - ) + def get_compression_failure_cooldown_row(self, session_id: str) -> Dict[str, Any]: + """Exact stored cooldown columns, no expiry filtering, so compression + cancellation can roll back an expired, partially-null, or absent row exactly.""" + row = self._read_one(_COOLDOWN_ROW_SQL, (session_id,)) if session_id else None if row is None: return {"session_exists": False, "cooldown_until": None, "error": None} - cooldown_until = row[0] - error = row[1] return { "session_exists": True, - "cooldown_until": ( - float(cooldown_until) if cooldown_until is not None else None - ), - "error": error, + "cooldown_until": float(row[0]) if row[0] is not None else None, + "error": row[1], } - def restore_compression_failure_cooldown_row( - self, - session_id: str, - snapshot: Dict[str, Any], - ) -> None: - """Restore and verify an exact cooldown-row snapshot. Unlike record/clear, - this rollback API propagates write and verification failures: cancellation - must not be reported mutation-free when compensation failed.""" - expected_exists = bool(snapshot.get("session_exists", False)) - if not expected_exists: - actual = self.get_compression_failure_cooldown_row(session_id) - if actual.get("session_exists", False): - raise RuntimeError( - "cannot restore absent compression cooldown row: session now exists" - ) + def restore_compression_failure_cooldown_row(self, session_id: str, snapshot: Dict[str, Any]) -> None: + """Restore and verify an exact cooldown-row snapshot. Unlike record/clear this + rollback API propagates write and verification failures: cancellation must not + be reported mutation-free when compensation failed.""" + if not snapshot.get("session_exists", False): + if self.get_compression_failure_cooldown_row(session_id).get("session_exists", False): + raise RuntimeError("cannot restore absent compression cooldown row: session now exists") return - deadline = snapshot.get("cooldown_until") error = snapshot.get("error") @@ -426,9 +322,7 @@ class SessionCompressionMixin: (deadline, error, session_id), ) if cursor.rowcount != 1: - raise RuntimeError( - f"compression cooldown rollback session missing: {session_id}" - ) + raise RuntimeError(f"compression cooldown rollback session missing: {session_id}") self._execute_write(_do) actual = self.get_compression_failure_cooldown_row(session_id) @@ -447,27 +341,19 @@ class SessionCompressionMixin: """Clear any persisted compression-failure cooldown for a session.""" if not session_id: return - - try: - self._write_sql( - "UPDATE sessions SET compression_failure_cooldown_until = NULL, " - "compression_failure_error = NULL WHERE id = ?", - (session_id,), - ) - except sqlite3.Error as exc: - logger.warning( - "clear_compression_failure_cooldown(%s) failed: %s", - session_id, exc, - ) + self._write_sql_logged( + "clear_compression_failure_cooldown", session_id, + "UPDATE sessions SET compression_failure_cooldown_until = NULL, " + "compression_failure_error = NULL WHERE id = ?", + (session_id,), + ) def _read_session_number(self, column: str, session_id: str, cast: type, zero: Any) -> Any: - """Read one numeric ``sessions`` column clamped at ``zero``; a missing - session, NULL, or unparsable value also reads as ``zero``.""" + """Read one numeric ``sessions`` column clamped at ``zero``; a missing session, + NULL, or unparsable value also reads as ``zero``.""" if not session_id: return zero - row = self._read_one( - f"SELECT {column} FROM sessions WHERE id = ?", (session_id,) - ) + row = self._read_one(f"SELECT {column} FROM sessions WHERE id = ?", (session_id,)) if row is None: return zero try: @@ -488,9 +374,9 @@ class SessionCompressionMixin: ) def get_compression_ineffective_count(self, session_id: str) -> int: - """Persisted ineffective-compaction strike count: the durable half of - the built-in compressor's anti-thrash guard, so a fresh compressor bound - to a resumed session inherits an armed/tripped guard across restarts.""" + """Persisted ineffective-compaction strike count — the durable half of the + built-in compressor's anti-thrash guard, so a fresh compressor bound to a resumed + session inherits an armed/tripped guard across restarts.""" return self._read_session_number("compression_ineffective_count", session_id, int, 0) def set_compression_ineffective_count(self, session_id: str, count: int) -> None: @@ -502,10 +388,8 @@ class SessionCompressionMixin: ) def get_compression_recovery_deadline(self, session_id: str) -> float: - """Persisted anti-thrash recovery deadline (epoch; ``0.0`` = not armed). - Durable because the gateway rebuilds the compressor every turn / cache - eviction: a process-local deadline restarted on each rebuild, so a - tripped session never earned its probe.""" + """Persisted anti-thrash recovery deadline (epoch; ``0.0`` = not armed). Durable + because the gateway rebuilds the compressor every turn / cache eviction.""" return self._read_session_number("compression_recovery_deadline", session_id, float, 0.0) def set_compression_recovery_deadline(self, session_id: str, deadline: float) -> None: @@ -516,39 +400,23 @@ class SessionCompressionMixin: normalized = max(0.0, float(deadline or 0.0)) except (TypeError, ValueError): normalized = 0.0 - stored = normalized if normalized > 0.0 else None - self._write_sql( "UPDATE sessions SET compression_recovery_deadline = ? WHERE id = ?", - (stored, session_id), + (normalized if normalized > 0.0 else None, session_id), ) - def refresh_compression_lock( - self, - session_id: str, - holder: str, - ttl_seconds: float = 300.0, - ) -> bool: + def refresh_compression_lock(self, session_id: str, holder: str, ttl_seconds: float = 300.0) -> bool: """Extend the compression lock lease if ``holder`` still owns it. - Ownership is decided by ``holder`` alone, deliberately NOT ``expires_at``: - a live owner whose refresher stalled past its TTL (GC pause, loaded CI - runner, slow write escaping ``_execute_write``'s retry budget) must be - able to revive its still-unclaimed row. Requiring ``expires_at >= now`` - made such a stall permanent — every later refresh matched 0 rows and the - owner kept compressing/rotating with no lease, exactly the window in - which a competing path can fork the lineage. - - It cannot resurrect a lock someone else took: SQLite serialises writes, - so :meth:`try_acquire_compression_lock`'s reclaim (DELETE-expired + - INSERT-or-IGNORE) never interleaves with this UPDATE. Reclaim-first - replaces ``holder`` and this matches nothing; refresh-first pushes - ``expires_at`` forward and the reclaimer's DELETE matches nothing.""" + Ownership is decided by ``holder`` alone, deliberately NOT ``expires_at``: a live + owner whose refresher stalled past its TTL must be able to revive its still- + unclaimed row, otherwise it keeps compressing with no lease — the window in + which a competing path can fork the lineage. It cannot resurrect a lock someone + else took: SQLite serialises writes, so the reclaim (DELETE-expired + INSERT OR + IGNORE) never interleaves with this UPDATE.""" if not session_id or not holder: return False - now = time.time() - expires_at = now + ttl_seconds - + expires_at = time.time() + ttl_seconds try: return self._write_rowcount( "UPDATE compression_locks SET expires_at = ? " @@ -556,27 +424,17 @@ class SessionCompressionMixin: (expires_at, session_id, holder), ) > 0 except sqlite3.Error as exc: - logger.warning( - "refresh_compression_lock(%s) failed: %s", - session_id, exc, - ) + logger.warning("refresh_compression_lock(%s) failed: %s", session_id, exc) return False - def try_acquire_compression_lock( - self, - session_id: str, - holder: str, - ttl_seconds: float = 300.0, - ) -> bool: + def try_acquire_compression_lock(self, session_id: str, holder: str, ttl_seconds: float = 300.0) -> bool: """Try to atomically acquire the compression lock for ``session_id``. - ``True``: caller owns the lock and must :meth:`release_compression_lock`. - ``False``: another holder owns a live lock and the caller MUST NOT - compress — its rotation would race the holder's and split the lineage. - Expired locks and structured holders whose local ``pid=`` is dead are - reclaimed transparently, so a gateway killed mid-compression doesn't - stall its replacement for the full TTL. Single-transaction DELETE-expired - + INSERT-or-IGNORE + SELECT-to-confirm; SQLite serialises writes, so it's atomic.""" + ``False``: another holder owns a live lock and the caller MUST NOT compress (its + rotation would split the lineage). Expired locks and structured holders whose + local ``pid=`` is dead are reclaimed transparently. Single-transaction DELETE- + expired + INSERT OR IGNORE + SELECT-to-confirm (INSERT OR IGNORE gives no + rowcount signal).""" from hermes_state import _compression_lock_holder_process_is_dead if not session_id: return False @@ -585,90 +443,54 @@ class SessionCompressionMixin: def _do(conn): reclaimed_holder = None - row = conn.execute( - "SELECT holder, expires_at FROM compression_locks " - "WHERE session_id = ?", - (session_id,), - ).fetchone() + row = conn.execute(_LOCK_ROW_SQL, (session_id,)).fetchone() if row is not None: - current_holder = ( - row[0] - ) - current_expires_at = ( - row[1] - ) - if ( - current_expires_at < now - or _compression_lock_holder_process_is_dead(current_holder) - ): + current_holder, current_expires_at = row[0], row[1] + if current_expires_at < now or _compression_lock_holder_process_is_dead(current_holder): conn.execute( "DELETE FROM compression_locks " "WHERE session_id = ? AND holder = ?", (session_id, current_holder), ) reclaimed_holder = current_holder - # INSERT OR IGNORE gives no rowcount signal — verify ownership via SELECT. conn.execute( "INSERT OR IGNORE INTO compression_locks " "(session_id, holder, acquired_at, expires_at) " "VALUES (?, ?, ?, ?)", (session_id, holder, now, expires_at), ) - row = conn.execute( - "SELECT holder FROM compression_locks WHERE session_id = ?", - (session_id,), - ).fetchone() - acquired = row is not None and ( - row[0] - ) == holder - return acquired, reclaimed_holder + row = conn.execute("SELECT holder FROM compression_locks WHERE session_id = ?", (session_id,)).fetchone() + return row is not None and row[0] == holder, reclaimed_holder try: acquired, reclaimed_holder = self._execute_write(_do) if reclaimed_holder: logger.warning( - "Reclaimed stale compression lock for session=%s " - "(holder=%s)", - session_id, - reclaimed_holder, + "Reclaimed stale compression lock for session=%s (holder=%s)", session_id, reclaimed_holder, ) return bool(acquired) except sqlite3.Error as exc: - logger.warning( - "try_acquire_compression_lock(%s) failed: %s", - session_id, exc, - ) - # False makes the caller skip compression — the safe behaviour - # when the lock subsystem is broken. + # False makes the caller skip compression — safe when the lock subsystem is broken. + logger.warning("try_acquire_compression_lock(%s) failed: %s", session_id, exc) return False def release_compression_lock(self, session_id: str, holder: str) -> None: - """Release the compression lock for ``session_id`` iff we own it. Idempotent - when the lock is gone or reclaimed; the ``holder`` check stops a late - compressor clobbering someone else's fresh lock.""" + """Release the compression lock iff we own it; idempotent when gone/reclaimed.""" if not session_id: return - - try: - self._write_sql( - "DELETE FROM compression_locks " - "WHERE session_id = ? AND holder = ?", - (session_id, holder), - ) - except sqlite3.Error as exc: - logger.warning( - "release_compression_lock(%s) failed: %s", - session_id, exc, - ) + self._write_sql_logged( + "release_compression_lock", session_id, + "DELETE FROM compression_locks " + "WHERE session_id = ? AND holder = ?", + (session_id, holder), + ) def _session_turn_lease_key_on_conn(self, conn, session_id: str) -> str: """Walk compression parents on ``conn`` to the conversation lease key. - Must share the connection of the lease INSERT/UPDATE/DELETE: a failed - ``get_session`` must not yield a child id the write then persists - (refresh would walk to the parent and fail-close). Markers bind to - ``parent_session_id`` (as in ``_NON_CONTINUATION_CHILD_FILTER_SQL``). - Lock errors propagate so ``_execute_write`` / ``acquire_session_turn_lease`` can retry.""" + Must share the connection of the lease INSERT/UPDATE/DELETE: a failed lookup + must not yield a child id the write then persists. Markers bind to + ``parent_session_id``. Lock errors propagate so ``_execute_write`` can retry.""" if not session_id: return session_id @@ -684,11 +506,7 @@ class SessionCompressionMixin: seen = {session_id} while current: parent_id = current.get("parent_session_id") - if ( - not parent_id - or parent_id in seen - or self._is_explicit_fork_child_row(current) - ): + if not parent_id or parent_id in seen or self._is_explicit_fork_child_row(current): break parent = _row(parent_id) if not parent or parent.get("end_reason") != "compression": @@ -698,29 +516,19 @@ class SessionCompressionMixin: return str(current.get("id") or session_id) if current else session_id def _session_turn_lease_key(self, session_id: str) -> str: - """Return the stable serialization key for every compression segment. - - Acquire/refresh/release resolve this inside their write transaction; this - is for tests/diagnostics. It does not swallow lock errors — a swallowed - walk plus a later successful write was the fail-open that replayed the - post-rotation refresh miss.""" + """Stable serialization key for every compression segment (tests/diagnostics; + the write paths resolve it inside their own txn). Does not swallow lock errors.""" if not session_id: return session_id with self._read_ctx() as conn: return self._session_turn_lease_key_on_conn(conn, session_id) def try_acquire_session_turn_lease( - self, - session_id: str, - holder: str, - *, - ttl_seconds: float = 300.0, - patience_s: Optional[float] = None, + self, session_id: str, holder: str, *, ttl_seconds: float = 300.0, patience_s: Optional[float] = None, ) -> bool: - """Atomically acquire the cross-process turn lease for a conversation. - Compression rotates a session into child segments, so the durable key is - the lineage root, not the current segment id. The walk, the INSERT, and - reclaim of expired or dead-local-PID leases share one write transaction.""" + """Atomically acquire the cross-process turn lease for a conversation (keyed by + the lineage root). The walk, the INSERT, and reclaim of expired or dead-local-PID + leases share one write transaction.""" from hermes_state import _compression_lock_holder_process_is_dead if not session_id or not holder: return False @@ -736,10 +544,7 @@ class SessionCompressionMixin: ).fetchone() if row is not None: current_holder = row["holder"] - if ( - float(row["expires_at"]) <= now - or _compression_lock_holder_process_is_dead(current_holder) - ): + if float(row["expires_at"]) <= now or _compression_lock_holder_process_is_dead(current_holder): conn.execute( "DELETE FROM session_turn_leases " "WHERE conversation_id = ? AND holder = ?", @@ -752,32 +557,23 @@ class SessionCompressionMixin: (conversation_id, holder, now, expires_at), ) owner = conn.execute( - "SELECT holder FROM session_turn_leases WHERE conversation_id = ?", - (conversation_id,), + "SELECT holder FROM session_turn_leases WHERE conversation_id = ?", (conversation_id,), ).fetchone() return owner is not None and owner["holder"] == holder return bool(self._execute_write(_do, patience_s=patience_s)) def acquire_session_turn_lease( - self, - session_id: str, - holder: str, - *, - ttl_seconds: float = 300.0, - wait_seconds: float = 1800.0, - poll_interval_seconds: float = 1.0, - on_wait=None, - wait_notice_interval_seconds: float = 15.0, - should_abort=None, + self, session_id: str, holder: str, *, ttl_seconds: float = 300.0, + wait_seconds: float = 1800.0, poll_interval_seconds: float = 1.0, on_wait=None, + wait_notice_interval_seconds: float = 15.0, should_abort=None, acquire_patience_s: float = 0.5, ) -> bool: """Wait for a cross-process turn lease without holding a SQLite lock. - ``on_wait(elapsed)`` is best-effort: called when the first attempt fails - (elapsed ~0) and about every ``wait_notice_interval_seconds`` after, so - UIs can show another process holds the conversation. ``should_abort()`` - True (e.g. ``/stop``) returns False at once, not after ``wait_seconds``.""" + ``on_wait(elapsed)`` is best-effort: called when the first attempt fails and + about every ``wait_notice_interval_seconds`` after. ``should_abort()`` True + (e.g. ``/stop``) returns False at once.""" from hermes_state import classify_persistence_error deadline = time.monotonic() + max(0.0, float(wait_seconds)) wait_started = None @@ -789,22 +585,15 @@ class SessionCompressionMixin: if should_abort(): return False except Exception: - logger.debug( - "session turn lease should_abort callback failed", - exc_info=True, - ) + logger.debug("session turn lease should_abort callback failed", exc_info=True) try: if self.try_acquire_session_turn_lease( - session_id, - holder, - ttl_seconds=ttl_seconds, - patience_s=acquire_patience_s, + session_id, holder, ttl_seconds=ttl_seconds, patience_s=acquire_patience_s, ): return True except sqlite3.Error as exc: - # Long holder transactions (compression publish, large flushes) - # can exhaust one write-patience budget; keep polling until - # wait_seconds or should_abort. + # Long holder transactions can exhaust one write-patience budget; keep + # polling until wait_seconds or should_abort. if classify_persistence_error(exc) != "locked": raise now = time.monotonic() @@ -814,27 +603,16 @@ class SessionCompressionMixin: if wait_started is None: wait_started = now if on_wait is not None and ( - last_notice_at is None - or notice_every == 0.0 - or (now - last_notice_at) >= notice_every + last_notice_at is None or notice_every == 0.0 or (now - last_notice_at) >= notice_every ): try: on_wait(max(0.0, now - wait_started)) except Exception: - logger.debug( - "session turn lease on_wait callback failed", - exc_info=True, - ) + logger.debug("session turn lease on_wait callback failed", exc_info=True) last_notice_at = now time.sleep(min(max(0.01, float(poll_interval_seconds)), remaining)) - def refresh_session_turn_lease( - self, - session_id: str, - holder: str, - *, - ttl_seconds: float = 300.0, - ) -> bool: + def refresh_session_turn_lease(self, session_id: str, holder: str, *, ttl_seconds: float = 300.0) -> bool: """Extend a turn lease only while ``holder`` still owns it.""" if not session_id or not holder: return False @@ -867,24 +645,20 @@ class SessionCompressionMixin: self._execute_write(_do) def get_compression_lock_holder(self, session_id: str) -> Optional[str]: - """Return the current (non-expired) holder for ``session_id``, or None. - Diagnostic only — not part of the locking protocol.""" + """Current (non-expired) holder for ``session_id``, or None. Diagnostic only.""" if not session_id: return None - now = time.time() row = self._read_one( "SELECT holder FROM compression_locks " "WHERE session_id = ? AND expires_at >= ?", - (session_id, now), + (session_id, time.time()), ) - if row is None: - return None - return row[0] + return None if row is None else row[0] def finalize_orphaned_compression_sessions(self) -> int: - """Mark orphaned compression continuations (parent ended by compression; - child has messages, no end_reason/ended_at, api_call_count=0) as - ``orphaned_compression``. Non-destructive: messages are preserved.""" + """Mark orphaned compression continuations (parent ended by compression; child + has messages, no end_reason/ended_at, api_call_count=0, older than 7 days) as + ``orphaned_compression``. Non-destructive.""" cutoff = time.time() - 604800 # 7 days def _do(conn): @@ -917,29 +691,22 @@ class SessionCompressionMixin: return self._execute_write(_do) or 0 def get_compression_chain(self, session_id: str) -> List[str]: - """Walk the compression-continuation chain forward and return every id. + """Walk the compression-continuation chain forward: root-first through the tip + (``[session_id]`` when no continuation). ``get_compression_tip`` is this walk's + last element. - Root-first, ending at the tip; ``[session_id]`` when no continuation - exists. ``get_compression_tip`` is this walk's last element — one - implementation so the two can never disagree. - - A continuation is a child of a session with ``end_reason='compression'``. - Older builds also required ``child.started_at >= parent.ended_at``; - too brittle — gateway + compression races can insert the real - continuation before the parent's ``ended_at`` is written while a stale - websocket later creates a sibling that passes the timestamp test, so - desktop resume followed the sibling and recent messages looked "lost". - Instead: follow only children of compression-ended parents, exclude - explicit branch/delegate/tool children, and prefer children that continue - the chain (``end_reason='compression'``) or are still live over stale - closed siblings such as ``ws_orphan_reap``.""" + A continuation is a child of a session with ``end_reason='compression'``. The + old ``child.started_at >= parent.ended_at`` test was too brittle (gateway + + compression races insert the real continuation before ``ended_at`` is written, + while a stale websocket later creates a sibling that passes it). Instead exclude + branch/delegate/tool children and prefer children that continue the chain or + are still live over stale closed siblings such as ``ws_orphan_reap``.""" current = session_id chain = [current] if current else [] seen = {current} if current else set() - # Defensive bound; chains this deep are pathological. - for _ in range(100): + for _ in range(100): # defensive bound; chains this deep are pathological with self._read_ctx() as conn: - cursor = conn.execute( + row = conn.execute( f""" SELECT child.id FROM sessions parent @@ -961,8 +728,7 @@ class SessionCompressionMixin: LIMIT 1 """, (current,), - ) - row = cursor.fetchone() + ).fetchone() if row is None: return chain child_id = row["id"] @@ -974,8 +740,8 @@ class SessionCompressionMixin: return chain def get_compression_tip(self, session_id: str) -> Optional[str]: - """Live tip of a compression chain (walk semantics: ``get_compression_chain``); - the input id when no continuation exists.""" + """Live tip of a compression chain (``get_compression_chain`` semantics); the + input id when no continuation exists.""" chain = self.get_compression_chain(session_id) return chain[-1] if chain else session_id @@ -991,7 +757,6 @@ class SessionCompressionMixin: session = self.get_session(session_id) if not session or self._is_explicit_fork_child_row(session): return [session_id] if session else [] - root = session ancestors = {root["id"]} while self._is_compression_child_row(root): @@ -1000,7 +765,6 @@ class SessionCompressionMixin: break root = parent ancestors.add(root["id"]) - lineage = [root["id"]] seen = {root["id"]} current = root @@ -1013,18 +777,11 @@ class SessionCompressionMixin: """, (current["id"],), ) - next_child = None - for row in rows: - candidate = dict(row) - if self._is_compression_child_row(candidate): - next_child = candidate - break + next_child = next((dict(row) for row in rows if self._is_compression_child_row(dict(row))), None) if not next_child or next_child["id"] in seen: break lineage.append(next_child["id"]) seen.add(next_child["id"]) current = next_child - if current["id"] == session_id: - # Later tips are included only when the requested session itself was compacted. - continue + # Later tips are included only when the requested session itself was compacted. return lineage if session_id in lineage else [session_id] diff --git a/hermes_state_dbfile.py b/hermes_state_dbfile.py index ba0af9d837..a6ee6c9c5a 100644 --- a/hermes_state_dbfile.py +++ b/hermes_state_dbfile.py @@ -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//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 ``-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 ``-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//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//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) diff --git a/hermes_state_gateway.py b/hermes_state_gateway.py index f74b7dcce0..a54e305052 100644 --- a/hermes_state_gateway.py +++ b/hermes_state_gateway.py @@ -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( diff --git a/hermes_state_maintenance.py b/hermes_state_maintenance.py index 89829b9191..e6d1d38202 100644 --- a/hermes_state_maintenance.py +++ b/hermes_state_maintenance.py @@ -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 diff --git a/hermes_state_messages.py b/hermes_state_messages.py index 4e5091d46c..2a3f57a1f7 100644 --- a/hermes_state_messages.py +++ b/hermes_state_messages.py @@ -1,10 +1,9 @@ """Transcript persistence for SessionDB. -Mixin split out of ``hermes_state.py``; bound onto ``SessionDB`` via the MRO -and built on its ``_read_ctx`` / ``_execute_write`` / ``_write_sql`` / -``_read_one`` / ``_read_all`` primitives. Covers message append / replace / -rewind, reactions, resume-conversation assembly and replayed-user-message -duplicate detection. +Mixin bound onto ``SessionDB`` via the MRO, built on its ``_read_ctx`` / +``_execute_write`` / ``_write_sql`` / ``_read_one`` / ``_read_all`` primitives. +Covers message append / replace / rewind, reactions, resume-conversation +assembly and replayed-user-message duplicate detection. """ from __future__ import annotations @@ -17,42 +16,96 @@ from typing import Any, Dict, List, Optional, Tuple from agent.context_compressor import _DB_PERSISTED_MARKER as _DB_PERSISTED_MARKER_KEY from agent.memory_manager import sanitize_context from agent.message_sanitization import _sanitize_surrogates -from hermes_state_common import ( - _RESET_END_REASONS, - _RESET_END_REASONS_SQL, - _legacy_reset_child_sql, -) +from hermes_state_common import _RESET_END_REASONS, _RESET_END_REASONS_SQL, _legacy_reset_child_sql # Log-record parity with the origin module (caplog tests pin "hermes_state"). logger = logging.getLogger("hermes_state") +# One INSERT shape for every message writer (append, batch, replace, compact, import). +_INSERT_MESSAGE_SQL = """INSERT INTO messages (session_id, role, content, tool_call_id, + tool_calls, tool_name, effect_disposition, timestamp, token_count, finish_reason, + reasoning, reasoning_content, reasoning_details, codex_reasoning_items, + codex_message_items, platform_message_id, observed, _compressed_summary, active, api_content, display_kind, display_metadata) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""" + +_ENDED_BY_COMPRESSION_SQL = "SELECT ended_at, end_reason FROM sessions WHERE id = ?" +_COMPRESSION_LOCK_ROW_SQL = "SELECT holder, expires_at FROM compression_locks WHERE session_id = ?" +_TURN_LEASE_ROW_SQL = "SELECT holder, expires_at FROM session_turn_leases WHERE conversation_id = ?" +_DISPLAY_ACTIVE_CLAUSE = " AND (active = 1 OR compacted = 1)" +_DELETE_COMPRESSION_LOCK_SQL = "DELETE FROM compression_locks WHERE session_id = ? AND holder = ?" + + +def _placeholders(items) -> str: + return ",".join("?" for _ in items) + + +def _json_or(raw: Any, fallback: Any, warning: str) -> Any: + """``json.loads(raw)``; on failure log *warning* and return *fallback*.""" + try: + return json.loads(raw) + except (json.JSONDecodeError, TypeError): + logger.warning(warning) + return fallback + + +def _tool_calls_len(raw: Any) -> int: + """Tool-call count of a stored ``tool_calls`` column (0 unless a JSON list).""" + if not raw: + return 0 + try: + parsed = json.loads(raw) if isinstance(raw, str) else raw + except (TypeError, ValueError): + return 0 + return len(parsed) if isinstance(parsed, list) else 0 + + +def _coerce_timestamp(value: Any, default: float) -> float: + """Explicit message timestamp (datetime or number) or *default* when invalid.""" + if value is None: + return default + try: + return float(value.timestamp()) if hasattr(value, "timestamp") else float(value) + except (TypeError, ValueError): + logger.debug("Ignoring invalid explicit message timestamp: %r", value) + return default + + +def _parse_tool_calls(tool_calls: Any) -> Any: + """tool_calls may be a list (live agent) or a JSON string (import/export); parse + first so json.dumps never double-encodes.""" + if isinstance(tool_calls, str): + try: + return json.loads(tool_calls) + except (json.JSONDecodeError, TypeError): + return [] + return tool_calls + + +def _tool_calls_count(tool_calls: Any) -> int: + if tool_calls is None: + return 0 + return len(tool_calls) if isinstance(tool_calls, list) else 1 + + +def _ended_by_compression(row) -> bool: + return row is not None and row["ended_at"] is not None and row["end_reason"] == "compression" + class SessionMessagesMixin: """Message append/replace/rewind, reactions, resume conversations, replay dedupe.""" def _bump_conversation_generation(self, conn, session_id: str, end_reason: str) -> None: - """Advance this peer's conversation generation past a boundary. + """Advance this peer's conversation generation past a boundary, inside the + transaction that writes the boundary. - Called inside the transaction that writes the boundary, so the - generation and the ``end_reason`` that caused it commit together. - - Only ``_RESET_END_REASONS`` count: ``compression`` continues one - conversation, and an accidental close is not a replacement. Rows with - no ``session_key`` have no routing peer to advance. - - The counter deliberately does NOT read the session rows. An aggregate - over them (COUNT/MAX of boundaries) can return a pair it already - emitted once ``delete_session()`` or bulk pruning removes an ended row, - which would hand a new conversation a retired affinity identity. This - value only ever increments, so a generation is never reused for a peer - even if every row behind it is gone. + Only ``_RESET_END_REASONS`` count (``compression`` continues one conversation). + The counter never reads the session rows: an aggregate over them could re-emit a + pair once ``delete_session()``/pruning removes an ended row and hand a new + conversation a retired affinity identity. It only ever increments. """ if end_reason not in _RESET_END_REASONS: return - row = conn.execute( - "SELECT source, session_key FROM sessions WHERE id = ?", - (session_id,), - ).fetchone() + row = conn.execute("SELECT source, session_key FROM sessions WHERE id = ?", (session_id,)).fetchone() if row is None: return source = str(row["source"] or "").strip() @@ -71,62 +124,40 @@ class SessionMessagesMixin: @classmethod def _encode_content(cls, content: Any) -> Any: - """Serialize structured (list/dict) message content for sqlite. - - sqlite3 can only bind ``str``, ``bytes``, ``int``, ``float``, and ``None`` - to query parameters. Multimodal messages have ``content`` as a list of - parts (``[{"type": "text", ...}, {"type": "image_url", ...}]``), which - raises ``ProgrammingError: Error binding parameter N: type 'list' is - not supported`` when bound directly. - - Returns the value unchanged when it's already a safe scalar, or a - sentinel-prefixed JSON string for lists/dicts. Paired with - :meth:`_decode_content` on read. + """Serialize list/dict content (multimodal parts) as a sentinel-prefixed JSON + string; sqlite3 can only bind str/bytes/int/float/None. Lone surrogates are + scrubbed from text so persistence never fails. Paired with :meth:`_decode_content`. """ if isinstance(content, str): - # Lone UTF-16 surrogates reach here inside tool results scraped - # from the web/social platforms (the same input that crashed the - # guardrail hasher). The proactive sanitizer upstream only cleans - # the *api_messages* copy, and the recovery sanitizer only runs - # after the API call itself raises — which it no longer does — so - # the canonical history keeps them and this write is where they - # land. Left raw, sqlite3 raises UnicodeEncodeError, the flush is - # abandoned, and the session silently stops persisting for the - # rest of its life. Scrub so persistence never fails. + # Lone UTF-16 surrogates arrive in tool results scraped from the web. The + # upstream sanitizer only cleans the api_messages copy and the recovery + # sanitizer only runs after the API call raises (it no longer does), so the + # canonical history keeps them and this write is where they land. Left raw, + # sqlite3 raises UnicodeEncodeError, the flush is abandoned, and the session + # silently stops persisting for the rest of its life. return _sanitize_surrogates(content) if content is None or isinstance(content, (bytes, int, float)): return content try: - # json.dumps defaults to ensure_ascii=True, which escapes any - # surrogate as \udXXX — already safe to bind. + # ensure_ascii=True escapes surrogates as \\udXXX — safe to bind. return cls._CONTENT_JSON_PREFIX + json.dumps(content) except (TypeError, ValueError): - # Last-resort fallback: stringify so persistence never fails. return _sanitize_surrogates(str(content)) @classmethod def _decode_content(cls, content: Any) -> Any: """Reverse :meth:`_encode_content`; returns scalars unchanged.""" if isinstance(content, str) and content.startswith(cls._CONTENT_JSON_PREFIX): - try: - return json.loads(content[len(cls._CONTENT_JSON_PREFIX):]) - except (json.JSONDecodeError, TypeError): - logger.warning( - "Failed to decode JSON-encoded message content; " - "returning raw string" - ) - return content + return _json_or( + content[len(cls._CONTENT_JSON_PREFIX):], content, + "Failed to decode JSON-encoded message content; returning raw string", + ) return content @staticmethod def _encode_display_metadata(display_metadata: Any) -> Optional[str]: - """Serialize ``display_metadata`` for its TEXT column without double-encoding. - - Import/replace paths can hand us an already-serialized JSON string (the - same hazard ``tool_calls`` guards against above). ``json.dumps`` on that - string would store a quoted JSON string, and the single ``json.loads`` - on read then yields a ``str`` instead of a dict. - """ + """Serialize ``display_metadata`` for its TEXT column without double-encoding an + already-serialized JSON string (import/replace paths hand those in).""" if not display_metadata: return None if isinstance(display_metadata, str): @@ -142,134 +173,15 @@ class SessionMessagesMixin: if isinstance(display_metadata, dict): return json.dumps(display_metadata) logger.warning( - "Ignoring unexpected display metadata type on write: %s", - type(display_metadata).__name__, + "Ignoring unexpected display metadata type on write: %s", type(display_metadata).__name__, ) return None - def _check_transcript_write_guards( - self, - conn, - session_id: str, - compression_lock_holder: Optional[str], - turn_lease_holder: Optional[str] = None, - turn_lease_ttl_seconds: float = 300.0, - reject_active_turn_lease: bool = False, - reject_active_compression_lock: bool = False, - allow_closed_compression_parent: bool = False, - ) -> None: - """Transcript-write admission checks, run INSIDE the write txn. - - Shared by :meth:`append_message` and :meth:`append_messages_batch` so - the two writers can never diverge on these correctness invariants - (this guard has already needed targeted fixes — see the #74478 patience - note below). User-initiated transcript mutations may opt in to rejecting - an active unowned turn lease in that same transaction. - """ - from hermes_state import CompressionSessionClosedError, SessionCompressionInProgressError, SessionTurnLeaseLostError, _compression_lock_holder_process_is_dead - # NOTE (#75316 redesign): appends do NOT check compression_locks. - # The lock's job is to stop two COMPRESSIONS colliding, not to fence - # ordinary transcript writes. Concurrent appends during a compression - # are safe by construction: archive_and_compact() commits against a - # watermark captured at compression start and clones every row that - # arrived after it back into the live transcript, in the same write - # transaction. Blocking appends here was the root cause of a whole - # symptom family — turns dying as session_persistence_failed while a - # slow provider summary held the lease (#74568, #77386), including - # stale locks from dead PIDs blocking writes for the full TTL. - # Destructive user mutations are different: a compressor that already - # captured its watermark can otherwise publish the pre-rewind snapshot - # after the mutation and resurrect the removed turn. Keep that narrow - # fence opt-in so ordinary appends retain the watermark behavior. - if reject_active_compression_lock: - active_lock = conn.execute( - "SELECT holder, expires_at FROM compression_locks " - "WHERE session_id = ?", - (session_id,), - ).fetchone() - if active_lock is not None: - current_holder = active_lock["holder"] - if ( - float(active_lock["expires_at"]) <= time.time() - or _compression_lock_holder_process_is_dead(current_holder) - ): - conn.execute( - "DELETE FROM compression_locks " - "WHERE session_id = ? AND holder = ?", - (session_id, current_holder), - ) - elif current_holder != compression_lock_holder: - raise SessionCompressionInProgressError( - f"Session {session_id!r} is being compressed by another writer" - ) - if turn_lease_holder or reject_active_turn_lease: - conversation_id = self._session_turn_lease_key_on_conn(conn, session_id) - lease = conn.execute( - "SELECT holder, expires_at FROM session_turn_leases " - "WHERE conversation_id = ?", - (conversation_id,), - ).fetchone() - now = time.time() - if turn_lease_holder: - if lease is None or lease["holder"] != turn_lease_holder: - raise SessionTurnLeaseLostError( - f"Session turn lease lost; refusing transcript write " - f"for {session_id!r}" - ) - if float(lease["expires_at"]) <= now: - # Expiry makes the row reclaimable; it does not prove that a - # takeover occurred. BEGIN IMMEDIATE serializes this renewal - # with acquisition, so a still-matching owner can recover from - # a starved refresher without weakening the foreign-holder fence. - conn.execute( - "UPDATE session_turn_leases SET expires_at = ? " - "WHERE conversation_id = ? AND holder = ?", - ( - now + max(0.1, float(turn_lease_ttl_seconds)), - conversation_id, - turn_lease_holder, - ), - ) - elif lease is not None: - current_holder = lease["holder"] - if ( - float(lease["expires_at"]) <= now - or _compression_lock_holder_process_is_dead(current_holder) - ): - # Match acquisition semantics: an expired or provably dead - # owner is reclaimable. Deleting it inside this BEGIN IMMEDIATE - # transaction also fences a stale late flush after the mutation. - conn.execute( - "DELETE FROM session_turn_leases " - "WHERE conversation_id = ? AND holder = ?", - (conversation_id, current_holder), - ) - else: - raise SessionTurnLeaseLostError( - f"Session has an active turn lease; refusing transcript " - f"mutation for {session_id!r}" - ) - session = conn.execute( - "SELECT ended_at, end_reason FROM sessions WHERE id = ?", - (session_id,), - ).fetchone() - if ( - session is not None - and session["ended_at"] is not None - and session["end_reason"] == "compression" - and not allow_closed_compression_parent - ): - raise CompressionSessionClosedError(session_id) - @staticmethod def _decode_display_metadata(raw: Any) -> Optional[Dict[str, Any]]: - """Decode a ``display_metadata`` column into the dict every reader expects. - - Every message read path must go through this. Returning the raw TEXT - instead reaches the desktop as a string, where ``'task_count' in meta`` - throws and fails the whole resume. Rows written before the encode guard - landed are double-encoded, so unwrap a second layer when we find one. - """ + """Decode a ``display_metadata`` column into a dict (never the raw TEXT — the + desktop does ``'task_count' in meta``). Pre-guard rows are double-encoded, so a + second string layer is unwrapped.""" if raw is None: return None try: @@ -286,151 +198,171 @@ class SessionMessagesMixin: @staticmethod def _reasoning_json_text(value: Any) -> Optional[str]: - """Serialize a structured reasoning field for its TEXT column. - - ``reasoning_details`` / ``codex_reasoning_items`` / ``codex_message_items`` - arrive as list/dict structures from the live runtime, but callers that - round-trip stored rows — ``get_messages`` straight into - ``replace_messages``, e.g. the POST /api/sessions/{id}/fork handler — - hand back the raw TEXT these columns already hold, because - ``get_messages`` only deserializes ``content`` and ``tool_calls``. - Re-dumping that TEXT double-encodes it, and the forked session's next - ``get_messages_as_conversation`` json.loads then yields the inner - string instead of the original list, so every reasoning-replay consumer - (all of which check ``isinstance(..., list)``) silently drops it. - Strings are therefore stored as-is; structures are dumped. - """ + """Serialize a structured reasoning field for its TEXT column. Strings are + stored as-is: round-tripping callers (get_messages -> replace_messages, e.g. the + fork handler) hand back the raw TEXT, and re-dumping would double-encode it so + every reasoning-replay consumer (``isinstance(..., list)``) drops it.""" if not value: return None - if isinstance(value, str): - return value - return json.dumps(value) + return value if isinstance(value, str) else json.dumps(value) - def append_message( - self, - session_id: str, - role: str, - content: str = None, - tool_name: str = None, - tool_calls: Any = None, - tool_call_id: str = None, - token_count: int = None, - finish_reason: str = None, - reasoning: str = None, - reasoning_content: str = None, - reasoning_details: Any = None, - codex_reasoning_items: Any = None, - codex_message_items: Any = None, - platform_message_id: str = None, - observed: bool = False, - effect_disposition: Optional[str] = None, - _compressed_summary: bool = False, - timestamp: Any = None, - api_content: Optional[str] = None, - display_kind: Optional[str] = None, - display_metadata: Optional[Dict[str, Any]] = None, - compression_lock_holder: Optional[str] = None, - turn_lease_holder: Optional[str] = None, - turn_lease_ttl_seconds: float = 300.0, - ) -> int: + def _check_transcript_write_guards( + self, conn, session_id: str, compression_lock_holder: Optional[str], + turn_lease_holder: Optional[str] = None, turn_lease_ttl_seconds: float = 300.0, + reject_active_turn_lease: bool = False, reject_active_compression_lock: bool = False, + allow_closed_compression_parent: bool = False, + ) -> None: + """Transcript-write admission checks, run INSIDE the write txn. + + Shared by every transcript writer so they cannot diverge. Ordinary appends do + NOT check compression_locks: the lock only stops two COMPRESSIONS colliding, and + archive_and_compact() commits against a watermark and clones later rows, so + concurrent appends are safe by construction (blocking them killed turns while a + slow summary held the lease). Destructive user mutations opt in via + ``reject_active_compression_lock`` / ``reject_active_turn_lease`` so a compressor + that captured its watermark cannot resurrect the removed turn. """ - Append a message to a session. Returns the message row ID. + from hermes_state import CompressionSessionClosedError, SessionCompressionInProgressError, SessionTurnLeaseLostError, _compression_lock_holder_process_is_dead + if reject_active_compression_lock: + active_lock = conn.execute(_COMPRESSION_LOCK_ROW_SQL, (session_id,)).fetchone() + if active_lock is not None: + current_holder = active_lock["holder"] + if ( + float(active_lock["expires_at"]) <= time.time() + or _compression_lock_holder_process_is_dead(current_holder) + ): + conn.execute(_DELETE_COMPRESSION_LOCK_SQL, (session_id, current_holder)) + elif current_holder != compression_lock_holder: + raise SessionCompressionInProgressError( + f"Session {session_id!r} is being compressed by another writer" + ) + if turn_lease_holder or reject_active_turn_lease: + conversation_id = self._session_turn_lease_key_on_conn(conn, session_id) + lease = conn.execute(_TURN_LEASE_ROW_SQL, (conversation_id,)).fetchone() + now = time.time() + if turn_lease_holder: + if lease is None or lease["holder"] != turn_lease_holder: + raise SessionTurnLeaseLostError( + f"Session turn lease lost; refusing transcript write for {session_id!r}" + ) + if float(lease["expires_at"]) <= now: + # Expiry makes the row reclaimable, it does not prove a takeover; + # BEGIN IMMEDIATE serializes this renewal with acquisition, so a + # still-matching owner recovers from a starved refresher. + conn.execute( + "UPDATE session_turn_leases SET expires_at = ? " + "WHERE conversation_id = ? AND holder = ?", + (now + max(0.1, float(turn_lease_ttl_seconds)), conversation_id, turn_lease_holder), + ) + elif lease is not None: + current_holder = lease["holder"] + if ( + float(lease["expires_at"]) <= now + or _compression_lock_holder_process_is_dead(current_holder) + ): + # Same reclaim rule as acquisition (expired or provably dead owner); + # deleting here also fences a stale late flush after the mutation. + conn.execute( + "DELETE FROM session_turn_leases WHERE conversation_id = ? AND holder = ?", + (conversation_id, current_holder), + ) + else: + raise SessionTurnLeaseLostError( + f"Session has an active turn lease; refusing transcript mutation for {session_id!r}" + ) + session = conn.execute(_ENDED_BY_COMPRESSION_SQL, (session_id,)).fetchone() + if _ended_by_compression(session) and not allow_closed_compression_parent: + raise CompressionSessionClosedError(session_id) - Also increments the session's message_count (and tool_call_count - if role is 'tool' or tool_calls is present). + def _message_row_params( + self, session_id: str, role: str, msg: Dict[str, Any], tool_calls: Any, + message_timestamp: float, *, keep_reasoning: bool, + ) -> tuple: + """Bind values for ``_INSERT_MESSAGE_SQL`` from one message dict. - ``platform_message_id`` is the external messaging platform's own - message ID (e.g. Telegram update_id, Yuanbao msg_id). It is - independent of the SQLite autoincrement primary key and is used by - platform-specific flows like yuanbao's recall guard to redact a - message by its platform-side identifier. - - ``api_content`` is the exact content string sent to the API for this - message when it differs from ``content`` (ephemeral memory/plugin - injections, persist overrides). It is a byte-fidelity sidecar for - prompt-cache-stable replay — stored as sent, except lone surrogates - (which sqlite3 cannot bind and which the conversation loop scrubs - from every outgoing payload anyway, so the scrubbed form IS the - wire bytes). + *tool_calls* is the already-parsed value (see ``_parse_tool_calls``). + *keep_reasoning* False stores NULL for every reasoning/codex column. """ from hermes_state import _scrub_surrogates - # Display metadata is presentation-only and never changes the model - # context role/content replayed to providers. + + def _str_or_none(value): + return _scrub_surrogates(value) if isinstance(value, str) else None + + def _reasoning(key): + return msg.get(key) if keep_reasoning else None + + return ( + session_id, + role, + self._encode_content(msg.get("content")), + msg.get("tool_call_id"), + json.dumps(tool_calls) if tool_calls else None, + _scrub_surrogates(msg.get("tool_name")), + msg.get("effect_disposition"), + message_timestamp, + msg.get("token_count"), + msg.get("finish_reason"), + _scrub_surrogates(_reasoning("reasoning")), + _scrub_surrogates(_reasoning("reasoning_content")), + self._reasoning_json_text(_reasoning("reasoning_details")), + self._reasoning_json_text(_reasoning("codex_reasoning_items")), + self._reasoning_json_text(_reasoning("codex_message_items")), + # `message_id` is yuanbao's existing convention on message dicts. + msg.get("platform_message_id") or msg.get("message_id"), + 1 if msg.get("observed") else 0, + 1 if msg.get("_compressed_summary") else 0, + 1, + _str_or_none(msg.get("api_content")), + _str_or_none(msg.get("display_kind")), + self._encode_display_metadata(msg.get("display_metadata")), + ) + + def append_message( + self, session_id: str, role: str, content: str = None, tool_name: str = None, + tool_calls: Any = None, tool_call_id: str = None, token_count: int = None, + finish_reason: str = None, reasoning: str = None, reasoning_content: str = None, + reasoning_details: Any = None, codex_reasoning_items: Any = None, + codex_message_items: Any = None, platform_message_id: str = None, observed: bool = False, + effect_disposition: Optional[str] = None, _compressed_summary: bool = False, + timestamp: Any = None, api_content: Optional[str] = None, + display_kind: Optional[str] = None, display_metadata: Optional[Dict[str, Any]] = None, + compression_lock_holder: Optional[str] = None, turn_lease_holder: Optional[str] = None, + turn_lease_ttl_seconds: float = 300.0, + ) -> int: + """Append one message; returns the row id. Bumps ``message_count`` (and + ``tool_call_count`` when tool_calls are present). + + ``platform_message_id`` is the platform's own id (Telegram update_id, Yuanbao + msg_id) used by recall-style flows. ``api_content`` is the byte-fidelity + sidecar — the exact string sent to the API when it differed from ``content`` — + stored as sent except lone surrogates (which the loop scrubs anyway). + """ + msg = { + "content": content, "tool_name": tool_name, "tool_call_id": tool_call_id, + "token_count": token_count, "finish_reason": finish_reason, "reasoning": reasoning, + "reasoning_content": reasoning_content, "reasoning_details": reasoning_details, + "codex_reasoning_items": codex_reasoning_items, "codex_message_items": codex_message_items, + "platform_message_id": platform_message_id, "message_id": platform_message_id, + "observed": observed, "effect_disposition": effect_disposition, + "_compressed_summary": _compressed_summary, "api_content": api_content, + "display_kind": display_kind, "display_metadata": display_metadata, + } + # Encode outside the write txn (display metadata first: log-order parity). display_metadata_json = self._encode_display_metadata(display_metadata) - # Serialize structured fields to JSON before entering the write txn - reasoning_details_json = self._reasoning_json_text(reasoning_details) - codex_items_json = self._reasoning_json_text(codex_reasoning_items) - codex_message_items_json = self._reasoning_json_text(codex_message_items) - # tool_calls may arrive as a Python list (from the live agent) or - # as a JSON string (from import/export). Parse first to avoid - # double-encoding. - if isinstance(tool_calls, str): - try: - tool_calls = json.loads(tool_calls) - except (json.JSONDecodeError, TypeError): - tool_calls = [] - tool_calls_json = json.dumps(tool_calls) if tool_calls else None - # Multimodal content (list of parts) must be JSON-encoded: sqlite3 - # cannot bind list/dict parameters directly. - stored_content = self._encode_content(content) - - message_timestamp = time.time() - if timestamp is not None: - try: - if hasattr(timestamp, "timestamp"): - message_timestamp = float(timestamp.timestamp()) - else: - message_timestamp = float(timestamp) - except (TypeError, ValueError): - logger.debug("Ignoring invalid explicit message timestamp: %r", timestamp) - - # Pre-compute tool call count - num_tool_calls = 0 - if tool_calls is not None: - num_tool_calls = len(tool_calls) if isinstance(tool_calls, list) else 1 + msg["display_metadata"] = display_metadata_json + tool_calls = _parse_tool_calls(tool_calls) + message_timestamp = _coerce_timestamp(timestamp, time.time()) + num_tool_calls = _tool_calls_count(tool_calls) + params = self._message_row_params( + session_id, role, msg, tool_calls, message_timestamp, keep_reasoning=True, + ) def _do(conn): self._check_transcript_write_guards( - conn, - session_id, - compression_lock_holder, - turn_lease_holder=turn_lease_holder, - turn_lease_ttl_seconds=turn_lease_ttl_seconds, + conn, session_id, compression_lock_holder, + turn_lease_holder=turn_lease_holder, turn_lease_ttl_seconds=turn_lease_ttl_seconds, ) - cursor = conn.execute( - """INSERT INTO messages (session_id, role, content, tool_call_id, - tool_calls, tool_name, effect_disposition, timestamp, token_count, finish_reason, - reasoning, reasoning_content, reasoning_details, codex_reasoning_items, - codex_message_items, platform_message_id, observed, _compressed_summary, active, api_content, display_kind, display_metadata) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", - ( - session_id, - role, - stored_content, - tool_call_id, - tool_calls_json, - _scrub_surrogates(tool_name), - effect_disposition, - message_timestamp, - token_count, - finish_reason, - _scrub_surrogates(reasoning), - _scrub_surrogates(reasoning_content), - reasoning_details_json, - codex_items_json, - codex_message_items_json, - platform_message_id, - 1 if observed else 0, - 1 if _compressed_summary else 0, - 1, - _scrub_surrogates(api_content) if isinstance(api_content, str) else None, - _scrub_surrogates(display_kind) if isinstance(display_kind, str) else None, - display_metadata_json, - ), - ) - msg_id = cursor.lastrowid - - # Update counters + msg_id = conn.execute(_INSERT_MESSAGE_SQL, params).lastrowid if num_tool_calls > 0: conn.execute( """UPDATE sessions SET message_count = message_count + 1, @@ -439,96 +371,53 @@ class SessionMessagesMixin: ) else: conn.execute( - "UPDATE sessions SET message_count = message_count + 1 WHERE id = ?", - (session_id,), + "UPDATE sessions SET message_count = message_count + 1 WHERE id = ?", (session_id,), ) return msg_id - # Transcript append is THE critical write: its failure aborts the - # user's turn (session_persistence_failed). Use the long patience so - # a sibling process legitimately holding the write lock for seconds - # (VACUUM, TRUNCATE checkpoint at close, an older pre-bounded-merge - # process's FTS optimize) can't destroy a healthy turn (#74478). - return self._execute_write( - _do, patience_s=self._TRANSCRIPT_WRITE_PATIENCE_S - ) + # THE critical write (its failure aborts the turn): long patience so a sibling + # legitimately holding the lock for seconds (VACUUM, checkpoint) can't kill it. + return self._execute_write(_do, patience_s=self._TRANSCRIPT_WRITE_PATIENCE_S) def append_messages_batch( - self, - session_id: str, - messages: List[Dict[str, Any]], - compression_lock_holder: Optional[str] = None, - turn_lease_holder: Optional[str] = None, - chunk_rows: Optional[int] = None, - turn_lease_ttl_seconds: float = 300.0, + self, session_id: str, messages: List[Dict[str, Any]], + compression_lock_holder: Optional[str] = None, turn_lease_holder: Optional[str] = None, + chunk_rows: Optional[int] = None, turn_lease_ttl_seconds: float = 300.0, ) -> int: - """Append multiple messages atomically in ONE write transaction. + """Append *messages* (``_insert_message_rows`` dict shape) in ONE write txn. - ``messages`` is a list of dicts in the same shape - :meth:`_insert_message_rows` already consumes for replace/compact/ - import (role, content, tool_name, tool_calls, tool_call_id, - finish_reason, reasoning*, codex_*, timestamp, api_content, - display_kind, display_metadata, ...). Reusing that helper keeps ONE - row-serialization path for every multi-row writer. - - A turn-boundary flush writes the whole turn (user + assistant + tool - rows, typically 3-8 messages) as one BEGIN IMMEDIATE / commit pair - instead of one transaction (and, off WAL, one fsync) per row. - - Atomicity contract: all rows land or none do (the caller re-flushes - unstamped messages on the next attempt). The same admission guards - as :meth:`append_message` run once for the batch — same session, - same instant. - - ``chunk_rows`` bounds the transaction size for LARGE copies (branch - seeds can be thousands of rows; measured: 10k rows ≈ 2.4s inside one - BEGIN IMMEDIATE because the FTS triggers run per row, which would - monopolize the write lock and starve concurrent writers). When set, - the batch commits in chunks of at most that many rows — same - recovery semantics as the old per-row loops (a mid-copy failure - leaves a partial seed), just with bounded lock holds. A turn flush - never needs it. Returns the inserted row count. + All rows land or none do; the admission guards run once for the batch. + ``chunk_rows`` bounds transaction size for LARGE copies (branch seeds: FTS + triggers run per row, 10k rows ≈ 2.4s under one lock) — commits in chunks with + the old per-row-loop recovery semantics. Returns the inserted row count. """ if not messages: return 0 - if chunk_rows is not None and len(messages) > chunk_rows: - inserted_total = 0 - for start in range(0, len(messages), chunk_rows): - inserted_total += self.append_messages_batch( - session_id, - messages[start:start + chunk_rows], + return sum( + self.append_messages_batch( + session_id, messages[start:start + chunk_rows], compression_lock_holder=compression_lock_holder, turn_lease_holder=turn_lease_holder, turn_lease_ttl_seconds=turn_lease_ttl_seconds, ) - return inserted_total + for start in range(0, len(messages), chunk_rows) + ) def _do(conn): self._check_transcript_write_guards( - conn, - session_id, - compression_lock_holder, - turn_lease_holder=turn_lease_holder, - turn_lease_ttl_seconds=turn_lease_ttl_seconds, + conn, session_id, compression_lock_holder, + turn_lease_holder=turn_lease_holder, turn_lease_ttl_seconds=turn_lease_ttl_seconds, ) from agent.transcript_repair import resolve_and_repair_transcript_batch inserted_rows = resolve_and_repair_transcript_batch( - conn, - session_id, - messages, - encode_content_fn=self._encode_content, - decode_content_fn=self._decode_content, + conn, session_id, messages, + encode_content_fn=self._encode_content, decode_content_fn=self._decode_content, ) - inserted = 0 - tool_calls_total = 0 + inserted = tool_calls_total = 0 if inserted_rows: - inserted, tool_calls_total = self._insert_message_rows( - conn, session_id, inserted_rows - ) - - # One aggregated counter update for the newly inserted rows. + inserted, tool_calls_total = self._insert_message_rows(conn, session_id, inserted_rows) if tool_calls_total > 0: conn.execute( """UPDATE sessions SET message_count = message_count + ?, @@ -542,22 +431,17 @@ class SessionMessagesMixin: ) return inserted - # Same criticality as append_message: this IS the turn's transcript. - return self._execute_write( - _do, patience_s=self._TRANSCRIPT_WRITE_PATIENCE_S - ) + return self._execute_write(_do, patience_s=self._TRANSCRIPT_WRITE_PATIENCE_S) def set_latest_matching_message_display_kind( self, session_id: str, *, role: str, content: str, display_kind: str, display_metadata: Optional[Dict[str, Any]] = None, ) -> bool: - """Stamp presentation metadata on this turn's freshly persisted row. - - The model still receives ``role`` and ``content`` unchanged. Gateway and - CLI synthetic inputs call this immediately after their serial turn has - flushed, preserving producer provenance without classifying by content - during transcript rendering. - """ + """Stamp presentation metadata on this turn's freshly persisted row; the model + still receives ``role``/``content`` unchanged. Gateway/CLI synthetic inputs call + this immediately after their serial turn has flushed (the target is resolved as + newest-active-row-by-content), preserving producer provenance without + classifying by content at render time.""" from hermes_state import _scrub_surrogates if not session_id or not content or not display_kind: return False @@ -572,30 +456,25 @@ class SessionMessagesMixin: return False conn.execute( "UPDATE messages SET display_kind = ?, display_metadata = ? WHERE id = ?", - ( - _scrub_surrogates(display_kind), - self._encode_display_metadata(display_metadata), - row[0], - ), + (_scrub_surrogates(display_kind), self._encode_display_metadata(display_metadata), row[0]), ) return True return bool(self._execute_write(_do)) + def _reaction_list(self, meta: Optional[Dict[str, Any]]) -> List[Dict[str, Any]]: + """Well-formed (dict) reactions stored under ``REACTIONS_METADATA_KEY``.""" + reactions = (meta or {}).get(self.REACTIONS_METADATA_KEY) + return [r for r in reactions if isinstance(r, dict)] if isinstance(reactions, list) else [] + def set_message_reaction( - self, - session_id: str, - message_row_id: int, - emoji: Optional[str], - *, - author: str = "user", + self, session_id: str, message_row_id: int, emoji: Optional[str], *, author: str = "user", ) -> Optional[List[Dict[str, Any]]]: """Set (or with ``emoji=None`` clear) *author*'s reaction on one message. - iOS Tapback semantics: one reaction per author per message. Re-sending - the same emoji clears it, a different emoji replaces it. Returns the - message's full reaction list after the write, or ``None`` when the row - doesn't exist or isn't part of *session_id*. + Tapback semantics: one reaction per author per message; the same emoji again + clears it, a different one replaces it. Returns the message's reaction list + after the write, or ``None`` when the row isn't part of *session_id*. """ from hermes_state import _scrub_surrogates if not session_id or message_row_id is None: @@ -608,36 +487,17 @@ class SessionMessagesMixin: ).fetchone() if row is None: return None - meta = self._decode_display_metadata(row[0]) or {} - existing = meta.get(self.REACTIONS_METADATA_KEY) - reactions = [ - r - for r in (existing if isinstance(existing, list) else []) - if isinstance(r, dict) and r.get("author") != author - ] - previous = next( - ( - r - for r in (existing if isinstance(existing, list) else []) - if isinstance(r, dict) and r.get("author") == author - ), - None, - ) - # Tapping the live reaction again retracts it. - toggling_off = ( - emoji is not None and previous is not None and previous.get("emoji") == emoji - ) + existing = self._reaction_list(meta) + reactions = [r for r in existing if r.get("author") != author] + previous = next((r for r in existing if r.get("author") == author), None) + toggling_off = emoji is not None and previous is not None and previous.get("emoji") == emoji if emoji and not toggling_off: - reactions.append( - {"emoji": _scrub_surrogates(emoji), "author": author, "at": time.time()} - ) - + reactions.append({"emoji": _scrub_surrogates(emoji), "author": author, "at": time.time()}) if reactions: meta[self.REACTIONS_METADATA_KEY] = reactions else: meta.pop(self.REACTIONS_METADATA_KEY, None) - conn.execute( "UPDATE messages SET display_metadata = ? WHERE id = ?", (self._encode_display_metadata(meta) if meta else None, message_row_id), @@ -646,34 +506,21 @@ class SessionMessagesMixin: return self._execute_write(_do) - def get_message_reactions( - self, session_id: str, message_row_id: int - ) -> List[Dict[str, Any]]: - """Return the reaction list persisted on one message row (never ``None``).""" + def get_message_reactions(self, session_id: str, message_row_id: int) -> List[Dict[str, Any]]: + """Reaction list persisted on one message row (never ``None``).""" if not session_id or message_row_id is None: return [] - row = self._read_one( "SELECT display_metadata FROM messages WHERE id = ? AND session_id = ?", (message_row_id, session_id), ) + return self._reaction_list(self._decode_display_metadata(row[0])) if row is not None else [] - if row is None: - return [] - - meta = self._decode_display_metadata(row[0]) or {} - reactions = meta.get(self.REACTIONS_METADATA_KEY) - - return [r for r in reactions if isinstance(r, dict)] if isinstance(reactions, list) else [] - - def take_unseen_reactions( - self, session_id: str, *, author: str = "user" - ) -> List[Dict[str, Any]]: + def take_unseen_reactions(self, session_id: str, *, author: str = "user") -> List[Dict[str, Any]]: """Return *author*'s not-yet-surfaced reactions and mark them seen. - Powers the cache-safe model-context path: reactions are announced on the - NEXT user turn (never by rewriting the message that was reacted to), and - the ``seen`` stamp guarantees each one is announced exactly once. + Reactions are announced on the NEXT user turn (never by rewriting the reacted + message — cache-safe); the ``seen`` stamp makes each announcement exactly once. """ if not session_id: return [] @@ -685,7 +532,6 @@ class SessionMessagesMixin: "ORDER BY id", (session_id,), ).fetchall() - pending = [] for row in rows: meta = self._decode_display_metadata(row["display_metadata"]) @@ -694,33 +540,24 @@ class SessionMessagesMixin: reactions = meta.get(self.REACTIONS_METADATA_KEY) if not isinstance(reactions, list): continue - changed = False for reaction in reactions: - if ( - not isinstance(reaction, dict) - or reaction.get("author") != author - or reaction.get("seen") - ): + if not isinstance(reaction, dict) or reaction.get("author") != author or reaction.get("seen"): continue reaction["seen"] = True changed = True content = self._decode_content(row["content"]) - pending.append( - { - "row_id": row["id"], - "role": row["role"], - "emoji": reaction.get("emoji") or "", - "text": content if isinstance(content, str) else "", - } - ) - + pending.append({ + "row_id": row["id"], + "role": row["role"], + "emoji": reaction.get("emoji") or "", + "text": content if isinstance(content, str) else "", + }) if changed: conn.execute( "UPDATE messages SET display_metadata = ? WHERE id = ?", (self._encode_display_metadata(meta), row["id"]), ) - return pending return self._execute_write(_do) or [] @@ -730,248 +567,99 @@ class SessionMessagesMixin: ) -> Optional[int]: """Row id of the most recent active message with *role*, or ``None``. - Two callers, same need — "the message I mean, without an id": the agent - defaulting to the turn that triggered it, and the desktop reacting to a - live message that hasn't round-tripped through a resume yet. - ``offset`` steps to earlier turns (1 = the one before the latest) so a - reaction can land retroactively — "two messages ago" is how the caller - thinks about it. - - ``require_text`` (default) skips rows with no plain-text content — - tool-call-only assistant turns and attachment stubs don't render as - bubbles, so "the latest message" as a HUMAN means it must never - resolve to one (a reaction landing on an invisible row looks dropped, - and its annotation quotes an empty string). + ``offset`` steps to earlier turns (1 = the one before the latest). ``require_text`` + skips rows without plain-text content (tool-call-only turns, attachment stubs) + so "the latest message" never resolves to an invisible bubble. """ if not session_id or role not in {"user", "assistant"} or offset < 0: return None - - text_filter = ( - "AND content IS NOT NULL AND TRIM(content) != '' " if require_text else "" - ) - + text_filter = "AND content IS NOT NULL AND TRIM(content) != '' " if require_text else "" row = self._read_one( "SELECT id FROM messages WHERE session_id = ? AND role = ? " f"AND active = 1 {text_filter}ORDER BY id DESC LIMIT 1 OFFSET ?", (session_id, role, int(offset)), ) - return row[0] if row else None def latest_user_message_row_id(self, session_id: str) -> Optional[int]: - """Row id of the most recent active user message, or ``None``. - - The agent's default reaction target: "the message that triggered me", - so the model never has to thread row ids through a tool call (mirrors - the photon adapter's ``_record_last_inbound``). - """ + """Row id of the most recent active user message ("the message that triggered + me"), or ``None``.""" return self.latest_message_row_id(session_id, role="user") def get_message_role(self, session_id: str, row_id: int) -> Optional[str]: - """Role of the active message at *row_id* in *session_id*, or ``None``. - - Lets a reaction event carry the target's role so a renderer can match - a live message that doesn't know its durable row id yet. - """ + """Role of the active message at *row_id* in *session_id*, or ``None``.""" if not session_id: return None - row = self._read_one( "SELECT role FROM messages WHERE id = ? AND session_id = ? AND active = 1", (int(row_id), session_id), ) - return row[0] if row else None def _insert_message_rows(self, conn, session_id: str, messages: List[Dict[str, Any]]) -> tuple[int, int]: - """Insert *messages* as fresh active rows for *session_id*. + """Insert *messages* as fresh active rows inside the caller's write txn. - Shared by :meth:`replace_messages` (delete-then-insert) and - :meth:`archive_and_compact` (soft-archive-then-insert). Runs inside the - caller's write transaction (takes the live ``conn``). Returns - ``(inserted_count, tool_call_count)``. Does NOT touch sessions.* counters - — the caller owns that, since the two flows reconcile counts differently. + Returns ``(inserted_count, tool_call_count)``; does NOT touch sessions.* + counters (callers reconcile them differently). Reasoning columns are kept for + assistant rows only. Stamps ``msg["_row_id"]``. """ - from hermes_state import _scrub_surrogates now_ts = time.time() - inserted = 0 - tool_calls_total = 0 + inserted = tool_calls_total = 0 for msg in messages: role = msg.get("role", "unknown") - tool_calls = msg.get("tool_calls") - message_timestamp = now_ts - if msg.get("timestamp") is not None: - try: - ts_value = msg.get("timestamp") - if hasattr(ts_value, "timestamp"): - message_timestamp = float(ts_value.timestamp()) - else: - message_timestamp = float(ts_value) - except (TypeError, ValueError): - logger.debug("Ignoring invalid explicit message timestamp: %r", msg.get("timestamp")) - reasoning_details = msg.get("reasoning_details") if role == "assistant" else None - codex_reasoning_items = ( - msg.get("codex_reasoning_items") if role == "assistant" else None - ) - codex_message_items = ( - msg.get("codex_message_items") if role == "assistant" else None - ) - reasoning_details_json = self._reasoning_json_text(reasoning_details) - codex_items_json = self._reasoning_json_text(codex_reasoning_items) - codex_message_items_json = self._reasoning_json_text(codex_message_items) - # tool_calls may arrive as a Python list (from the live agent) - # or as a JSON string (from import_sessions / export_session, - # which store it as TEXT). json.dumps on an already-serialized - # string double-encodes it, so parse first. - if isinstance(tool_calls, str): - try: - tool_calls = json.loads(tool_calls) - except (json.JSONDecodeError, TypeError): - tool_calls = [] - tool_calls_json = json.dumps(tool_calls) if tool_calls else None - # Accept either `platform_message_id` (new explicit name) or - # `message_id` (yuanbao's existing convention on message dicts). - platform_msg_id = ( - msg.get("platform_message_id") or msg.get("message_id") - ) - - api_content = msg.get("api_content") - + tool_calls = _parse_tool_calls(msg.get("tool_calls")) + message_timestamp = _coerce_timestamp(msg.get("timestamp"), now_ts) cur = conn.execute( - """INSERT INTO messages (session_id, role, content, tool_call_id, - tool_calls, tool_name, effect_disposition, timestamp, token_count, finish_reason, - reasoning, reasoning_content, reasoning_details, codex_reasoning_items, - codex_message_items, platform_message_id, observed, _compressed_summary, active, api_content, display_kind, display_metadata) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", - ( - session_id, - role, - self._encode_content(msg.get("content")), - msg.get("tool_call_id"), - tool_calls_json, - _scrub_surrogates(msg.get("tool_name")), - msg.get("effect_disposition"), - message_timestamp, - msg.get("token_count"), - msg.get("finish_reason"), - _scrub_surrogates(msg.get("reasoning")) if role == "assistant" else None, - _scrub_surrogates(msg.get("reasoning_content")) if role == "assistant" else None, - reasoning_details_json, - codex_items_json, - codex_message_items_json, - platform_msg_id, - 1 if msg.get("observed") else 0, - 1 if msg.get("_compressed_summary") else 0, - 1, - _scrub_surrogates(api_content) if isinstance(api_content, str) else None, - _scrub_surrogates(msg.get("display_kind")) if isinstance(msg.get("display_kind"), str) else None, - self._encode_display_metadata(msg.get("display_metadata")), + _INSERT_MESSAGE_SQL, + self._message_row_params( + session_id, role, msg, tool_calls, message_timestamp, keep_reasoning=role == "assistant", ), ) if isinstance(msg, dict) and cur.lastrowid is not None: msg["_row_id"] = cur.lastrowid inserted += 1 - if tool_calls is not None: - tool_calls_total += ( - len(tool_calls) if isinstance(tool_calls, list) else 1 - ) + tool_calls_total += _tool_calls_count(tool_calls) now_ts = max(now_ts + 1e-6, message_timestamp + 1e-6) return inserted, tool_calls_total def replace_messages( - self, - session_id: str, - messages: List[Dict[str, Any]], - active_only: bool = False, - archive_dropped: bool = False, - reject_active_turn_lease: bool = False, + self, session_id: str, messages: List[Dict[str, Any]], active_only: bool = False, + archive_dropped: bool = False, reject_active_turn_lease: bool = False, ) -> None: - """Atomically replace the stored messages for a session. + """Atomically replace the stored messages for a session (/retry, /undo, /compress). - Used by transcript-rewrite flows such as /retry, /undo, and /compress. - The delete + reinsert sequence must commit as one transaction so a - mid-rewrite failure does not leave SQLite with a partial transcript. - - DESTRUCTIVE by default: every row for the session is DELETEd (and drops - out of the FTS index). For compaction that must preserve the - pre-compaction transcript under the same id, use - :meth:`archive_and_compact` instead. - - Pass ``active_only=True`` to replace ONLY the live (``active = 1``) rows, - leaving soft-archived rows (``active = 0`` — e.g. the ``compacted = 1`` - turns that :meth:`archive_and_compact` keeps on disk for #38763 - durability, or rewind/undo rows) untouched. Callers that share a session - id with an agent already running in-place compaction must use this so a - full-history rewrite doesn't wipe the rows the agent deliberately - archived. ``message_count``/``tool_call_count`` then track the live set, - matching :meth:`archive_and_compact`. - - Pass ``archive_dropped=True`` to SOFT-archive the live rows instead of - DELETEing them: the replaced turns stay on disk with ``active = 0``, - ``compacted = 0`` — the same "the user took it back" marking - :meth:`rewind_to_message` applies — and stay readable via - :meth:`get_messages` with ``include_inactive=True``. This is the mode a - rewind/edit/regenerate must use: those flows overwrite a transcript the - user may not have meant to drop, and a plain DELETE also evicts the rows - from the FTS index, leaving nothing to recover from (#82756). It implies - active-only handling — already-archived rows are never touched — so - ``active_only`` is redundant with it. The rewritten set is inserted as - fresh active rows exactly as in the destructive path, so the live view - is identical either way; only the durability of the dropped turns - differs. - - Pass ``reject_active_turn_lease=True`` for user-initiated rewrites that - do not already own the cross-process turn lease. The lease check and - transcript mutation then share one write transaction, so a second - process cannot archive or replace a turn that is still being produced. + DESTRUCTIVE by default: every row is DELETEd (and leaves the FTS index). + ``active_only=True`` replaces only ``active = 1`` rows, leaving soft-archived + rows (compacted turns, rewind rows) untouched — required when sharing a session + id with an agent doing in-place compaction. ``archive_dropped=True`` SOFT-archives + the live rows (``active = 0, compacted = 0``, rewind-style) instead of deleting: + the mode rewind/edit/regenerate must use, since a DELETE leaves nothing to + recover from; it implies active-only handling. ``reject_active_turn_lease=True`` + runs the lease check in the same write txn for user-initiated rewrites that do + not own the cross-process lease. """ from hermes_state import CompressionSessionClosedError - active_clause = " AND active = 1" if active_only else "" def _do(conn): if reject_active_turn_lease: self._check_transcript_write_guards( - conn, - session_id, - None, - reject_active_turn_lease=True, - reject_active_compression_lock=True, + conn, session_id, None, reject_active_turn_lease=True, reject_active_compression_lock=True, ) - else: - session = conn.execute( - "SELECT ended_at, end_reason FROM sessions WHERE id = ?", - (session_id,), - ).fetchone() - if ( - session is not None - and session["ended_at"] is not None - and session["end_reason"] == "compression" - ): - raise CompressionSessionClosedError(session_id) + elif _ended_by_compression(conn.execute(_ENDED_BY_COMPRESSION_SQL, (session_id,)).fetchone()): + raise CompressionSessionClosedError(session_id) if archive_dropped: - # Content-preserving UPDATE: the rows keep their FTS entries - # (the messages_fts triggers fire on INSERT / DELETE / UPDATE - # of content columns, not on `active`), so the replaced turns - # stay readable via get_messages(include_inactive=True) and - # searchable with include_inactive=True after the rewrite. + # Content-preserving UPDATE: FTS triggers don't fire on `active`, so the + # replaced turns stay searchable/readable with include_inactive=True. conn.execute( - "UPDATE messages SET active = 0 " - "WHERE session_id = ? AND active = 1", - (session_id,), + "UPDATE messages SET active = 0 WHERE session_id = ? AND active = 1", (session_id,), ) else: - conn.execute( - f"DELETE FROM messages WHERE session_id = ?{active_clause}", - (session_id,), - ) + conn.execute(f"DELETE FROM messages WHERE session_id = ?{active_clause}", (session_id,)) conn.execute( - "UPDATE sessions SET message_count = 0, tool_call_count = 0 WHERE id = ?", - (session_id,), - ) - total_messages, total_tool_calls = self._insert_message_rows( - conn, session_id, messages + "UPDATE sessions SET message_count = 0, tool_call_count = 0 WHERE id = ?", (session_id,), ) + total_messages, total_tool_calls = self._insert_message_rows(conn, session_id, messages) conn.execute( "UPDATE sessions SET message_count = ?, tool_call_count = ? WHERE id = ?", (total_messages, total_tool_calls, session_id), @@ -980,108 +668,83 @@ class SessionMessagesMixin: self._execute_write(_do) def has_archived_messages(self, session_id: str) -> bool: - """Return True if the session has any soft-archived (``active = 0``) rows. - - Cheap existence probe — does not load rows. NOTE: production rewrite - paths no longer branch on this (they pass ``active_only=True`` - unconditionally — a probe can fail open or race a concurrent - ``archive_and_compact``, #80216); kept for tests and diagnostics. - """ + """True if the session has any soft-archived (``active = 0``) rows. Cheap probe; + production rewrite paths no longer branch on it (kept for tests/diagnostics).""" return self._read_one( - "SELECT 1 FROM messages WHERE session_id = ? AND active = 0 LIMIT 1", - (session_id,), + "SELECT 1 FROM messages WHERE session_id = ? AND active = 0 LIMIT 1", (session_id,), ) is not None def get_active_message_watermark(self, session_id: str) -> int: - """MAX(id) of the session's active rows — the compression watermark. - - Captured at compression START (before the slow provider summary call). - Every active row with ``id > watermark`` at commit time arrived - concurrently and must survive the compaction verbatim. Returns 0 for - an empty/unknown session. - """ + """MAX(id) of the session's active rows — captured at compression START; every + active row above it arrived concurrently and must survive compaction verbatim. + 0 for an empty/unknown session.""" if not session_id: return 0 row = self._read_one( - "SELECT COALESCE(MAX(id), 0) FROM messages " - "WHERE session_id = ? AND active = 1", - (session_id,), + "SELECT COALESCE(MAX(id), 0) FROM messages WHERE session_id = ? AND active = 1", (session_id,), ) return int(row[0]) if row else 0 + def _tail_rows_after_watermark(self, conn, sql: str, params) -> Tuple[List[int], int]: + """``(ids, tool_call_count)`` of the concurrent-tail rows selected by *sql* + (``SELECT id, tool_calls ...``).""" + rows = conn.execute(sql, params).fetchall() + return [int(r["id"]) for r in rows], sum(_tool_calls_len(r["tool_calls"]) for r in rows) + + def _clone_message_rows(self, conn, tail_ids: List[int], *, session_id: Optional[str] = None) -> None: + """Pure-SQL column clone of *tail_ids* as fresh live rows (new id, active=1, + compacted=0, everything else byte-exact; FTS triggers index the clones). With + *session_id* the clones land in that session instead of the originals'.""" + skip = ("id", "active", "compacted") + (("session_id",) if session_id is not None else ()) + col_list = ", ".join(c for c in self._message_column_names(conn) if c not in skip) + placeholders = _placeholders(tail_ids) + if session_id is None: + conn.execute( + f"INSERT INTO messages ({col_list}, active, compacted) " + f"SELECT {col_list}, 1, 0 FROM messages " + f"WHERE id IN ({placeholders}) ORDER BY id", + tail_ids, + ) + else: + conn.execute( + f"INSERT INTO messages ({col_list}, session_id, active, compacted) " + f"SELECT {col_list}, ?, 1, 0 FROM messages " + f"WHERE id IN ({placeholders}) ORDER BY id", + [session_id, *tail_ids], + ) + def archive_and_compact( - self, - session_id: str, - compacted_messages: List[Dict[str, Any]], - model_config_patch: Optional[Dict[str, Any]] = None, - watermark: Optional[int] = None, - lock_holder: Optional[str] = None, - tail_count: int = 0, + self, session_id: str, compacted_messages: List[Dict[str, Any]], + model_config_patch: Optional[Dict[str, Any]] = None, watermark: Optional[int] = None, + lock_holder: Optional[str] = None, tail_count: int = 0, ) -> int: - """Non-destructive in-place compaction for a single durable session id. + """Non-destructive in-place compaction under ONE durable session id. - Soft-archives the active messages (``active = 0``) and inserts - *compacted_messages* as fresh active rows — atomically, in one write - transaction. The conversation keeps ONE session id for life (#38763) - WITHOUT destroying history: + Soft-archives the active rows (``active=0, compacted=1`` — "summarized away", + still found by search_messages and readable with include_inactive) and inserts + *compacted_messages* as fresh active rows, atomically. Live-context loads + filter ``active = 1`` so the model reloads only the compacted set. - - The live-context load (:meth:`get_messages_as_conversation`, - :meth:`get_messages`) filters ``active = 1`` by default, so the model - reloads ONLY the compacted set. - - The archived pre-compaction turns stay on disk (active=0) and stay - DISCOVERABLE: they are marked compacted=1, and search_messages() - includes compacted=1 rows by default — so session_search still finds - them, unlike rewind/undo rows (active=0, compacted=0) which stay - hidden. They remain in the FTS index (the messages_fts* triggers - index on INSERT / drop on DELETE and don't key on active/compacted; - flipping to active=0 is a content-preserving UPDATE) and are - recoverable via get_messages(..., include_inactive=True). + *watermark* (``get_active_message_watermark`` at compression START): rows with + ``id > watermark`` arrived during the slow summary and are re-sequenced after + the compacted set by a pure-SQL column clone (fresh ids — consumers re-resolve + by content); ``None`` archives everything. *lock_holder*: the commit verifies + inside the txn that the compression lock is still held and unexpired, so a + reclaimed lease fails instead of clobbering the winner. *tail_count*: the LAST + N rows of *compacted_messages* are the verbatim carried-forward tail; their + originals (at/below the watermark) and the watermark clones' originals are + superseded duplicates and get rewind-style flags (``active=0, compacted=0``) so + session_search doesn't return each carried message once per compaction. - Concurrent-append safety (#75316): when *watermark* is provided (the - value of :meth:`get_active_message_watermark` captured at compression - START), rows that arrived during the slow provider summary call - (``id > watermark``) are NOT summarized away. They are re-sequenced - after the compacted set by a pure-SQL column clone (every column - except ``id`` — content, api_content, platform_message_id, token - counts, reasoning sidecars all survive byte-exact, and the FTS - triggers index the clones naturally), and the originals are archived. - NOTE: re-sequencing assigns the tail rows fresh ids; consumers that - reference durable row ids re-resolve by content (see 3e8ab0610). - ``watermark=None`` preserves the historical archive-everything - behavior. - - Commit-fence safety: when *lock_holder* is provided, the commit - verifies INSIDE the transaction that the compression lock is still - held by that holder and unexpired — a compression whose lease was - reclaimed (crash cleanup, TTL expiry, competing writer) fails the - commit instead of clobbering the winner's transcript. - - *tail_count* (default 0) names how many of the LAST rows of - *compacted_messages* are the verbatim carried-forward tail the - compressor protected rather than summarized (#86366). Those rows' - ORIGINALS — which this call archives as a side effect of the blanket - soft-archive — are superseded byte-identical duplicates, not - "summarized away" content, so they are stamped rewind-style - (``active=0, compacted=0``, hidden from search_messages) instead of - ``compacted=1``. Without this the tail originals satisfy the recall - filter alongside their live clones and session_search returns every - carried-forward message once per compaction. Callers that cannot know - their tail shape keep the historical archive-everything behavior. - - ``message_count`` is set to the ACTIVE count after commit, matching - what the live load returns. ``model_config_patch`` is merged into the - session's JSON config in the same transaction; a ``None`` value - removes that key. Returns the new active count. + ``message_count`` becomes the ACTIVE count; ``model_config_patch`` merges into + the session JSON in the same txn (``None`` value removes a key). Returns the new + active count. """ from hermes_state import SessionCompressionInProgressError def _do(conn): if lock_holder is not None: - lock_row = conn.execute( - "SELECT holder, expires_at FROM compression_locks " - "WHERE session_id = ?", - (session_id,), - ).fetchone() + lock_row = conn.execute(_COMPRESSION_LOCK_ROW_SQL, (session_id,)).fetchone() if ( lock_row is None or lock_row["holder"] != lock_holder @@ -1091,55 +754,25 @@ class SessionMessagesMixin: f"Compression lease for {session_id!r} lost before " "commit; refusing to publish a stale compaction" ) - patched_model_config = None if model_config_patch is not None: - # on_missing="raise": a prune/compaction must not commit - # against a vanished session row (the compressor's caller - # converts the raised error into a safe keep-the-original - # no-op), unlike the flag setters which tolerate missing rows. + # on_missing="raise": never commit against a vanished session row (the + # compressor's caller turns the error into a keep-the-original no-op). patched_model_config = self._merge_model_config_json( conn, session_id, model_config_patch, on_missing="raise" ) - - # Concurrent tail: active rows that arrived after the watermark. - # Snapshot their ids and tool_calls now — the clone below needs a - # stable id list, and the tool-call count keeps sessions.* honest. tail_ids: list[int] = [] tail_tool_calls = 0 if watermark is not None: - for row in conn.execute( + tail_ids, tail_tool_calls = self._tail_rows_after_watermark( + conn, "SELECT id, tool_calls FROM messages " "WHERE session_id = ? AND active = 1 AND id > ? " "ORDER BY id", (session_id, int(watermark)), - ).fetchall(): - tail_ids.append(int(row["id"])) - raw = row["tool_calls"] - if raw: - try: - parsed = json.loads(raw) if isinstance(raw, str) else raw - tail_tool_calls += len(parsed) if isinstance(parsed, list) else 0 - except (TypeError, ValueError): - pass - - # Soft-archive the live turns: active=0 hides them from the live - # context load, compacted=1 marks them as "summarized away" (vs - # rewind/undo's active=0+compacted=0, which means "user took it - # back"). search_messages includes compacted=1 rows by default so - # the pre-compaction transcript stays discoverable; live-context - # loads (active=1 only) still exclude them. Tail originals whose - # verbatim clones ride inside *compacted_messages* (tail_count) - # are superseded duplicates instead (#86366): they get the - # rewind-style flags so they stop matching the recall filter. - # Rewind-target ids: the originals of the carried-forward tail - # rows (tail_count), captured BEFORE any flag flips. Named apart - # from the watermark `tail_ids` below on purpose — the two are - # different sets (#86366): rewind targets sit AT/BELOW the - # watermark (the compressor only saw rows up to it), while - # `tail_ids` are concurrent appends ABOVE it. Without the bound, - # a concurrent append would steal a LIMIT slot and leave a real - # carried-forward original stamped compacted=1. + ) + # Rewind targets sit AT/BELOW the watermark (the compressor only saw rows up + # to it); without the bound a concurrent append would steal a LIMIT slot. rewind_tail_ids: Optional[list[int]] = None if tail_count > 0: if watermark is not None: @@ -1156,15 +789,9 @@ class SessionMessagesMixin: (session_id, int(tail_count)), ).fetchall() rewind_tail_ids = [int(row["id"]) for row in tail_rows] - - # The watermark clone below re-inserts `tail_ids` rows byte-exact - # as live rows — their originals are the SAME superseded-duplicate - # class as the carried-forward tail (#86366), so they take the - # rewind flags too instead of double-matching the recall filter. rewind_ids = [*(rewind_tail_ids or []), *tail_ids] - if rewind_ids: - placeholders = ",".join("?" for _ in rewind_ids) + placeholders = _placeholders(rewind_ids) conn.execute( "UPDATE messages SET active = 0, compacted = 0 " f"WHERE session_id = ? AND id IN ({placeholders})", @@ -1182,31 +809,11 @@ class SessionMessagesMixin: "WHERE session_id = ? AND active = 1", (session_id,), ) - inserted, tool_calls_total = self._insert_message_rows( - conn, session_id, compacted_messages - ) - + inserted, tool_calls_total = self._insert_message_rows(conn, session_id, compacted_messages) if tail_ids: - # Re-sequence the concurrent tail after the compacted set via - # a pure-SQL column clone: no decode/re-encode round trip, no - # field drift — new id, active=1, compacted=0, all else exact. - placeholders = ",".join("?" for _ in tail_ids) - clone_cols = [ - c for c in self._message_column_names(conn) - if c not in ("id", "active", "compacted") - ] - col_list = ", ".join(clone_cols) - conn.execute( - f"INSERT INTO messages ({col_list}, active, compacted) " - f"SELECT {col_list}, 1, 0 FROM messages " - f"WHERE id IN ({placeholders}) ORDER BY id", - tail_ids, - ) + self._clone_message_rows(conn, tail_ids) inserted += len(tail_ids) tool_calls_total += tail_tool_calls - - # message_count / tool_call_count reflect the LIVE (active) set — - # the archived rows are still on disk but not part of the live count. if model_config_patch is None: conn.execute( "UPDATE sessions SET message_count = ?, tool_call_count = ? WHERE id = ?", @@ -1231,50 +838,33 @@ class SessionMessagesMixin: self._message_columns_cache = cols return cols - def set_latest_user_api_content( - self, session_id: str, content: Any, api_content: str - ) -> int: + def set_latest_user_api_content(self, session_id: str, content: Any, api_content: str) -> int: """Backfill the ``api_content`` sidecar onto the newest ACTIVE user row. - In-place preflight compaction (:meth:`archive_and_compact`) inserts the - current turn's user row BEFORE the turn prologue composes the - prefetch/plugin sidecar, and the subsequent crash persist identity-skips - every compacted dict — without this backfill the stamped sidecar would - never land in the DB and any reload would replay clean content, - re-introducing the prompt-cache divergence the sidecar exists to close. - - The ``content`` match is a defensive guard: if the newest active user - row is not the message the caller stamped (racing rewrite, unexpected - tail shape), nothing is written. Returns the number of rows updated - (0 or 1). + In-place preflight compaction inserts the current user row BEFORE the turn + prologue composes the sidecar, and the later persist identity-skips compacted + dicts; without this the reload would replay clean content and reopen the + prompt-cache divergence. The ``content`` match guards against a racing rewrite. + Returns rows updated (0 or 1). """ from hermes_state import _scrub_surrogates - encoded = self._encode_content(content) - return self._write_rowcount( "UPDATE messages SET api_content = ? WHERE id = (" "SELECT id FROM messages " "WHERE session_id = ? AND role = 'user' AND active = 1 " "ORDER BY id DESC LIMIT 1" ") AND content IS ?", - (_scrub_surrogates(api_content), session_id, encoded), + (_scrub_surrogates(api_content), session_id, self._encode_content(content)), ) def _dedupe_display_generations(self, rows): - """Collapse compaction generations so each message appears once. + """Collapse compaction generations so each logical message appears once. - Compaction epochs copy the protected tail into each new generation, so - one logical message can exist as several rows (identical - role/content/timestamp) with different ``active`` flags and ids. A - display read must surface each exactly once: prefer the live row, then - the newest generation. - - This is the ONE definition shared by every display projection — - :meth:`get_messages` (REST), :meth:`get_resume_conversations` and - :meth:`get_ancestor_display_prefix` (gateway resume), and - :meth:`get_messages_as_conversation` (warm-session payload) — so the - surfaces cannot disagree about the same transcript. *rows* must already - be ordered by ``id``; the returned list keeps that order. + Compaction copies the protected tail into each generation (same + role/content/timestamp, different ``active``/id); prefer the live row, then the + newest generation. The ONE definition shared by every display projection + (get_messages, get_resume_conversations, get_ancestor_display_prefix, + get_messages_as_conversation). *rows* must be ordered by ``id``; order is kept. """ seen: Dict[Tuple[Any, ...], Any] = {} for row in rows: @@ -1282,107 +872,76 @@ class SessionMessagesMixin: if row["role"] == "user": from agent.context_compressor import split_user_originated_turn - candidate = { + handoff, live_view = split_user_originated_turn({ "role": "user", "content": self._decode_content(row["content"]), "display_kind": row["display_kind"], - "display_metadata": self._decode_display_metadata( - row["display_metadata"] - ), - } - handoff, live_view = split_user_originated_turn(candidate) + "display_metadata": self._decode_display_metadata(row["display_metadata"]), + }) if handoff is not None and live_view is not None: dedupe_content = self._encode_content(live_view.get("content")) - # Tool fields participate in the dedupe key: compaction copies them - # verbatim, so identical tool messages across generations still - # collapse, while distinct tool calls that happen to share - # role/content/timestamp are never merged. + # Tool fields are part of the key: identical tool messages across generations + # collapse, distinct tool calls sharing role/content/timestamp never merge. key = ( - row["role"], - dedupe_content, - row["timestamp"], - row["tool_call_id"], - row["tool_calls"], - row["tool_name"], + row["role"], dedupe_content, row["timestamp"], + row["tool_call_id"], row["tool_calls"], row["tool_name"], ) cur = seen.get(key) if cur is None or (row["active"], row["id"]) > (cur["active"], cur["id"]): seen[key] = row return sorted(seen.values(), key=lambda r: r["id"]) + def _row_to_message_dict(self, row, *, warn_context: str, summary_flag: bool) -> Dict[str, Any]: + """``dict(row)`` with content/tool_calls/display_metadata decoded. *summary_flag* + pops ``_compressed_summary`` and keeps it only as ``True``.""" + msg = dict(row) + if summary_flag and msg.pop("_compressed_summary", 0): + msg["_compressed_summary"] = True + if "content" in msg: + msg["content"] = self._decode_content(msg["content"]) + if msg.get("tool_calls"): + msg["tool_calls"] = _json_or( + msg["tool_calls"], [], + f"Failed to deserialize tool_calls in {warn_context}, falling back to []", + ) + if msg.get("display_metadata") is not None: + msg["display_metadata"] = self._decode_display_metadata(msg["display_metadata"]) + return msg + + @staticmethod + def _active_clause(include_inactive: bool, include_compacted: bool) -> str: + """Audit reads: every row; display reads: active plus compaction-archived + (never Undo/Rewind rows); default: live only.""" + if include_inactive: + return "" + return _DISPLAY_ACTIVE_CLAUSE if include_compacted else " AND active = 1" + def get_messages( - self, - session_id: str, - include_inactive: bool = False, - include_compacted: bool = False, - limit: Optional[int] = None, - offset: int = 0, - latest: bool = False, + self, session_id: str, include_inactive: bool = False, include_compacted: bool = False, + limit: Optional[int] = None, offset: int = 0, latest: bool = False, after_id: Optional[int] = None, ) -> List[Dict[str, Any]]: - """Load messages for a session in insertion order. + """Load messages for a session in insertion order (AUTOINCREMENT id, never + timestamp — clocks regress on WSL2/NTP steps). - By default only active messages are returned. Pass - ``include_inactive=True`` to load soft-deleted rows (e.g. for - audit / debug views of rewound history). See - :meth:`rewind_to_message` for the soft-delete mechanic. - - Pass ``include_compacted=True`` to additionally load rows preserved - by in-place context compaction (``active=0, compacted=1``). Those are - durable display history, not soft-deleted rows — a user-visible - transcript read must not drop them, or earlier turns silently become - unreachable once the UI exhausts its active-only window. Soft-deleted - Undo/Rewind rows (``active=0, compacted=0``) stay excluded; use - ``include_inactive`` for those. - - Ordered by AUTOINCREMENT id (true insertion order) rather than - timestamp — see c03acca50 for the WSL2 clock-regression rationale. - - When ``limit`` is provided, returns at most ``limit`` messages - starting from ``offset`` (0-based, in insertion order). Enables - pagination for the API endpoint to avoid loading entire transcripts. - With ``latest=True``, the offset is measured back from the newest - message and the selected page is still returned in chronological - order. ``offset`` alone (without ``limit``) also pages — SQLite - requires a LIMIT clause for OFFSET, so it's emitted as ``LIMIT -1`` - (unbounded). - - ``after_id`` enables keyset pagination (``id > after_id``): O(1) - page seeks on huge transcripts where OFFSET degrades to O(n) per - page. Ascending order only (incompatible with ``latest``/``offset``). + ``include_inactive`` loads soft-deleted rewind rows; ``include_compacted`` adds + rows preserved by in-place compaction (durable display history a transcript + read must not drop) but not rewind rows. ``limit``/``offset`` page; ``latest`` + measures the offset back from the newest row and still returns chronological + order. ``after_id`` is keyset paging (``id > after_id``), ascending only. """ if after_id is not None and (latest or offset): raise ValueError("after_id is incompatible with latest/offset paging") if after_id is not None and include_compacted: raise ValueError("after_id is incompatible with include_compacted (deduped display reads use offset paging)") - if include_inactive: - # Audit / debug reads: every row, including soft-deleted. - active_clause = "" - elif include_compacted: - # Display history: active rows plus rows preserved by in-place - # compaction (active=0, compacted=1), but never soft-deleted - # Undo/Rewind rows (active=0, compacted=0). - active_clause = " AND (active = 1 OR compacted = 1)" - else: - active_clause = " AND active = 1" - keyset_clause = " AND id > ?" if after_id is not None else "" - sql = ( - "SELECT * FROM messages WHERE session_id = ?" - f"{active_clause}{keyset_clause} ORDER BY id {'DESC' if latest else 'ASC'}" - ) - params: list = [session_id] - if after_id is not None: - params.append(after_id) + active_clause = self._active_clause(include_inactive, include_compacted) if include_compacted: - # Read the full display set (a session's rows are bounded; the - # UI-level 500-row cap lives in the endpoint, not here), dedupe - # generations, then apply paging. - all_rows = self._read_all( - "SELECT * FROM messages WHERE session_id = ?" + active_clause - + " ORDER BY id ASC", + # Read the full display set (the UI-level row cap lives in the endpoint), + # dedupe generations, then page. + rows = self._dedupe_display_generations(self._read_all( + "SELECT * FROM messages WHERE session_id = ?" + active_clause + " ORDER BY id ASC", [session_id], - ) - rows = self._dedupe_display_generations(all_rows) + )) if latest: rows = rows[::-1] rows = rows[offset:] @@ -1391,6 +950,14 @@ class SessionMessagesMixin: if latest: rows = rows[::-1] else: + keyset_clause = " AND id > ?" if after_id is not None else "" + sql = ( + "SELECT * FROM messages WHERE session_id = ?" + f"{active_clause}{keyset_clause} ORDER BY id {'DESC' if latest else 'ASC'}" + ) + params: list = [session_id] + if after_id is not None: + params.append(after_id) if limit is not None or offset: # SQLite's OFFSET requires LIMIT; -1 means "no limit". sql += " LIMIT ? OFFSET ?" @@ -1398,41 +965,18 @@ class SessionMessagesMixin: rows = self._read_all(sql, params) if latest: rows.reverse() - result = [] - for row in rows: - msg = dict(row) - if msg.pop("_compressed_summary", 0): - msg["_compressed_summary"] = True - if "content" in msg: - msg["content"] = self._decode_content(msg["content"]) - if msg.get("tool_calls"): - try: - msg["tool_calls"] = json.loads(msg["tool_calls"]) - except (json.JSONDecodeError, TypeError): - logger.warning("Failed to deserialize tool_calls in get_messages, falling back to []") - msg["tool_calls"] = [] - if msg.get("display_metadata") is not None: - msg["display_metadata"] = self._decode_display_metadata(msg["display_metadata"]) - result.append(msg) - return result + return [self._row_to_message_dict(row, warn_context="get_messages", summary_flag=True) for row in rows] def find_pr_url_messages(self, session_ids: List[str]) -> List[Dict[str, Any]]: - """Tool results in these sessions that mention a GitHub PR url. - - A candidate scan, deliberately loose: it hands back every tool result - containing ``/pull/`` and leaves the caller to decide which ones make a - claim (see the desktop's PR recovery, which only accepts an output that - is a bare PR url — the signature of ``gh pr create``). Ordered - oldest-first per session so the caller can take the last match. - """ + """Tool results in these sessions containing ``/pull/`` — a deliberately loose + candidate scan, oldest-first per session so the caller can take the last match.""" found: List[Dict[str, Any]] = [] ids = [s for s in session_ids if s] for start in range(0, len(ids), 900): # SQLite's bound-variable ceiling. chunk = ids[start : start + 900] - placeholders = ",".join("?" * len(chunk)) rows = self._read_all( f"""SELECT session_id, content FROM messages - WHERE session_id IN ({placeholders}) + WHERE session_id IN ({",".join("?" * len(chunk))}) AND role = 'tool' AND content LIKE '%/pull/%' ORDER BY id ASC""", chunk, @@ -1440,44 +984,21 @@ class SessionMessagesMixin: found.extend({"session_id": row[0], "content": row[1]} for row in rows) return found - def get_messages_around( - self, - session_id: str, - around_message_id: int, - window: int = 5, - ) -> Dict[str, Any]: - """Load a window of messages anchored on a specific message id. + def get_messages_around(self, session_id: str, around_message_id: int, window: int = 5) -> Dict[str, Any]: + """Window of up to *window* messages either side of an anchor id (id ascending). - Returns a dict with: - - ``window``: up to ``window`` messages before the anchor, the anchor - itself, and up to ``window`` messages after, ordered by id ascending. - - ``messages_before``: count of messages strictly before the anchor - still in the session (== window unless we hit the start). - - ``messages_after``: count of messages strictly after the anchor - still in the session (== window unless we hit the end). - - Used by ``session_search`` for both the discovery shape (anchored on the - FTS5 match) and the scroll shape (anchored on any message id). The - ``messages_before`` / ``messages_after`` counts let the caller detect - session boundaries: when either is less than ``window``, the agent has - reached one end of the session. - - Returns an empty window when ``around_message_id`` is not a real id in - ``session_id`` — callers decide how to surface that. + ``messages_before``/``messages_after`` count rows in the returned slice strictly + before/after the anchor; less than *window* means a session boundary. Empty + window when the anchor is not a row of *session_id*. """ - if window < 0: - window = 0 + window = max(window, 0) with self._read_ctx() as conn: - # Confirm the anchor exists in this session. anchor_exists = conn.execute( "SELECT 1 FROM messages WHERE id = ? AND session_id = ? LIMIT 1", (around_message_id, session_id), ).fetchone() if not anchor_exists: return {"window": [], "messages_before": 0, "messages_after": 0} - - # Two queries: anchor + before (DESC, take window+1), and after - # (ASC, take window). Final order is id ASC. before_rows = conn.execute( "SELECT * FROM messages " "WHERE session_id = ? AND id <= ? " @@ -1490,106 +1011,48 @@ class SessionMessagesMixin: "ORDER BY id ASC LIMIT ?", (session_id, around_message_id, window), ).fetchall() - - # before_rows is DESC; reverse so it's ASC, then concatenate after_rows. rows = list(reversed(before_rows)) + list(after_rows) - result = [] - for row in rows: - msg = dict(row) - if "content" in msg: - msg["content"] = self._decode_content(msg["content"]) - if msg.get("tool_calls"): - try: - msg["tool_calls"] = json.loads(msg["tool_calls"]) - except (json.JSONDecodeError, TypeError): - logger.warning( - "Failed to deserialize tool_calls in get_messages_around, falling back to []" - ) - msg["tool_calls"] = [] - if msg.get("display_metadata") is not None: - msg["display_metadata"] = self._decode_display_metadata(msg["display_metadata"]) - result.append(msg) - - # before_rows includes the anchor itself; subtract 1 for the count of - # messages strictly before the anchor in the returned slice. - messages_before = max(0, len(before_rows) - 1) - messages_after = len(after_rows) return { - "window": result, - "messages_before": messages_before, - "messages_after": messages_after, + "window": [ + self._row_to_message_dict(row, warn_context="get_messages_around", summary_flag=False) + for row in rows + ], + "messages_before": max(0, len(before_rows) - 1), # before_rows includes the anchor + "messages_after": len(after_rows), } def resolve_resume_session_id(self, session_id: str) -> str: """Redirect a resume target to the descendant session that holds the messages. - Context compression ends the current session and forks a new child session - (linked via ``parent_session_id``). The flush cursor is reset, so the - child is where new messages actually land — the parent ends up with - ``message_count = 0`` rows unless messages had already been flushed to - it before compression. See #15000. - - This helper walks ``parent_session_id`` forward from ``session_id`` and - returns the descendant in the chain that has the **most recent** messages. - Unlike the original logic, it does NOT short-circuit when the starting - session already has messages — a descendant that was created by - compression may hold the continuation content and should be preferred - by the WebUI and gateway for ``--resume`` and session loading. - - If no descendant (including the starting session) has any messages, - the original ``session_id`` is returned unchanged. - - The chain is always walked via the child whose ``started_at`` is - latest; that matches the single-chain shape that compression creates. - A depth cap (32) guards against accidental loops in malformed data. + Follows the compression chain to the live tip first (``get_compression_tip`` is + lineage-aware: only children of compression-ended parents, so delegation/branch + children never hijack the resume), then walks ``parent_session_id`` forward, + returning the deepest node with messages — never short-circuiting on the start + node, since a continuation may hold the newer turns. Branch, delegate, reset + and tool children are skipped (they carry ``parent_session_id`` too). Returns + *session_id* unchanged when nothing has messages. Depth cap 32. """ if not session_id: return session_id - - # Follow the compression-continuation chain forward to the live tip - # FIRST. Auto-compression ends the current session and forks a - # continuation child, but a long-lived parent keeps its own flushed - # message rows — so the empty-head walk below never redirects it, and - # resuming the parent id reloads the pre-compression transcript while - # the turns generated *after* compression (and their responses) sit in - # the continuation. ``get_compression_tip`` is lineage-aware: it only - # follows children whose parent ended with ``end_reason='compression'`` - # (created after the parent was ended), so delegation / branch children - # never hijack the resume. This is the fix for the desktop "I came back - # and the reply isn't there" report on large sessions. try: tip = self.get_compression_tip(session_id) except Exception: tip = session_id if tip and tip != session_id: session_id = tip - with self._read_ctx() as conn: current = session_id seen = {current} - best = None # tracks the last (deepest) node with messages - + best = None # deepest node with messages for _ in range(32): - # Check if the current node has messages. try: row = conn.execute( - "SELECT 1 FROM messages WHERE session_id = ? LIMIT 1", - (current,), + "SELECT 1 FROM messages WHERE session_id = ? LIMIT 1", (current,), ).fetchone() except Exception: return session_id if row is not None: best = current - - # Walk to the most-recently-started child — but skip explicit - # branch (`_branched_from`), delegate/subagent (`_delegate_from`), - # reset-continuation (`_reset_from` or the legacy same-key - # heuristic — a post-reset conversation must never be reached - # by resuming the parent the user reset away), and tool - # children. They also carry a ``parent_session_id`` yet - # are NOT compression continuations; following them would hijack - # the resume target to an unrelated session (e.g. a subagent - # run). This mirrors the child-exclusion in ``get_compression_tip``. try: child_row = conn.execute( "SELECT id FROM sessions AS child " @@ -1611,259 +1074,148 @@ class SessionMessagesMixin: break seen.add(child_id) current = child_id - return best if best is not None else session_id - def get_messages_as_conversation( - self, - session_id: str, - include_ancestors: bool = False, - include_inactive: bool = False, - repair_alternation: bool = False, - include_row_ids: bool = False, - include_compacted: bool = False, - ) -> List[Dict[str, Any]]: - """ - Load messages in the OpenAI conversation format (role + content dicts). - Used by the gateway to restore conversation history. - - By default only active messages are returned. Pass - ``include_inactive=True`` to load soft-deleted (rewound) rows - as well. See :meth:`rewind_to_message`. - - ``include_compacted=True`` additionally loads rows preserved by - in-place compaction (``active=0, compacted=1``), deduped by - :meth:`_dedupe_display_generations`. DISPLAY reads want this; the - model-fed restore must NOT pass it, or a resumed session regrows the - very history compaction just summarized away. - - ``repair_alternation=True`` runs ``repair_message_sequence`` over the - loaded list before returning it. Callers that restore a session for - LIVE REPLAY should pass it: a durable alternation violation (e.g. a - ``user;user`` pair left by a turn that persisted no assistant row) - otherwise re-triggers the pre-request defensive repair on every - single request for the rest of the session's life — the repair - mutates only the per-request list, never the stored transcript. - Inspection/export consumers keep the default and see the transcript - verbatim. - """ - session_ids = [session_id] - if include_ancestors and not self._is_explicit_branch_session(session_id): - session_ids = self._session_lineage_root_to_tip(session_id) - - if include_inactive: - active_clause = "" - elif include_compacted: - active_clause = " AND (active = 1 OR compacted = 1)" - else: - active_clause = " AND active = 1" + def _fetch_conversation_rows(self, session_ids: List[str], active_clause: str, *, with_session_id: bool): + """``_CONVERSATION_ROW_COLUMNS`` rows for *session_ids*, ORDER BY id (insertion + order — timestamps are not monotonic and would break tool-call adjacency).""" + prefix = "SELECT session_id, " if with_session_id else "SELECT " with self._read_ctx() as conn: - placeholders = ",".join("?" for _ in session_ids) - rows = conn.execute( - f"SELECT {self._CONVERSATION_ROW_COLUMNS} " - f"FROM messages WHERE session_id IN ({placeholders})" - # Order by AUTOINCREMENT id (true insertion order), NOT timestamp: - # append_message stamps rows with time.time(), which is not - # monotonic (WSL2, NTP steps, VM/laptop sleep resume). A later - # row can carry an earlier timestamp than its predecessor, and - # ORDER BY timestamp would then sort an assistant tool_calls row - # after its tool response, breaking tool-call/response adjacency - # and triggering an HTTP 400 on replay. This matches get_messages - # — see c03acca50 for the original fix. + return conn.execute( + f"{prefix}{self._CONVERSATION_ROW_COLUMNS} " + f"FROM messages WHERE session_id IN ({_placeholders(session_ids)})" f"{active_clause} ORDER BY id", tuple(session_ids), ).fetchall() + def get_messages_as_conversation( + self, session_id: str, include_ancestors: bool = False, include_inactive: bool = False, + repair_alternation: bool = False, include_row_ids: bool = False, + include_compacted: bool = False, + ) -> List[Dict[str, Any]]: + """Load messages in OpenAI conversation format (gateway history restore). + + ``include_compacted`` adds compaction-archived rows deduped by + :meth:`_dedupe_display_generations` — DISPLAY reads only; the model-fed restore + must not pass it or a resume regrows the history compaction summarized away. + ``repair_alternation`` runs ``repair_message_sequence`` on the loaded list + (LIVE REPLAY callers) so a durable ``user;user`` pair doesn't re-trigger the + per-request repair forever; the stored transcript is never mutated. + """ + session_ids = [session_id] + if include_ancestors and not self._is_explicit_branch_session(session_id): + session_ids = self._session_lineage_root_to_tip(session_id) + rows = self._fetch_conversation_rows( + session_ids, self._active_clause(include_inactive, include_compacted), with_session_id=False, + ) if include_compacted: rows = self._dedupe_display_generations(rows) - return self._rows_to_conversation( - rows, - session_id=session_id, - include_ancestors=include_ancestors, - repair_alternation=repair_alternation, - include_row_ids=include_row_ids, + rows, session_id=session_id, include_ancestors=include_ancestors, + repair_alternation=repair_alternation, include_row_ids=include_row_ids, ) - def _rows_to_conversation( - self, - rows, - *, - session_id: str, - include_ancestors: bool, - repair_alternation: bool, - include_row_ids: bool = False, - include_summary_markers: bool = False, - ) -> List[Dict[str, Any]]: - """Decode fetched message rows into the OpenAI conversation format. + def _dedupe_replayed_user(self, messages, msg, exact_user_clones) -> Tuple[bool, Any]: + """Ancestor-lineage dedupe for one decoded user *msg*. - Extracted from get_messages_as_conversation so get_resume_conversations - can build the model-fed and display views from one SELECT. ``rows`` must - already be ordered by ``id`` (insertion order) and filtered to the - desired session set / active state by the caller. + Returns ``(skip, exact_clone_key)``. Watermark rotation column-clones the + concurrent tail into the child after the summary, so the copies need not be + adjacent: an exact ``(timestamp, canonical content)`` clone index is checked + first, then the adjacent-duplicate heuristic. A rotated child carrier wins over + the simpler ancestor copy (it owns the durable row id and the summary scaffold). + """ + canonical_content, _is_composite = self._canonical_replayed_user_content(msg) + exact_clone_key = self._exact_replayed_user_clone_key(msg.get("timestamp"), canonical_content) + previous_exact = exact_user_clones.get(exact_clone_key) if exact_clone_key is not None else None + duplicate = None + if previous_exact is not None: + previous_index = next( + (index for index, candidate in enumerate(messages) if candidate is previous_exact), None, + ) + if previous_index is not None: + duplicate = (previous_index, True) + if duplicate is None: + duplicate = self._find_duplicate_replayed_user_message(messages, msg) + if duplicate is not None: + duplicate_index, prefer_current = duplicate + if not prefer_current: + return True, exact_clone_key + messages.pop(duplicate_index) + return False, exact_clone_key + + def _rows_to_conversation( + self, rows, *, session_id: str, include_ancestors: bool, repair_alternation: bool, + include_row_ids: bool = False, include_summary_markers: bool = False, + ) -> List[Dict[str, Any]]: + """Decode fetched message rows (ordered by id, pre-filtered) into OpenAI format. + + Every dict is stamped ``_DB_PERSISTED_MARKER_KEY`` at the source (born durable) + so an identity-losing handoff never re-appends the whole transcript on flush. + ``_row_id`` is opt-in (gateway reactions). ``api_content`` is returned VERBATIM + (no sanitize/strip): the replay path substitutes it to keep the provider prompt + cache byte-stable. Reasoning fields are restored on assistant rows only. """ from hermes_state import _strip_background_review_harness, _strip_stale_tool_call_markers messages = [] - # Watermark rotation column-clones concurrent tail rows into the child - # after the new summary, so the copies need not be adjacent. Index the - # exact durable clone identity while decoding instead of rescanning the - # whole accumulated lineage for every user row. exact_user_clones: Dict[Tuple[Any, str], Dict[str, Any]] = {} for row in rows: content = self._decode_content(row["content"]) if row["role"] in {"user", "assistant"} and isinstance(content, str): content = sanitize_context(content).strip() msg = {"role": row["role"], "content": content} - # Born durable (#92231): this dict is materialized FROM a durable - # row, so stamp the persistence marker at the source instead of - # relying on every restore caller to thread the loaded list back - # through a flush as ``conversation_history=`` — any - # identity-losing handoff (compression's durable-snapshot - # adoption, incremental persists with no history arg) would - # otherwise re-append the ENTIRE transcript on flush. - # Underscore-prefixed like ``_row_id``: every transport strips it - # before the wire, and compression's assembly copies deliberately - # strip it so rotated child handoffs still flush (see - # _fresh_compaction_message_copy). + # Underscore-prefixed like ``_row_id``: every transport strips it before the + # wire, and compression's assembly copies deliberately strip it so rotated + # child handoffs still flush (see _fresh_compaction_message_copy). msg[_DB_PERSISTED_MARKER_KEY] = True - # Durable per-message identity for surfaces that need to address a - # specific row later (desktop reactions). OPT-IN: only the gateway - # asks for it — every other consumer (ACP restore, export, - # inspection) gets the transcript in its historical shape. - # Underscore-prefixed so every transport's convert_messages() - # strips it before the wire. if include_row_ids and row["id"] is not None: msg["_row_id"] = row["id"] - # api_content is the byte-fidelity sidecar: the exact string sent - # to the API when it differed from the clean content. Returned - # VERBATIM — no sanitize_context, no strip — because the replay - # path substitutes it for content to keep the provider prompt - # cache prefix byte-stable across turns. Cleaning it here would - # re-introduce the divergence it exists to remove. - if row["api_content"]: - msg["api_content"] = row["api_content"] - if row["display_kind"]: - msg["display_kind"] = row["display_kind"] + for col in ("api_content", "display_kind"): + if row[col]: + msg[col] = row[col] if row["display_metadata"]: decoded = self._decode_display_metadata(row["display_metadata"]) if decoded is not None: msg["display_metadata"] = decoded if include_summary_markers and row["_compressed_summary"]: msg["_compressed_summary"] = True - if row["timestamp"]: - msg["timestamp"] = row["timestamp"] - if row["tool_call_id"]: - msg["tool_call_id"] = row["tool_call_id"] - if row["tool_name"]: - msg["tool_name"] = row["tool_name"] - if row["effect_disposition"]: - msg["effect_disposition"] = row["effect_disposition"] + for col in ("timestamp", "tool_call_id", "tool_name", "effect_disposition"): + if row[col]: + msg[col] = row[col] if row["tool_calls"]: - try: - msg["tool_calls"] = json.loads(row["tool_calls"]) - except (json.JSONDecodeError, TypeError): - logger.warning("Failed to deserialize tool_calls in conversation replay, falling back to []") - msg["tool_calls"] = [] - # Surface the platform-side message id (e.g. yuanbao msg_id, - # telegram update_id) so platform-specific flows like recall - # can match by external identifier instead of having to fall - # back to content-match heuristics. Exposed as ``message_id`` - # for backward compatibility with the JSONL transcript shape. + msg["tool_calls"] = _json_or( + row["tool_calls"], [], + "Failed to deserialize tool_calls in conversation replay, falling back to []", + ) + # Platform-side id exposed as ``message_id`` (JSONL transcript compat). if row["platform_message_id"]: msg["message_id"] = row["platform_message_id"] if row["observed"]: msg["observed"] = True - # Restore reasoning fields on assistant messages so providers - # that replay reasoning (OpenRouter, OpenAI, Nous) receive - # coherent multi-turn reasoning context. if row["role"] == "assistant": - if row["finish_reason"]: - msg["finish_reason"] = row["finish_reason"] - if row["reasoning"]: - msg["reasoning"] = row["reasoning"] + for col in ("finish_reason", "reasoning"): + if row[col]: + msg[col] = row[col] if row["reasoning_content"] is not None: msg["reasoning_content"] = row["reasoning_content"] - if row["reasoning_details"]: - try: - msg["reasoning_details"] = json.loads(row["reasoning_details"]) - except (json.JSONDecodeError, TypeError): - logger.warning("Failed to deserialize reasoning_details, falling back to None") - msg["reasoning_details"] = None - if row["codex_reasoning_items"]: - try: - msg["codex_reasoning_items"] = json.loads(row["codex_reasoning_items"]) - except (json.JSONDecodeError, TypeError): - logger.warning("Failed to deserialize codex_reasoning_items, falling back to None") - msg["codex_reasoning_items"] = None - if row["codex_message_items"]: - try: - msg["codex_message_items"] = json.loads(row["codex_message_items"]) - except (json.JSONDecodeError, TypeError): - logger.warning("Failed to deserialize codex_message_items, falling back to None") - msg["codex_message_items"] = None + for col in ("reasoning_details", "codex_reasoning_items", "codex_message_items"): + if row[col]: + msg[col] = _json_or( + row[col], None, f"Failed to deserialize {col}, falling back to None", + ) + exact_clone_key = None if include_ancestors: - canonical_content, _is_composite = ( - self._canonical_replayed_user_content(msg) - ) - exact_clone_key = self._exact_replayed_user_clone_key( - msg.get("timestamp"), canonical_content - ) - previous_exact = ( - exact_user_clones.get(exact_clone_key) - if exact_clone_key is not None - else None - ) - duplicate = None - if previous_exact is not None: - previous_index = next( - ( - index - for index, candidate in enumerate(messages) - if candidate is previous_exact - ), - None, - ) - if previous_index is not None: - duplicate = (previous_index, True) - if duplicate is None: - duplicate = self._find_duplicate_replayed_user_message( - messages, msg - ) - if duplicate is not None: - duplicate_index, prefer_current = duplicate - if prefer_current: - # A rotated compression child can carry the same live - # ask as the parent row plus the only surviving summary - # scaffold. Keep the child carrier (and its durable row - # id), not the simpler ancestor copy. - messages.pop(duplicate_index) - else: - continue + skip, exact_clone_key = self._dedupe_replayed_user(messages, msg, exact_user_clones) + if skip: + continue messages.append(msg) if include_ancestors and exact_clone_key is not None: exact_user_clones[exact_clone_key] = msg - # DEFENSE-IN-DEPTH against background-review session pollution: a forked - # skill/memory review that (in older builds, before the _persist_disabled - # fix) shared the parent's session_id wrote its harness turn into this - # real session. The harness is a user/system message instructing the - # agent to "Review the conversation above and update the skill library / - # save to memory" under a hard tool restriction; re-loading it as live - # history makes the agent adopt the curator role and refuse the user's - # actual task. Strip any such harness message AND the curator-mode - # assistant reply immediately following it, so a polluted session - # resumes clean even if stray rows exist. + # Defense-in-depth: strip a background-review harness turn (older builds shared + # the parent's session_id) plus its curator reply, and bare tool-call marker + # content ("[memory]") persisted as an answer before the loop fix. messages = _strip_background_review_harness(messages) - # DEFENSE-IN-DEPTH against #78148: before that fix, a bare tool-call - # marker (e.g. "[memory]") could get cached as a fallback and - # persisted as if it were the model's real answer. Sessions written - # before the fix can still carry those rows — clear the stray - # content on load so replaying history doesn't re-teach the model - # to keep emitting the marker. No-op for unaffected sessions. messages = _strip_stale_tool_call_markers(messages) if repair_alternation and messages: - # Lazy import: hermes_state already depends on agent.* (see - # sanitize_context above), but keep this optional path from - # widening the import surface at module load. from agent.agent_runtime_helpers import repair_message_sequence repaired = repair_message_sequence(None, messages) @@ -1877,145 +1229,62 @@ class SessionMessagesMixin: ) return messages - def get_resume_conversations( - self, session_id: str - ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: - """Return ``(model_history, display_history)`` for a session resume in ONE SELECT. + def get_resume_conversations(self, session_id: str) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: + """``(model_history, display_history)`` for a session resume from ONE SELECT. - ``session.resume`` needs two projections of the same lineage: - - - ``model_history`` — the tip session's active rows, alternation-repaired - (the live-replay working conversation). Equivalent to - ``get_messages_as_conversation(session_id, repair_alternation=True)``. - - ``display_history`` — the full compression lineage (ancestors → tip), - verbatim, with replayed-user dedup. Explicit ``/branch`` sessions are - excluded from this lineage because their own rows already contain the - copied transcript; including the live parent's rows would let messages - written to the original after the fork leak into the branch. - - The display projection also includes rows preserved by IN-PLACE - compaction (``active=0, compacted=1``), deduped by - :meth:`_dedupe_display_generations`. Without them a compacted - conversation resumes showing only its summary plus the carried-forward - tail — the user's own turns read as deleted even though every row is - still on disk, and the REST transcript read (which has always included - them) disagreed with this one about the same session (#92080). - - The display fetch already reads a superset of the model fetch (the tip - rows are part of the lineage), so serving both from one lineage SELECT - halves the resume's DB work versus two separate calls, with byte-identical - output (see test_get_resume_conversations_matches_separate_reads). + ``model_history``: the tip's active rows, alternation-repaired, with the summary + marker kept for pre-compress checkpointing. ``display_history``: the full + compression lineage (``/branch`` sessions are their own lineage) verbatim, with + compaction-archived rows included and deduped, plus replayed-user dedup. Byte- + identical to the separate reads (test_get_resume_conversations_matches_separate_reads). """ session_ids = self._resume_lineage_ids(session_id) - with self._read_ctx() as conn: - placeholders = ",".join("?" for _ in session_ids) - rows = conn.execute( - f"SELECT session_id, {self._CONVERSATION_ROW_COLUMNS} " - f"FROM messages WHERE session_id IN ({placeholders}) " - # Compaction-archived rows (active=0, compacted=1) are display - # history; Undo/Rewind rows (active=0, compacted=0) are not. - "AND (active = 1 OR compacted = 1) " - # ORDER BY id (insertion order) — see get_messages_as_conversation - # for why timestamp ordering is unsafe. - "ORDER BY id", - tuple(session_ids), - ).fetchall() - - # Tip rows are exactly the model-fed set (get_messages_as_conversation - # with session_ids=[session_id]); filtering the lineage fetch preserves - # their relative id order. The model projection stays active-only — it - # is the compressed working context and must not regrow the history - # compaction just summarized away. + rows = self._fetch_conversation_rows(session_ids, _DISPLAY_ACTIVE_CLAUSE, with_session_id=True) + # The model projection stays active-only: it is the compressed working context. tip_rows = [r for r in rows if r["session_id"] == session_id and r["active"]] model_history = self._rows_to_conversation( - tip_rows, - session_id=session_id, - include_ancestors=False, - repair_alternation=True, - include_row_ids=True, - # Pre-compress checkpointing: the resumed model history must keep - # the summary marker so checkpoint providers can exclude derivative - # summaries after a process restart (marker survives restart). - include_summary_markers=True, + tip_rows, session_id=session_id, include_ancestors=False, repair_alternation=True, + include_row_ids=True, include_summary_markers=True, ) display_history = self._rows_to_conversation( - self._dedupe_display_generations(rows), - session_id=session_id, - include_ancestors=True, - repair_alternation=False, - include_row_ids=True, + self._dedupe_display_generations(rows), session_id=session_id, + include_ancestors=True, repair_alternation=False, include_row_ids=True, ) return model_history, display_history def _resume_lineage_ids(self, session_id: str) -> List[str]: - """Session ids a full (display) resume materializes for *session_id*. - - Compression continuations need their ended ancestors' rows for the - display transcript; an explicit ``/branch`` copy already owns its - transcript, so its lineage is itself alone. This is the ONE definition - shared by the resume readers (``get_resume_conversations``, - ``get_ancestor_display_prefix``) and the resume guard - (``assert_resume_safe`` / ``get_resume_message_count``) — the guard must - count exactly the rows a resume would load, never a superset. - """ + """Session ids a full (display) resume materializes: the compression lineage, + or the session alone for an explicit ``/branch`` copy. Shared by the resume + readers and the resume guard so the guard counts exactly what a resume loads.""" if self._is_explicit_branch_session(session_id): return [session_id] return self._session_lineage_root_to_tip(session_id) - def get_resume_message_count( - self, session_id: str, *, tip_only: bool = False - ) -> int: - """Count the rows that a resume would materialize. + def _resume_count_scope(self, session_id: str, tip_only: bool) -> Tuple[List[str], str]: + """``tip_only``: the tip's ACTIVE rows (model restore); else the full-lineage + DISPLAY set (active + compaction-archived) that get_resume_conversations loads.""" + if tip_only: + return [session_id], "active = 1" + return self._resume_lineage_ids(session_id), "(active = 1 OR compacted = 1)" - ``tip_only=True`` counts the tip segment's ACTIVE rows — the set a - model-history restore loads (``get_messages_as_conversation`` without - ancestors, or the deferred Desktop resume that pages the display - transcript over REST and never materializes the ancestor prefix in - memory). - - Otherwise this counts the full-lineage DISPLAY set — active rows plus - the compaction-archived rows ``get_resume_conversations`` now loads - for the transcript. Counting only active rows here would let a - heavily-compacted conversation pass a limit sized for a handful of - live rows and then materialize tens of thousands. - """ - session_ids = [session_id] if tip_only else self._resume_lineage_ids(session_id) - active_clause = "active = 1" if tip_only else "(active = 1 OR compacted = 1)" - placeholders = ",".join("?" for _ in session_ids) + def get_resume_message_count(self, session_id: str, *, tip_only: bool = False) -> int: + """Count the rows a resume would materialize (see ``_resume_count_scope``).""" + session_ids, active_clause = self._resume_count_scope(session_id, tip_only) row = self._read_one( f"SELECT COUNT(*) FROM messages " - f"WHERE session_id IN ({placeholders}) AND {active_clause}", + f"WHERE session_id IN ({_placeholders(session_ids)}) AND {active_clause}", tuple(session_ids), ) return int(row[0] if row else 0) - def assert_resume_safe( - self, - session_id: str, - max_messages: Optional[int] = None, - *, - tip_only: bool = False, - ) -> int: - """Return resume row count or reject a transcript too large to load. + def assert_resume_safe(self, session_id: str, max_messages: Optional[int] = None, *, tip_only: bool = False) -> int: + """Return the resume row count or raise ``SessionResumeTooLargeError``. - ``max_messages=None`` resolves the limit from config - (``sessions.max_resume_messages``); 0 disables the guard and returns - the (bounded) count without raising. - - ``tip_only=True`` bounds only the tip segment's ACTIVE rows, for - callers that never materialize the ancestor lineage or the - compaction archive in memory (tip-only model restore, deferred - Desktop resume whose display history is REST-paginated). A - heavily-compressed conversation — 85 compaction segments and ~29k - lineage rows behind a ~700-row tip — is exactly the shape compression - is supposed to produce; counting its whole lineage against a limit - sized for in-memory materialization rejected the healthiest sessions - (Desktop Bot Chat stuck on "Waking up…" with code 4130) while the - process would only ever have held the tip. - - The full (non-``tip_only``) bound counts the DISPLAY set — active plus - compaction-archived rows — because that is what - ``get_resume_conversations`` materializes for the transcript. + ``max_messages=None`` reads ``sessions.max_resume_messages``; 0 disables the + guard and returns 0 without counting. ``tip_only`` bounds only the tip's active + rows, for callers that never materialize the lineage in memory — a heavily + compressed conversation (~29k lineage rows behind a ~700-row tip) is exactly + what compression should produce and must not be rejected. """ from hermes_state import SessionResumeTooLargeError, resolved_max_resume_messages if max_messages is None: @@ -2023,17 +1292,11 @@ class SessionMessagesMixin: if max_messages < 0: raise ValueError("max_messages must be non-negative") if max_messages == 0: - # Guard disabled by config — skip counting entirely. Every live - # caller invokes this for its raise side effect and ignores the - # return value, and an unbounded lineage COUNT here would do the - # exact pathological work the disable exists to avoid. return 0 - session_ids = [session_id] if tip_only else self._resume_lineage_ids(session_id) - active_clause = "active = 1" if tip_only else "(active = 1 OR compacted = 1)" - placeholders = ",".join("?" for _ in session_ids) + session_ids, active_clause = self._resume_count_scope(session_id, tip_only) row = self._read_one( "SELECT COUNT(*) FROM (" - f"SELECT 1 FROM messages WHERE session_id IN ({placeholders}) " + f"SELECT 1 FROM messages WHERE session_id IN ({_placeholders(session_ids)}) " f"AND {active_clause} LIMIT ?" ")", (*session_ids, max_messages + 1), @@ -2041,117 +1304,66 @@ class SessionMessagesMixin: message_count = int(row[0] if row else 0) if message_count > max_messages: raise SessionResumeTooLargeError( - message_count, - max_messages, + message_count, max_messages, scope="in its tip segment" if tip_only else "across its lineage", ) return message_count def get_ancestor_display_prefix(self, session_id: str) -> List[Dict[str, Any]]: - """Return the ancestor-only display messages for a session lineage. + """Ancestor-only display messages of a lineage (rows with ``session_id !=`` tip). - These are messages from parent/grandparent sessions (compression - ancestors) that appear in the display transcript but NOT in the - tip session's model-fed history. Used by ``session.resume`` to - build the ``display_history_prefix`` that ``_live_session_payload`` - prepends to the live model history. - - Previously the prefix was calculated as - ``display_history[:len(display) - len(raw)]``, but that overcounts - when ``repair_message_sequence`` removes messages from the MIDDLE - of the tip history (e.g. verification candidates collapsed by the - consecutive-assistant merge) — the length difference includes both - ancestor messages AND repair-removed tip messages, but the slice - only captures the first N display messages (which are tip messages - when there are no ancestors), causing duplication. This method - returns ONLY the genuine ancestor messages, identified by - ``session_id != tip_session_id``. (#65919) + ``session.resume`` prepends this to the live model history. Identifying + ancestors by row origin (not ``display[:len(display) - len(model)]``) avoids + overcounting when alternation repair removes tip messages from the middle. """ session_ids = self._resume_lineage_ids(session_id) if len(session_ids) <= 1: return [] - with self._read_ctx() as conn: - placeholders = ",".join("?" for _ in session_ids) - rows = conn.execute( - f"SELECT session_id, {self._CONVERSATION_ROW_COLUMNS} " - f"FROM messages WHERE session_id IN ({placeholders}) " - # Display read: compaction-archived rows included, Undo/Rewind - # rows excluded (see get_resume_conversations). - "AND (active = 1 OR compacted = 1) " - "ORDER BY id", - tuple(session_ids), - ).fetchall() - rows = self._dedupe_display_generations(rows) - ancestor_ids = { - int(row["id"]) - for row in rows - if row["session_id"] != session_id and row["id"] is not None - } + rows = self._dedupe_display_generations( + self._fetch_conversation_rows(session_ids, _DISPLAY_ACTIVE_CLAUSE, with_session_id=True) + ) + ancestor_ids = {int(row["id"]) for row in rows if row["session_id"] != session_id and row["id"] is not None} if not ancestor_ids: return [] lineage = self._rows_to_conversation( - rows, - session_id=session_id, - include_ancestors=True, - repair_alternation=False, - include_row_ids=True, + rows, session_id=session_id, include_ancestors=True, repair_alternation=False, include_row_ids=True, ) prefix: List[Dict[str, Any]] = [] for message in lineage: - if message.get("_row_id") not in ancestor_ids: - continue - projected = message.copy() - projected.pop("_row_id", None) - prefix.append(projected) + if message.get("_row_id") in ancestor_ids: + projected = message.copy() + projected.pop("_row_id", None) + prefix.append(projected) return prefix def get_conversation_root(self, session_id: str) -> str: - """Return the ROOT id of *session_id*'s lineage chain. - - The root is the stable "conversation id": context compression - rotates ``session_id`` to a new segment linked via - ``parent_session_id``, and delegate subagents hang off their - parent the same way. Walking to the root gives every segment of - one user-facing conversation (and its delegation tree) a single - identifier — used for Nous Portal ``conversation=`` usage tagging. - Returns *session_id* unchanged when it has no recorded parent. - """ + """ROOT id of *session_id*'s lineage — the stable conversation id across + compression segments and delegate subagents (Nous Portal usage tagging). + Unchanged when there is no recorded parent.""" chain = self._session_lineage_root_to_tip(session_id) - return (chain[0] if chain and chain[0] else session_id) + return chain[0] if chain and chain[0] else session_id @staticmethod - def _canonical_replayed_user_content( - msg: Dict[str, Any], - ) -> Tuple[Any, bool]: + def _canonical_replayed_user_content(msg: Dict[str, Any]) -> Tuple[Any, bool]: """Return canonical live content and whether *msg* is composite.""" if msg.get("role") != "user": return None, False - from agent.context_compressor import split_user_originated_turn handoff, live_view = split_user_originated_turn(msg) is_composite = handoff is not None and live_view is not None return ( - live_view.get("content") - if is_composite and live_view is not None - else msg.get("content"), + live_view.get("content") if is_composite and live_view is not None else msg.get("content"), is_composite, ) @staticmethod - def _exact_replayed_user_clone_key( - timestamp: Any, content: Any - ) -> Optional[Tuple[Any, str]]: + def _exact_replayed_user_clone_key(timestamp: Any, content: Any) -> Optional[Tuple[Any, str]]: """Return a hashable key for a column-exact rotation clone.""" if timestamp is None or content in (None, "", []): return None try: - encoded = json.dumps( - content, - ensure_ascii=False, - sort_keys=True, - separators=(",", ":"), - ) + encoded = json.dumps(content, ensure_ascii=False, sort_keys=True, separators=(",", ":")) except (TypeError, ValueError): return None return timestamp, encoded @@ -2162,48 +1374,32 @@ class SessionMessagesMixin: ) -> Optional[Tuple[int, bool]]: """Return an adjacent replay duplicate and whether *msg* must win. - Compression rotation may persist the current ask once in the parent - and again inside a composite child carrier. Compare the canonical live - payload for that carrier, while retaining the historical exact-string - dedupe for ordinary replayed users. The child carrier wins because it - owns both the current durable row identity and the retained scaffold. + Rotation may persist the current ask once in the parent and again inside a + composite child carrier; compare the canonical live payload for carriers while + keeping the exact-string dedupe for ordinary replayed users. The child carrier + wins (it owns the durable row id and the retained scaffold). """ from hermes_state import SessionDB if msg.get("role") != "user": return None - content, prefer_current = SessionDB._canonical_replayed_user_content(msg) if content in (None, "", []): return None - for index in range(len(messages) - 1, -1, -1): prev = messages[index] if prev.get("role") == "user": - prev_content, prev_is_composite = ( - SessionDB._canonical_replayed_user_content(prev) - ) - if prev_content == content and ( - prefer_current - or prev_is_composite - or isinstance(content, str) - ): + prev_content, prev_is_composite = SessionDB._canonical_replayed_user_content(prev) + if prev_content == content and (prefer_current or prev_is_composite or isinstance(content, str)): return index, prefer_current if prev.get("role") == "assistant" and (prev.get("content") or prev.get("tool_calls")): return None return None def get_active_message_ids(self, session_id: str) -> List[int]: - """Return the ordered physical ids pinned by rewind CAS checks. - - Conversation projections intentionally omit legacy background-review - harness rows. Destructive rewinds must nevertheless pin every active - physical row so the caller snapshot matches the transaction-local - comparison in :meth:`rewind_to_message`. - """ + """Ordered physical active ids pinned by rewind CAS checks (includes legacy + harness rows that conversation projections omit).""" rows = self._read_all( - "SELECT id FROM messages " - "WHERE session_id = ? AND active = 1 ORDER BY id", - (session_id,), + "SELECT id FROM messages WHERE session_id = ? AND active = 1 ORDER BY id", (session_id,), ) return [int(row[0]) for row in rows] @@ -2211,9 +1407,7 @@ class SessionMessagesMixin: def _active_transcript_counts(conn, session_id: str) -> tuple[int, int]: """Return active message/tool-call counts inside the caller's txn.""" rows = conn.execute( - "SELECT tool_calls FROM messages " - "WHERE session_id = ? AND active = 1", - (session_id,), + "SELECT tool_calls FROM messages WHERE session_id = ? AND active = 1", (session_id,), ).fetchall() tool_call_count = 0 for row in rows: @@ -2230,176 +1424,105 @@ class SessionMessagesMixin: tool_call_count += 1 return len(rows), tool_call_count + def _split_rewind_target(self, target_row: Dict[str, Any], expected_target_content: Any, preserve_compaction_handoff: bool): + """Validate an active rewind target and return its handoff scaffold (or None). + + Raises ``ValueError`` for an inactive / non-user-originated target or a missing + composite carrier, ``RuntimeError`` when the canonical live payload no longer + matches *expected_target_content*. + """ + if not target_row.get("active"): + raise ValueError("rewind target is not active") + from agent.context_compressor import split_user_originated_turn + + split_target = target_row.copy() + split_target["content"] = self._decode_content(split_target.get("content")) + split_target["display_metadata"] = self._decode_display_metadata(split_target.get("display_metadata")) + handoff, live_view = split_user_originated_turn(split_target) + if live_view is None: + raise ValueError("rewind target is not a user-originated turn") + live_content = live_view.get("content") + if isinstance(live_content, str): + live_content = sanitize_context(live_content).strip() + if expected_target_content is not None and live_content != expected_target_content: + raise RuntimeError("rewind target changed before it could be persisted") + if preserve_compaction_handoff and handoff is None: + raise ValueError("preserve_compaction_handoff requires an active composite carrier") + return handoff if preserve_compaction_handoff else None + def rewind_to_message( - self, - session_id: str, - target_message_id: int, - *, - preserve_compaction_handoff: bool = False, - expected_active_ids: Optional[List[int]] = None, - expected_target_content: Any = None, + self, session_id: str, target_message_id: int, *, preserve_compaction_handoff: bool = False, + expected_active_ids: Optional[List[int]] = None, expected_target_content: Any = None, ) -> Dict[str, Any]: - """Soft-delete all messages with id >= ``target_message_id`` in *session_id*. + """Soft-delete (``active=0``) every message with id >= *target_message_id*. - The target message itself becomes inactive as well so the caller - can pre-fill it as the next user prompt without it appearing - twice in the replayed transcript. Rewound rows are kept on - disk with ``active=0`` for audit / forensic inspection — use - :meth:`get_messages` with ``include_inactive=True`` to see them. + The target itself goes inactive so the caller can pre-fill it as the next + prompt. Returns ``{"rewound_count", "target_message", "new_head_id"}`` (plus + ``replacement_message_id`` with ``preserve_compaction_handoff``, which archives a + composite summary carrier and inserts its hidden handoff scaffold as the new + head in the same txn). Raises ``ValueError`` when the target is missing or not a + ``user`` row. - Returns a dict:: - - { - "rewound_count": int, # number of rows newly flipped to active=0 - "target_message": dict, # full row dict of the target - "new_head_id": int|None # id of the last still-active row, or None - } - - Raises ``ValueError`` if the target message does not exist in - *session_id* or if its role is not ``"user"``. With - ``preserve_compaction_handoff=True``, a composite summary carrier is - split inside the same write transaction: its original row is archived - and its canonical hidden handoff scaffold is inserted as the new head. - That opt-in result also contains ``replacement_message_id``. - - ``expected_active_ids`` optionally pins the ordered active row set. - ``expected_target_content`` additionally pins the selected canonical - live-user payload. Both checks run inside the write transaction before - any row or counter mutation. Presentation-only metadata changes (for - example Desktop reactions) deliberately do not invalidate a rewind. - A live cross-process turn lease always refuses the rewind; expired or - provably dead holders are reclaimed inside the mutation transaction. - - Always increments ``sessions.rewind_count`` — even when the - target is already inactive — so the counter accurately reflects - the number of rewind operations performed against the session. - Idempotent on the ``active`` flag: re-rewinding past the same - target is a no-op on row state but still bumps the counter. + ``expected_active_ids`` / ``expected_target_content`` pin the active row set and + the canonical live payload inside the txn before any mutation (presentation-only + metadata changes do not invalidate a rewind). A live cross-process turn lease + refuses the rewind; expired/dead holders are reclaimed. ``rewind_count`` always + increments, even when the target was already inactive. """ def _do(conn): - # Rewind changes the active transcript and must honor the same - # compression/closed-parent and cross-process turn guards as - # append writers. self._check_transcript_write_guards( - conn, - session_id, - None, - reject_active_turn_lease=True, - reject_active_compression_lock=True, + conn, session_id, None, reject_active_turn_lease=True, reject_active_compression_lock=True, ) - if expected_active_ids is not None: active_rows = conn.execute( - "SELECT id FROM messages " - "WHERE session_id = ? AND active = 1 ORDER BY id", - (session_id,), + "SELECT id FROM messages WHERE session_id = ? AND active = 1 ORDER BY id", (session_id,), ).fetchall() - active_ids = [int(active_row[0]) for active_row in active_rows] - if active_ids != expected_active_ids: - raise RuntimeError( - "active transcript changed before the rewind could be persisted" - ) - + if [int(active_row[0]) for active_row in active_rows] != expected_active_ids: + raise RuntimeError("active transcript changed before the rewind could be persisted") row = conn.execute( - "SELECT * FROM messages WHERE id = ? AND session_id = ?", - (target_message_id, session_id), + "SELECT * FROM messages WHERE id = ? AND session_id = ?", (target_message_id, session_id), ).fetchone() if row is None: - raise ValueError( - f"message {target_message_id} not found in session {session_id}" - ) + raise ValueError(f"message {target_message_id} not found in session {session_id}") target_row = dict(row) if target_row.get("role") != "user": raise ValueError( f"rewind target must be a 'user' message (got role=" f"{target_row.get('role')!r}, id={target_message_id})" ) - replacement_message_id: Optional[int] = None replacement: Optional[Dict[str, Any]] = None if preserve_compaction_handoff or expected_target_content is not None: - if not target_row.get("active"): - raise ValueError("rewind target is not active") - from agent.context_compressor import split_user_originated_turn - - split_target = target_row.copy() - split_target["content"] = self._decode_content( - split_target.get("content") - ) - split_target["display_metadata"] = self._decode_display_metadata( - split_target.get("display_metadata") - ) - handoff, live_view = split_user_originated_turn(split_target) - if live_view is None: - raise ValueError("rewind target is not a user-originated turn") - live_content = live_view.get("content") - if isinstance(live_content, str): - live_content = sanitize_context(live_content).strip() - if ( - expected_target_content is not None - and live_content != expected_target_content - ): - raise RuntimeError( - "rewind target changed before it could be persisted" - ) - if preserve_compaction_handoff and handoff is None: - raise ValueError( - "preserve_compaction_handoff requires an active composite carrier" - ) - replacement = handoff if preserve_compaction_handoff else None - + replacement = self._split_rewind_target(target_row, expected_target_content, preserve_compaction_handoff) cursor = conn.execute( - "SELECT id FROM messages " - "WHERE session_id = ? AND id >= ? AND active = 1", + "SELECT id FROM messages WHERE session_id = ? AND id >= ? AND active = 1", (session_id, target_message_id), ) ids = [r[0] for r in cursor.fetchall()] if ids: - placeholders = ",".join("?" for _ in ids) - conn.execute( - f"UPDATE messages SET active = 0 WHERE id IN ({placeholders})", - ids, - ) + conn.execute(f"UPDATE messages SET active = 0 WHERE id IN ({_placeholders(ids)})", ids) if replacement is not None: self._insert_message_rows(conn, session_id, [replacement]) - inserted = conn.execute("SELECT last_insert_rowid()").fetchone() - replacement_message_id = int(inserted[0]) + replacement_message_id = int(conn.execute("SELECT last_insert_rowid()").fetchone()[0]) conn.execute( - "UPDATE sessions SET rewind_count = COALESCE(rewind_count, 0) + 1 " - "WHERE id = ?", - (session_id,), - ) - message_count, tool_call_count = self._active_transcript_counts( - conn, session_id + "UPDATE sessions SET rewind_count = COALESCE(rewind_count, 0) + 1 WHERE id = ?", (session_id,), ) + message_count, tool_call_count = self._active_transcript_counts(conn, session_id) conn.execute( - "UPDATE sessions SET message_count = ?, tool_call_count = ? " - "WHERE id = ?", + "UPDATE sessions SET message_count = ?, tool_call_count = ? WHERE id = ?", (message_count, tool_call_count, session_id), ) head_row = conn.execute( - "SELECT MAX(id) FROM messages WHERE session_id = ? AND active = 1", - (session_id,), + "SELECT MAX(id) FROM messages WHERE session_id = ? AND active = 1", (session_id,), ).fetchone() - new_head_id = ( - head_row[0] if head_row and head_row[0] is not None else None - ) + new_head_id = head_row[0] if head_row and head_row[0] is not None else None return target_row, ids, new_head_id, replacement_message_id - target_row, rewound, new_head_id, replacement_message_id = ( - self._execute_write(_do) - ) - - # Decode content for callers (prefill the prompt buffer) without a - # second fallible database operation after the transaction commits. + target_row, rewound, new_head_id, replacement_message_id = self._execute_write(_do) + # Decode for the prompt-buffer prefill without a second fallible DB operation. target_row["content"] = self._decode_content(target_row.get("content")) - - result = { - "rewound_count": len(rewound), - "target_message": target_row, - "new_head_id": new_head_id, - } + result = {"rewound_count": len(rewound), "target_message": target_row, "new_head_id": new_head_id} if preserve_compaction_handoff: result["replacement_message_id"] = replacement_message_id return result @@ -2408,40 +1531,27 @@ class SessionMessagesMixin: """Count messages, optionally for a specific session.""" with self._read_ctx() as conn: if session_id: - cursor = conn.execute( - "SELECT COUNT(*) FROM messages WHERE session_id = ?", (session_id,) - ) + cursor = conn.execute("SELECT COUNT(*) FROM messages WHERE session_id = ?", (session_id,)) else: cursor = conn.execute("SELECT COUNT(*) FROM messages") return cursor.fetchone()[0] - def has_platform_message_id( - self, session_id: str, platform_message_id: str - ) -> bool: - """Check if a message with the given platform_message_id exists. - - Uses the idx_messages_platform_msg_id partial index for efficient - lookup. Used by the gateway's transient-failure dedupe guard (#47237) - to skip re-persisting a user message that was already saved on a - prior retry of the same inbound platform message. - """ + def has_platform_message_id(self, session_id: str, platform_message_id: str) -> bool: + """True when a message with *platform_message_id* exists (uses the + idx_messages_platform_msg_id partial index; the gateway's transient-failure + dedupe guard).""" return self._read_one( - "SELECT 1 FROM messages " - "WHERE session_id = ? AND platform_message_id = ? LIMIT 1", + "SELECT 1 FROM messages WHERE session_id = ? AND platform_message_id = ? LIMIT 1", (session_id, platform_message_id), ) is not None def _is_explicit_fork_child_row(self, session: Dict[str, Any]) -> bool: - """True when ``session`` is a branch, delegate, or tool child of its parent. + """True when *session* is a branch, delegate, or tool child of its parent. - Markers only count as a fork when they point at ``parent_session_id``. - Compression copies ``model_config`` onto the continuation - (``publish_compression_child`` callers pass - ``agent._session_init_model_config``), so a delegate's continuation - carries ``_delegate_from=``. Presence-only - matching would treat that real continuation as a fork — the same - misclassification ``_NON_CONTINUATION_CHILD_FILTER_SQL`` already - avoids by binding both markers to the queried parent. + Markers only count when they point at ``parent_session_id``: compression copies + ``model_config`` onto the continuation, so a delegate's continuation carries + ``_delegate_from=`` and presence-only matching would + misclassify it (same binding as ``_NON_CONTINUATION_CHILD_FILTER_SQL``). """ if session.get("source") == "tool": return True @@ -2462,63 +1572,31 @@ class SessionMessagesMixin: return branched is not None or delegated is not None def is_explicit_fork_child(self, session_id: str) -> bool: - """True when ``session_id`` is a /branch, delegate, or tool child row. - - Read-only public view of :meth:`_is_explicit_fork_child_row` for - callers that must respect the fork boundary without re-implementing - its marker rules (``agent/prompt_cache_scope.py`` keeps a declared - conversation key from crossing it). A missing row is not a fork. - """ + """Public read-only view of :meth:`_is_explicit_fork_child_row`; a missing row + is not a fork. ``agent/prompt_cache_scope.py`` uses it to keep a declared + conversation key from crossing the fork boundary.""" session = self.get_session(session_id) return bool(session and self._is_explicit_fork_child_row(session)) - def latest_conversation_boundary( - self, session_key: str, source: str - ) -> Optional[int]: - """How many conversation boundaries this routing peer has crossed. + def latest_conversation_boundary(self, session_key: str, source: str) -> Optional[int]: + """How many conversation boundaries (``_RESET_END_REASONS`` ends) this routing + peer has crossed, or ``None`` when never reset. - A boundary is a row this peer ended at an intentional conversation - break — the ``_RESET_END_REASONS`` set (``/new``, ``/switch``, idle, - daily, suspended, resume_pending_expired). That is the same fence - :meth:`find_latest_gateway_session_for_peer` refuses to reach behind, - so the two agree on where one conversation stops and the next begins - and cannot drift. - - The peer is ``(session_key, source)``, the SAME identity tuple recovery - uses — never the key alone. ``X-Hermes-Session-Key`` accepts any - authenticated caller-supplied string, so an API conversation may - legally carry the same key as a Telegram row in one database; keying - on the string alone would let a ``/new`` on that unrelated row rotate - this conversation's affinity identity while recovery correctly refuses - to cross the same line. - - Returns the count, or ``None`` when this peer has never been reset. - - The value comes from ``conversation_generations``, which - :meth:`_bump_conversation_generation` advances inside the transaction - that writes each boundary — NOT from an aggregate over the session - rows. An aggregate cannot prove non-reuse: ``delete_session()`` - orphans children and deletes the row, and bulk prune selects ended - rows, so ``COUNT``/``MAX`` over boundaries can return a pair it already - emitted and hand a new conversation a retired affinity identity. It is - also wall-clock-free, so a backwards NTP correction cannot reorder it. - - Databases upgraded mid-conversation start at no generation and take - their first one from the next boundary written; a conversation that - reset before the upgrade shares its predecessor's scope once, which - costs a warm prompt-cache bucket and never crosses an identity. - - These rows are never garbage-collected, by design: dropping one resets - the peer to "no generation", so its next boundary writes ``1`` again - and re-issues a scope a retired conversation already used — the ABA - this counter exists to prevent. See the schema comment in - ``hermes_state_common.py``. + The peer is ``(session_key, source)`` — the identity recovery uses — never the + key alone (an API caller may legally reuse a Telegram row's key). Read from + ``conversation_generations`` (advanced inside each boundary's txn), not an + aggregate over session rows: deletes/prunes would let an aggregate re-emit a + retired pair. Rows are never garbage-collected, by design (dropping one would + re-issue generation 1 — the ABA this counter prevents). Wall-clock-free, so a + backwards NTP correction cannot reorder it. DBs upgraded mid-conversation start + at no generation and take their first from the next boundary written; a + conversation that reset before the upgrade shares its predecessor's scope once + (costs a warm prompt-cache bucket, never crosses an identity). """ if not session_key or not source: return None row = self._read_one( - "SELECT generation FROM conversation_generations " - "WHERE source = ? AND session_key = ?", + "SELECT generation FROM conversation_generations WHERE source = ? AND session_key = ?", (source, session_key), ) if row is None or row["generation"] is None: @@ -2529,48 +1607,21 @@ class SessionMessagesMixin: def clear_messages(self, session_id: str) -> None: """Delete all messages for a session and reset its counters.""" def _do(conn): + conn.execute("DELETE FROM messages WHERE session_id = ?", (session_id,)) conn.execute( - "DELETE FROM messages WHERE session_id = ?", (session_id,) - ) - conn.execute( - "UPDATE sessions SET message_count = 0, tool_call_count = 0 WHERE id = ?", - (session_id,), + "UPDATE sessions SET message_count = 0, tool_call_count = 0 WHERE id = ?", (session_id,), ) self._execute_write(_do) - def purge_stale_tool_call_markers( - self, *, dry_run: bool = False, backup: bool = True - ) -> Dict[str, Any]: - """Permanently clear bare tool-call marker content (e.g. "[memory]") - left in the ``messages`` table by sessions persisted before the - #78148 fix in ``agent.conversation_loop``. + def purge_stale_tool_call_markers(self, *, dry_run: bool = False, backup: bool = True) -> Dict[str, Any]: + """Permanently clear bare tool-call marker content (e.g. "[memory]") left by + pre-fix sessions. ``_rows_to_conversation`` repairs this in memory on every load, + so this is optional; it just stops the re-scan and removes the bytes. - ``_strip_stale_tool_call_markers`` already repairs this in memory on - every session load (see ``_rows_to_conversation``), so running this - is optional — but for long-lived sessions the same rows get - re-scanned and re-repaired on every resume, which is wasted work - and keeps the contaminated bytes sitting in the DB (and in any - downstream cache/backup snapshot of it) indefinitely. This rewrites - the affected rows once, in place. - - Only the ``content`` column is touched — ``role``, ``tool_calls``, - and every other column on the row are left exactly as they are, so - provider tool_call/tool_result pairing is unaffected. - - Unlike the in-memory repair, this UPDATE is permanent and can't be - undone from within the DB. Since ``backup`` defaults to True, a - timestamped full snapshot is taken via ``VACUUM INTO`` (safe against - a live connection, unlike the raw-copy ``_backup_db_file`` used for - malformed-schema repair) before any row is touched — mirroring - ``repair_state_db_schema``'s backup-by-default convention for - destructive state.db operations. No snapshot is taken when there is - nothing to change. - - With ``dry_run=True``, reports the affected row count/ids without - writing or backing up (read-only, no write lock taken). - - Returns ``{"dry_run": bool, "rows_affected": int, "row_ids": [...], - "backup_path": str|None}``. + Only ``content`` is touched (tool_call pairing unaffected). With ``backup`` a + ``VACUUM INTO`` snapshot (safe against a live connection) is taken first; none + when nothing changes. ``dry_run`` reports without writing or backing up. + Returns ``{"dry_run", "rows_affected", "row_ids", "backup_path"}``. """ from hermes_state import _STALE_TOOL_CALL_MARKER_RE @@ -2579,40 +1630,24 @@ class SessionMessagesMixin: "SELECT id, content FROM messages " "WHERE role = 'assistant' AND tool_calls IS NOT NULL AND tool_calls != ''" ) - affected: List[int] = [] - for row in cursor.fetchall(): - content = row["content"] - if isinstance(content, str) and _STALE_TOOL_CALL_MARKER_RE.fullmatch(content.strip()): - affected.append(row["id"]) - return affected + return [ + row["id"] for row in cursor.fetchall() + if isinstance(row["content"], str) and _STALE_TOOL_CALL_MARKER_RE.fullmatch(row["content"].strip()) + ] + + def _result(affected, backup_path=None): + return {"dry_run": dry_run, "rows_affected": len(affected), "row_ids": affected, "backup_path": backup_path} with self._read_ctx() as conn: affected_ids = _find_affected(conn) - - if dry_run: - return { - "dry_run": True, - "rows_affected": len(affected_ids), - "row_ids": affected_ids, - "backup_path": None, - } - - if not affected_ids: - return { - "dry_run": False, - "rows_affected": 0, - "row_ids": [], - "backup_path": None, - } - + if dry_run or not affected_ids: + return _result(affected_ids) backup_path: Optional[str] = None if backup: import datetime stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") - dest = self.db_path.with_name( - f"{self.db_path.name}.pre-clean-markers-backup-{stamp}" - ) + dest = self.db_path.with_name(f"{self.db_path.name}.pre-clean-markers-backup-{stamp}") with self._lock: self._conn.execute("VACUUM INTO ?", (str(dest),)) backup_path = str(dest) @@ -2621,22 +1656,12 @@ class SessionMessagesMixin: def _do(conn): ids = _find_affected(conn) if ids: - placeholders = ",".join("?" * len(ids)) - conn.execute( - f"UPDATE messages SET content = '' WHERE id IN ({placeholders})", - ids, - ) + conn.execute(f"UPDATE messages SET content = '' WHERE id IN ({','.join('?' * len(ids))})", ids) return ids affected_ids = self._execute_write(_do) if affected_ids: logger.info( - "Permanently cleared %d stale tool-call marker row(s) in state.db (#78148)", - len(affected_ids), + "Permanently cleared %d stale tool-call marker row(s) in state.db (#78148)", len(affected_ids), ) - return { - "dry_run": False, - "rows_affected": len(affected_ids), - "row_ids": affected_ids, - "backup_path": backup_path, - } + return _result(affected_ids, backup_path) diff --git a/hermes_state_portability.py b/hermes_state_portability.py index 2f740786ff..e4b1836d4b 100644 --- a/hermes_state_portability.py +++ b/hermes_state_portability.py @@ -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": [], } diff --git a/hermes_state_registry.py b/hermes_state_registry.py index 70d83cd34e..900d4b404d 100644 --- a/hermes_state_registry.py +++ b/hermes_state_registry.py @@ -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()), } diff --git a/hermes_state_repair.py b/hermes_state_repair.py index ba10d93376..a4ec8dbcfc 100644 --- a/hermes_state_repair.py +++ b/hermes_state_repair.py @@ -31,6 +31,74 @@ from hermes_state_common import ( # Log-record parity with the origin module (caplog tests pin "hermes_state"). logger = logging.getLogger("hermes_state") +_REPAIR_LOCK_POLL_SECONDS = 0.1 +# Snapshot copies are data transfer, not inter-process locking: bound them +# separately at 10 MiB/s, with the historical two-minute floor. +_REPAIR_SNAPSHOT_MIN_THROUGHPUT_BYTES_PER_SECOND = 10 * 1024 * 1024 +_MAX_PERSISTENT_REPAIR_ATTEMPTS = 3 +_MAX_MALFORMED_BACKUPS = 3 +# Sidecars copied alongside a damaged DB and pruned with it. ``-journal`` +# matters because rollback-journal (DELETE) mode — the fallback on NFS/SMB/ +# FUSE/ZFS and WAL-reset-vulnerable builds — leaves a hot journal whenever a +# transaction was open; without it the forensic copy cannot be rolled back. +_DB_SIDECAR_SUFFIXES = ("-wal", "-shm", "-journal") +# Head/tail bytes sampled by ``_db_fingerprint``: changes on any genuine +# repair/truncation/restore while staying O(1) on a multi-GB file. +_FINGERPRINT_SAMPLE_BYTES = 65536 +# Header ranges that move on ordinary commits rather than on repair, masked +# out of the content sample: file change counter (24-27) and version-valid-for +# (92-95). In DELETE mode a commit writes the main file directly and a +# malformed-SCHEMA DB still accepts writes, so without the mask any live write +# re-keys the ledger and the repair budget resets to 1 forever. The page-1 +# sqlite_master b-tree — what repair identity depends on — sits after byte 100. +# (WAL mode routes commits to the -wal sidecar; masking is harmless there.) +_FINGERPRINT_VOLATILE_HEADER_RANGES = ((24, 28), (92, 96)) +# Free-space headroom for the pre-repair forensic backup (a full raw copy of +# the damaged DB plus sidecars; a repair loop on a large state.db is a disk +# amplifier). Proportional, not a flat multi-GB floor: a refused backup is a +# HARD STOP, and a large absolute reserve would turn "repair loops" into +# "repair never runs" on small container/VM volumes. +_REPAIR_BACKUP_MIN_FREE_BYTES = 256 * 1024 * 1024 # 256 MiB absolute floor +_REPAIR_BACKUP_FREE_FRACTION = 0.02 # plus 2% of the volume +_FTS_TABLES = ("messages_fts", "messages_fts_trigram", "messages_fts_cjk") +_MANUAL_RECOVER_HINT = 'Free disk space, then retry (or recover manually with `sqlite3 {db_path} ".recover"`).' + + +def _sidecars(db_path: Path): + """The three SQLite sidecar paths for *db_path* (present or not).""" + return (db_path.with_name(db_path.name + suffix) for suffix in _DB_SIDECAR_SUFFIXES) + + +def _bundle_bytes(db_path: Path) -> int: + """Size of the main file plus every PRESENT sidecar (OSError propagates).""" + return db_path.stat().st_size + sum(p.stat().st_size for p in _sidecars(db_path) if p.exists()) + + +def _unlink_quiet(path: Path) -> None: + """Best-effort unlink; a failure here is never the caller's error.""" + try: + path.unlink(missing_ok=True) + except OSError: + pass + + +def _offline_access_tools(): + """``(offline_file_access, LiveConnectionError)`` from hermes_cli, or inert + stand-ins on scaffold/embed installs (no tracked connections exist there, + so a raw read is safe).""" + try: + from hermes_cli.sqlite_safe_read import LiveConnectionError, offline_file_access + return offline_file_access, LiveConnectionError + except ImportError: + @contextmanager + def offline_file_access(_path, **_kw): + yield + + class LiveConnectionError(Exception): + pass + + return offline_file_access, LiveConnectionError + def _claim_repair_attempt(db_path: Path) -> bool: """Claim the one-shot per-process repair attempt for *db_path*. @@ -47,12 +115,40 @@ def _claim_repair_attempt(db_path: Path) -> bool: return True -_REPAIR_LOCK_POLL_SECONDS = 0.1 +def _open_lock_file(db_path: Path, suffix: str, what: str, tail: str): + """Open ``.`` for locking; on failure warn and return None.""" + lock_path = db_path.with_name(db_path.name + suffix) + try: + lock_path.parent.mkdir(parents=True, exist_ok=True) + return lock_path, lock_path.open("a+b") + except OSError as exc: + logger.warning(f"Could not open state.db {what} lock %s (%s) — {tail}", lock_path, exc) + return lock_path, None -# Snapshot copies are data transfer, not inter-process locking: bound them -# separately at 10 MiB/s, with the historical two-minute floor. -_REPAIR_SNAPSHOT_MIN_THROUGHPUT_BYTES_PER_SECOND = 10 * 1024 * 1024 +def _msvcrt_lock(handle, flag_name: str) -> None: + import msvcrt + + handle.seek(0) + msvcrt.locking(handle.fileno(), getattr(msvcrt, flag_name), 1) # type: ignore[attr-defined] + + +def _release_lock_handle(handle, *, clear_record: bool = False) -> None: + """Drop the advisory lock on *handle* (best effort) and close it.""" + from hermes_state import _IS_WINDOWS + try: + if _IS_WINDOWS: + _msvcrt_lock(handle, "LK_UNLCK") + else: + import fcntl + + if clear_record: + _clear_lock_holder_record(handle) + fcntl.flock(handle.fileno(), fcntl.LOCK_UN) + except OSError: # pragma: no cover - best effort release + pass + finally: + handle.close() @contextlib.contextmanager @@ -61,9 +157,8 @@ def _cross_process_repair_lock(db_path: Path): Yields True when this process holds the repair lock for *db_path*, False when the bounded acquire timed out or the lock file could not be opened. - Unlike the kanban init lock (idempotent critical section), running surgery - unlocked IS the unsafe interleaving this prevents: a caller that gets - False must NOT do surgery. + Running surgery unlocked IS the unsafe interleaving this prevents: a caller + that gets False must NOT do surgery. ``flock`` because the kernel drops it when the holder dies (a pidfile would wedge every future repair); a forked child that inherited the fd is @@ -71,23 +166,16 @@ def _cross_process_repair_lock(db_path: Path): breaks the lock when that holder is provably dead (``_acquire_db_flock``). The acquire is bounded because a *live* repairer can sit in ``VACUUM`` for minutes, and an unbounded wait would hang the caller's open silently. + An unopenable lock file (out of space/inodes/descriptors) fails closed + too: a sibling that opened ITS handle before the disk filled may still be + inside surgery. """ from hermes_state import _IS_WINDOWS, _REPAIR_LOCK_TIMEOUT_SECONDS - lock_path = db_path.with_name(db_path.name + ".repair.lock") - try: - lock_path.parent.mkdir(parents=True, exist_ok=True) - handle = lock_path.open("a+b") - except OSError as exc: - # Fail closed, like a timed-out acquire. An unopenable lock file means - # out of space/inodes/descriptors — and a sibling that opened ITS - # handle before the disk filled may still be inside surgery; yielding - # True here once let two processes run surgery on the same live - # state.db. Callers handle False by re-probing. - logger.warning( - "Could not open state.db repair lock %s (%s) — skipping schema " - "surgery rather than running it without cross-process authority.", - lock_path, exc, - ) + lock_path, handle = _open_lock_file( + db_path, ".repair.lock", "repair", + "skipping schema surgery rather than running it without cross-process authority.", + ) + if handle is None: yield False return @@ -97,10 +185,7 @@ def _cross_process_repair_lock(db_path: Path): deadline = time.monotonic() + _REPAIR_LOCK_TIMEOUT_SECONDS while True: try: - import msvcrt - - handle.seek(0) - msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1) + _msvcrt_lock(handle, "LK_NBLCK") acquired = True break except (BlockingIOError, OSError) as exc: @@ -117,41 +202,24 @@ def _cross_process_repair_lock(db_path: Path): time.sleep(_REPAIR_LOCK_POLL_SECONDS) else: acquired, handle = _acquire_db_flock( - str(lock_path), - handle, - _REPAIR_LOCK_TIMEOUT_SECONDS, - _REPAIR_LOCK_POLL_SECONDS, - "state.db repair lock", + str(lock_path), handle, _REPAIR_LOCK_TIMEOUT_SECONDS, + _REPAIR_LOCK_POLL_SECONDS, "state.db repair lock", ) if acquired is None: - # Non-contention failure already logged with its errno. - acquired = False + acquired = False # non-contention failure already logged with its errno elif not acquired: record = None if _IS_WINDOWS else _read_lock_holder_record(handle) logger.warning( "state.db repair lock %s held by another process for more " "than %.0fs — skipping schema surgery in this process to " "avoid racing the repairer. Recorded holder: %s.", - lock_path, _REPAIR_LOCK_TIMEOUT_SECONDS, - _describe_lock_holder(record), + lock_path, _REPAIR_LOCK_TIMEOUT_SECONDS, _describe_lock_holder(record), ) yield acquired finally: - try: - if acquired: - if _IS_WINDOWS: - import msvcrt - - handle.seek(0) - msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1) - else: - import fcntl - - _clear_lock_holder_record(handle) - fcntl.flock(handle.fileno(), fcntl.LOCK_UN) - except OSError: # pragma: no cover - best effort release - pass - finally: + if acquired: + _release_lock_handle(handle, clear_record=True) + else: handle.close() @@ -163,27 +231,14 @@ def _try_acquire_auto_maintenance_lock(db_path: Path) -> Optional[Any]: check and the second prunes a row the first has only just closed recoverably. """ from hermes_state import _IS_WINDOWS - lock_path = db_path.with_name(db_path.name + ".auto-maintenance.lock") - try: - lock_path.parent.mkdir(parents=True, exist_ok=True) - handle = lock_path.open("a+b") - except OSError as exc: - logger.warning( - "Could not open state.db auto-maintenance lock %s (%s) — skipping " - "automatic maintenance.", - lock_path, - exc, - ) + _lock_path, handle = _open_lock_file( + db_path, ".auto-maintenance.lock", "auto-maintenance", "skipping automatic maintenance." + ) + if handle is None: return None - try: if _IS_WINDOWS: - import msvcrt - - handle.seek(0) - msvcrt.locking( # type: ignore[attr-defined] - handle.fileno(), msvcrt.LK_NBLCK, 1 # type: ignore[attr-defined] - ) + _msvcrt_lock(handle, "LK_NBLCK") else: import fcntl @@ -196,23 +251,7 @@ def _try_acquire_auto_maintenance_lock(db_path: Path) -> Optional[Any]: def _release_auto_maintenance_lock(handle: Any) -> None: """Release a handle returned by :func:`_try_acquire_auto_maintenance_lock`.""" - from hermes_state import _IS_WINDOWS - try: - if _IS_WINDOWS: - import msvcrt - - handle.seek(0) - msvcrt.locking( # type: ignore[attr-defined] - handle.fileno(), msvcrt.LK_UNLCK, 1 # type: ignore[attr-defined] - ) - else: - import fcntl - - fcntl.flock(handle.fileno(), fcntl.LOCK_UN) - except OSError: # pragma: no cover - best effort release - pass - finally: - handle.close() + _release_lock_handle(handle) def _bump_schema_cookie(conn: sqlite3.Connection) -> None: @@ -233,36 +272,6 @@ def _bump_schema_cookie(conn: sqlite3.Connection) -> None: logger.warning("Could not bump state.db schema cookie: %s", exc) -_MAX_PERSISTENT_REPAIR_ATTEMPTS = 3 - - -_MAX_MALFORMED_BACKUPS = 3 - - -# Sidecars copied alongside a damaged DB and pruned with it. ``-journal`` -# matters because rollback-journal (DELETE) mode — Hermes's fallback on -# NFS/SMB/FUSE/ZFS and WAL-reset-vulnerable SQLite builds — leaves a hot -# journal whenever a transaction was open; without it the forensic copy -# cannot be rolled back to a consistent state by hand. -_DB_SIDECAR_SUFFIXES = ("-wal", "-shm", "-journal") - - -# Head/tail bytes sampled by ``_db_fingerprint``: changes on any genuine -# repair/truncation/restore while staying O(1) on a multi-GB file. -_FINGERPRINT_SAMPLE_BYTES = 65536 - - -# Header ranges that move on ordinary commits rather than on repair, masked -# out of the content sample: file change counter (24-27) and version-valid-for -# (92-95). In DELETE mode a commit writes the main file directly and a -# malformed-SCHEMA DB still accepts writes, so without the mask any live write -# re-keys the ledger and the repair budget resets to 1 forever. (WAL mode -# routes commits to the -wal sidecar; masking is harmless there.) The page-1 -# sqlite_master b-tree — what repair identity depends on — sits after byte 100 -# and stays in the sample. -_FINGERPRINT_VOLATILE_HEADER_RANGES = ((24, 28), (92, 96)) - - def _mask_volatile_header(head: bytes) -> bytes: """Zero the commit-counter fields so ordinary writes don't re-key the ledger.""" if len(head) < 96: @@ -273,26 +282,9 @@ def _mask_volatile_header(head: bytes) -> bytes: return bytes(buf) -# Free-space headroom for the pre-repair forensic backup: a full raw copy of -# the damaged DB plus sidecars, so a repair loop on a large state.db is a disk -# amplifier (one incident wrote ~98MB every ~10s until the volume was nearly -# full). Proportional, not a flat floor: an absolute multi-GB reserve would -# refuse backups that fit on small container/VM volumes, and since a refused -# backup is a HARD STOP that would turn "repair loops" into "repair never -# runs" there. Require the copy plus a small slice of the volume, with a -# modest floor. -_REPAIR_BACKUP_MIN_FREE_BYTES = 256 * 1024 * 1024 # 256 MiB absolute floor - - -_REPAIR_BACKUP_FREE_FRACTION = 0.02 # plus 2% of the volume - - def _repair_backup_headroom_bytes(total_bytes: int) -> int: """Free space required *beyond* the copy itself, for a volume of *total_bytes*.""" - return max( - _REPAIR_BACKUP_MIN_FREE_BYTES, - int(total_bytes * _REPAIR_BACKUP_FREE_FRACTION), - ) + return max(_REPAIR_BACKUP_MIN_FREE_BYTES, int(total_bytes * _REPAIR_BACKUP_FREE_FRACTION)) def _repair_scratch_space_error(db_path: Path) -> Optional[str]: @@ -300,19 +292,13 @@ def _repair_scratch_space_error(db_path: Path) -> Optional[str]: import shutil try: - main_bytes = db_path.stat().st_size - snapshot_bytes = main_bytes - for suffix in _DB_SIDECAR_SUFFIXES: - sidecar = db_path.with_name(db_path.name + suffix) - if sidecar.exists(): - snapshot_bytes += sidecar.stat().st_size + snapshot_bytes = _bundle_bytes(db_path) usage = shutil.disk_usage(db_path.parent) headroom = _repair_backup_headroom_bytes(usage.total) # Strategy 2 runs VACUUM on the staged DB, which SQLite documents may # need up to 2x the database size in extra space; the same reserve then # covers transactional promotion into the live DB. - required = snapshot_bytes + (2 * snapshot_bytes) + headroom - if usage.free >= required: + if usage.free >= snapshot_bytes + (2 * snapshot_bytes) + headroom: return None return ( f"only {usage.free / 1e9:.2f}GB free on {db_path.parent}; the " @@ -336,20 +322,12 @@ def _repair_snapshot_timeout_seconds(source_path: Path) -> float: """ from hermes_state import _REPAIR_LOCK_TIMEOUT_SECONDS, _REPAIR_SNAPSHOT_MIN_THROUGHPUT_BYTES_PER_SECOND source_bytes = 0 - for suffix in ("", *_DB_SIDECAR_SUFFIXES): - candidate = ( - source_path - if not suffix - else source_path.with_name(source_path.name + suffix) - ) + for candidate in (source_path, *_sidecars(source_path)): try: source_bytes += candidate.stat().st_size except FileNotFoundError: continue - return max( - _REPAIR_LOCK_TIMEOUT_SECONDS, - source_bytes / _REPAIR_SNAPSHOT_MIN_THROUGHPUT_BYTES_PER_SECOND, - ) + return max(_REPAIR_LOCK_TIMEOUT_SECONDS, source_bytes / _REPAIR_SNAPSHOT_MIN_THROUGHPUT_BYTES_PER_SECOND) def _repair_failure_consumes_attempt(exc: BaseException) -> bool: @@ -366,16 +344,11 @@ def _repair_failure_consumes_attempt(exc: BaseException) -> bool: error_code = getattr(exc, "sqlite_errorcode", None) if isinstance(error_code, int): # Extended result codes keep the primary code in the low byte. - primary_code = error_code & 0xFF - return primary_code in (sqlite3.SQLITE_CORRUPT, sqlite3.SQLITE_NOTADB) - + return (error_code & 0xFF) in (sqlite3.SQLITE_CORRUPT, sqlite3.SQLITE_NOTADB) # Older sqlite3 without result-code attributes: narrow message match only, # never turning generic "disk is full"/"readonly" into permanent failures. message = str(exc).lower() - return ( - "file is not a database" in message - or "database disk image is malformed" in message - ) + return "file is not a database" in message or "database disk image is malformed" in message def _repair_ledger_path(db_path: Path) -> Path: @@ -387,11 +360,10 @@ def _db_fingerprint(db_path: Path) -> "Optional[str]": Deliberately EXCLUDES mtime: the malformed-schema class still accepts writes, so live writers, WAL checkpoints and the strategies themselves move - mtime between passes; keyed on mtime, every pass looked like a NEW file, - the attempt counter reset to 1 forever and each pass wrote another - full-size forensic copy. Hashing a multi-GB file on every open is the cost - this ledger exists to avoid, so sample the head/tail slices any real - repair, truncation or restore necessarily changes. + mtime between passes; keyed on mtime, every pass looked like a NEW file and + the attempt counter reset to 1 forever. Hashing a multi-GB file on every + open is the cost this ledger exists to avoid, so sample the head/tail + slices any real repair, truncation or restore necessarily changes. Runs under ``offline_file_access``: ``close()`` on ANY raw descriptor cancels every POSIX advisory lock this process holds on the file, including @@ -400,35 +372,19 @@ def _db_fingerprint(db_path: Path) -> "Optional[str]": ``_backup_db_file``'s ``has_live_connection`` guard). Returns ``None`` ("identity unavailable") when that makes the read unsafe. Callers MUST NOT substitute a differently-shaped key: the ledger compares keys for equality, - so alternating shapes never matches and the unbounded loop returns; the - ledger helpers keep the recorded key instead. + so alternating shapes never matches and the unbounded loop returns. """ try: st = db_path.stat() - try: - from hermes_cli.sqlite_safe_read import ( - LiveConnectionError, - offline_file_access, - ) - except ImportError: - # Scaffold/embed installs ship hermes_state without hermes_cli; no - # tracked connections exist there, so the raw read is safe. - @contextmanager - def offline_file_access(_path, **_kw): - yield - - class LiveConnectionError(Exception): - pass - + offline_file_access, LiveConnectionError = _offline_access_tools() try: with offline_file_access(db_path, what="fingerprint"): with open(db_path, "rb") as fh: head = fh.read(_FINGERPRINT_SAMPLE_BYTES) + tail = b"" if st.st_size > _FINGERPRINT_SAMPLE_BYTES: fh.seek(max(0, st.st_size - _FINGERPRINT_SAMPLE_BYTES)) tail = fh.read(_FINGERPRINT_SAMPLE_BYTES) - else: - tail = b"" except LiveConnectionError: return None digest = hashlib.sha256(_mask_volatile_header(head) + tail).hexdigest()[:32] @@ -441,31 +397,18 @@ def _backup_content_identity(db_path: Path) -> "Optional[str]": """Recovery-image identity for forensic-backup dedupe: whole file + sidecars. A DIFFERENT equivalence relation from :func:`_db_fingerprint`; never - conflate them. The fingerprint answers "same repair epoch?" and masks - commit counters / samples only head+tail so an ordinary write does not mint - a fresh repair budget. A live writer can commit rows into an *interior* - page while preserving size and the first/last 64 KiB, so two materially - different recovery images share one fingerprint; reusing a backup on that - basis hands the operator a snapshot predating real user data. A forensic - copy must claim byte identity, so this digests the ENTIRE main file plus - every present sidecar (the WAL can hold uncheckpointed committed - frames). The O(n) read is cheaper than the O(n) write it avoids. Runs under - ``offline_file_access`` (same POSIX-lock reason as ``_db_fingerprint``); - ``None`` when a live connection makes the read unsafe — the caller then - takes a fresh backup, never a false reuse. + conflate them. The fingerprint answers "same repair epoch?" and samples + only head+tail; a live writer can commit rows into an *interior* page while + preserving size and both 64 KiB slices, so two materially different + recovery images share one fingerprint, and reusing a backup on that basis + hands the operator a snapshot predating real user data. A forensic copy + must claim byte identity, so this digests the ENTIRE main file plus every + present sidecar (the WAL can hold uncheckpointed committed frames). Runs + under ``offline_file_access`` (same POSIX-lock reason); ``None`` when a + live connection makes the read unsafe — the caller then takes a fresh + backup, never a false reuse. """ - try: - from hermes_cli.sqlite_safe_read import ( - LiveConnectionError, - offline_file_access, - ) - except ImportError: - @contextmanager - def offline_file_access(_path, **_kw): - yield - - class LiveConnectionError(Exception): - pass + offline_file_access, LiveConnectionError = _offline_access_tools() def _hash_whole(path: Path, hasher: "Any") -> None: with open(path, "rb") as fh: @@ -480,15 +423,12 @@ def _backup_content_identity(db_path: Path) -> "Optional[str]": # coincide with a main+sidecar split and dedupe two images together. hasher.update(f"\0main:{db_path.stat().st_size}\0".encode()) _hash_whole(db_path, hasher) - for suffix in _DB_SIDECAR_SUFFIXES: - sidecar = db_path.with_name(db_path.name + suffix) + for suffix, sidecar in zip(_DB_SIDECAR_SUFFIXES, _sidecars(db_path)): if sidecar.exists(): hasher.update(f"\0{suffix}:{sidecar.stat().st_size}\0".encode()) _hash_whole(sidecar, hasher) return hasher.hexdigest() - except LiveConnectionError: - return None - except OSError: + except (LiveConnectionError, OSError): return None @@ -541,9 +481,7 @@ def _persistent_repair_exhausted_error(db_path: Path) -> str: ) -def _record_repair_outcome( - db_path: Path, *, repaired: bool, fingerprint: "Optional[str]" = None -) -> None: +def _record_repair_outcome(db_path: Path, *, repaired: bool, fingerprint: "Optional[str]" = None) -> None: """Update the persistent attempt ledger after a repair pass. Never raises. Defaults to the post-attempt fingerprint (what the NEXT exhaustion probe @@ -565,21 +503,15 @@ def _record_repair_outcome( # in-process claim and cross-process lock still bound this run. return fp = recorded - attempts = ( - int(ledger.get("failed_attempts", 0)) + 1 if recorded == fp else 1 - ) + attempts = int(ledger.get("failed_attempts", 0)) + 1 if recorded == fp else 1 import datetime ledger_path.write_text( - json.dumps( - { - "fingerprint": fp, - "failed_attempts": attempts, - "last_attempt": datetime.datetime.now().isoformat( - timespec="seconds" - ), - } - ), + json.dumps({ + "fingerprint": fp, + "failed_attempts": attempts, + "last_attempt": datetime.datetime.now().isoformat(timespec="seconds"), + }), encoding="utf-8", ) except Exception as exc: # pragma: no cover - best effort @@ -591,10 +523,8 @@ def _existing_malformed_backups(db_path: Path) -> "List[Path]": prefix = f"{db_path.name}.malformed-backup-" try: found = [ - p - for p in db_path.parent.iterdir() - if p.name.startswith(prefix) - and not p.name.endswith(_DB_SIDECAR_SUFFIXES) + p for p in db_path.parent.iterdir() + if p.name.startswith(prefix) and not p.name.endswith(_DB_SIDECAR_SUFFIXES) ] except OSError: return [] @@ -604,16 +534,76 @@ def _existing_malformed_backups(db_path: Path) -> "List[Path]": def _prune_malformed_backups(db_path: Path, keep: int = _MAX_MALFORMED_BACKUPS) -> None: """Delete all but the *keep* newest forensic backups (and sidecars).""" for stale in _existing_malformed_backups(db_path)[keep:]: - for victim in ( - stale, - *(stale.with_name(stale.name + suffix) for suffix in _DB_SIDECAR_SUFFIXES), - ): + for victim in (stale, *_sidecars(stale)): try: victim.unlink(missing_ok=True) except OSError as exc: # pragma: no cover - best effort logger.warning("Could not prune stale DB backup %s: %s", victim, exc) +def _backup_free_space_error(db_path: Path) -> Optional[str]: + """Disk guard for the forensic copy: reason to refuse, or None. + + A full raw copy on a nearly-full volume (which a preceding repair loop may + itself have caused) can finish off the disk and every process on the + machine. Fails CLOSED on stat()/disk_usage() errors: the nearly-full volume + this guard exists for is exactly where they are most likely to fail, and + proceeding would take the copy that finishes off the disk. + """ + import shutil + + hint = _MANUAL_RECOVER_HINT.format(db_path=db_path) + try: + need = _bundle_bytes(db_path) + usage = shutil.disk_usage(db_path.parent) + headroom = _repair_backup_headroom_bytes(usage.total) + if usage.free - need >= headroom: + return None + return ( + f"only {usage.free / 1e9:.2f}GB free on {db_path.parent}; " + f"copying the damaged DB needs {need / 1e9:.2f}GB and must " + f"leave {headroom / 1e9:.2f}GB headroom. {hint}" + ) + except OSError as exc: + return ( + f"could not determine free space on {db_path.parent} ({exc}); " + f"refusing the forensic copy rather than risk filling the volume. {hint}" + ) + + +def _publish_backup_bundle(db_path: Path, staging: Path, backup_path: Path) -> None: + """Copy DB + sidecars to *staging* names, then rename each into place. + + PUBLICATION ORDER MATTERS: the main DB name is the bundle's commit marker + (what ``_existing_malformed_backups`` counts), so sidecars go FIRST and the + main DB LAST; a failure partway then never leaves a countable main backup + over a missing sidecar. On any failure, unpublished staging files AND + anything already promoted are removed, so no official ``backup_path`` + survives a partial bundle. + """ + import shutil + + pairs: "List[Tuple[Path, Path, Path]]" = [ + (sidecar, staging.with_name(staging.name + suffix), backup_path.with_name(backup_path.name + suffix)) + for suffix, sidecar in zip(_DB_SIDECAR_SUFFIXES, _sidecars(db_path)) + if sidecar.exists() + ] + published: "List[Path]" = [] + try: + shutil.copy2(db_path, staging) + for sidecar, staged, _dst in pairs: + shutil.copy2(sidecar, staged) + for _src, staged, dst in (*pairs, (db_path, staging, backup_path)): + os.replace(staged, dst) + published.append(dst) + except Exception: + for staged in (staging, *(s for _src, s, _d in pairs)): + _unlink_quiet(staged) + for dst in published: + _unlink_quiet(dst) + raise + + def _backup_db_file(db_path: Path) -> "Tuple[Optional[Path], Optional[str]]": """Raw-copy a (possibly malformed) DB plus sidecars to a timestamped backup. @@ -623,11 +613,18 @@ def _backup_db_file(db_path: Path) -> "Tuple[Optional[Path], Optional[str]]": because the forensic bundle is the recovery path when every strategy fails. Refuses while a connection to this DB is live in the process: reading the file would ``close()`` a descriptor and cancel that connection's POSIX - advisory locks (see ``hermes_cli.sqlite_safe_read``) — a real case, since - one SessionDB can enter repair while the gateway holds others. + advisory locks (see ``hermes_cli.sqlite_safe_read``) — a real case: one + SessionDB can enter repair while the gateway holds others. + + Dedupe: if the newest existing backup is byte-identical to the current + recovery image (``_backup_content_identity`` — NOT mtime, NOT + ``_db_fingerprint``), reuse it; a repair loop once copied the same damaged + bytes on every restart. The copy lands under a staging name OUTSIDE the + ``.malformed-backup-`` prefix: a staging name inside it counts as a backup, + sorts NEWEST (prune kept partials and deleted intact copies) and dedupe + could return it with no real forensic copy on disk. """ import datetime - import shutil try: from hermes_cli.sqlite_safe_read import has_live_connection @@ -645,13 +642,10 @@ def _backup_db_file(db_path: Path) -> "Tuple[Optional[Path], Optional[str]]": stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") backup_path = db_path.with_name(f"{db_path.name}.malformed-backup-{stamp}") - # Same-second collision (two damaged states within one second) must not - # overwrite the earlier forensic copy. + # Same-second collision must not overwrite the earlier forensic copy. seq = 1 while backup_path.exists(): - backup_path = db_path.with_name( - f"{db_path.name}.malformed-backup-{stamp}_{seq}" - ) + backup_path = db_path.with_name(f"{db_path.name}.malformed-backup-{stamp}_{seq}") seq += 1 try: # Sweep staging debris from an earlier interrupted pass BEFORE the @@ -659,22 +653,9 @@ def _backup_db_file(db_path: Path) -> "Tuple[Optional[Path], Optional[str]]": # dedupe would hand it back as a legitimate backup. Also sweeps the # pre-merge ``.incomplete`` spelling, which prefix-matches as a backup, # sorts NEWEST and would otherwise survive prune forever. - for pattern in ( - f"{db_path.name}.backup-staging-*", - f"{db_path.name}.malformed-backup-*.incomplete*", - ): + for pattern in (f"{db_path.name}.backup-staging-*", f"{db_path.name}.malformed-backup-*.incomplete*"): for old in db_path.parent.glob(pattern): - try: - old.unlink(missing_ok=True) - except OSError: # pragma: no cover - best effort - pass - # Dedupe: a repair loop used to copy the SAME damaged bytes on every - # restart (~900MB a pass, 89GB over 11 days). If the newest existing - # backup is byte-identical to the current recovery image, reuse it. - # Match on ``_backup_content_identity`` — NOT mtime (the malformed- - # SCHEMA class still accepts writes, so mtime missed every pass) and - # NOT ``_db_fingerprint`` (see its docstring: an interior-page write - # changes the recovery image without changing the fingerprint). + _unlink_quiet(old) try: # Only hash the source when there is a candidate to compare # against; hashing a multi-GB source right before copying it is @@ -691,90 +672,12 @@ def _backup_db_file(db_path: Path) -> "Tuple[Optional[Path], Optional[str]]": return existing, None except OSError: pass - # Disk guard: a full raw copy on a nearly-full volume (which a - # preceding repair loop may itself have caused) can finish off the - # disk and every process on the machine. Refuse while there is room to. - try: - need = db_path.stat().st_size - for suffix in _DB_SIDECAR_SUFFIXES: - sidecar = db_path.with_name(db_path.name + suffix) - if sidecar.exists(): - need += sidecar.stat().st_size - usage = shutil.disk_usage(db_path.parent) - headroom = _repair_backup_headroom_bytes(usage.total) - if usage.free - need < headroom: - reason = ( - f"only {usage.free / 1e9:.2f}GB free on {db_path.parent}; " - f"copying the damaged DB needs {need / 1e9:.2f}GB and must " - f"leave {headroom / 1e9:.2f}GB headroom. Free disk space, " - f"then retry (or recover manually with `sqlite3 {db_path} " - '".recover"`).' - ) - logger.error("Refusing forensic backup of %s: %s", db_path, reason) - return None, reason - except OSError as exc: - # Fail CLOSED: the nearly-full volume this guard exists for is - # exactly where stat()/disk_usage() is most likely to fail, and - # proceeding would take the copy that finishes off the disk. Repair - # then waits (HARD STOP) for a human to free space — the safe side. - reason = ( - f"could not determine free space on {db_path.parent} ({exc}); " - "refusing the forensic copy rather than risk filling the " - f"volume. Free disk space, then retry (or recover manually " - f'with `sqlite3 {db_path} ".recover"`).' - ) + reason = _backup_free_space_error(db_path) + if reason is not None: logger.error("Refusing forensic backup of %s: %s", db_path, reason) return None, reason - # Copy to a staging name OUTSIDE the ``.malformed-backup-`` prefix and - # rename into place only once every copy succeeded. A staging name - # inside the prefix (e.g. ``…-.incomplete``) counts as a backup, - # sorts NEWEST (so prune kept partials and deleted intact copies), and - # dedupe could return it as ``backup_path`` — passing the hard stop with - # no real forensic copy on disk. staging = db_path.with_name(f"{db_path.name}.backup-staging-{stamp}") - # (staging_src, final_dst) pairs. PUBLICATION ORDER MATTERS: the main - # DB name is the bundle's commit marker (what - # ``_existing_malformed_backups`` counts), so sidecars go FIRST and the - # main DB LAST; a failure partway then never leaves a countable main - # backup over a missing sidecar that would pass the hard stop and dedupe. - staged_sidecars: "List[Tuple[Path, Path, Path]]" = [] - for suffix in _DB_SIDECAR_SUFFIXES: - sidecar = db_path.with_name(db_path.name + suffix) - if sidecar.exists(): - side_staging = staging.with_name(staging.name + suffix) - side_dst = backup_path.with_name(backup_path.name + suffix) - staged_sidecars.append((sidecar, side_staging, side_dst)) - main_pair = (staging, backup_path) - published: "List[Path]" = [] - all_staging_srcs = [staging] + [s for _src, s, _d in staged_sidecars] - try: - shutil.copy2(db_path, staging) - for sidecar, side_staging, _side_dst in staged_sidecars: - shutil.copy2(sidecar, side_staging) - publish_order = [ - (s, d) for _src, s, d in staged_sidecars - ] + [main_pair] - for src, dst in publish_order: - os.replace(src, dst) - published.append(dst) - except Exception: - # Roll back unpublished staging files AND anything already promoted, - # so a failure after the main os.replace leaves no official backup_path. - for src in all_staging_srcs: - try: - src.unlink(missing_ok=True) - except OSError: - pass - for dst in published: - try: - dst.unlink(missing_ok=True) - except OSError: - pass - try: - staging.unlink(missing_ok=True) - except OSError: - pass - raise + _publish_backup_bundle(db_path, staging, backup_path) _prune_malformed_backups(db_path) return backup_path, None except Exception as exc: # pragma: no cover - best effort @@ -782,11 +685,7 @@ def _backup_db_file(db_path: Path) -> "Tuple[Optional[Path], Optional[str]]": return None, f"backup copy failed: {exc}" -def preflight_db_writability( - db_path: Path, - *, - db_label: str = "state.db", -) -> None: +def preflight_db_writability(db_path: Path, *, db_label: str = "state.db") -> None: """Refuse-or-repair read-only DB files BEFORE the first connection opens. A stray read-only ``state.db`` / ``-wal`` / ``-shm`` (sudo run, restored @@ -803,7 +702,6 @@ def preflight_db_writability( raw = str(db_path) if raw == ":memory:" or raw.startswith("file:"): return - try: home: Optional[Path] = Path(get_hermes_home()).resolve() except Exception: # pragma: no cover - defensive @@ -831,17 +729,14 @@ def preflight_db_writability( if os.access(p, os.R_OK | os.W_OK): logger.info( "%s preflight: repaired read-only %s (chmod u+rw%s)", - db_label, - p, - "x" if is_dir else "", + db_label, p, "x" if is_dir else "", ) return kind = "directory" if is_dir else "file" wal_note = ( " Do NOT delete the -wal file — it contains committed data that " "will be merged into the database once it is writable." - if p.name.endswith("-wal") - else "" + if p.name.endswith("-wal") else "" ) raise sqlite3.OperationalError( f"{db_label} is not writable: {kind} {p} is read-only for this " @@ -855,16 +750,13 @@ def preflight_db_writability( # SQLite needs a writable directory in every journal mode (WAL/SHM # sidecars, or the rollback journal in DELETE mode). _ensure_writable(parent, is_dir=True) - for suffix in ("", "-wal", "-shm"): p = db_path.with_name(db_path.name + suffix) if suffix else db_path if p.is_file(): _ensure_writable(p) -def _connect_repair_durable( - db_path: Path, *, timeout: float = 5.0 -) -> sqlite3.Connection: +def _connect_repair_durable(db_path: Path, *, timeout: float = 5.0) -> sqlite3.Connection: """``sqlite3.connect`` for the repair/probe paths, with macOS write barriers. These paths open ``state.db`` directly (not via ``SessionDB`` / @@ -897,10 +789,7 @@ def _reapply_durability_barriers(conn: sqlite3.Connection) -> bool: _apply_macos_checkpoint_barrier(conn) _enforce_macos_synchronous_full(conn) return True - except sqlite3.DatabaseError: - # Schema still unparseable — pragmas cannot be set yet. - return False - except Exception: + except Exception: # schema still unparseable, or anything else — pragmas cannot be set yet return False @@ -921,14 +810,21 @@ def apply_durability_barriers(conn: sqlite3.Connection) -> bool: cfg = load_config_readonly() raw_synchronous = cfg_get(cfg, "database", "synchronous", default=None) if raw_synchronous is not None: - _apply_synchronous_pragma( - conn, raw_synchronous, db_label="state.db (guest)" - ) + _apply_synchronous_pragma(conn, raw_synchronous, db_label="state.db (guest)") except Exception: pass return ok +def _close_unpinned(conn: sqlite3.Connection) -> None: + """Leave EXCLUSIVE locking mode (so the file is never left pinned) and close.""" + try: + conn.execute("PRAGMA locking_mode=NORMAL") + except Exception: + pass + conn.close() + + @contextmanager def _exclusive_repair_db_guard(db_path: Path): """Yield one live connection that excludes writers for repair surgery. @@ -940,44 +836,32 @@ def _exclusive_repair_db_guard(db_path: Path): stays open across the whole snapshot -> strategies -> promotion window, so no other writer can commit a change promotion would overwrite. Existing readers make acquisition fail rather than being disturbed: repair fails - closed unless this process owns the whole window. + closed unless this process owns the whole window. Timeout 0: the + cross-process repair lock already serializes repairers, and a partial + repair is less safe than an explicit "stop the gateway and retry". """ guard: Optional[sqlite3.Connection] = None try: - # The cross-process repair lock already serializes repairers. Do not - # wait behind an ordinary application connection: a partial repair is - # less safe than an explicit "stop the gateway and retry". guard = _connect_repair_durable(db_path, timeout=0.0) guard.execute("PRAGMA locking_mode=EXCLUSIVE") guard.execute("BEGIN EXCLUSIVE") guard.execute("ROLLBACK") except (sqlite3.Error, OSError) as exc: if guard is not None: - try: - guard.execute("PRAGMA locking_mode=NORMAL") - except Exception: - pass - guard.close() + _close_unpinned(guard) yield None, exc return - try: yield guard, None finally: - try: - # Release the exclusive locks before close; also keeps a close-time - # checkpoint from being mistaken for a repair write by callers that - # immediately reopen state.db. - guard.execute("PRAGMA locking_mode=NORMAL") - except Exception: - pass - guard.close() + # Releasing the exclusive locks before close also keeps a close-time + # checkpoint from being mistaken for a repair write by callers that + # immediately reopen state.db. + _close_unpinned(guard) def _copy_database_snapshot( - source_path: Path, - destination_path: Path, - *, + source_path: Path, destination_path: Path, *, source_connection: Optional[sqlite3.Connection] = None, destination_connection: Optional[sqlite3.Connection] = None, ) -> None: @@ -993,15 +877,10 @@ def _copy_database_snapshot( deadline = time.monotonic() + deadline_seconds source = source_connection or _connect_repair_durable(source_path) destination = destination_connection - own_source = source_connection is None - own_destination = destination_connection is None def _check_deadline(_status: int, _remaining: int, _total: int) -> None: if time.monotonic() >= deadline: - raise TimeoutError( - "timed out copying SQLite repair snapshot after " - f"{deadline_seconds:.0f}s" - ) + raise TimeoutError(f"timed out copying SQLite repair snapshot after {deadline_seconds:.0f}s") try: if destination is None: @@ -1009,19 +888,12 @@ def _copy_database_snapshot( elif destination.in_transaction: # sqlite3_backup needs a transaction-free destination; the exclusive # guard retains exclusion via locking_mode, not a transaction. - raise sqlite3.ProgrammingError( - "SQLite repair backup destination has an active transaction" - ) - source.backup( - destination, - pages=256, - progress=_check_deadline, - sleep=_REPAIR_LOCK_POLL_SECONDS, - ) + raise sqlite3.ProgrammingError("SQLite repair backup destination has an active transaction") + source.backup(destination, pages=256, progress=_check_deadline, sleep=_REPAIR_LOCK_POLL_SECONDS) finally: - if own_destination and destination is not None: + if destination_connection is None and destination is not None: destination.close() - if own_source: + if source_connection is None: source.close() @@ -1039,9 +911,7 @@ def _db_opens_cleanly(db_path: Path) -> Optional[str]: try: # Best-effort tokenizer load: messages_fts_cjk needs cjk_unicode61 # before any statement (incl. the trigger-driven write probe) can touch - # it. Without it this probe sees the DB as a tokenizer-less SessionDB - # would (which drops the cjk triggers), so tokenizer absence must never - # classify as corruption. + # it; tokenizer absence must never classify as corruption. load_fts5_cjk_extension(conn) conn.execute("PRAGMA journal_mode").fetchone() rows = conn.execute("PRAGMA integrity_check").fetchall() @@ -1050,33 +920,24 @@ def _db_opens_cleanly(db_path: Path) -> Optional[str]: return "; ".join(problems[:3]) conn.execute("SELECT COUNT(*) FROM sessions").fetchone() - # FTS5 read probe. The write probe below misses partial shadow-table - # corruption where MATCH / snippet / rank raise DatabaseError("database - # disk image is malformed"), silently breaking session_search and - # /resume title resolution while check-only reports healthy. - for fts_table in ("messages_fts", "messages_fts_trigram", "messages_fts_cjk"): + # FTS5 read probe: partial shadow-table corruption makes MATCH / + # snippet / rank raise while check-only reports healthy. MATCH '""' + # (empty phrase) parses, scans zero rows and exercises the shadow-table + # read path; FTS5 rejects MATCH '' outright. + for fts_table in _FTS_TABLES: try: - # Trigram backs title resolution, so probe it too. MATCH '""' - # (empty phrase) parses, scans zero rows and exercises the - # shadow-table read path; FTS5 rejects MATCH '' outright. - conn.execute( - f"SELECT 1 FROM {fts_table} WHERE {fts_table} MATCH '\"\"' LIMIT 1" - ).fetchone() + conn.execute(f"SELECT 1 FROM {fts_table} WHERE {fts_table} MATCH '\"\"' LIMIT 1").fetchone() except sqlite3.OperationalError as exc: - # Canonical capability classifier: on builds without fts5 a - # legacy messages_fts table may exist and MATCH raises "no such - # module: fts5"; treating that as corruption would send the DB - # into repair, whose final fallback deletes the messages_fts% - # schema. Covers "no such tokenizer: trigram" too. + # Builds without fts5 / trigram raise "no such module|tokenizer"; + # treating that as corruption would send the DB into repair, + # whose final fallback deletes the messages_fts% schema. if SessionDB._is_fts5_unavailable_error(exc): continue msg = str(exc).lower() if "no such table" in msg or "no such column" in msg: - # FTS5 not built yet (brand new file mid-init). - continue + continue # FTS5 not built yet (brand new file mid-init) return f"fts5 read probe failed on {fts_table}: {exc}" except sqlite3.DatabaseError as exc: - # Partial shadow-table damage: MATCH raises though the table parses. return f"fts5 read probe failed on {fts_table}: {exc}" # FTS write probe: drive a row through the messages_fts* triggers in a @@ -1096,7 +957,6 @@ def _db_opens_cleanly(db_path: Path) -> Optional[str]: ) conn.execute("ROLLBACK") except sqlite3.OperationalError as exc: - # Missing tables / FTS disabled — not the corruption class we probe. try: conn.execute("ROLLBACK") except sqlite3.Error: @@ -1128,10 +988,9 @@ def _live_writer_holds_db(db_path: Path) -> bool: busy/locked signal — refusing to repair a DB nobody holds would strand the self-heal path. - Scope: WAL mode only. In ``journal_mode=DELETE`` (Hermes's fallback on - WAL-reset-vulnerable builds and NFS/SMB) a held reader takes only SHARED - and this returns False; repair is then serialised only by the cross-process - repairer lock. Broadening to DELETE mode is a follow-up. + Scope: WAL mode only. In ``journal_mode=DELETE`` a held reader takes only + SHARED and this returns False; repair is then serialised only by the + cross-process repairer lock. """ probe = None try: @@ -1143,40 +1002,35 @@ def _live_writer_holds_db(db_path: Path) -> bool: except sqlite3.OperationalError as exc: lowered = str(exc).lower() return "locked" in lowered or "busy" in lowered - except sqlite3.DatabaseError: - # Malformed/unreadable: no evidence of a live holder either way. - return False - except Exception: + except Exception: # malformed/unreadable: no evidence of a live holder either way return False finally: if probe is not None: try: - # Drop exclusive mode before close so the probe never leaves - # the file pinned. - probe.execute("PRAGMA locking_mode=NORMAL") - except Exception: - pass - try: - probe.close() + _close_unpinned(probe) except Exception: pass +def _repair_skip(report: Dict[str, Any], verb: str, error: str) -> Dict[str, Any]: + """Record *error* on *report* and log it as ``state.db repair ``.""" + report["error"] = error + logger.error(f"state.db repair {verb}: %s", report["error"]) + return report + + def repair_state_db_schema(db_path: Path, *, backup: bool = True) -> Dict[str, Any]: """Repair a state.db whose ``sqlite_master`` is malformed or whose FTS indexes reject writes. Two corruption classes: malformed schema / "duplicate object definition" - (even ``PRAGMA`` fails), and FTS write-corruption (base tables read fine, - ``integrity_check`` passes, writes fail through ``messages_fts*`` - triggers). Least-destructive first: (1) rebuild FTS in place via FTS5 - ``'rebuild'``; (2) de-duplicate ``sqlite_master`` (lowest rowid per - ``type``/``name``), FTS preserved; (3) drop the FTS schema + ``VACUUM``, - rebuilt on the next ``SessionDB()`` open. Canonical rows are never - modified by a failed attempt: strategies run on a complete SQLite snapshot - and a successful result is copied back transactionally. A raw backup is - taken first unless ``backup=False``. Surgery is serialised across - processes (:func:`_cross_process_repair_lock`): the gateway, Desktop + (even ``PRAGMA`` fails), and FTS write-corruption (reads and + ``integrity_check`` pass, writes fail through ``messages_fts*`` triggers). + Strategies run least-destructive first (see ``_REPAIR_STRATEGIES``) on a + complete SQLite snapshot; a successful result is copied back + transactionally, so canonical rows are never modified by a failed attempt. + A raw backup is taken first unless ``backup=False``. Surgery is serialised + across processes (:func:`_cross_process_repair_lock`): the gateway, Desktop backend and CLI all open the same file, and concurrent ``writable_schema`` surgery is itself a corruption source. @@ -1184,12 +1038,7 @@ def repair_state_db_schema(db_path: Path, *, backup: bool = True) -> Dict[str, A error: str|None}``. """ from hermes_state import _cross_process_repair_lock, _db_opens_cleanly, _live_writer_holds_db, _persistent_repair_attempts_exhausted, _probe_journal_mode_for_repair, _record_repair_outcome, _repair_state_db_schema_locked - report: Dict[str, Any] = { - "repaired": False, - "strategy": None, - "backup_path": None, - "error": None, - } + report: Dict[str, Any] = {"repaired": False, "strategy": None, "backup_path": None, "error": None} # Startup-watchdog progress lease: repair is I/O-bound (near-zero CPU), # which the watchdog's CPU fallback would misread as a parked deadlock. A @@ -1204,12 +1053,9 @@ def repair_state_db_schema(db_path: Path, *, backup: bool = True) -> Dict[str, A # Cross-restart attempt cap: the in-memory claim bounds one process, but a # class the strategies cannot heal (b-tree page damage) used to re-run the - # whole surgery, with a fresh forensic backup, on EVERY restart. After - # _MAX_PERSISTENT_REPAIR_ATTEMPTS failures on the same file, stop. + # whole surgery, with a fresh forensic backup, on EVERY restart. if _persistent_repair_attempts_exhausted(db_path): - report["error"] = _persistent_repair_exhausted_error(db_path) - logger.error("state.db repair skipped: %s", report["error"]) - return report + return _repair_skip(report, "skipped", _persistent_repair_exhausted_error(db_path)) result = report with _cross_process_repair_lock(db_path) as holding_lock: @@ -1229,32 +1075,27 @@ def repair_state_db_schema(db_path: Path, *, backup: bool = True) -> Dict[str, A ) else: # Recheck exhaustion after acquisition: a queued repairer can have - # recorded the final failure while this process waited, and this - # process must not start a fourth attempt. + # recorded the final failure while this process waited. if _persistent_repair_attempts_exhausted(db_path): - report["error"] = _persistent_repair_exhausted_error(db_path) - logger.error("state.db repair skipped: %s", report["error"]) + _repair_skip(report, "skipped", _persistent_repair_exhausted_error(db_path)) # WAL-holder preflight: fail-closed for active readers before a # forensic backup is taken. Not the race defence — the exclusive # guard in the locked routine excludes writers through promotion and # rejects DELETE-mode readers this probe cannot see. elif _live_writer_holds_db(db_path): - report["error"] = ( + _repair_skip( + report, "skipped", "a live writer still holds state.db; skipped schema surgery " "to avoid tearing b-tree pages under a concurrent writer. " - "Stop the gateway (hermes gateway stop) and retry." + "Stop the gateway (hermes gateway stop) and retry.", ) - logger.error("state.db repair skipped: %s", report["error"]) else: # Probe the journal mode BEFORE surgery: a rebuilt file comes # back in the default (delete) mode and nothing else records - # the flip (see _restore_journal_mode_after_repair). The probe - # may fail on a damaged file; then database.journal_mode is - # the restore target. + # the flip. The probe may fail on a damaged file; then + # database.journal_mode is the restore target. before_mode = _probe_journal_mode_for_repair(db_path) - result = _repair_state_db_schema_locked( - db_path, backup=backup, report=report - ) + result = _repair_state_db_schema_locked(db_path, backup=backup, report=report) if result.get("repaired"): result["journal_mode_before"] = before_mode _restore_journal_mode_after_repair(db_path, before_mode) @@ -1266,9 +1107,7 @@ def repair_state_db_schema(db_path: Path, *, backup: bool = True) -> Dict[str, A # not record at all. attempted = bool(result.pop("_repair_attempted", False)) if attempted or result.get("repaired"): - _record_repair_outcome( - db_path, repaired=bool(result.get("repaired")) - ) + _record_repair_outcome(db_path, repaired=bool(result.get("repaired"))) return result @@ -1297,12 +1136,11 @@ def _restore_journal_mode_after_repair(db_path: Path, before_mode: Optional[str] this, a corruption event silently moves a WAL store out of WAL (the open-time WAL-reset gate never sees a flip made inside repair). Routed through :func:`apply_wal_with_fallback`, not a direct pragma, so it - inherits the vulnerable-SQLite WAL-reset gate (a rebuilt file IS a new - database; on a vulnerable runtime the gate deliberately keeps DELETE, and - "could not reach WAL" is expected there), the macOS-NFS silent-refusal - handling, and the WAL companions (size limit, checkpoint barrier, - synchronous=FULL). ``before_mode`` (None if unprobeable) is only for the - log comparison; the target comes from ``database.journal_mode``. + inherits the vulnerable-SQLite WAL-reset gate (on a vulnerable runtime the + gate deliberately keeps DELETE and the resulting journal_mode-changed + WARNING is expected there), the macOS-NFS silent-refusal handling, + and the WAL companions. ``before_mode`` (None if unprobeable) is only for + the log comparison; the target comes from ``database.journal_mode``. Best-effort: the repair already succeeded, so failures log at WARNING. """ from hermes_state import apply_wal_with_fallback @@ -1328,36 +1166,31 @@ def _restore_journal_mode_after_repair(db_path: Path, before_mode: Optional[str] ) -def _repair_state_db_schema_locked( - db_path: Path, *, backup: bool, report: Dict[str, Any] -) -> Dict[str, Any]: +def _repair_state_db_schema_locked(db_path: Path, *, backup: bool, report: Dict[str, Any]) -> Dict[str, Any]: """Repair strategies for :func:`repair_state_db_schema`. Caller must hold the cross-process repair lock for *db_path*. Strategies run on a SCRATCH COPY; the result is copied back through SQLite's transactional backup API only once proven to open cleanly, so a failed - repair cannot modify or lose committed canonical data. (A WAL checkpoint - of already-committed frames on guard release is not a repair mutation.) + repair cannot modify or lose committed canonical data. (A WAL checkpoint of + already-committed frames on guard release is not a repair mutation.) WHY not in place: Strategy 2 ends in ``VACUUM``, which rebuilds the file from the schema SQLite can still parse. When the damage IS in the schema b-tree — the ``malformed database schema ()`` class handled here — every table hanging off the unreadable part is silently dropped, the probe then correctly reports STILL malformed, and repair returned ``repaired=False`` - having destroyed what it was asked to save. The forensic backup does not - close this (nothing reads it back). Not mutating the original is the - property that holds without a human in the loop. + having destroyed what it was asked to save. Not mutating the original is + the property that holds without a human in the loop. """ from hermes_state import _backup_db_file, _copy_database_snapshot, _db_opens_cleanly, _repair_scratch_space_error, _run_repair_strategies, _unlink_db_triple scratch = db_path.with_name(f"{db_path.name}.repair-scratch") cleanup_error = _unlink_db_triple(scratch) if cleanup_error is not None: - report["error"] = ( - "could not remove a stale repair snapshot before probing state.db: " - f"{cleanup_error}" + return _repair_skip( + report, "aborted", + f"could not remove a stale repair snapshot before probing state.db: {cleanup_error}", ) - logger.error("state.db repair aborted: %s", report["error"]) - return report # Re-probe under the lock: a process we queued behind may have just # repaired the file; redoing surgery would undo its work (the @@ -1373,12 +1206,11 @@ def _repair_state_db_schema_locked( if bpath is None: # HARD STOP: the forensic image is still required when corruption # defeats every strategy, even though strategies run on a snapshot. - report["error"] = ( + return _repair_skip( + report, "aborted", "pre-repair backup refused; aborting schema repair to avoid " - f"mutating the only copy of the damaged DB: {backup_error}" + f"mutating the only copy of the damaged DB: {backup_error}", ) - logger.error("state.db repair aborted: %s", report["error"]) - return report # The forensic copy deliberately precedes this guard: its raw-copy safety # checks inspect real live holders and would be poisoned by our exclusive @@ -1386,38 +1218,31 @@ def _repair_state_db_schema_locked( # happens only after writer exclusion is held. with _exclusive_repair_db_guard(db_path) as (live_guard, guard_error): if live_guard is None: - report["error"] = ( + if guard_error is not None and _repair_failure_consumes_attempt(guard_error): + report["_repair_attempted"] = True + return _repair_skip( + report, "skipped", "could not acquire exclusive state.db repair ownership; " "skipped schema surgery to avoid overwriting a concurrent " - f"writer. Stop the gateway and retry: {guard_error}" + f"writer. Stop the gateway and retry: {guard_error}", ) - if guard_error is not None and _repair_failure_consumes_attempt( - guard_error - ): - report["_repair_attempted"] = True - logger.error("state.db repair skipped: %s", report["error"]) - return report space_error = _repair_scratch_space_error(db_path) if space_error is not None: - report["error"] = space_error - logger.error("state.db repair aborted: %s", report["error"]) - return report + return _repair_skip(report, "aborted", space_error) try: # Reuse live_guard rather than a second source connection: the # guard owns the exclusion, and a second connection could be # blocked by our own EXCLUSIVE lock on some SQLite builds. - _copy_database_snapshot( - db_path, scratch, source_connection=live_guard - ) + _copy_database_snapshot(db_path, scratch, source_connection=live_guard) except (OSError, sqlite3.Error, TimeoutError) as exc: - report["error"] = ( - f"could not stage a complete SQLite repair snapshot of {db_path}: {exc}" - ) if _repair_failure_consumes_attempt(exc): report["_repair_attempted"] = True - logger.error("state.db repair aborted: %s", report["error"]) + _repair_skip( + report, "aborted", + f"could not stage a complete SQLite repair snapshot of {db_path}: {exc}", + ) _unlink_db_triple(scratch) return report @@ -1433,27 +1258,17 @@ def _repair_state_db_schema_locked( # under open handles and POSIX would leave those handles on # the old inode. The guard that staged the live image # receives the promotion, keeping writer exclusion throughout. - _copy_database_snapshot( - scratch, - db_path, - destination_connection=live_guard, - ) + _copy_database_snapshot(scratch, db_path, destination_connection=live_guard) except (OSError, sqlite3.Error, TimeoutError) as exc: report["repaired"] = False report["strategy"] = None - report["_repair_attempted"] = _repair_failure_consumes_attempt( - exc - ) - report["error"] = ( - "repaired snapshot could not be promoted transactionally: " - f"{exc}" - ) + report["_repair_attempted"] = _repair_failure_consumes_attempt(exc) + report["error"] = f"repaired snapshot could not be promoted transactionally: {exc}" logger.error("state.db repair promotion failed: %s", exc) else: logger.warning( "state.db repaired via '%s' and promoted transactionally: %s", - report.get("strategy"), - db_path, + report.get("strategy"), db_path, ) if not report.get("repaired"): # Logged HERE, not in the strategies: they see the scratch copy, @@ -1463,8 +1278,7 @@ def _repair_state_db_schema_locked( "state.db schema repair could not recover %s automatically " "(no committed canonical data was modified or lost; backup: %s); " "manual restore from backup may be required.", - db_path, - report["backup_path"], + db_path, report["backup_path"], ) return report finally: @@ -1472,18 +1286,14 @@ def _repair_state_db_schema_locked( # or human to mistake for the real thing. cleanup_error = _unlink_db_triple(scratch) if cleanup_error is not None: - logger.warning( - "Could not remove state.db repair snapshot after repair: %s", - cleanup_error, - ) + logger.warning("Could not remove state.db repair snapshot after repair: %s", cleanup_error) def _unlink_db_triple(path: Path) -> Optional[str]: """Remove *path* and every SQLite sidecar; return any cleanup failure.""" from hermes_state import _IS_WINDOWS failures: List[str] = [] - for suffix in ("", *_DB_SIDECAR_SUFFIXES): - victim = path if not suffix else path.with_name(path.name + suffix) + for victim in (path, *_sidecars(path)): for attempt in range(10): try: victim.unlink() @@ -1505,135 +1315,126 @@ def _unlink_db_triple(path: Path) -> Optional[str]: return "; ".join(failures) or None -def _run_repair_strategies( - db_path: Path, report: Dict[str, Any] -) -> Dict[str, Any]: +# ── Repair strategies, least destructive first (each mutates its connection's DB) ── + +def _strategy_rebuild_fts(conn: sqlite3.Connection) -> None: + """FTS5 'rebuild' rewrites each index from the content table: the least- + destructive fix for an index that rejects writes while reads work.""" + from hermes_state import load_fts5_cjk_extension + # The cjk index can only be rebuilt with its tokenizer loaded + # (best-effort; a tokenizer-less host skips it below). + load_fts5_cjk_extension(conn) + for table_name in _FTS_TABLES: + try: + conn.execute(f"INSERT INTO {table_name}({table_name}) VALUES('rebuild')") + except sqlite3.OperationalError: + continue # table absent (FTS disabled / trigram off / cjk not present) + + +def _strategy_reindex(conn: sqlite3.Connection) -> None: + """integrity_check reports "wrong # of entries in index" when a B-tree + index drifts from its base table; REINDEX rewrites it from canonical rows.""" + # REINDEX rewrites every index b-tree; take the barriers now that the + # schema parses, in case the open-time attempt was refused. + _reapply_durability_barriers(conn) + conn.execute("REINDEX") + conn.commit() + + +def _strategy_dedup_schema(conn: sqlite3.Connection) -> None: + """De-duplicate sqlite_master (lowest rowid per type/name), keeping FTS.""" + conn.execute("PRAGMA writable_schema=ON") + dupes = conn.execute( + "SELECT type, name, COUNT(*) AS c, MIN(rowid) AS keep " + "FROM sqlite_master GROUP BY type, name HAVING c > 1" + ).fetchall() + for type_, name, _count, keep in dupes: + conn.execute( + "DELETE FROM sqlite_master " + "WHERE type IS ? AND name IS ? AND rowid <> ?", + (type_, name, keep), + ) + if dupes: + _bump_schema_cookie(conn) + conn.execute("PRAGMA writable_schema=OFF") + conn.commit() + + +def _strategy_drop_fts_vacuum(conn: sqlite3.Connection) -> None: + """Drop all FTS schema and VACUUM; indexes rebuild on the next open. + + The destructive one, and why the strategies run on a scratch copy: on a + damaged schema b-tree VACUUM silently drops every table hanging off the + unreadable part (see _repair_state_db_schema_locked). + """ + conn.execute("PRAGMA writable_schema=ON") + conn.execute("DELETE FROM sqlite_master WHERE name LIKE 'messages_fts%'") + _bump_schema_cookie(conn) + conn.execute("PRAGMA writable_schema=OFF") + conn.commit() + # The schema parses now, so the barriers can finally stick — and VACUUM + # rewrites the entire file, the worst operation to lose halfway. + _reapply_durability_barriers(conn) + conn.execute("VACUUM") + + +# (strategy name, body, success log, failure log) in escalation order. The +# first three log a warning on failure and fall through; the last records the +# failure in report["error"] for the caller. +_REPAIR_STRATEGIES = ( + ("rebuild_fts", _strategy_rebuild_fts, + "state.db FTS indexes rebuilt in place (schema preserved): %s", + "state.db FTS in-place rebuild pass failed: %s"), + ("reindex_btree", _strategy_reindex, + "state.db B-tree indexes rebuilt via REINDEX: %s", + "state.db REINDEX pass failed: %s"), + ("dedup_schema", _strategy_dedup_schema, + "state.db schema repaired by de-duplicating sqlite_master (FTS index preserved): %s", + "state.db dedup repair pass failed: %s"), +) +_FINAL_STRATEGY = ( + "drop_fts_rebuild", _strategy_drop_fts_vacuum, + "state.db schema repaired by dropping FTS schema; indexes will rebuild from messages on next open: %s", +) + + +def _run_repair_strategies(db_path: Path, report: Dict[str, Any]) -> Dict[str, Any]: """Escalating repair attempts, applied to *db_path* IN PLACE. Every strategy mutates its argument, so this is only ever called by :func:`_repair_state_db_schema_locked` on a scratch copy nothing else - holds open — never on the user's database. + holds open — never on the user's database. The "could not recover" log + lives in the caller: it must name the user's database, not the scratch copy. """ - from hermes_state import _db_opens_cleanly, load_fts5_cjk_extension - # ── Strategy 0: rebuild FTS indexes in place (FTS write-corruption) ── - # FTS5 'rebuild' rewrites the index from the content table: the - # least-destructive fix for an index that rejects writes while reads work. - try: - conn = _connect_repair_durable(db_path) - try: - # The cjk index can only be rebuilt with its tokenizer loaded - # (best-effort; a tokenizer-less host skips it below). - load_fts5_cjk_extension(conn) - for table_name in ( - "messages_fts", "messages_fts_trigram", "messages_fts_cjk" - ): - try: - conn.execute( - f"INSERT INTO {table_name}({table_name}) VALUES('rebuild')" - ) - except sqlite3.OperationalError: - # Table absent (FTS disabled / trigram off / cjk not present - # or tokenizer unavailable). - continue - finally: - conn.close() - if _db_opens_cleanly(db_path) is None: - report["repaired"] = True - report["strategy"] = "rebuild_fts" - logger.warning( - "state.db FTS indexes rebuilt in place (schema preserved): %s", - db_path, - ) - return report - except sqlite3.DatabaseError as exc: - logger.warning("state.db FTS in-place rebuild pass failed: %s", exc) + from hermes_state import _db_opens_cleanly - # ── Strategy 0.5: rebuild stale B-tree indexes ── - # integrity_check reports "wrong # of entries in index" when a B-tree index - # drifts from its base table; REINDEX rewrites it from the canonical rows. - try: + def _apply(body) -> Optional[str]: conn = _connect_repair_durable(db_path) try: - # REINDEX rewrites every index b-tree; take the barriers now that - # the schema parses, in case the open-time attempt was refused. - _reapply_durability_barriers(conn) - conn.execute("REINDEX") - conn.commit() + body(conn) finally: conn.close() - if _db_opens_cleanly(db_path) is None: - report["repaired"] = True - report["strategy"] = "reindex_btree" - logger.warning( - "state.db B-tree indexes rebuilt via REINDEX: %s", db_path - ) - return report - except sqlite3.DatabaseError as exc: - logger.warning("state.db REINDEX pass failed: %s", exc) + return _db_opens_cleanly(db_path) - # ── Strategy 1: de-duplicate sqlite_master (keeps FTS index) ── - try: - conn = _connect_repair_durable(db_path) - try: - conn.execute("PRAGMA writable_schema=ON") - dupes = conn.execute( - "SELECT type, name, COUNT(*) AS c, MIN(rowid) AS keep " - "FROM sqlite_master GROUP BY type, name HAVING c > 1" - ).fetchall() - for type_, name, _count, keep in dupes: - conn.execute( - "DELETE FROM sqlite_master " - "WHERE type IS ? AND name IS ? AND rowid <> ?", - (type_, name, keep), - ) - if dupes: - _bump_schema_cookie(conn) - conn.execute("PRAGMA writable_schema=OFF") - conn.commit() - finally: - conn.close() - if _db_opens_cleanly(db_path) is None: - report["repaired"] = True - report["strategy"] = "dedup_schema" - logger.warning( - "state.db schema repaired by de-duplicating sqlite_master " - "(FTS index preserved): %s", db_path - ) - return report - except sqlite3.DatabaseError as exc: - logger.warning("state.db dedup repair pass failed: %s", exc) + def _succeed(name: str, message: str) -> Dict[str, Any]: + report["repaired"] = True + report["strategy"] = name + logger.warning(message, db_path) + return report - # ── Strategy 2: drop all FTS schema, VACUUM, rebuild on next open ── - # The destructive one, and why this path runs on a scratch copy: on a - # damaged schema b-tree VACUUM silently drops every table hanging off the - # unreadable part (see _repair_state_db_schema_locked). - try: - conn = _connect_repair_durable(db_path) + for name, body, success_msg, failure_msg in _REPAIR_STRATEGIES: try: - conn.execute("PRAGMA writable_schema=ON") - conn.execute("DELETE FROM sqlite_master WHERE name LIKE 'messages_fts%'") - _bump_schema_cookie(conn) - conn.execute("PRAGMA writable_schema=OFF") - conn.commit() - # The schema parses now, so the barriers can finally stick — and - # VACUUM rewrites the entire file, the worst operation to lose halfway. - _reapply_durability_barriers(conn) - conn.execute("VACUUM") - finally: - conn.close() - reason = _db_opens_cleanly(db_path) + if _apply(body) is None: + return _succeed(name, success_msg) + except sqlite3.DatabaseError as exc: + logger.warning(failure_msg, exc) + + name, body, success_msg = _FINAL_STRATEGY + try: + reason = _apply(body) if reason is None: - report["repaired"] = True - report["strategy"] = "drop_fts_rebuild" - logger.warning( - "state.db schema repaired by dropping FTS schema; indexes " - "will rebuild from messages on next open: %s", db_path - ) - return report + return _succeed(name, success_msg) report["error"] = reason except sqlite3.DatabaseError as exc: report["error"] = str(exc) - - # The "could not recover" log lives in the caller: it must name the user's - # database, not the scratch copy. return report diff --git a/hermes_state_schema.py b/hermes_state_schema.py index 0130fd434f..49ac7e1291 100644 --- a/hermes_state_schema.py +++ b/hermes_state_schema.py @@ -21,21 +21,9 @@ from typing import Dict, List, Optional, Sequence from hermes_constants import get_hermes_home from hermes_startup_watchdog import report_startup_progress from hermes_state_common import ( - DEFERRED_INDEX_SQL, - FTS_CJK_STALE_KEY, - FTS_REBUILD_DEFERRAL_KEY, - FTS_STALE_KEY, - FTS_SQL, - FTS_STORAGE_VERSION, - FTS_TRIGRAM_SQL, - LEGACY_FTS_SQL, - LEGACY_FTS_TRIGRAM_SQL, - SCHEMA_SQL, - SCHEMA_VERSION, - _FTS_CJK_TRIGGERS, - _FTS_TRIGGERS, - _ephemeral_child_sql, - fts_rebuild_admission, + DEFERRED_INDEX_SQL, FTS_CJK_STALE_KEY, FTS_REBUILD_DEFERRAL_KEY, FTS_STALE_KEY, FTS_SQL, + FTS_STORAGE_VERSION, FTS_TRIGRAM_SQL, LEGACY_FTS_SQL, LEGACY_FTS_TRIGRAM_SQL, SCHEMA_SQL, + SCHEMA_VERSION, _FTS_CJK_TRIGGERS, _FTS_TRIGGERS, _ephemeral_child_sql, fts_rebuild_admission, ) # Keep the pre-split logger identity so log filtering/capture is unchanged. @@ -45,9 +33,8 @@ _FTS_HOLDER_ESCALATE_ATTEMPTS = 3 _FTS_HOLDER_ESCALATE_SECONDS = 60.0 # In-process retry cadence for a deferred stale-FTS rebuild # (``retry_deferred_fts_recovery``): startup paid the full admission wait once; -# later retries are non-blocking probes so a live holder never stalls a -# long-lived writer. Each failed retry doubles the spacing up to the cap, so a -# permanent holder costs one deferral warning per hour, not per minute. +# later retries are non-blocking probes. Each failed retry doubles the spacing +# up to the cap, so a permanent holder costs one warning per hour, not per minute. _FTS_STALE_RETRY_SECONDS = 60.0 _FTS_STALE_RETRY_MAX_SECONDS = 3600.0 @@ -55,46 +42,106 @@ _FTS_STALE_RETRY_MAX_SECONDS = 3600.0 # in-memory SQLite database, so do it once per process. _READ_PROBE_STATEMENTS: Optional[tuple] = None -# The trigram triggers come ONLY from FTS_TRIGRAM_SQL / LEGACY_FTS_TRIGRAM_SQL, -# whose CREATE VIRTUAL TABLE needs the trigram tokenizer (SQLite >= 3.34); -# without it _ensure_fts_schema soft-fails that DDL and "all six present" is -# permanently unsatisfiable. Split the set so a trigger's absence is only -# measured against the DDL that can create it. Exhaustive and disjoint by -# construction; pinned by test_fts_trigger_subsets_match_the_ddl. +# Trigram triggers come ONLY from FTS_TRIGRAM_SQL / LEGACY_FTS_TRIGRAM_SQL, whose +# CREATE VIRTUAL TABLE needs the trigram tokenizer (SQLite >= 3.34); without it +# _ensure_fts_schema soft-fails that DDL and "all six present" is unsatisfiable. +# Split so a trigger's absence is measured only against the DDL that can create +# it. Exhaustive and disjoint by construction (test_fts_trigger_subsets_match_the_ddl). _FTS_TRIGRAM_TRIGGERS = tuple(n for n in _FTS_TRIGGERS if "_trigram_" in n) _FTS_BASE_TRIGGERS = tuple(n for n in _FTS_TRIGGERS if n not in _FTS_TRIGRAM_TRIGGERS) +_LEGACY_INLINE_CONCAT_SQL = ( + "COALESCE(content, '') || ' ' || COALESCE(tool_name, '') || ' ' || COALESCE(tool_calls, '') " +) +_SESSION_MODEL_USAGE_INDEX_SQL = ( + "CREATE INDEX IF NOT EXISTS idx_session_model_usage_session ON session_model_usage(session_id)", + "CREATE INDEX IF NOT EXISTS idx_session_model_usage_model ON session_model_usage(model)", +) +_SESSION_MODEL_USAGE_HEAL_DDL = """CREATE TABLE session_model_usage ( + session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, + model TEXT NOT NULL, + billing_provider TEXT NOT NULL DEFAULT '', + billing_base_url TEXT NOT NULL DEFAULT '', + billing_mode TEXT NOT NULL DEFAULT '', + task TEXT NOT NULL DEFAULT '', + api_call_count INTEGER NOT NULL DEFAULT 0, + input_tokens INTEGER NOT NULL DEFAULT 0, + output_tokens INTEGER NOT NULL DEFAULT 0, + cache_read_tokens INTEGER NOT NULL DEFAULT 0, + cache_write_tokens INTEGER NOT NULL DEFAULT 0, + reasoning_tokens INTEGER NOT NULL DEFAULT 0, + estimated_cost_usd REAL NOT NULL DEFAULT 0, + actual_cost_usd REAL NOT NULL DEFAULT 0, + cost_status TEXT, + cost_source TEXT, + first_seen REAL, + last_seen REAL, + PRIMARY KEY (session_id, model, billing_provider, billing_base_url, billing_mode, task) +)""" +# Same table as emitted by the v22 migration: column lines at 35 spaces, closing +# paren at 31 (statement text is pinned by the SQL trace harness). +_SESSION_MODEL_USAGE_V22_DDL = "\n".join( + [_SESSION_MODEL_USAGE_HEAL_DDL.splitlines()[0]] + + [" " * 35 + ln.strip() for ln in _SESSION_MODEL_USAGE_HEAL_DDL.splitlines()[1:-1]] + + [" " * 31 + ")"] +) +# Statement text pinned by the SQL trace harness (whitespace included). +_SESSION_MODEL_USAGE_V20_SEED_SQL = """INSERT OR IGNORE INTO session_model_usage ( + session_id, model, billing_provider, + billing_base_url, billing_mode, + 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 + ) + SELECT id, COALESCE(model, 'unknown'), + COALESCE(billing_provider, ''), + COALESCE(billing_base_url, ''), + COALESCE(billing_mode, ''), + COALESCE(api_call_count, 0), + COALESCE(input_tokens, 0), + COALESCE(output_tokens, 0), + COALESCE(cache_read_tokens, 0), + COALESCE(cache_write_tokens, 0), + COALESCE(reasoning_tokens, 0), + COALESCE(estimated_cost_usd, 0), + COALESCE(actual_cost_usd, 0), + cost_status, cost_source, + started_at, COALESCE(ended_at, started_at) + FROM sessions + WHERE COALESCE(input_tokens, 0) + + COALESCE(output_tokens, 0) + + COALESCE(cache_read_tokens, 0) + + COALESCE(cache_write_tokens, 0) + + COALESCE(reasoning_tokens, 0) > 0""" +_TITLE_UNIQUE_INDEX_SQL = ( + "CREATE UNIQUE INDEX IF NOT EXISTS idx_sessions_title_unique " + "ON sessions(title) WHERE title IS NOT NULL" +) + + +def _q(ident: str) -> str: + """Double-quote an SQL identifier.""" + return '"' + ident.replace('"', '""') + '"' + def schema_read_probe_statements() -> tuple: """SELECT statements that fail iff a live store is behind SCHEMA_SQL. - Read-only opens skip ``_reconcile_columns()`` by design (no DDL against - another profile's live DB), so a store created before a schema addition - keeps failing on read paths until something opens it writable. Healing - callers (``_open_session_db_at_path`` in the web server) run these probes - after a read-only open: a missing table/column raises at prepare time. - - Derived from SCHEMA_SQL so a column added there is covered automatically - (a hand-maintained list went stale within days). Each statement is - ``LIMIT 0`` (resolution at prepare time, zero rows read). Column - references are table-qualified: an unqualified double-quoted identifier - that fails to resolve silently degrades to a string literal (SQLite - misfeature), which would make the probe pass on exactly the stale store - it exists to catch. - """ + another profile's live DB), so healing callers (``_open_session_db_at_path`` + in the web server) run these probes after a read-only open: a missing + table/column raises at prepare time. Derived from SCHEMA_SQL so a column + added there is covered automatically (a hand-maintained list went stale + within days); ``LIMIT 0`` so zero rows are read. Column references are + table-qualified: an unqualified double-quoted identifier that fails to + resolve silently degrades to a string literal (SQLite misfeature), which + would make the probe pass on exactly the stale store it exists to catch.""" global _READ_PROBE_STATEMENTS if _READ_PROBE_STATEMENTS is None: tables = SessionSchemaMixin._parse_schema_columns(SCHEMA_SQL) _READ_PROBE_STATEMENTS = tuple( - 'SELECT {} FROM "{}" LIMIT 0'.format( - ", ".join( - '"{}"."{}"'.format( - table.replace('"', '""'), col.replace('"', '""') - ) - for col in cols - ), - table.replace('"', '""'), - ) + "SELECT {} FROM {} LIMIT 0".format(", ".join(f"{_q(table)}.{_q(col)}" for col in cols), _q(table)) for table, cols in sorted(tables.items()) ) return _READ_PROBE_STATEMENTS @@ -105,28 +152,22 @@ class SessionSchemaMixin: def _dedupe_legacy_system_prompts(self, cursor: sqlite3.Cursor) -> None: """Move inline prompt snapshots into the shared content-addressed table. - Contention-safe: any ``OperationalError`` mid-loop returns instead of raising. Partial migration is safe — the legacy ``system_prompt`` column stays a read fallback and the next schema init resumes. Propagating the error aborted schema init, left the version below - 25, and re-entered this migration on every open (gateway crash loop). - """ + 25, and re-entered this migration on every open (gateway crash loop).""" try: rows = cursor.execute( - "SELECT id, system_prompt FROM sessions " - "WHERE system_prompt IS NOT NULL" + "SELECT id, system_prompt FROM sessions WHERE system_prompt IS NOT NULL" ).fetchall() except sqlite3.OperationalError: return - for session_id, prompt in rows: try: prompt_hash = self._store_system_prompt(cursor, prompt) cursor.execute( - "UPDATE sessions " - "SET system_prompt_hash = ?, system_prompt = NULL " - "WHERE id = ?", + "UPDATE sessions SET system_prompt_hash = ?, system_prompt = NULL WHERE id = ?", (prompt_hash, session_id), ) except sqlite3.OperationalError as exc: @@ -158,15 +199,11 @@ class SessionSchemaMixin: pass @staticmethod - def _fts_trigger_count( - cursor: sqlite3.Cursor, - names: Sequence[str] = _FTS_TRIGGERS, - ) -> int: + def _fts_trigger_count(cursor: sqlite3.Cursor, names: Sequence[str] = _FTS_TRIGGERS) -> int: """Count how many of *names* currently exist as triggers (pass _FTS_BASE_TRIGGERS / _FTS_TRIGRAM_TRIGGERS to check one half).""" if not names: - # "name IN ()" is a SQLite syntax error. - return 0 + return 0 # "name IN ()" is a SQLite syntax error placeholders = ",".join("?" for _ in names) row = cursor.execute( f"SELECT COUNT(*) FROM sqlite_master " @@ -177,33 +214,23 @@ class SessionSchemaMixin: @staticmethod def _fts_update_trigger_needs_narrowing(sql: Optional[str]) -> bool: - """True when trigger SQL is missing AFTER UPDATE OF (still broad).""" + """True when trigger SQL is a broad AFTER UPDATE (missing ``OF``).""" if not sql: return False - # Collapse whitespace so multi-line DDL still matches. - compact = " ".join(sql.split()).upper() - # Already narrowed. - if "AFTER UPDATE OF " in compact: - return False - # Broad UPDATE trigger that we still need to replace. - return "AFTER UPDATE ON " in compact + compact = " ".join(sql.split()).upper() # multi-line DDL still matches + return "AFTER UPDATE OF " not in compact and "AFTER UPDATE ON " in compact def _migrate_broad_fts_update_triggers(self, cursor: sqlite3.Cursor) -> int: """Replace broad AFTER UPDATE FTS triggers with AFTER UPDATE OF variants. - ``CREATE TRIGGER IF NOT EXISTS`` never replaces an existing broad trigger, so it would keep firing on every messages row touch. Drop still-broad UPDATE triggers and re-apply the current DDL. No FTS rebuild: correctness was already gated by WHEN clauses; OF only skips - unnecessary trigger evaluation. Returns the number dropped. - """ + unnecessary trigger evaluation. Returns the number dropped.""" # CJK is v23-only. Decide the layout before selecting destructive # candidates so the legacy branch never drops a trigger it won't recreate. legacy_layout = self._db_has_legacy_inline_fts(cursor) - update_names = ( - "messages_fts_update", - "messages_fts_trigram_update", - ) + update_names = ("messages_fts_update", "messages_fts_trigram_update") if not legacy_layout: update_names += ("messages_fts_cjk_update",) placeholders = ", ".join("?" for _ in update_names) @@ -212,43 +239,31 @@ class SessionSchemaMixin: f"WHERE type = 'trigger' AND name IN ({placeholders})", update_names, ).fetchall() - to_drop = [ - name for name, sql in rows - if self._fts_update_trigger_needs_narrowing(sql) - ] + to_drop = [name for name, sql in rows if self._fts_update_trigger_needs_narrowing(sql)] if not to_drop: return 0 - for name in to_drop: - # Names are drawn from the update_names literal allowlist above — - # never user input — so the identifier is interpolation-safe. + # Names come from the literal allowlist above — interpolation-safe. cursor.execute(f"DROP TRIGGER IF EXISTS {name}") - # Re-apply current DDL so CREATE TRIGGER installs the OF variants. - # Choose legacy vs v23 the same way _init_schema does. + # Re-apply current DDL (legacy vs v23 chosen as _init_schema does) so + # CREATE TRIGGER installs the OF variants. if legacy_layout: self._ensure_fts_schema(cursor, "messages_fts", LEGACY_FTS_SQL) - self._ensure_fts_schema( - cursor, "messages_fts_trigram", LEGACY_FTS_TRIGRAM_SQL - ) + self._ensure_fts_schema(cursor, "messages_fts_trigram", LEGACY_FTS_TRIGRAM_SQL) else: self._ensure_fts_schema(cursor, "messages_fts", FTS_SQL) - self._ensure_fts_schema( - cursor, "messages_fts_trigram", FTS_TRIGRAM_SQL - ) + self._ensure_fts_schema(cursor, "messages_fts_trigram", FTS_TRIGRAM_SQL) # Only recreate the CJK trigger this migration actually dropped. # ``_ensure_fts_cjk_schema`` soft-fails OperationalError by clearing - # availability (never raises), so after ensure require a narrowed - # CJK UPDATE trigger or durable quarantine (stale breadcrumb + - # unavailable). + # availability (never raises), so afterwards require a narrowed CJK + # UPDATE trigger or durable quarantine (stale breadcrumb + unavailable). if "messages_fts_cjk_update" in to_drop: try: self._ensure_fts_cjk_schema(cursor) except Exception: self._quarantine_cjk_after_update_of_migration(cursor) - logger.exception( - "CJK FTS re-ensure after UPDATE OF migration failed" - ) + logger.exception("CJK FTS re-ensure after UPDATE OF migration failed") raise if not self._cjk_update_trigger_is_narrowed(cursor): self._quarantine_cjk_after_update_of_migration(cursor) @@ -256,10 +271,8 @@ class SessionSchemaMixin: "CJK FTS UPDATE trigger missing or still broad after " "UPDATE OF migration; marked stale and unavailable" ) - logger.info( - "Migrated %d broad FTS UPDATE trigger(s) to AFTER UPDATE OF " - "(no rebuild required)", + "Migrated %d broad FTS UPDATE trigger(s) to AFTER UPDATE OF " "(no rebuild required)", len(to_drop), ) return len(to_drop) @@ -267,15 +280,12 @@ class SessionSchemaMixin: def _cjk_update_trigger_is_narrowed(self, cursor: sqlite3.Cursor) -> bool: """True when messages_fts_cjk_update exists with AFTER UPDATE OF.""" row = cursor.execute( - "SELECT sql FROM sqlite_master " - "WHERE type = 'trigger' AND name = ?", + "SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = ?", ("messages_fts_cjk_update",), ).fetchone() return bool(row) and not self._fts_update_trigger_needs_narrowing(row[0]) - def _quarantine_cjk_after_update_of_migration( - self, cursor: sqlite3.Cursor - ) -> None: + def _quarantine_cjk_after_update_of_migration(self, cursor: sqlite3.Cursor) -> None: """Fail closed after dropping the CJK UPDATE trigger mid-migration: clear availability, persist ``fts_cjk_stale``, drop any residual CJK UPDATE trigger so a later open cannot IF-NOT-EXISTS over a gap.""" @@ -283,72 +293,48 @@ class SessionSchemaMixin: try: self.set_meta(FTS_CJK_STALE_KEY, "1", cursor=cursor) except Exception: - logger.debug( - "Could not persist CJK FTS stale breadcrumb", - exc_info=True, - ) + logger.debug("Could not persist CJK FTS stale breadcrumb", exc_info=True) try: cursor.execute("DROP TRIGGER IF EXISTS messages_fts_cjk_update") except Exception: - logger.debug( - "Could not drop residual CJK UPDATE trigger after quarantine", - exc_info=True, - ) - + logger.debug("Could not drop residual CJK UPDATE trigger after quarantine", exc_info=True) @staticmethod - def _rebuild_fts_indexes( - cursor: sqlite3.Cursor, - *, - include_trigram: bool = True, - ) -> None: - # v23+ external-content tables: 'rebuild' repopulates the inverted - # index from the content source (messages / messages_fts_trigram_src). + def _rebuild_fts_indexes(cursor: sqlite3.Cursor, *, include_trigram: bool = True) -> None: + """v23+ external-content tables: 'rebuild' repopulates the inverted + index from the content source (messages / messages_fts_trigram_src). + 'rebuild' indexes EVERY row, so the deferred-backfill markers are + cleared or the worker would re-insert covered rows (duplicates).""" cursor.execute("INSERT INTO messages_fts(messages_fts) VALUES('rebuild')") if include_trigram: - cursor.execute( - "INSERT INTO messages_fts_trigram(messages_fts_trigram) VALUES('rebuild')" - ) - # 'rebuild' indexes EVERY row: clear deferred-backfill markers or the - # worker would re-insert rows already covered (duplicates). + cursor.execute("INSERT INTO messages_fts_trigram(messages_fts_trigram) VALUES('rebuild')") cursor.execute( - "DELETE FROM state_meta WHERE key IN " - "('fts_rebuild_high_water', 'fts_rebuild_progress')" + "DELETE FROM state_meta WHERE key IN ('fts_rebuild_high_water', 'fts_rebuild_progress')" ) @staticmethod - def _rebuild_legacy_fts_indexes( - cursor: sqlite3.Cursor, - *, - include_trigram: bool = True, - ) -> None: + def _rebuild_legacy_fts_indexes(cursor: sqlite3.Cursor, *, include_trigram: bool = True) -> None: """Rebuild the LEGACY inline (pre-v23) FTS indexes from messages. - Inline tables have no external-content 'rebuild' source, so DELETE + reinsert the concatenated content the legacy triggers produced. - Never touches the v23 shape. - """ + Never touches the v23 shape.""" tables = ("messages_fts", "messages_fts_trigram") if include_trigram else ("messages_fts",) for tbl in tables: cursor.execute(f"DELETE FROM {tbl}") - cursor.execute( - f"INSERT INTO {tbl}(rowid, content) " - "SELECT id, " - "COALESCE(content, '') || ' ' || " - "COALESCE(tool_name, '') || ' ' || " - "COALESCE(tool_calls, '') " - "FROM messages" - ) + cursor.execute(f"INSERT INTO {tbl}(rowid, content) SELECT id, {_LEGACY_INLINE_CONCAT_SQL}FROM messages") def _fts_table_probe(self, cursor: sqlite3.Cursor, table_name: str) -> Optional[bool]: + """True = queryable, False = absent, None = FTS module/tokenizer missing + or content undecodable (index degraded, store accessible). + + Invalid UTF-8 in FTS content surfaces as a bare UnicodeDecodeError on + some builds and as OperationalError("Could not decode to UTF-8 ...") on + others; both are caught so the probe never raises into writable-init / + recovery flows. Anything else (malformed schema, corrupt vtable) re-raises.""" try: cursor.execute(f"SELECT * FROM {table_name} LIMIT 0") return True except (sqlite3.OperationalError, UnicodeDecodeError) as exc: - # Invalid UTF-8 in FTS content surfaces as a bare UnicodeDecodeError - # (not sqlite3.Error) on some builds and as OperationalError("Could - # not decode to UTF-8 ...") on others; catch both so the probe never - # raises into writable-init/recovery flows. if isinstance(exc, sqlite3.OperationalError): if self._is_fts5_unavailable_error(exc): # A missing trigram tokenizer only affects trigram search; @@ -360,11 +346,8 @@ class SessionSchemaMixin: return None if "no such table" in str(exc).lower(): return False - # Anything else (malformed schema, corrupt vtable) re-raises. if "decode to utf-8" not in str(exc).lower(): raise - # Decode error: index degraded, store accessible; writable init / - # recovery schedules a rebuild or degrades to LIKE. logger.warning( "%s probe encountered invalid UTF-8 in FTS content; " "search may return incomplete results until FTS is rebuilt: %s", @@ -373,90 +356,84 @@ class SessionSchemaMixin: ) return None - def _recover_stale_fts( - self, cursor: sqlite3.Cursor, *, legacy: bool, timeout_seconds=None - ) -> bool: - """Atomically rebuild stale base/trigram indexes and resume syncing. + # ── Stale-FTS recovery ───────────────────────────────────────────────── - *timeout_seconds* bounds the cross-process admission wait; None uses - the full startup budget, ``0`` is the non-blocking in-process retry. - """ - foreign_holders = self._foreign_state_db_holders() - if foreign_holders: - now = time.time() - record = None - try: - row = cursor.execute( - "SELECT value FROM state_meta WHERE key = ? LIMIT 1", - (FTS_REBUILD_DEFERRAL_KEY,), - ).fetchone() - if row: - parsed = json.loads(row[0]) - if isinstance(parsed, dict): - record = parsed - except (sqlite3.Error, TypeError, ValueError, json.JSONDecodeError): - record = None + def _defer_stale_fts_for_holders(self, cursor: sqlite3.Cursor, foreign_holders) -> bool: + """Record a deferral diagnostic for the foreign processes holding the + DB and decide whether to defer; True = defer (holders remain). - try: - first_seen = float((record or {}).get("first_seen", now)) - attempts = int((record or {}).get("attempts", 0)) + 1 - except (TypeError, ValueError): - first_seen = now - attempts = 1 - if first_seen > now or first_seen < 0: - first_seen = now - holder_pids = sorted({pid for pid, _path in foreign_holders if pid > 0}) - diagnostic = { - "first_seen": first_seen, - "last_seen": now, - "attempts": attempts, - "holder_pids": holder_pids, - } - cursor.execute( - "INSERT INTO state_meta (key, value) VALUES (?, ?) " - "ON CONFLICT(key) DO UPDATE SET value = excluded.value", - (FTS_REBUILD_DEFERRAL_KEY, json.dumps(diagnostic, sort_keys=True)), + After ``_FTS_HOLDER_ESCALATE_ATTEMPTS`` deferrals spanning + ``_FTS_HOLDER_ESCALATE_SECONDS``, provably inactive orphan Desktop + backends are reaped and the holders re-checked.""" + now = time.time() + record = {} + try: + row = cursor.execute( + "SELECT value FROM state_meta WHERE key = ? LIMIT 1", (FTS_REBUILD_DEFERRAL_KEY,), + ).fetchone() + if row: + parsed = json.loads(row[0]) + if isinstance(parsed, dict): + record = parsed + except (sqlite3.Error, TypeError, ValueError, json.JSONDecodeError): + record = {} + try: + first_seen = float(record.get("first_seen", now)) + attempts = int(record.get("attempts", 0)) + 1 + except (TypeError, ValueError): + first_seen, attempts = now, 1 + if first_seen > now or first_seen < 0: + first_seen = now + diagnostic = { + "first_seen": first_seen, "last_seen": now, "attempts": attempts, + "holder_pids": sorted({pid for pid, _path in foreign_holders if pid > 0}), + } + cursor.execute( + "INSERT INTO state_meta (key, value) VALUES (?, ?) " + "ON CONFLICT(key) DO UPDATE SET value = excluded.value", + (FTS_REBUILD_DEFERRAL_KEY, json.dumps(diagnostic, sort_keys=True)), + ) + if attempts >= _FTS_HOLDER_ESCALATE_ATTEMPTS and now - first_seen >= _FTS_HOLDER_ESCALATE_SECONDS: + reaped = self._reap_inactive_orphan_desktop_holders( + foreign_holders, min_age_seconds=_FTS_HOLDER_ESCALATE_SECONDS, ) - - escalated = ( - attempts >= _FTS_HOLDER_ESCALATE_ATTEMPTS - and now - first_seen >= _FTS_HOLDER_ESCALATE_SECONDS - ) - if escalated: - reaped = self._reap_inactive_orphan_desktop_holders( - foreign_holders, - min_age_seconds=_FTS_HOLDER_ESCALATE_SECONDS, - ) - if reaped: - logger.error( - "Reaped inactive orphan Desktop backend(s) %s after %d " - "state.db FTS rebuild deferrals; checking holders again.", - reaped, - attempts, - ) - foreign_holders = self._foreign_state_db_holders() - if foreign_holders: - logger.error( - "state.db FTS repair remains blocked after %d deferrals " - "by holder(s) %s. Stop the listed processes, then run " - "`hermes sessions optimize-storage` with the gateway stopped. " - "`hermes doctor` reports this degraded state.", - attempts, - foreign_holders, - ) - - if foreign_holders: - logger.warning( - "Deferred stale state.db FTS rebuild while foreign processes " - "hold the database or WAL sidecars (%s); canonical writes and " - "LIKE search remain available (deferral %d).", - foreign_holders, + if reaped: + logger.error( + "Reaped inactive orphan Desktop backend(s) %s after %d " + "state.db FTS rebuild deferrals; checking holders again.", + reaped, attempts, ) - return False - # Full structural rebuild: admit through the cross-process authority - # (fail closed). Losing the race means another process is doing this - # exact recovery; the breadcrumb stays set and we retry later. + foreign_holders = self._foreign_state_db_holders() + if foreign_holders: + logger.error( + "state.db FTS repair remains blocked after %d deferrals " + "by holder(s) %s. Stop the listed processes, then run " + "`hermes sessions optimize-storage` with the gateway stopped. " + "`hermes doctor` reports this degraded state.", + attempts, + foreign_holders, + ) + if not foreign_holders: + return False + logger.warning( + "Deferred stale state.db FTS rebuild while foreign processes " + "hold the database or WAL sidecars (%s); canonical writes and " + "LIKE search remain available (deferral %d).", + foreign_holders, + attempts, + ) + return True + + def _recover_stale_fts(self, cursor: sqlite3.Cursor, *, legacy: bool, timeout_seconds=None) -> bool: + """Atomically rebuild stale base/trigram indexes and resume syncing. + *timeout_seconds* bounds the cross-process admission wait; None uses + the full startup budget, ``0`` is the non-blocking in-process retry. + Fails closed: foreign holders or a lost admission race leave the + breadcrumb set and defer to a later retry.""" + foreign_holders = self._foreign_state_db_holders() + if foreign_holders and self._defer_stale_fts_for_holders(cursor, foreign_holders): + return False with fts_rebuild_admission(self.db_path, timeout_seconds=timeout_seconds) as admitted: if not admitted: logger.warning( @@ -468,19 +445,15 @@ class SessionSchemaMixin: return self._recover_stale_fts_locked(cursor, legacy=legacy) def retry_deferred_fts_recovery(self) -> bool: - """Retry a deferred stale-FTS rebuild on this open SessionDB. - - ``_recover_stale_fts`` fails closed at open when holders or the rebuild - lock are busy, leaving ``_fts_stale`` set and search on LIKE. Live - write/search paths must never start a full rebuild, and a gateway - opens state.db once for days, so "next open" never comes. This is the - in-process retry from the gateway housekeeping tick: bounded backoff - (``_FTS_STALE_RETRY_SECONDS`` doubling to the max), non-blocking - admission (``timeout=0``), no new thread. - + """Retry a deferred stale-FTS rebuild on this open SessionDB (gateway + housekeeping tick). ``_recover_stale_fts`` fails closed at open when + holders or the rebuild lock are busy, leaving ``_fts_stale`` set and + search on LIKE; live write/search paths must never start a full + rebuild, and a gateway opens state.db once for days, so "next open" + never comes. Bounded backoff (``_FTS_STALE_RETRY_SECONDS`` doubling to + the max), non-blocking admission (``timeout=0``), no new thread. Returns True only when the index was rebuilt and sync triggers - restored. Never raises. - """ + restored. Never raises.""" if not self._fts_stale or self.read_only or self._conn is None: return False now = time.monotonic() @@ -491,8 +464,7 @@ class SessionSchemaMixin: interval = _FTS_STALE_RETRY_SECONDS self._fts_stale_retry_after = now + interval self._fts_stale_retry_interval = min( - max(interval, _FTS_STALE_RETRY_SECONDS, 1.0) * 2.0, - _FTS_STALE_RETRY_MAX_SECONDS, + max(interval, _FTS_STALE_RETRY_SECONDS, 1.0) * 2.0, _FTS_STALE_RETRY_MAX_SECONDS, ) try: with self._lock: @@ -500,9 +472,7 @@ class SessionSchemaMixin: return False cursor = self._conn.cursor() legacy = self._db_has_legacy_inline_fts(cursor) - recovered = self._recover_stale_fts( - cursor, legacy=legacy, timeout_seconds=0.0 - ) + recovered = self._recover_stale_fts(cursor, legacy=legacy, timeout_seconds=0.0) if recovered: # CJK was detached alongside the base indexes; its own # ensure path decides when it comes back online. @@ -521,10 +491,10 @@ class SessionSchemaMixin: ) return False - def _recover_stale_fts_locked( - self, cursor: sqlite3.Cursor, *, legacy: bool - ) -> bool: - """Body of :meth:`_recover_stale_fts`; caller holds rebuild authority.""" + def _recover_stale_fts_locked(self, cursor: sqlite3.Cursor, *, legacy: bool) -> bool: + """Body of :meth:`_recover_stale_fts`; caller holds rebuild authority. + One write transaction closes the dangerous gap: no canonical writer + can slip between the full rebuild and trigger restoration.""" try: trigram_status = self._fts_table_probe(cursor, "messages_fts_trigram") except (sqlite3.DatabaseError, UnicodeDecodeError): @@ -533,9 +503,7 @@ class SessionSchemaMixin: trigram_status = True include_trigram = trigram_status is True - drop_sql = "".join( - f"DROP TRIGGER IF EXISTS {trigger};" for trigger in _FTS_TRIGGERS - ) + drop_sql = "".join(f"DROP TRIGGER IF EXISTS {trigger};" for trigger in _FTS_TRIGGERS) if include_trigram: drop_sql += "DROP TABLE IF EXISTS messages_fts_trigram;" drop_sql += "DROP VIEW IF EXISTS messages_fts_trigram_src;" @@ -567,21 +535,11 @@ class SessionSchemaMixin: schema_sql = FTS_SQL if include_trigram: schema_sql += FTS_TRIGRAM_SQL - rebuild_sql = schema_sql + ( - "INSERT INTO messages_fts(messages_fts) VALUES('rebuild');" - ) + rebuild_sql = schema_sql + "INSERT INTO messages_fts(messages_fts) VALUES('rebuild');" if include_trigram: - rebuild_sql += ( - "INSERT INTO messages_fts_trigram(messages_fts_trigram) " - "VALUES('rebuild');" - ) - rebuild_sql += ( - "DELETE FROM state_meta WHERE key IN " - "('fts_rebuild_high_water', 'fts_rebuild_progress');" - ) + rebuild_sql += "INSERT INTO messages_fts_trigram(messages_fts_trigram) VALUES('rebuild');" + rebuild_sql += "DELETE FROM state_meta WHERE key IN ('fts_rebuild_high_water', 'fts_rebuild_progress');" - # One write transaction closes the dangerous gap: no canonical writer - # can slip between the full rebuild and trigger restoration. recovery_sql = ( "BEGIN IMMEDIATE;" + drop_sql @@ -612,22 +570,21 @@ class SessionSchemaMixin: self._fts_enabled = True self._trigram_available = include_trigram logger.warning( - "Rebuilt stale state.db FTS indexes from canonical messages and " - "restored sync triggers." + "Rebuilt stale state.db FTS indexes from canonical messages and restored sync triggers." ) return True + # ── Declarative column reconciliation ────────────────────────────────── + @staticmethod def _parse_schema_columns(schema_sql: str) -> Dict[str, Dict[str, str]]: """Expected columns per table, parsed from SCHEMA_SQL. - Executes the DDL in an in-memory SQLite database and reads PRAGMA table_info, so SQLite handles every syntax edge case (no regex). The result is memoized on disk keyed by a hash of the DDL (~85ms per startup otherwise; a pure function of the DDL text). Only the reference-side parse is cached — diffing the LIVE database still runs - every startup. A corrupt or stale cache degrades to recomputation. - """ + every startup. A corrupt or stale cache degrades to recomputation.""" cache_path = None schema_hash = hashlib.sha256(schema_sql.encode("utf-8")).hexdigest() try: @@ -642,8 +599,7 @@ class SessionSchemaMixin: ): tables = blob["tables"] if all( - isinstance(cols, dict) - and all(isinstance(v, str) for v in cols.values()) + isinstance(cols, dict) and all(isinstance(v, str) for v in cols.values()) for cols in tables.values() ): return tables @@ -655,8 +611,7 @@ class SessionSchemaMixin: ref.executescript(schema_sql) table_columns: Dict[str, Dict[str, str]] = {} for (tbl,) in ref.execute( - "SELECT name FROM sqlite_master " - "WHERE type='table' AND name NOT LIKE 'sqlite_%'" + "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'" ).fetchall(): cols: Dict[str, str] = {} for _cid, col_name, col_type, notnull, default, pk in ref.execute( @@ -676,9 +631,7 @@ class SessionSchemaMixin: if cache_path is not None: try: cache_path.parent.mkdir(parents=True, exist_ok=True) - fd, tmp = tempfile.mkstemp( - dir=str(cache_path.parent), prefix=".schema_columns." - ) + fd, tmp = tempfile.mkstemp(dir=str(cache_path.parent), prefix=".schema_columns.") with os.fdopen(fd, "w", encoding="utf-8") as fh: json.dump({"schema_hash": schema_hash, "tables": table_columns}, fh) os.replace(tmp, cache_path) @@ -688,48 +641,38 @@ class SessionSchemaMixin: def _reconcile_columns(self, cursor: sqlite3.Cursor) -> None: """ADD every SCHEMA_SQL column missing from the live tables. - Beets/sqlite-utils pattern: SCHEMA_SQL is the single source of truth; - column additions are declarative and need no version-gated migration. - """ + column additions are declarative and need no version-gated migration.""" expected = self._parse_schema_columns(SCHEMA_SQL) for table_name, declared_cols in expected.items(): try: - rows = cursor.execute( - f'PRAGMA table_info("{table_name}")' - ).fetchall() + rows = cursor.execute(f'PRAGMA table_info("{table_name}")').fetchall() except sqlite3.OperationalError: continue # Table doesn't exist yet (shouldn't happen after executescript) # PRAGMA table_info rows: (cid, name, type, notnull, dflt_value, pk) live_cols = {row[1] for row in rows} - for col_name, col_type in declared_cols.items(): - if col_name not in live_cols: - safe_name = col_name.replace('"', '""') - try: - cursor.execute( - f'ALTER TABLE "{table_name}" ADD COLUMN "{safe_name}" {col_type}' - ) - except sqlite3.OperationalError as exc: - message = str(exc).lower() - if "duplicate column" in message: - # A sibling process won the ADD race; store is correct. - logger.debug( - "reconcile %s.%s: %s", table_name, col_name, exc, - ) - continue - if "locked" in message or "busy" in message: - # Lock contention: swallowing it left the store - # half-reconciled ("no such column" on every read). - # Re-raise so _connect_and_init_with_lock_patience - # retries the WHOLE init (idempotent) with backoff. - raise - # Anything else is a schema mistake that permanently - # strands the store behind SCHEMA_SQL — be loud. - logger.warning( - "reconcile %s.%s failed; store remains behind " - "SCHEMA_SQL: %s", table_name, col_name, exc, - ) + if col_name in live_cols: + continue + try: + cursor.execute(f'ALTER TABLE "{table_name}" ADD COLUMN {_q(col_name)} {col_type}') + except sqlite3.OperationalError as exc: + message = str(exc).lower() + if "duplicate column" in message: + # A sibling process won the ADD race; store is correct. + logger.debug("reconcile %s.%s: %s", table_name, col_name, exc) + continue + if "locked" in message or "busy" in message: + # Swallowing lock contention left the store half-reconciled + # ("no such column" on every read). Re-raise so + # _connect_and_init_with_lock_patience retries the WHOLE + # init (idempotent) with backoff. + raise + # Anything else permanently strands the store behind SCHEMA_SQL — be loud. + logger.warning( + "reconcile %s.%s failed; store remains behind " + "SCHEMA_SQL: %s", table_name, col_name, exc, + ) @staticmethod def _live_pk_columns(cursor: sqlite3.Cursor, table: str) -> Optional[List[str]]: @@ -744,45 +687,47 @@ class SessionSchemaMixin: # row: (cid, name, type, notnull, dflt_value, pk) return [r[1] for r in sorted((r for r in rows if r[5]), key=lambda r: r[5])] + @staticmethod + def _rebuild_table(cursor: sqlite3.Cursor, table: str, legacy_name: str, ddl: str, copy_sql: str, indexes=()) -> None: + """RENAME *table* to *legacy_name*, CREATE it fresh from *ddl*, copy rows + back with *copy_sql*, DROP the legacy copy, recreate *indexes*.""" + cursor.execute(f"ALTER TABLE {table} RENAME TO {legacy_name}") + cursor.execute(ddl) + cursor.execute(copy_sql) + cursor.execute(f"DROP TABLE {legacy_name}") + for sql in indexes: + cursor.execute(sql) + def _heal_gateway_routing_pk(self, cursor: sqlite3.Cursor) -> None: """Rebuild ``gateway_routing`` when its PRIMARY KEY predates scoping. - Early builds used ``session_key TEXT PRIMARY KEY``; the reconciler ADDs ``scope`` but SQLite cannot ALTER a PK, so the composite key never lands and every routing write fails (ON CONFLICT mismatch / UNIQUE violation across scopes) with per-save warning spam. Rebuild once, preserving rows; on a cross-scope session_key collision the newest - row wins. - """ + row wins (INSERT OR REPLACE in updated_at order).""" pk_cols = self._live_pk_columns(cursor, "gateway_routing") if pk_cols is None or pk_cols == ["scope", "session_key"]: return - logger.info( "gateway_routing has legacy primary key %r; rebuilding with " "composite (scope, session_key) key", pk_cols, ) - cursor.execute( - "ALTER TABLE gateway_routing RENAME TO gateway_routing_legacy_pk" - ) - cursor.execute( + self._rebuild_table( + cursor, "gateway_routing", "gateway_routing_legacy_pk", """CREATE TABLE gateway_routing ( scope TEXT NOT NULL DEFAULT '', session_key TEXT NOT NULL, entry_json TEXT NOT NULL, updated_at REAL NOT NULL, PRIMARY KEY (scope, session_key) -)""" - ) - # INSERT OR REPLACE in updated_at order: newest row per key wins. - cursor.execute( +)""", "INSERT OR REPLACE INTO gateway_routing " "(scope, session_key, entry_json, updated_at) " "SELECT COALESCE(scope, ''), session_key, entry_json, updated_at " - "FROM gateway_routing_legacy_pk ORDER BY updated_at ASC" + "FROM gateway_routing_legacy_pk ORDER BY updated_at ASC", ) - cursor.execute("DROP TABLE gateway_routing_legacy_pk") def _heal_session_model_usage_pk(self, cursor: sqlite3.Cursor) -> None: """Rebuild ``session_model_usage`` when its PRIMARY KEY lacks ``task``. @@ -793,53 +738,26 @@ class SessionSchemaMixin: Every ``_record_model_usage()`` upsert then fails (ON CONFLICT mismatch), aborting the write transaction and silently zeroing token and cost accounting. Idempotent; no-op on healthy databases. - """ + + FK-off window: INSERT OR IGNORE does NOT suppress foreign-key + violations, so an orphaned usage row (partial prune while accounting + was broken) would abort the whole rebuild. PRAGMA foreign_keys is a + no-op inside a transaction — fine here, _init_schema runs on an + isolation_level=None connection with no transaction open. OR IGNORE: + COALESCE(task, '') on legacy NULL rows can collide with a genuine + ''-task row — keep the first rather than fail.""" pk_cols = self._live_pk_columns(cursor, "session_model_usage") if pk_cols is None or "task" in pk_cols: return - logger.info( "session_model_usage has legacy primary key %r (missing task); " "rebuilding with composite 6-column key", sorted(pk_cols), ) - # FK-off window: INSERT OR IGNORE does NOT suppress foreign-key - # violations, so an orphaned usage row (partial prune while accounting - # was broken) would abort the whole rebuild. PRAGMA foreign_keys is a - # no-op inside a transaction — fine here, _init_schema runs on an - # isolation_level=None connection with no transaction open. cursor.execute("PRAGMA foreign_keys=OFF") try: - cursor.execute( - "ALTER TABLE session_model_usage " - "RENAME TO session_model_usage_legacy_pk" - ) - cursor.execute( - """CREATE TABLE session_model_usage ( - session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, - model TEXT NOT NULL, - billing_provider TEXT NOT NULL DEFAULT '', - billing_base_url TEXT NOT NULL DEFAULT '', - billing_mode TEXT NOT NULL DEFAULT '', - task TEXT NOT NULL DEFAULT '', - api_call_count INTEGER NOT NULL DEFAULT 0, - input_tokens INTEGER NOT NULL DEFAULT 0, - output_tokens INTEGER NOT NULL DEFAULT 0, - cache_read_tokens INTEGER NOT NULL DEFAULT 0, - cache_write_tokens INTEGER NOT NULL DEFAULT 0, - reasoning_tokens INTEGER NOT NULL DEFAULT 0, - estimated_cost_usd REAL NOT NULL DEFAULT 0, - actual_cost_usd REAL NOT NULL DEFAULT 0, - cost_status TEXT, - cost_source TEXT, - first_seen REAL, - last_seen REAL, - PRIMARY KEY (session_id, model, billing_provider, billing_base_url, billing_mode, task) -)""" - ) - # OR IGNORE: COALESCE(task, '') on legacy NULL rows can collide - # with a genuine ''-task row — keep the first rather than fail. - cursor.execute( + self._rebuild_table( + cursor, "session_model_usage", "session_model_usage_legacy_pk", _SESSION_MODEL_USAGE_HEAL_DDL, """INSERT OR IGNORE INTO session_model_usage ( session_id, model, billing_provider, billing_base_url, billing_mode, task, api_call_count, input_tokens, @@ -856,40 +774,29 @@ class SessionSchemaMixin: output_tokens, cache_read_tokens, cache_write_tokens, reasoning_tokens, estimated_cost_usd, actual_cost_usd, cost_status, cost_source, first_seen, last_seen - FROM session_model_usage_legacy_pk""" - ) - cursor.execute("DROP TABLE session_model_usage_legacy_pk") - cursor.execute( - "CREATE INDEX IF NOT EXISTS idx_session_model_usage_session " - "ON session_model_usage(session_id)" - ) - cursor.execute( - "CREATE INDEX IF NOT EXISTS idx_session_model_usage_model " - "ON session_model_usage(model)" + FROM session_model_usage_legacy_pk""", + _SESSION_MODEL_USAGE_INDEX_SQL, ) except sqlite3.OperationalError as exc: logger.debug("session_model_usage PK heal skipped: %s", exc) finally: cursor.execute("PRAGMA foreign_keys=ON") + # ── _init_schema ─────────────────────────────────────────────────────── + def _init_schema(self): """Create tables and FTS if missing, reconcile columns, run data migrations. - SCHEMA_SQL is the single source of truth: column additions are declarative via _reconcile_columns(), so reordered migrations can never skip a column. schema_version remains for data migrations - (row transforms) that cannot be expressed declaratively. - """ + (row transforms) that cannot be expressed declaratively.""" # Startup-watchdog progress lease: on multi-GB state.db files the - # reconciliation + data migrations are legitimately slow and I/O-bound - # (near-zero CPU), which the watchdog's CPU fallback would misread as - # a parked deadlock. Single lease is deliberate (clamped to - # _MAX_LEASE_S=900): a genuinely wedged init delays supervisor respawn - # by up to the lease; per-chunk renewal isn't worth the complexity. + # reconciliation + data migrations are I/O-bound (near-zero CPU), which + # the watchdog's CPU fallback would misread as a parked deadlock. Single + # lease (clamped to _MAX_LEASE_S=900) is deliberate: a wedged init delays + # supervisor respawn by up to the lease; per-chunk renewal isn't worth it. report_startup_progress(600.0, phase="state_db_init_schema") - cursor = self._conn.cursor() - cursor.executescript(SCHEMA_SQL) # Idempotent, self-healing column reconciliation, then the two @@ -909,9 +816,7 @@ class SessionSchemaMixin: ) except sqlite3.OperationalError as exc: logger.debug("idx_messages_platform_msg_id create skipped: %s", exc) - - # Same ordering constraint (idx_messages_session_active on ``active``). - cursor.executescript(DEFERRED_INDEX_SQL) + cursor.executescript(DEFERRED_INDEX_SQL) # same ordering constraint (``active``) # Heal NULL ``active`` rows on every startup: older reconciler builds # added ``active`` without its NOT NULL DEFAULT 1, so INSERTs omitting @@ -919,14 +824,11 @@ class SessionSchemaMixin: # Unconditional because a ``current_version < 12`` gate never re-ran # for already-v12+ databases. try: - cursor.execute( - "UPDATE messages SET active = 1 WHERE active IS NULL" - ) + cursor.execute("UPDATE messages SET active = 1 WHERE active IS NULL") except sqlite3.OperationalError: pass fts5_available = self._sqlite_supports_fts5(cursor) - fts_migrations_complete = True self._fts_stale = cursor.execute( "SELECT 1 FROM state_meta WHERE key = ? LIMIT 1", (FTS_STALE_KEY,), @@ -944,161 +846,143 @@ class SessionSchemaMixin: row = cursor.execute("SELECT version FROM schema_version LIMIT 1").fetchone() if row is None: - cursor.execute( - "INSERT INTO schema_version (version) VALUES (?)", - (SCHEMA_VERSION,), - ) + cursor.execute("INSERT INTO schema_version (version) VALUES (?)", (SCHEMA_VERSION,)) # Store provenance so fresh vs wiped stores are distinguishable. now_iso = datetime.datetime.now(datetime.timezone.utc).isoformat() instance_id = str(uuid.uuid4()) cursor.executemany( "INSERT OR IGNORE INTO state_meta (key, value) VALUES (?, ?)", - [ - ("store_instance_id", instance_id), - ("store_created_at_utc", now_iso), - ], + [("store_instance_id", instance_id), ("store_created_at_utc", now_iso)], ) - else: - current_version = row[0] - # Renew the lease: the version-gated chain can rewrite whole tables - # on large DBs (same single-lease trade-off as above). - report_startup_progress(600.0, phase="state_db_data_migrations") - # Version-gated chain for data migrations only (row backfills, - # version-specific index changes); column additions never belong here. - if current_version < 10 and SCHEMA_VERSION == 10: - # v10: one-time trigram backfill. Only when v10 itself is the - # target: v11+ drops and rebuilds both FTS tables, so the - # backfill would only burn startup time and WAL space. - if fts5_available: - _fts_trigram_exists = self._fts_table_probe( - cursor, "messages_fts_trigram" - ) - if _fts_trigram_exists is False: - if self._ensure_fts_schema( - cursor, "messages_fts_trigram", FTS_TRIGRAM_SQL - ): - cursor.execute( - "INSERT INTO messages_fts_trigram(rowid, content) " - "SELECT id, content FROM messages WHERE content IS NOT NULL" - ) - else: - fts_migrations_complete = False - elif _fts_trigram_exists is None: - fts_migrations_complete = False - else: - fts_migrations_complete = False - # (v11 inline FTS re-index was superseded by v23 and removed.) - if current_version < 16: - # v16: tag delegate subagent rows so pickers stay clean after - # parent deletes orphan them. The shared predicate excludes - # user-visible reset children. - try: - cursor.execute( - "UPDATE sessions SET model_config = json_set(" - "COALESCE(model_config, '{}'), '$._delegate_from', parent_session_id) " - f"WHERE parent_session_id IS NOT NULL " - "AND json_extract(COALESCE(model_config, '{}'), '$._delegate_from') IS NULL " - f"AND {_ephemeral_child_sql('sessions')}" - ) - cursor.execute( - "UPDATE sessions SET model_config = json_set(" - "COALESCE(model_config, '{}'), '$._delegate_from', '__orphaned__') " - "WHERE parent_session_id IS NULL " - "AND json_extract(COALESCE(model_config, '{}'), '$._delegate_from') IS NULL " - "AND json_extract(COALESCE(model_config, '{}'), '$._branched_from') IS NULL " - "AND title IS NULL " - "AND message_count <= 25 " - "AND EXISTS (SELECT 1 FROM messages m " - " WHERE m.session_id = sessions.id AND m.role = 'tool') " - "AND NOT EXISTS (SELECT 1 FROM sessions ch " - " WHERE ch.parent_session_id = sessions.id)" - ) - except sqlite3.OperationalError: - pass - if current_version < 18: - # v18: backfill gateway metadata from sessions.json. Best-effort: - # missing metadata just means consumers fall back to - # sessions.json until the gateway rewrites those rows. - try: - self._backfill_gateway_metadata_from_sessions_json(cursor) - except Exception as exc: - logger.debug("v18 gateway metadata backfill skipped: %s", exc) - if current_version < 20: - # v20: seed one session_model_usage row per historical session - # from the sessions aggregates. INSERT OR IGNORE: a row newer - # code already wrote wins over the stale aggregate. - try: - cursor.execute( - """INSERT OR IGNORE INTO session_model_usage ( - session_id, model, billing_provider, - billing_base_url, billing_mode, - 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 - ) - SELECT id, COALESCE(model, 'unknown'), - COALESCE(billing_provider, ''), - COALESCE(billing_base_url, ''), - COALESCE(billing_mode, ''), - COALESCE(api_call_count, 0), - COALESCE(input_tokens, 0), - COALESCE(output_tokens, 0), - COALESCE(cache_read_tokens, 0), - COALESCE(cache_write_tokens, 0), - COALESCE(reasoning_tokens, 0), - COALESCE(estimated_cost_usd, 0), - COALESCE(actual_cost_usd, 0), - cost_status, cost_source, - started_at, COALESCE(ended_at, started_at) - FROM sessions - WHERE COALESCE(input_tokens, 0) - + COALESCE(output_tokens, 0) - + COALESCE(cache_read_tokens, 0) - + COALESCE(cache_write_tokens, 0) - + COALESCE(reasoning_tokens, 0) > 0""" - ) - except sqlite3.OperationalError: - pass - if current_version < 22: - # v22: ``task`` joins the session_model_usage PRIMARY KEY ('' = - # main loop; 'vision'/'compression'/... = aux calls). SQLite - # cannot ALTER a PK, so rebuild; existing rows are main-loop - # accounting → task=''. - try: - legacy_pk = cursor.execute( - "SELECT COUNT(*) FROM pragma_table_info('session_model_usage') " - "WHERE name = 'task' AND pk > 0" - ).fetchone()[0] - if not legacy_pk: - cursor.execute("ALTER TABLE session_model_usage RENAME TO session_model_usage_v21") + self._run_data_migrations(cursor, row[0], fts5_available) + + self._ensure_unique_title_index(cursor) + if fts5_available: + self._init_fts(cursor) + self._conn.commit() + + def _run_data_migrations(self, cursor: sqlite3.Cursor, current_version: int, fts5_available: bool) -> None: + """Version-gated chain for DATA migrations only (row backfills, + version-specific index changes); column additions never belong here. + Advances schema_version at the end unless FTS work could not complete.""" + # Renew the lease: the chain can rewrite whole tables on large DBs. + report_startup_progress(600.0, phase="state_db_data_migrations") + fts_migrations_complete = True + if current_version < 10 and SCHEMA_VERSION == 10: + # v10: one-time trigram backfill. Only when v10 itself is the + # target: v11+ drops and rebuilds both FTS tables, so the + # backfill would only burn startup time and WAL space. + if fts5_available: + _fts_trigram_exists = self._fts_table_probe(cursor, "messages_fts_trigram") + if _fts_trigram_exists is False: + if self._ensure_fts_schema(cursor, "messages_fts_trigram", FTS_TRIGRAM_SQL): cursor.execute( - """CREATE TABLE session_model_usage ( - session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, - model TEXT NOT NULL, - billing_provider TEXT NOT NULL DEFAULT '', - billing_base_url TEXT NOT NULL DEFAULT '', - billing_mode TEXT NOT NULL DEFAULT '', - task TEXT NOT NULL DEFAULT '', - api_call_count INTEGER NOT NULL DEFAULT 0, - input_tokens INTEGER NOT NULL DEFAULT 0, - output_tokens INTEGER NOT NULL DEFAULT 0, - cache_read_tokens INTEGER NOT NULL DEFAULT 0, - cache_write_tokens INTEGER NOT NULL DEFAULT 0, - reasoning_tokens INTEGER NOT NULL DEFAULT 0, - estimated_cost_usd REAL NOT NULL DEFAULT 0, - actual_cost_usd REAL NOT NULL DEFAULT 0, - cost_status TEXT, - cost_source TEXT, - first_seen REAL, - last_seen REAL, - PRIMARY KEY (session_id, model, billing_provider, billing_base_url, billing_mode, task) - )""" + "INSERT INTO messages_fts_trigram(rowid, content) " + "SELECT id, content FROM messages WHERE content IS NOT NULL" ) - cursor.execute( - """INSERT INTO session_model_usage ( + else: + fts_migrations_complete = False + elif _fts_trigram_exists is None: + fts_migrations_complete = False + else: + fts_migrations_complete = False + # (v11 inline FTS re-index was superseded by v23 and removed.) + if current_version < 16: + # v16: tag delegate subagent rows so pickers stay clean after + # parent deletes orphan them. The shared predicate excludes + # user-visible reset children. + try: + cursor.execute( + "UPDATE sessions SET model_config = json_set(" + "COALESCE(model_config, '{}'), '$._delegate_from', parent_session_id) " + f"WHERE parent_session_id IS NOT NULL " + "AND json_extract(COALESCE(model_config, '{}'), '$._delegate_from') IS NULL " + f"AND {_ephemeral_child_sql('sessions')}" + ) + cursor.execute( + "UPDATE sessions SET model_config = json_set(" + "COALESCE(model_config, '{}'), '$._delegate_from', '__orphaned__') " + "WHERE parent_session_id IS NULL " + "AND json_extract(COALESCE(model_config, '{}'), '$._delegate_from') IS NULL " + "AND json_extract(COALESCE(model_config, '{}'), '$._branched_from') IS NULL " + "AND title IS NULL " + "AND message_count <= 25 " + "AND EXISTS (SELECT 1 FROM messages m " + " WHERE m.session_id = sessions.id AND m.role = 'tool') " + "AND NOT EXISTS (SELECT 1 FROM sessions ch " + " WHERE ch.parent_session_id = sessions.id)" + ) + except sqlite3.OperationalError: + pass + if current_version < 18: + # v18: backfill gateway metadata from sessions.json. Best-effort: + # consumers fall back to sessions.json until the gateway rewrites. + try: + self._backfill_gateway_metadata_from_sessions_json(cursor) + except Exception as exc: + logger.debug("v18 gateway metadata backfill skipped: %s", exc) + if current_version < 20: + # v20: seed one session_model_usage row per historical session + # from the sessions aggregates. INSERT OR IGNORE: a row newer + # code already wrote wins over the stale aggregate. + try: + cursor.execute(_SESSION_MODEL_USAGE_V20_SEED_SQL) + except sqlite3.OperationalError: + pass + if current_version < 22: + self._migrate_v22_session_model_usage(cursor) + # v23: FTS storage redesign (external-content tables; inline v11 tables + # were ~75% of state.db on heavy installs). OPT-IN, NOT AUTOMATIC: the + # transition is disk-heavy (~2x transient) and long (hours on 25 GB), so + # an existing install only gets a flag; `hermes sessions optimize-storage` + # performs it in the foreground. The FTS layout is tracked by the + # independent `fts_storage_version` marker, so schema_version still + # advances here and future migrations land for legacy-FTS users too. + if current_version < 23 and fts5_available and self._db_has_legacy_inline_fts(cursor): + self.set_meta("fts_optimize_available", "1", cursor=cursor) + if current_version < 25: + # v25: de-duplicate system prompt snapshots into the shared + # content-addressed table; the old column stays a read fallback + # for partially migrated or externally written rows. + self._dedupe_legacy_system_prompts(cursor) + + # Stamp the FTS layout version (fresh/optimized DBs); a legacy DB keeps + # its absent/0 marker until optimize-storage runs. An INTERRUPTED optimize + # (rebuild markers, trash tables, or an empty external index against + # non-empty messages) is NOT stamped: the marker is the source of truth + # for "fully optimized" and keeps the resume offer alive. + if ( + fts5_available + and not self._db_has_legacy_inline_fts(cursor) + and cursor.execute( + "SELECT 1 FROM state_meta WHERE key = 'fts_rebuild_high_water' LIMIT 1" + ).fetchone() is None + and not self._has_fts_trash(cursor) + and not self._fts_external_index_empty_with_messages(cursor) + ): + self.set_meta("fts_storage_version", str(FTS_STORAGE_VERSION), cursor=cursor) + + # Advance schema_version — deliberately NOT gated on the FTS opt-in (that + # would block every future migration for a user who never optimizes). + # FTS5 unavailable is the one skip: claiming current would lie. + if current_version < SCHEMA_VERSION and fts_migrations_complete and fts5_available: + cursor.execute("UPDATE schema_version SET version = ?", (SCHEMA_VERSION,)) + + def _migrate_v22_session_model_usage(self, cursor: sqlite3.Cursor) -> None: + """v22: ``task`` joins the session_model_usage PRIMARY KEY ('' = main + loop; 'vision'/'compression'/... = aux calls). SQLite cannot ALTER a + PK, so rebuild; existing rows are main-loop accounting → task=''.""" + try: + legacy_pk = cursor.execute( + "SELECT COUNT(*) FROM pragma_table_info('session_model_usage') " + "WHERE name = 'task' AND pk > 0" + ).fetchone()[0] + if legacy_pk: + return + self._rebuild_table( + cursor, "session_model_usage", "session_model_usage_v21", _SESSION_MODEL_USAGE_V22_DDL, + """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, @@ -1110,85 +994,19 @@ class SessionSchemaMixin: output_tokens, cache_read_tokens, cache_write_tokens, reasoning_tokens, estimated_cost_usd, actual_cost_usd, cost_status, cost_source, first_seen, last_seen - FROM session_model_usage_v21""" - ) - cursor.execute("DROP TABLE session_model_usage_v21") - cursor.execute( - "CREATE INDEX IF NOT EXISTS idx_session_model_usage_session " - "ON session_model_usage(session_id)" - ) - cursor.execute( - "CREATE INDEX IF NOT EXISTS idx_session_model_usage_model " - "ON session_model_usage(model)" - ) - except sqlite3.OperationalError as exc: - logger.debug("v22 session_model_usage rebuild skipped: %s", exc) - # v23: FTS storage redesign (external-content tables; inline v11 - # tables were ~75% of state.db on heavy installs). OPT-IN, NOT - # AUTOMATIC: the transition is disk-heavy (~2x transient) and long - # (hours on a 25 GB DB), so an existing install only gets a flag - # advertising it; `hermes sessions optimize-storage` performs it as - # a deliberate foreground operation. DECOUPLED VERSIONING: the FTS - # layout is tracked by the independent `fts_storage_version` - # marker, so schema_version still advances here and future - # migrations land for legacy-FTS users too. - if ( - current_version < 23 - and fts5_available - and self._db_has_legacy_inline_fts(cursor) - ): - self.set_meta("fts_optimize_available", "1", cursor=cursor) + FROM session_model_usage_v21""", + _SESSION_MODEL_USAGE_INDEX_SQL, + ) + except sqlite3.OperationalError as exc: + logger.debug("v22 session_model_usage rebuild skipped: %s", exc) - if current_version < 25: - # v25: de-duplicate system prompt snapshots into the shared - # content-addressed table; the old column stays a read fallback - # for partially migrated or externally written rows. - self._dedupe_legacy_system_prompts(cursor) - - # Stamp the FTS layout version (fresh/optimized DBs) so the main - # version can always advance; a legacy DB keeps its absent/0 marker - # until optimize-storage runs. An INTERRUPTED optimize (rebuild - # markers, trash tables, or an empty external index against - # non-empty messages) is NOT stamped: the marker is the source of - # truth for "fully optimized" and keeps the resume offer alive. - if ( - fts5_available - and not self._db_has_legacy_inline_fts(cursor) - and cursor.execute( - "SELECT 1 FROM state_meta " - "WHERE key = 'fts_rebuild_high_water' LIMIT 1" - ).fetchone() is None - and not self._has_fts_trash(cursor) - and not self._fts_external_index_empty_with_messages(cursor) - ): - self.set_meta( - "fts_storage_version", str(FTS_STORAGE_VERSION), cursor=cursor - ) - - # Advance schema_version — deliberately NOT gated on the FTS opt-in - # (that would block every future migration for a user who never - # optimizes). FTS5 unavailable is the one skip: we can't have - # created the current FTS objects, so claiming current would lie. - if ( - current_version < SCHEMA_VERSION - and fts_migrations_complete - and fts5_available - ): - cursor.execute( - "UPDATE schema_version SET version = ?", - (SCHEMA_VERSION,), - ) - - # Unique title index. Older DBs may hold duplicate aliases from before - # the constraint; keep every session, the newest retains the alias. - title_index_sql = ( - "CREATE UNIQUE INDEX IF NOT EXISTS idx_sessions_title_unique " - "ON sessions(title) WHERE title IS NOT NULL" - ) + def _ensure_unique_title_index(self, cursor: sqlite3.Cursor) -> None: + """Unique title index. Older DBs may hold duplicate aliases from before + the constraint; keep every session, the newest retains the alias. The + index must never abort opening the DB, so the repair is guarded too.""" try: - cursor.execute(title_index_sql) + cursor.execute(_TITLE_UNIQUE_INDEX_SQL) except sqlite3.IntegrityError: - # The index must never abort opening the DB; guard the repair too. try: cursor.execute( """UPDATE sessions AS older @@ -1204,94 +1022,73 @@ class SessionSchemaMixin: "Cleared %d duplicate session title(s) while restoring the unique index", cursor.rowcount, ) - cursor.execute(title_index_sql) + cursor.execute(_TITLE_UNIQUE_INDEX_SQL) except sqlite3.Error: - logger.exception( - "Could not repair duplicate session titles; " - "unique title index not created" - ) + logger.exception("Could not repair duplicate session titles; unique title index not created") except sqlite3.OperationalError: pass # Index already exists - if fts5_available: - # Run the FTS DDL even when the vtable exists so CREATE TRIGGER IF - # NOT EXISTS repairs trigger-only degradation from a no-FTS5 runtime. - # OPT-IN v23 boundary: a legacy v22 inline install must keep its - # inline schema + triggers — the v23 external-content DDL would - # create the trigram source VIEW and leave a mixed state — so it - # gets the legacy DDL only; fresh/opted-in DBs get v23. - legacy_fts = self._db_has_legacy_inline_fts(cursor) - if self._fts_stale: - if self._recover_stale_fts(cursor, legacy=legacy_fts): - # CJK was detached alongside the base indexes and has its - # own stale marker; its ensure path decides when it returns. - self._ensure_fts_cjk_schema(cursor) - else: - self._fts_enabled = False - self._trigram_available = False - self._fts_cjk_available = False + def _init_fts(self, cursor: sqlite3.Cursor) -> None: + """Create/repair the FTS objects on an FTS5-capable runtime. + The DDL runs even when the vtable exists so CREATE TRIGGER IF NOT + EXISTS repairs trigger-only degradation from a no-FTS5 runtime. + OPT-IN v23 boundary: a legacy v22 inline install must keep its inline + schema + triggers (the v23 external-content DDL would create the + trigram source VIEW and leave a mixed state), so it gets the legacy + DDL only; fresh/opted-in DBs get v23.""" + legacy_fts = self._db_has_legacy_inline_fts(cursor) + if self._fts_stale: + if self._recover_stale_fts(cursor, legacy=legacy_fts): + # CJK was detached alongside the base indexes and has its own + # stale marker; its ensure path decides when it returns. + self._ensure_fts_cjk_schema(cursor) else: - base_sql, trigram_sql, rebuild = ( - (LEGACY_FTS_SQL, LEGACY_FTS_TRIGRAM_SQL, self._rebuild_legacy_fts_indexes) - if legacy_fts - else (FTS_SQL, FTS_TRIGRAM_SQL, self._rebuild_fts_indexes) - ) - # Measure BEFORE the DDL below runs, so these describe the - # pre-repair state. Whether the trigram half is even - # creatable is only known AFTER _ensure_fts_schema, which is - # why the two halves are combined at the `if`, not here. - base_triggers_missing = ( - self._fts_trigger_count(cursor, _FTS_BASE_TRIGGERS) - < len(_FTS_BASE_TRIGGERS) - ) - trigram_triggers_missing = ( - self._fts_trigger_count(cursor, _FTS_TRIGRAM_TRIGGERS) - < len(_FTS_TRIGRAM_TRIGGERS) - ) - self._fts_enabled = self._ensure_fts_schema( - cursor, "messages_fts", base_sql - ) - if self._fts_enabled: - # Trigram FTS5 for CJK/substring search is optional - # relative to the main table; if it cannot be created, - # CJK search falls back to LIKE. - trigram_enabled = self._ensure_fts_schema( - cursor, "messages_fts_trigram", trigram_sql - ) - self._trigram_available = trigram_enabled - if base_triggers_missing or ( - trigram_enabled and trigram_triggers_missing - ): - self._run_admitted_startup_rebuild( - cursor, - lambda: rebuild(cursor, include_trigram=trigram_enabled), - ) - if not legacy_fts: - # CJK-bigram index (cjk_unicode61): strictly additive - # and gated on the loadable tokenizer. - self._ensure_fts_cjk_schema(cursor) - - # Replace any pre-existing broad AFTER UPDATE triggers with - # AFTER UPDATE OF variants. IF NOT EXISTS cannot rewrite them. + self._fts_enabled = False + self._trigram_available = False + self._fts_cjk_available = False + else: + base_sql, trigram_sql, rebuild = ( + (LEGACY_FTS_SQL, LEGACY_FTS_TRIGRAM_SQL, self._rebuild_legacy_fts_indexes) + if legacy_fts + else (FTS_SQL, FTS_TRIGRAM_SQL, self._rebuild_fts_indexes) + ) + # Measure BEFORE the DDL below runs (pre-repair state). Whether the + # trigram half is even creatable is only known AFTER + # _ensure_fts_schema, which is why the halves combine at the `if`. + base_triggers_missing = self._fts_trigger_count(cursor, _FTS_BASE_TRIGGERS) < len(_FTS_BASE_TRIGGERS) + trigram_triggers_missing = ( + self._fts_trigger_count(cursor, _FTS_TRIGRAM_TRIGGERS) < len(_FTS_TRIGRAM_TRIGGERS) + ) + self._fts_enabled = self._ensure_fts_schema(cursor, "messages_fts", base_sql) if self._fts_enabled: - self._migrate_broad_fts_update_triggers(cursor) - - self._conn.commit() + # Trigram is optional relative to the main table; without it + # CJK search falls back to LIKE. + trigram_enabled = self._ensure_fts_schema(cursor, "messages_fts_trigram", trigram_sql) + self._trigram_available = trigram_enabled + if base_triggers_missing or (trigram_enabled and trigram_triggers_missing): + self._run_admitted_startup_rebuild( + cursor, lambda: rebuild(cursor, include_trigram=trigram_enabled), + ) + if not legacy_fts: + # CJK-bigram index: strictly additive, gated on the loadable tokenizer. + self._ensure_fts_cjk_schema(cursor) + # IF NOT EXISTS cannot rewrite pre-existing broad AFTER UPDATE triggers. + if self._fts_enabled: + self._migrate_broad_fts_update_triggers(cursor) def _run_admitted_startup_rebuild(self, cursor, rebuild_fn) -> None: """Run a full trigger-repair FTS rebuild under cross-process admission. Reached when the sync triggers were missing and the DDL just recreated them: the index has a gap of unknown extent. Two processes opening the - same DB after an update commonly hit this simultaneously — the - concurrent-rebuild interleaving that structurally corrupted state.db - in production — so this admits through ``fts_rebuild_admission`` and - FAILS CLOSED. On deferral the just-repaired triggers are dropped again - and the stale breadcrumb persisted (``_enter_fts_fail_open``'s - ordering contract: triggers must never be live over an unrebuilt gap); - the winner's rebuild, ``retry_deferred_fts_recovery``, or - ``_recover_stale_fts`` at next startup restores index and triggers. - """ + same DB after an update commonly hit this simultaneously (the + interleaving that structurally corrupted state.db in production), so + this admits through ``fts_rebuild_admission`` and FAILS CLOSED. On + deferral the just-repaired triggers are dropped again and the stale + breadcrumb persisted — triggers must never be live over an unrebuilt + gap (``_enter_fts_fail_open``'s ordering contract); the winner's + rebuild, ``retry_deferred_fts_recovery`` or ``_recover_stale_fts`` at + next startup restores index and triggers.""" with fts_rebuild_admission(self.db_path) as admitted: if admitted: rebuild_fn() @@ -1312,9 +1109,7 @@ class SessionSchemaMixin: self._trigram_available = False self._fts_cjk_available = False - def _backfill_gateway_metadata_from_sessions_json( - self, cursor: sqlite3.Cursor - ) -> None: + def _backfill_gateway_metadata_from_sessions_json(self, cursor: sqlite3.Cursor) -> None: """One-time v18 backfill of gateway metadata from sessions.json. Only fills NULL columns — never overwrites data written by newer code.""" sessions_file = get_hermes_home() / "sessions" / "sessions.json" @@ -1331,6 +1126,7 @@ class SessionSchemaMixin: if not session_id: continue origin = entry.get("origin") + origin_dict = origin if isinstance(origin, dict) else None cursor.execute( """UPDATE sessions SET session_key = COALESCE(session_key, ?), @@ -1346,11 +1142,11 @@ class SessionSchemaMixin: WHERE id = ?""", ( entry.get("session_key") or key, - (origin or {}).get("chat_id") if isinstance(origin, dict) else None, + origin_dict.get("chat_id") if origin_dict is not None else None, entry.get("chat_type"), - (origin or {}).get("thread_id") if isinstance(origin, dict) else None, + origin_dict.get("thread_id") if origin_dict is not None else None, entry.get("display_name"), - json.dumps(origin) if isinstance(origin, dict) else None, + json.dumps(origin) if origin_dict is not None else None, 1 if entry.get("expiry_finalized") or entry.get("memory_flushed") else 0, str(session_id), ), diff --git a/hermes_state_search.py b/hermes_state_search.py index 7abfe3801f..25f8ebfb92 100644 --- a/hermes_state_search.py +++ b/hermes_state_search.py @@ -16,1324 +16,42 @@ from typing import Any, Callable, Collection, Dict, List, Optional, Tuple from agent.skill_commands import describe_skill_invocation from hermes_state_common import ( - FTS_CJK_STALE_KEY, - FTS_SQL, - FTS_STALE_KEY, - FTS_STORAGE_VERSION, - FTS_TRIGRAM_SQL, - MAX_FTS5_QUERY_CHARS, - SCHEMA_VERSION, - _FTS_CJK_TRIGGERS, - escape_like as _escape_like, - fts_rebuild_admission, + FTS_CJK_STALE_KEY, FTS_SQL, FTS_STALE_KEY, FTS_STORAGE_VERSION, FTS_TRIGRAM_SQL, + MAX_FTS5_QUERY_CHARS, SCHEMA_VERSION, _FTS_CJK_TRIGGERS, + escape_like as _escape_like, fts_rebuild_admission, ) # Keep the pre-split logger identity so log filtering/capture is unchanged. logger = logging.getLogger("hermes_state") -# Characters FTS5's query grammar rejects outside a quoted phrase. Anything -# missing here reaches MATCH raw and raises, which the execute site swallows -# into zero results. Assembled through re.escape so the backslash cannot be -# eaten as a regex escape. ``%`` is deliberately excluded: the CJK LIKE -# fallback needs it as a literal (that path escapes wildcards itself). +# Characters FTS5's query grammar rejects outside a quoted phrase; anything +# missing here reaches MATCH raw and raises (swallowed into zero results). +# re.escape so the backslash is not eaten. ``%`` is deliberately excluded: the +# CJK LIKE fallback needs it literal (that path escapes wildcards itself). _FTS5_SPECIAL_CHARS = '+{}():"^@/#&|~[]<>,;!?$=\\\'' _FTS5_SPECIAL_RE = re.compile(f"[{re.escape(_FTS5_SPECIAL_CHARS)}]") _FTS_OPERATORS = frozenset({"AND", "OR", "NOT"}) +_LIKE_SKIP_TOKENS = _FTS_OPERATORS | {"NEAR"} +_LIKE_TOKEN_RE = re.compile(r'"[^"]+"|\S+') # Column list shared by every search route (snippet + metadata, never content). -_SEARCH_SELECT_TAIL = ( - "m.timestamp, m.tool_name, s.source, s.model, s.started_at AS session_started" -) +_SEARCH_SELECT_TAIL = "m.timestamp, m.tool_name, s.source, s.model, s.started_at AS session_started" _LIKE_SNIPPET_SQL = "substr(m.content, max(1, instr(m.content, ?) - 40), 120) AS snippet" _LIKE_ANY_COLUMN_SQL = ( "(m.content LIKE ? ESCAPE '\\' OR m.tool_name LIKE ? ESCAPE '\\' " "OR m.tool_calls LIKE ? ESCAPE '\\')" ) - - -def _meta_row(conn, key: str) -> Optional[sqlite3.Row]: - """Point-read one ``state_meta`` row (``None`` when absent).""" - return conn.execute( - "SELECT value FROM state_meta WHERE key = ?", (key,) - ).fetchone() - - -def _delete_meta(conn, *keys: str) -> None: - conn.execute( - f"DELETE FROM state_meta WHERE key IN ({','.join('?' for _ in keys)})", keys - ) - - -def _quote_fts_tokens(raw_query: str) -> str: - """Quote each non-operator token (neutralising FTS5 special characters) - while preserving AND/OR/NOT.""" - return " ".join( - tok if tok.upper() in _FTS_OPERATORS else '"' + tok.replace('"', '""') + '"' - for tok in raw_query.split() - ) - - -def _search_filter_clauses( - where: List[str], - params: list, - *, - include_inactive: bool, - source_filter: Optional[List[str]], - exclude_sources: Optional[List[str]], - role_filter: Optional[List[str]], -) -> None: - """Append the visibility/source/role predicates every search route shares. - - Live rows (active=1) AND compaction-archived rows (compacted=1) are - discoverable; only rewind/undo rows (active=0, compacted=0) are hidden. - """ - if not include_inactive: - where.append("(m.active = 1 OR m.compacted = 1)") - if source_filter is not None: - where.append(f"s.source IN ({','.join('?' for _ in source_filter)})") - params.extend(source_filter) - if exclude_sources is not None: - where.append(f"s.source NOT IN ({','.join('?' for _ in exclude_sources)})") - params.extend(exclude_sources) - if role_filter: - where.append(f"m.role IN ({','.join('?' for _ in role_filter)})") - params.extend(role_filter) - - -class SessionSearchMixin: - """See module docstring — mixin for SessionDB (Search cluster).""" - - _SEARCH_MESSAGE_RESULT_FIELDS = ( - "id", - "session_id", - "role", - "snippet", - "timestamp", - "tool_name", - "source", - "model", - "session_started", - "context", - ) - - @classmethod - def _search_message_fields( - cls, fields: Optional[Collection[str]] - ) -> Optional[Tuple[str, ...]]: - """Validate and canonically order an optional result projection.""" - if fields is None: - return None - if isinstance(fields, str): - raise TypeError("search fields must be a collection of field names, not a string") - requested = set(fields) - unknown = requested.difference(cls._SEARCH_MESSAGE_RESULT_FIELDS) - if unknown: - raise ValueError(f"unknown search result field(s): {', '.join(sorted(unknown))}") - return tuple( - field for field in cls._SEARCH_MESSAGE_RESULT_FIELDS if field in requested - ) - - def _try_incremental_merge_fts(self) -> None: - """Run one bounded FTS5 merge pass without failing the completed write.""" - if not self._fts_enabled: - return - try: - self._merge_fts_incrementally( - max_pages=self._FTS_MERGE_MAX_PAGES_PER_INDEX - ) - except Exception as exc: # noqa: BLE001 - post-commit maintenance - # The canonical write is already committed. No maintenance failure - # — including the bare SystemError CPython's sqlite3 layer can raise - # under cross-thread errmsg scrambling — may escape and make the - # caller replay an ambiguous, possibly-durable write. - logger.warning("FTS incremental merge failed after commit: %s", exc) - - def fts_rebuild_status(self) -> Optional[Dict[str, Any]]: - """Deferred-rebuild progress ``{"pending", "total", "indexed", - "percent"}``, or None when no rebuild is pending. - - Reads state_meta via the pooled reader rather than get_meta() (which - takes self._lock) so search_messages never blocks on the writer lock. - """ - return self._rebuild_status("fts_rebuild") - - def _rebuild_status(self, prefix: str) -> Optional[Dict[str, Any]]: - rows = self._read_all( - "SELECT key, value FROM state_meta WHERE key IN (?, ?)", - (f"{prefix}_high_water", f"{prefix}_progress"), - ) - meta = {r["key"]: r["value"] for r in rows} - high_water = meta.get(f"{prefix}_high_water") - if high_water is None: - return None - progress = int(meta.get(f"{prefix}_progress") or 0) - total = int(high_water) - if total <= 0: - return None - pct = min(100, int(100 * progress / total)) - return {"pending": True, "total": total, "indexed": progress, "percent": pct} - - def _fts_rebuild_finish(self) -> None: - """Finalize the deferred rebuild: boundary sweep + clear markers. - - The sweep is cheap insurance against a write that slipped through the - migration-boundary instant (between high_water capture and trigger - activation). The trigram half is gated on ``_trigram_available``: - without the tokenizer/table an unconditional INSERT raises ``no such - table`` and aborts the whole rebuild (and optimize_fts_storage()). - """ - sweeps = [self._BOUNDARY_SWEEP_SQL.format(table="messages_fts", extra="")] - if self._trigram_available: - sweeps.append(self._BOUNDARY_SWEEP_SQL.format( - table="messages_fts_trigram", extra="AND m.role <> 'tool' " - )) - self._rebuild_finish("fts_rebuild", sweeps) - logger.info("Deferred FTS rebuild complete — all messages indexed.") - - # Re-index rows in an id window the index is missing. docsize has one row - # per indexed doc, so the anti-join is exact. - _BOUNDARY_SWEEP_SQL = ( - "INSERT INTO {table}(rowid, content, tool_name, tool_calls) " - "SELECT m.id, m.content, m.tool_name, m.tool_calls " - "FROM messages m " - "WHERE m.id > ? AND m.id <= ? {extra}" - "AND NOT EXISTS (SELECT 1 FROM {table}_docsize d WHERE d.id = m.id)" - ) - - def _rebuild_finish(self, prefix: str, sweep_sqls: List[str]) -> None: - """Sweep a generous window around the high-water boundary, then clear - the ``{prefix}_high_water`` / ``{prefix}_progress`` markers.""" - def _do(conn): - hw_row = _meta_row(conn, f"{prefix}_high_water") - if hw_row is not None: - hw = int(hw_row[0]) - for sql in sweep_sqls: - conn.execute(sql, (hw - 1000, hw + 1000)) - _delete_meta(conn, f"{prefix}_high_water", f"{prefix}_progress") - self._execute_write(_do) - - def _fts_teardown_trash_step(self) -> bool: - """Tear down one chunk of a demoted v22 FTS shadow table; True while - work remains. - - Trash tables are PLAIN tables (their vtable parent was demoted), so - chunked DELETE + final DROP involve no FTS5 machinery. Integer - single-column-key tables are drained with a high-water marker so each - chunk's scan is bounded (re-scanning from the start was O(n²) on - large tables). Compound-key tables cannot use a scalar high-water - comparison and keep the chunked ``LIMIT`` delete — they are small by - construction. - """ - with self._lock: - trash = [ - r[0] for r in self._conn.execute( - "SELECT name FROM sqlite_master WHERE type = 'table' " - "AND name LIKE ? ESCAPE '\\'", - (self._FTS_TRASH_PREFIX.replace("_", "\\_") + "%",), - ).fetchall() - ] - if not trash: - return False - - tbl = trash[0] - - def _do(conn): - pk_info = [ - (r[1], (r[2] or "").upper()) - for r in conn.execute(f"PRAGMA table_info({tbl})") - if r[5] > 0 - ] - pk_cols = [name for name, _typ in pk_info] - key = ", ".join(pk_cols) if pk_cols else "rowid" - - if len(pk_cols) == 1 and (not pk_info or pk_info[0][1] == "INTEGER"): - # High-water drain. The marker is read/written in the same - # BEGIN IMMEDIATE as the DELETE, so concurrent callers claim - # disjoint key ranges. Only integer PKs can anchor the numeric - # comparison — the config shadow table (TEXT pk) falls through - # to the chunked delete below. - marker_key = f"fts_teardown_{tbl}_progress" - row = _meta_row(conn, marker_key) - high_water = int(row[0]) if row is not None else 0 - - # Claim the chunk's upper bound: the LAST row of the - # LIMIT window, so a full chunk is deleted per step. - upper_rows = conn.execute( - f"SELECT {key} FROM {tbl} WHERE {key} > ? " - f"ORDER BY {key} LIMIT {self._FTS_REBUILD_CHUNK_ROWS}", - (high_water,), - ).fetchall() - if not upper_rows: - # Drained — the DROP is cheap now. - conn.execute(f"DROP TABLE IF EXISTS {tbl}") - _delete_meta(conn, marker_key) - logger.info("Old FTS shadow table %s torn down.", tbl) - return True - - upper = upper_rows[-1][0] - cur = conn.execute( - f"DELETE FROM {tbl} WHERE {key} > ? AND {key} <= ?", - (high_water, upper), - ) - if cur.rowcount > 0: - self.set_meta(marker_key, str(upper), cursor=conn) - return True - - # Compound-key or rowid trash table: chunked delete (small tables, - # quadratic re-scan is not a concern). - cur = conn.execute( - f"DELETE FROM {tbl} WHERE ({key}) IN " - f"(SELECT {key} FROM {tbl} LIMIT {self._FTS_REBUILD_CHUNK_ROWS})" - ) - if cur.rowcount == 0: - # Empty — the DROP is cheap now. - conn.execute(f"DROP TABLE IF EXISTS {tbl}") - logger.info("Old FTS shadow table %s torn down.", tbl) - return True # re-check: more trash tables / chunks may remain - - try: - return bool(self._execute_write(_do)) - except sqlite3.OperationalError as exc: - logger.debug("FTS trash teardown chunk failed (will retry): %s", exc) - return True - - def fts_rebuild_step(self) -> bool: - """Backfill one chunk of the deferred FTS rebuild; True while work - remains. Safe from any process: chunks are claimed atomically inside - the write transaction, so concurrent callers interleave instead of - duplicating rows.""" - if not self._fts_enabled: - return False - inserts = [self._CHUNK_INSERT_SQL.format(table="messages_fts", extra="")] - if self._trigram_available: - inserts.append(self._CHUNK_INSERT_SQL.format( - table="messages_fts_trigram", extra=" AND role <> 'tool'" - )) - return self._rebuild_step( - "fts_rebuild", inserts, - fail_msg="FTS rebuild chunk failed (will retry): %s", - finish=self._fts_rebuild_finish, - ) - - _CHUNK_INSERT_SQL = ( - "INSERT INTO {table}(rowid, content, tool_name, tool_calls) " - "SELECT id, content, tool_name, tool_calls FROM messages " - "WHERE id > ? AND id <= ?{extra}" - ) - - def _rebuild_step( - self, prefix: str, insert_sqls: List[str], *, fail_msg: str, finish - ) -> bool: - """Shared chunk engine for the base and CJK deferred backfills.""" - high_water_raw = self.get_meta(f"{prefix}_high_water") - if high_water_raw is None: - return False - high_water = int(high_water_raw) - chunk = self._FTS_REBUILD_CHUNK_ROWS - - def _do(conn): - # Re-read progress inside the write transaction (BEGIN IMMEDIATE - # is already held by _execute_write) — this is the claim: two - # workers can't read the same progress value concurrently. - row = _meta_row(conn, f"{prefix}_progress") - if row is None: - return False # finished (or cleared) by another process - progress = int(row[0]) - if progress >= high_water: - return False - - # The chunk upper bound is an id, not a row count, so gaps from - # deleted rows don't shrink chunks below the claimed range. - upper = min(progress + chunk, high_water) - for sql in insert_sqls: - conn.execute(sql, (progress, upper)) - # Publish progress in the same transaction as the rows it - # covers — crash-atomic: either both land or neither does. - conn.execute( - "UPDATE state_meta SET value = ? WHERE key = ?", - (str(upper), f"{prefix}_progress"), - ) - return upper < high_water - - try: - more = self._execute_write(_do) - except sqlite3.OperationalError as exc: - logger.debug(fail_msg, exc) - return True # transient (lock contention) — caller retries - if more is False: - status = self._rebuild_status(prefix) - if status is not None and status["indexed"] >= status["total"]: - finish() - return False - return bool(more) - - def fts_cjk_rebuild_status(self) -> Optional[Dict[str, Any]]: - """CJK-index backfill progress, or None when none is pending.""" - return self._rebuild_status("fts_cjk_rebuild") - - def fts_cjk_rebuild_step(self) -> bool: - """Backfill one chunk of the CJK index. True while work remains.""" - if not self._fts_enabled or not self._fts_cjk_loaded: - return False - return self._rebuild_step( - "fts_cjk_rebuild", - [self._CHUNK_INSERT_SQL.format( - table="messages_fts_cjk", extra=" AND role <> 'tool'" - )], - fail_msg="CJK FTS rebuild chunk failed (will retry): %s", - finish=self._fts_cjk_rebuild_finish, - ) - - def _fts_cjk_rebuild_finish(self) -> None: - """Boundary sweep + clear the cjk markers; index becomes servable.""" - self._rebuild_finish("fts_cjk_rebuild", [ - self._BOUNDARY_SWEEP_SQL.format( - table="messages_fts_cjk", extra="AND m.role <> 'tool' " - ) - ]) - self._fts_cjk_available = True - logger.info("CJK FTS index backfill complete — serving CJK search.") - - def _fts_cjk_reset_if_stale(self) -> None: - """From-scratch rebuild of a stale cjk index (triggers were dropped, - gap extent unknown): drop table + triggers, clear the breadcrumb, - recreate via ``_ensure_fts_cjk_schema`` (fresh backfill markers on a - populated DB). No-op when not stale.""" - if not self._fts_cjk_loaded: - return - - def _do(conn): - if _meta_row(conn, FTS_CJK_STALE_KEY) is None: - return False - for trig in _FTS_CJK_TRIGGERS: - conn.execute(f"DROP TRIGGER IF EXISTS {trig}") - conn.execute("DROP TABLE IF EXISTS messages_fts_cjk") - conn.execute("DROP VIEW IF EXISTS messages_fts_cjk_src") - _delete_meta( - conn, FTS_CJK_STALE_KEY, "fts_cjk_rebuild_high_water", "fts_cjk_rebuild_progress" - ) - return True - was_stale = self._execute_write(_do) - if was_stale: - # Recreate outside the write transaction — _ensure_fts_cjk_schema - # uses executescript(), which implicitly commits and must not run - # inside _execute_write's BEGIN IMMEDIATE. - with self._lock: - self._ensure_fts_cjk_schema(self._conn) - self._conn.commit() - - def _fts_external_index_empty_with_messages(self, conn) -> bool: - """True when the base FTS table indexes nothing while ``messages`` has - rows (the post-demote empty-index shape). Caller holds ``self._lock``. - Healthy and mid-backfill installs never match.""" - try: - has_msg = conn.execute( - "SELECT EXISTS(SELECT 1 FROM messages)" - ).fetchone()[0] - if not has_msg: - return False - # docsize is the authoritative "is this rowid indexed" surface for - # external-content FTS5 (probing the vtable is unreliable across - # builds). EXISTS not COUNT(*): this runs on every writable open - # and COUNT(*) is a full b-tree scan. - has_fts = conn.execute( - "SELECT EXISTS(SELECT 1 FROM messages_fts_docsize)" - ).fetchone()[0] - return not has_fts - except sqlite3.OperationalError: - # Table absent / FTS disabled mid-init — not this failure class. - return False - - def _fts_index_known_empty(self, conn) -> bool: - """True when the base external-content index holds no rows; a missing - table counts as empty (the schema ensure that follows creates it).""" - try: - n = conn.execute( - "SELECT COUNT(*) FROM messages_fts_docsize" - ).fetchone()[0] - return int(n) == 0 - except sqlite3.OperationalError: - return True - - def _reset_fts_index_to_empty(self, conn) -> None: - """Truncate the v23 external-content tables via FTS5 ``'delete-all'``. - - A plain ``DELETE`` is O(rows) on external-content FTS5 (minutes on a - large index, holding the write lock) and corrupts the index when - indexed rows have diverged from ``messages`` — precisely the shape - this repair handles. The backfill worker replays its id range with no - anti-join, so a replay from zero is only safe once the index is known - empty; this is how a partially indexed DB gets there. - """ - for tbl in ("messages_fts", "messages_fts_trigram"): - try: - conn.execute(f"INSERT INTO {tbl}({tbl}) VALUES('delete-all')") - except sqlite3.OperationalError: - pass # table absent — already an empty surface - - def _seed_fts_rebuild_markers(self, conn, *, force: bool = False) -> int: - """Write ``fts_rebuild_high_water`` / ``fts_rebuild_progress`` for a - full backfill; returns the high-water id. - - Without ``force`` and with high_water already set, only repairs a - missing progress key, resetting a partially indexed DB to a - known-empty surface first (the chunk worker replays without an - anti-join). Caller holds the write transaction. - """ - existing_hw = _meta_row(conn, "fts_rebuild_high_water") - if existing_hw is not None and not force: - if _meta_row(conn, "fts_rebuild_progress") is None: - # high_water without progress: fts_rebuild_step treats missing - # progress as "done by another process" and optimize would - # no-op then stamp. Re-seed progress so the chunk loop runs. - if not self._fts_index_known_empty(conn): - self._reset_fts_index_to_empty(conn) - self.set_meta("fts_rebuild_progress", "0", cursor=conn) - return int(existing_hw[0]) - - hw = conn.execute("SELECT COALESCE(MAX(id), 0) FROM messages").fetchone()[0] - self.set_meta("fts_rebuild_high_water", str(hw), cursor=conn) - self.set_meta("fts_rebuild_progress", "0", cursor=conn) - return int(hw) - - def _repair_optimize_bookkeeping(self) -> None: - """Heal interrupted demote/backfill bookkeeping before optimize runs. - - 1. Empty external-content index with messages and no markers (demote - crash window / settle without backfill): seed a full backfill. - 2. high_water without progress: seed progress (resetting a partially - populated index first so the anti-join-free replay cannot - duplicate rows). - - Must not invent markers on a still-legacy inline DB: optimize would - then skip demote and attempt v23 INSERTs against the inline table forever. - """ - def _do(conn): - if _meta_row(conn, "fts_rebuild_high_water") is not None: - # Repair orphan high_water-without-progress only. Never - # invent a fresh claim on a healthy complete index. - if _meta_row(conn, "fts_rebuild_progress") is None: - if not self._fts_index_known_empty(conn): - self._reset_fts_index_to_empty(conn) - self.set_meta("fts_rebuild_progress", "0", cursor=conn) - return - - # No markers. On a still-legacy DB demote owns marker creation. - if self._db_has_legacy_inline_fts(conn): - return - - # Non-legacy empty external index (demote crash window / premature - # stamp): seed a full backfill claim. - if self._fts_external_index_empty_with_messages(conn): - _delete_meta(conn, "fts_storage_version") - self._seed_fts_rebuild_markers(conn, force=True) - self._execute_write(_do) - - def fts_optimize_available(self) -> bool: - """True when `optimize_fts_storage()` has work: legacy inline FTS to - migrate, an interrupted optimize to resume (markers/trash remain), a - CJK-bigram backfill/rebuild on this tokenizer-capable host, or an - empty external index left without markers. False for fresh and - fully-optimized installs and when FTS5 is unavailable.""" - if not self._fts_enabled or self.read_only: - return False - with self._lock: - if self._db_has_legacy_inline_fts(self._conn): - return True - # Interrupted optimize: legacy vtables already demoted, but the - # transition is unfinished until markers clear and trash is gone. - if _meta_row(self._conn, "fts_rebuild_high_water") is not None: - return True - # CJK-bigram index work — only offerable when THIS process can - # tokenize: a pending backfill (markers set at creation on a - # populated DB) or a stale index awaiting a from-scratch rebuild. - if self._fts_cjk_loaded and ( - _meta_row(self._conn, "fts_cjk_rebuild_high_water") is not None - or _meta_row(self._conn, FTS_CJK_STALE_KEY) is not None - ): - return True - if self._has_fts_trash(self._conn): - return True - # Crash window: empty external index, messages present, no markers, - # no trash. Re-run seeds markers and backfills. - return self._fts_external_index_empty_with_messages(self._conn) - - def _demote_legacy_fts_to_trash(self) -> int: - """Demote the legacy inline FTS vtables and stage their shadow tables - for chunked teardown; returns MAX(messages.id) as the rebuild high - water. O(1) schema surgery — the heavy delete is deferred. - - Markers are written in the same BEGIN IMMEDIATE as the demote, BEFORE - the empty v23 schema is created (``executescript`` implicitly COMMITs - and cannot run inside that transaction). This closes the crash window - where trash + empty v23 tables exist with no backfill claim. - """ - def _stage(conn): - self._drop_fts_triggers(conn) - conn.execute("DROP VIEW IF EXISTS messages_fts_trigram_src") - had = bool(conn.execute( - "SELECT 1 FROM sqlite_master WHERE type = 'table' " - "AND name IN ('messages_fts', 'messages_fts_trigram') " - "AND sql LIKE 'CREATE VIRTUAL TABLE%' LIMIT 1" - ).fetchone()) - if had: - conn.execute("PRAGMA writable_schema=ON") - conn.execute( - "DELETE FROM sqlite_master WHERE type = 'table' " - "AND name IN ('messages_fts', 'messages_fts_trigram') " - "AND sql LIKE 'CREATE VIRTUAL TABLE%'" - ) - conn.execute("PRAGMA writable_schema=RESET") - shadows = [ - r[0] for r in conn.execute( - "SELECT name FROM sqlite_master WHERE type = 'table' " - "AND (name LIKE 'messages_fts_%' ESCAPE '\\' " - "OR name LIKE 'messages_fts_trigram_%' ESCAPE '\\')" - ).fetchall() - ] - for sh in shadows: - conn.execute(f"ALTER TABLE {sh} RENAME TO fts_v22_trash_{sh}") - # Claim the backfill BEFORE empty v23 tables exist so a crash - # before schema ensure resumes instead of stamping an empty index. - hw = self._seed_fts_rebuild_markers(conn, force=True) - _delete_meta(conn, "fts_optimize_available") - return hw - - hw = int(self._execute_write(_stage)) - - # Outside the write transaction: ``_ensure_fts_schema`` uses - # executescript(), which implicitly commits. Markers are durable. - self._ensure_v23_fts_tables( - "failed to create v23 messages_fts during optimize-storage demote" - ) - return hw - - def _ensure_v23_fts_tables(self, failure_message: str) -> None: - """Ensure the v23 external-content base + trigram tables under the - lock (IF NOT EXISTS, cheap); raise *failure_message* without the base - table, since the backfill loop would otherwise retry "no such table" - forever.""" - with self._lock: - base_ok = self._ensure_fts_schema(self._conn, "messages_fts", FTS_SQL) - trigram_ok = self._ensure_fts_schema( - self._conn, "messages_fts_trigram", FTS_TRIGRAM_SQL - ) - self._trigram_available = bool(trigram_ok) - if not base_ok: - raise sqlite3.OperationalError(failure_message) - self._conn.commit() - - def optimize_fts_storage( - self, - *, - progress_cb: Optional[Callable[[Dict[str, Any]], None]] = None, - vacuum: bool = True, - ) -> Dict[str, Any]: - """Migrate a legacy v22 inline-FTS DB to the v23 external-content - schema, foreground and to completion; re-running resumes an - interrupted attempt. ``progress_cb`` receives {"phase", "percent", - "indexed", "total"}. A missing trigram tokenizer is not fatal (CJK - falls back to LIKE, as at startup).""" - if not self._fts_enabled: - return {"ok": False, "reason": "fts5_unavailable"} - if self.read_only: - return {"ok": False, "reason": "read_only"} - - # Heal empty-index / orphan-marker bookkeeping BEFORE deciding whether - # to demote again, so the phases below actually run. - self._repair_optimize_bookkeeping() - - # Demote only when still on the legacy shape; a prior demote - # (markers/trash present) skips straight to backfill + teardown. - with self._lock: - legacy = self._db_has_legacy_inline_fts(self._conn) - pending = self.get_meta("fts_rebuild_high_water") is not None - if legacy and not pending: - self._demote_legacy_fts_to_trash() - elif pending and not legacy: - # Resume mid-demote: markers exist, empty v23 tables may still be - # missing if the process died between the staged demote commit and - # schema ensure. - self._ensure_v23_fts_tables( - "failed to re-create v23 messages_fts on optimize-storage resume" - ) - - # A stale CJK index can only be recovered from scratch; reset it so - # the cjk backfill phase rebuilds it. Then ensure table + markers - # exist (a v23 DB gaining the cjk index for the first time). - self._fts_cjk_reset_if_stale() - if self._fts_cjk_loaded: - with self._lock: - self._ensure_fts_cjk_schema(self._conn) - self._conn.commit() - - def _emit(phase: str) -> None: - if progress_cb is None: - return - st = self.fts_rebuild_status() - if st is None: - st = self.fts_cjk_rebuild_status() - progress_cb({ - "phase": phase, - "percent": st["percent"] if st else 100, - "indexed": st["indexed"] if st else 0, - "total": st["total"] if st else 0, - }) - - def _pause(chunk_seconds: float) -> None: - """Inter-chunk throttle — the single place the duty cycle is - enforced. Without it back-to-back BEGIN IMMEDIATE chunks starve a - live gateway/CLI sharing the DB out of its lock retries.""" - time.sleep(max( - self._FTS_REBUILD_MIN_PAUSE, - chunk_seconds * self._FTS_REBUILD_DUTY_FACTOR, - )) - - def _drive(phase: str, step) -> None: - """Run *step* to completion, emitting progress and throttling - between chunks so a live gateway sharing the DB stays responsive.""" - while True: - _t0 = time.monotonic() - if not step(): - break - _emit(phase) - _pause(time.monotonic() - _t0) - - # Phase 1: base backfill. Phase 1b: CJK-bigram backfill (its own - # marker pair; no-op without the tokenizer or pending work). - _emit("backfill") - _drive("backfill", self.fts_rebuild_step) - _emit("backfill") - _drive("backfill", self.fts_cjk_rebuild_step) - - # Phase 2: tear down the demoted legacy shadow tables in chunks. - _emit("teardown") - _drive("teardown", self._fts_teardown_trash_step) - - # Refuse to stamp "optimized" while work remains or the base index is - # empty against non-empty messages (settling after a no-op backfill - # meant permanent search-index loss for historical rows). - with self._lock: - still_pending = _meta_row(self._conn, "fts_rebuild_high_water") is not None - still_trash = self._has_fts_trash(self._conn) - empty_index = self._fts_external_index_empty_with_messages(self._conn) - if still_pending or still_trash or empty_index: - reason = ( - "backfill_incomplete" if still_pending or empty_index - else "teardown_incomplete" - ) - logger.warning( - "FTS storage optimization did not settle (%s): " - "pending=%s trash=%s empty_index=%s", - reason, still_pending, still_trash, empty_index, - ) - return {"ok": False, "reason": reason, "vacuumed": None} - - # Phase 3: reclaim freed pages to the OS. - vacuum_ok = None - if vacuum: - _emit("vacuum") - try: - with self._lock: - self._conn.execute("VACUUM") - vacuum_ok = True - except sqlite3.OperationalError as exc: - # Usually no free disk for VACUUM's temp copy; the optimization - # still succeeded, space is reclaimed by a later VACUUM. - logger.warning("VACUUM after FTS optimize failed: %s", exc) - vacuum_ok = False - # Best-effort WAL fold-back. REFUSED (SQLITE_BUSY) while another - # connection holds a WAL read-mark, so callers must NOT size the - # result by stat()ing the file — use :meth:`logical_size_bytes`. - # PASSIVE, not TRUNCATE: a TRUNCATE reset from this transient CLI - # process would race a live gateway writer and tear B-tree pages. - try: - with self._lock: - self._conn.execute("PRAGMA wal_checkpoint(PASSIVE)") - except Exception as exc: - logger.debug( - "WAL checkpoint (PASSIVE) after optimize VACUUM failed: %s", - exc, - ) - - # Phase 4: stamp the FTS layout (the source of truth for "optimized"), - # clear the "available" flag, and advance schema_version if a DB - # opened only by pre-decoupling code left it behind. - def _settle(conn): - # Re-check inside the write transaction so a concurrent writer - # cannot race a stamp past incomplete work. Returns a refusal - # reason (nothing stamped) or None. - if _meta_row(conn, "fts_rebuild_high_water") is not None: - return "backfill_incomplete" - if self._has_fts_trash(conn): - return "teardown_incomplete" - if self._fts_external_index_empty_with_messages(conn): - return "backfill_incomplete" - self.set_meta("fts_storage_version", str(FTS_STORAGE_VERSION), cursor=conn) - _delete_meta(conn, "fts_optimize_available") - conn.execute( - "UPDATE schema_version SET version = ? WHERE version < ?", - (SCHEMA_VERSION, SCHEMA_VERSION), - ) - return None - refusal = self._execute_write(_settle) - if refusal is not None: - # A concurrent process changed state since the pre-vacuum check; - # report instead of crashing the CLI — a re-run can still settle. - logger.warning( - "FTS storage optimization settle refused (%s)", refusal - ) - return {"ok": False, "reason": refusal, "vacuumed": vacuum_ok} - _emit("done") - logger.info( - "FTS storage optimization complete (layout v%d).", FTS_STORAGE_VERSION - ) - return {"ok": True, "vacuumed": vacuum_ok} - - def get_anchored_view( - self, - session_id: str, - around_message_id: int, - window: int = 5, - bookend: int = 3, - keep_roles: Optional[Tuple[str, ...]] = ("user", "assistant"), - ) -> Dict[str, Any]: - """Anchored window (``get_messages_around``) plus session bookends. - - - ``window``: filtered to ``keep_roles``, EXCEPT the anchor itself is - always kept regardless of role. - - ``bookend_start`` / ``bookend_end``: first/last ``bookend`` messages - with ids strictly outside the window (empty when the window already - overlaps the head/tail). Empty-content rows (tool-call-only turns) - are skipped so they don't crowd out prose. - - Bookends let a hit anywhere in a long session yield the goal and the - resolution in one call. Empty slices + zero counts when the anchor - isn't in the session. ``keep_roles=None`` disables role filtering. - """ - if bookend < 0: - bookend = 0 - - primitive = self.get_messages_around( - session_id, around_message_id, window=window - ) - window_rows = primitive["window"] - if not window_rows: - return { - "window": [], - "messages_before": 0, - "messages_after": 0, - "bookend_start": [], - "bookend_end": [], - } - - # Apply role filter to the window, but never drop the anchor itself. - if keep_roles is not None: - keep_set = set(keep_roles) - filtered_window = [ - m for m in window_rows - if m.get("id") == around_message_id or m.get("role") in keep_set - ] - else: - filtered_window = window_rows - - window_min_id = window_rows[0]["id"] - window_max_id = window_rows[-1]["id"] - - bookend_start_rows: List[Any] = [] - bookend_end_rows: List[Any] = [] - if bookend > 0: - role_clause = "" - role_params: list = [] - if keep_roles is not None: - role_clause = f" AND role IN ({','.join('?' for _ in keep_roles)})" - role_params = list(keep_roles) - - with self._read_ctx() as conn: - def _bookend(op: str, boundary_id: int, order: str): - return conn.execute( - f"SELECT * FROM messages " - f"WHERE session_id = ? AND id {op} ?{role_clause} " - f"AND length(content) > 0 " - f"ORDER BY id {order} LIMIT ?", - (session_id, boundary_id, *role_params, bookend), - ).fetchall() - - bookend_start_rows = _bookend("<", window_min_id, "ASC") - # End rows come back DESC for the LIMIT cap; flip to ASC. - bookend_end_rows = list(reversed(_bookend(">", window_max_id, "DESC"))) - - def _hydrate(row) -> Dict[str, Any]: - msg = dict(row) - if "content" in msg: - msg["content"] = self._decode_content(msg["content"]) - if msg.get("tool_calls"): - try: - msg["tool_calls"] = json.loads(msg["tool_calls"]) - except (json.JSONDecodeError, TypeError): - logger.warning( - "Failed to deserialize tool_calls in get_anchored_view, falling back to []" - ) - msg["tool_calls"] = [] - if msg.get("display_metadata") is not None: - msg["display_metadata"] = self._decode_display_metadata(msg["display_metadata"]) - return msg - - return { - "window": filtered_window, - "messages_before": primitive["messages_before"], - "messages_after": primitive["messages_after"], - "bookend_start": [_hydrate(r) for r in bookend_start_rows], - "bookend_end": [_hydrate(r) for r in bookend_end_rows], - } - - def list_recent_user_messages( - self, - session_id: str, - limit: int = 20, - include_inactive: bool = False, - ) -> List[Dict[str, Any]]: - """The *limit* most-recent real user turns, newest first, as - ``{id, timestamp, preview}`` (preview = first 80 chars, whitespace - collapsed). Used by /rewind and ``/undo [N]``. - - Bookkeeping timeline rows (``display_kind`` set) are excluded: they - are durable ``role='user'`` rows but no client counts them as user - turns, and including them made ``/undo`` soft-delete from a marker - instead of the last real turn. Only active messages by default. - """ - active_clause = "" if include_inactive else " AND active = 1" - display_clause = " AND (display_kind IS NULL OR display_kind = '')" - # Legacy standalone compaction handoffs are role='user' rows with NO - # display_kind — SQL can't see them, so fetch with headroom and drop - # them in the decode loop; otherwise /undo N pairs an in-memory count - # that excludes handoffs with a DB pick that includes them. - fetch_limit = int(limit) * 2 + 5 - with self._lock: - rows = self._conn.execute( - "SELECT id, timestamp, content FROM messages " - "WHERE session_id = ? AND role = 'user'" - f"{active_clause}{display_clause} " - "ORDER BY id DESC LIMIT ?", - (session_id, fetch_limit), - ).fetchall() - - from agent.context_compressor import ContextCompressor - - result: List[Dict[str, Any]] = [] - for row in rows: - if len(result) >= int(limit): - break - decoded = self._decode_content(row["content"]) - if ContextCompressor._is_context_summary_content(decoded): - continue # compaction handoff — never a user-originated turn - if isinstance(decoded, list): - # Multimodal — flatten text parts. - text_parts = [ - p.get("text", "") for p in decoded - if isinstance(p, dict) and p.get("type") == "text" - ] - preview = " ".join(t for t in text_parts if t).strip() - if not preview: - preview = "[multimodal content]" - elif isinstance(decoded, str): - # A /skill turn embeds the whole skill body; show what the user - # typed instead of the skill's opening prose. - preview = describe_skill_invocation(decoded) or decoded - else: - preview = "" - preview = " ".join(preview.split()) # collapse whitespace - if len(preview) > 80: - preview = preview[:77] + "..." - result.append({"id": row["id"], "timestamp": row["timestamp"], "preview": preview}) - return result - - @staticmethod - def _sanitize_fts5_query(query: str) -> str: - """Sanitize user input for FTS5 MATCH (raw special characters raise - ``sqlite3.OperationalError``): preserve paired quoted phrases, strip - unmatched special characters, and quote hyphenated/dotted terms so - FTS5 matches them as phrases instead of splitting (``chat-send``, - ``P2.2``, ``my-app.config.ts``).""" - # Cap before any regex processing so adversarial input stays bounded. - query = query[:MAX_FTS5_QUERY_CHARS] - - # Step 1: protect balanced quoted phrases via numbered placeholders. - # Linear scan, not regex, so pathological quote runs cannot backtrack. - _quoted_parts: list = [] - pieces: list[str] = [] - i = 0 - while i < len(query): - ch = query[i] - if ch != '"': - pieces.append(ch) - i += 1 - continue - end = query.find('"', i + 1) - if end == -1: - # Unmatched quote: replace with whitespace. - pieces.append(" ") - i += 1 - continue - _quoted_parts.append(query[i:end + 1]) - pieces.append(f"\x00Q{len(_quoted_parts) - 1}\x00") - i = end + 1 - - sanitized = "".join(pieces) - - # Step 2: strip remaining FTS5-special characters (see - # _FTS5_SPECIAL_CHARS); e.g. an unquoted ``TODO: fix`` parses as - # ``column:term`` and raises "no such column". - sanitized = _FTS5_SPECIAL_RE.sub(" ", sanitized) - - # Step 2b: ``%`` is only spared for the CJK LIKE fallback; a non-CJK - # query never reaches it, so ``50%`` would hit MATCH raw and raise. - if "%" in sanitized and not SessionSearchMixin._contains_cjk(sanitized): - sanitized = sanitized.replace("%", " ") - - # Step 3: collapse repeated * and drop leading * (prefix needs a char). - sanitized = re.sub(r"\*+", "*", sanitized) - sanitized = re.sub(r"(^|\s)\*", r"\1", sanitized) - - # Step 4: drop dangling boolean operators at start/end (syntax errors). - sanitized = re.sub(r"(?i)^(AND|OR|NOT)\b\s*", "", sanitized.strip()) - sanitized = re.sub(r"(?i)\s+(AND|OR|NOT)\s*$", "", sanitized.strip()) - - # Step 5: quote dotted/hyphenated/underscored terms in ONE pass (the - # tokenizer splits on them; sequential passes double-quote - # ``my-app.config``). - sanitized = re.sub(r"\b(\w+(?:[._-]\w+)+)\b", r'"\1"', sanitized) - - # Step 6: restore preserved quoted phrases. - for i, quoted in enumerate(_quoted_parts): - sanitized = sanitized.replace(f"\x00Q{i}\x00", quoted) - - return sanitized.strip() - - @staticmethod - def _is_cjk_codepoint(cp: int) -> bool: - return (0x4E00 <= cp <= 0x9FFF or # CJK Unified Ideographs - 0x3400 <= cp <= 0x4DBF or # CJK Extension A - 0x20000 <= cp <= 0x2A6DF or # CJK Extension B - 0x3000 <= cp <= 0x303F or # CJK Symbols - 0x3040 <= cp <= 0x309F or # Hiragana - 0x30A0 <= cp <= 0x30FF or # Katakana - 0xAC00 <= cp <= 0xD7AF) # Hangul Syllables - - @staticmethod - def _contains_cjk(text: str) -> bool: - """Check if text contains CJK (Chinese, Japanese, Korean) characters.""" - return any(SessionSearchMixin._is_cjk_codepoint(ord(ch)) for ch in text) - - @classmethod - def _count_cjk(cls, text: str) -> int: - """Count CJK characters in text.""" - return sum(1 for ch in text if cls._is_cjk_codepoint(ord(ch))) - - @classmethod - def _has_lone_cjk_run(cls, query: str) -> bool: - """True when any maximal CJK run in the query is a single char: the - cjk-bigram index stores unigrams only for isolated chars, so such a - term can't match inside longer runs — those queries keep LIKE.""" - run = 0 - for ch in query: - if cls._is_cjk_codepoint(ord(ch)): - run += 1 - else: - if run == 1: - return True - run = 0 - return run == 1 - - @staticmethod - def _trigram_eligible_tokens(query: str) -> bool: - """True when every non-operator token is >=3 chars: a shorter token - produces no trigrams, and with FTS5's implicit AND one such token - makes the whole MATCH return nothing.""" - tokens = [ - t for t in query.strip('"').strip().split() if t.upper() not in _FTS_OPERATORS - ] - return bool(tokens) and all(len(t) >= 3 for t in tokens) - - @classmethod - def _has_short_cjk_token(cls, raw_query: str) -> bool: - """True when any non-operator CJK token has fewer than 3 CJK chars — - the trigram tokenizer needs >=3 per token, so such a query returns - nothing there and must take the LIKE route.""" - return any( - cls._count_cjk(t) < 3 - for t in raw_query.split() - if t.upper() not in _FTS_OPERATORS and cls._contains_cjk(t) - ) - - def _run_trigram_search( - self, - raw_query: str, - *, - table: str = "messages_fts_trigram", - order_by_sql: str, - include_inactive: bool, - source_filter: List[str] = None, - exclude_sources: List[str] = None, - role_filter: List[str] = None, - limit: int = 20, - offset: int = 0, - ) -> Optional[List[Dict[str, Any]]]: - """Search a substring-capable index (``messages_fts_trigram`` or - ``messages_fts_cjk``): trigram matches substrings regardless of word - boundaries (CJK phrases unicode61 splits, Latin runs it fuses onto - adjacent CJK like ``修改youer服务端``); cjk-bigram splits Latin runs - off CJK for an exact ranked match. Returns ``None`` when the query - cannot execute (e.g. tokenizer unavailable) so the caller can fall - back.""" - tri_sql, tri_params = self._fts_match_sql( - table, _quote_fts_tokens(raw_query), order_by_sql, - include_inactive=include_inactive, source_filter=source_filter, - exclude_sources=exclude_sources, role_filter=role_filter, - limit=limit, offset=offset, - ) - with self._read_ctx() as conn: - try: - tri_cursor = conn.execute(tri_sql, tri_params) - except sqlite3.OperationalError: - # Query failed at runtime — let the caller fall back. - return None - return [dict(row) for row in tri_cursor.fetchall()] - - @staticmethod - def _fts_match_sql( - table: str, - match_query: str, - order_by_sql: str, - *, - include_inactive: bool, - source_filter: Optional[List[str]], - exclude_sources: Optional[List[str]], - role_filter: Optional[List[str]], - limit: int, - offset: int, - ) -> Tuple[str, list]: - """MATCH query + params against one FTS5 index joined to messages/sessions.""" - where = [f"{table} MATCH ?"] - params: list = [match_query] - _search_filter_clauses( - where, params, include_inactive=include_inactive, - source_filter=source_filter, exclude_sources=exclude_sources, - role_filter=role_filter, - ) - params.extend([limit, offset]) - sql = f""" - SELECT m.id, m.session_id, m.role, - snippet({table}, -1, '>>>', '<<<', '...', 40) AS snippet, - {_SEARCH_SELECT_TAIL} - FROM {table} - JOIN messages m ON m.id = {table}.rowid - JOIN sessions s ON s.id = m.session_id - WHERE {' AND '.join(where)} - {order_by_sql} - LIMIT ? OFFSET ? - """ - return sql, params - - def search_messages( - self, - query: str, - source_filter: List[str] = None, - exclude_sources: List[str] = None, - role_filter: List[str] = None, - limit: int = 20, - offset: int = 0, - sort: str = None, - include_inactive: bool = False, - fields: Optional[Collection[str]] = None, - ) -> List[Dict[str, Any]]: - """Instrumented wrapper around :meth:`_search_messages_impl`: logs one - line per slow search with the routing path taken so latency stays - attributable per query shape. Threshold HERMES_SEARCH_SLOW_MS - (default 1000; 0 logs every call).""" - started = time.time() - rows = None - try: - rows = self._search_messages_impl( - query, - source_filter=source_filter, - exclude_sources=exclude_sources, - role_filter=role_filter, - limit=limit, - offset=offset, - sort=sort, - include_inactive=include_inactive, - fields=fields, - ) - return rows - finally: - try: - threshold = float(os.getenv("HERMES_SEARCH_SLOW_MS", "1000")) - except (TypeError, ValueError): - threshold = 1000.0 - elapsed_ms = (time.time() - started) * 1000.0 - if elapsed_ms >= threshold: - logger.info( - "slow session search: path=%s elapsed=%.0fms rows=%s query=%r", - self._describe_search_path(query), - elapsed_ms, - len(rows) if rows is not None else "err", - query[:200], - ) - - def _describe_search_path(self, query: str) -> str: - """Best-effort name of the routing path a query takes (log-only).""" - try: - if self._fts_stale: - return "like_scan_fts_stale" - sanitized = self._sanitize_fts5_query(query or "") - if not sanitized: - return "empty" - if not self._contains_cjk(sanitized): - return "fts5" - raw = sanitized.strip('"').strip() - if self._fts_cjk_available and not self._has_lone_cjk_run(raw): - return "fts_cjk" - if ( - self._count_cjk(raw) >= 3 - and not self._has_short_cjk_token(raw) - and self._trigram_available - ): - return "trigram" - return "like_scan" - except Exception: - return "unknown" - - @staticmethod - def _compile_like_boolean_query( - query: str, - ) -> Tuple[str, List[Any], Optional[str]]: - """Compile the supported FTS boolean subset into LIKE predicates: - terms within an OR group are ANDed (FTS5's implicit conjunction) and - ``NOT`` negates the following term rather than being discarded.""" - groups: List[List[Tuple[str, bool]]] = [[]] - negate_next = False - for raw_token in re.findall(r'"[^"]+"|\S+', query): - operator = raw_token.upper() - if operator == "OR": - if groups[-1]: - groups.append([]) - negate_next = False - continue - if operator in {"AND", "NEAR"}: - continue - if operator == "NOT": - negate_next = True - continue - - term = raw_token.strip('"').strip("*").strip() - if term: - groups[-1].append((term, negate_next)) - negate_next = False - - compiled_groups: List[str] = [] - params: List[Any] = [] - snippet_term: Optional[str] = None - for group in groups: - if not group or not any(not negated for _, negated in group): - continue - clauses: List[str] = [] - for term, negated in group: - clause = ( - "(COALESCE(m.content, '') LIKE ? ESCAPE '\\' OR " - "COALESCE(m.tool_name, '') LIKE ? ESCAPE '\\' OR " - "COALESCE(m.tool_calls, '') LIKE ? ESCAPE '\\')" - ) - clauses.append(f"NOT {clause}" if negated else clause) - params.extend([f"%{_escape_like(term)}%"] * 3) - if snippet_term is None and not negated: - snippet_term = term - compiled_groups.append(f"({' AND '.join(clauses)})") - - return " OR ".join(compiled_groups), params, snippet_term - - def _search_messages_like_fallback( - self, - query: str, - *, - source_filter: Optional[List[str]], - exclude_sources: Optional[List[str]], - role_filter: Optional[List[str]], - limit: int, - offset: int, - sort: Optional[str], - include_inactive: bool, - ) -> List[Dict[str, Any]]: - """Search canonical messages while derived FTS state is stale.""" - predicate, params, snippet_term = self._compile_like_boolean_query(query) - if not predicate or snippet_term is None: - return [] - - where = [f"({predicate})"] - _search_filter_clauses( - where, params, include_inactive=include_inactive, - source_filter=source_filter, exclude_sources=exclude_sources, - role_filter=role_filter, - ) - order = ( - "ASC" - if isinstance(sort, str) and sort.strip().lower() == "oldest" - else "DESC" - ) - return self._like_rows( - where, [snippet_term, *params, limit, offset], - order_by=f"ORDER BY m.timestamp {order}, m.id {order}", limit_sql="LIMIT ? OFFSET ?", - ) - - def _like_rows( - self, where: List[str], params: list, *, order_by: str, limit_sql: str - ) -> List[Dict[str, Any]]: - """Canonical-table LIKE scan; ``params[0]`` is the snippet anchor term.""" - sql = f""" - SELECT m.id, m.session_id, m.role, - {_LIKE_SNIPPET_SQL}, - {_SEARCH_SELECT_TAIL} - FROM messages m - JOIN sessions s ON s.id = m.session_id - WHERE {' AND '.join(where)} - {order_by} - {limit_sql} - """ - return [dict(row) for row in self._read_all(sql, params)] - - def _refresh_fts_stale_state(self) -> None: - """Observe fail-open initiated by another process sharing state.db.""" - if self._fts_stale or not self._fts_enabled: - return - try: - stale = self._read_one( - "SELECT 1 FROM state_meta WHERE key = ? LIMIT 1", (FTS_STALE_KEY,) - ) - except sqlite3.Error: - return - if stale is not None: - self._fts_stale = True - self._fts_enabled = False - self._trigram_available = False - self._fts_cjk_available = False - - def _finalize_search_matches( - self, - matches: List[Dict[str, Any]], - result_fields: Optional[Collection[str]] = None, - ) -> List[Dict[str, Any]]: - """Attach neighboring messages (1 before + after, only when the - projection consumes ``context``) and trim full content. Each context - query takes its own read transaction, never a lock across N queries.""" - context_matches = ( - matches if result_fields is None or "context" in result_fields else () - ) - for match in context_matches: - try: - with self._read_ctx() as conn: - ctx_cursor = conn.execute( - """WITH target AS ( +_LIKE_COALESCED_COLUMN_SQL = ( + "(COALESCE(m.content, '') LIKE ? ESCAPE '\\' OR " + "COALESCE(m.tool_name, '') LIKE ? ESCAPE '\\' OR " + "COALESCE(m.tool_calls, '') LIKE ? ESCAPE '\\')" +) +# ``sort`` -> ORDER BY for the FTS routes; anything unknown is rank-only so +# callers can pass user input through. +_FTS_ORDER_BY = {"newest": "ORDER BY m.timestamp DESC, rank", "oldest": "ORDER BY m.timestamp ASC, rank"} +# One row before + the hit + one row after, in (timestamp, id) order. +_CONTEXT_WINDOW_SQL = """WITH target AS ( SELECT session_id, timestamp, id FROM messages WHERE id = ? @@ -1362,56 +80,1067 @@ class SessionSearchMixin: OR (m.timestamp = t.timestamp AND m.id > t.id) ORDER BY m.timestamp ASC, m.id ASC LIMIT 1 - )""", - (match["id"], match["id"]), - ) - context_msgs = [] - for row in ctx_cursor.fetchall(): - decoded = self._decode_content(row["content"]) - if isinstance(decoded, list): - text_parts = [ - part.get("text", "") - for part in decoded - if isinstance(part, dict) - and part.get("type") == "text" - ] - text = " ".join(t for t in text_parts if t).strip() - preview = text or "[multimodal content]" - elif isinstance(decoded, str): - preview = decoded - else: - preview = "" - context_msgs.append( - {"role": row["role"], "content": preview[:200]} - ) - match["context"] = context_msgs - except Exception: - match["context"] = [] + )""" - # No search route selects full content (snippet + metadata only); the - # pop is a guard for any future route that does. + +def _meta_row(conn, key: str) -> Optional[sqlite3.Row]: + """Point-read one ``state_meta`` row (``None`` when absent).""" + return conn.execute("SELECT value FROM state_meta WHERE key = ?", (key,)).fetchone() + + +def _delete_meta(conn, *keys: str) -> None: + conn.execute(f"DELETE FROM state_meta WHERE key IN ({','.join('?' for _ in keys)})", keys) + + +def _quote_fts_tokens(raw_query: str) -> str: + """Quote each non-operator token (neutralising FTS5 special characters) + while preserving AND/OR/NOT.""" + return " ".join( + tok if tok.upper() in _FTS_OPERATORS else '"' + tok.replace('"', '""') + '"' + for tok in raw_query.split() + ) + + +def _like_params(term: str) -> List[str]: + """One ``%term%`` bind per column of ``_LIKE_ANY_COLUMN_SQL``.""" + return [f"%{_escape_like(term)}%"] * 3 + + +def _flatten_text(decoded: Any) -> str: + """Multimodal part list -> joined text (or the placeholder); str passes + through; anything else is ''.""" + if isinstance(decoded, list): + parts = [p.get("text", "") for p in decoded if isinstance(p, dict) and p.get("type") == "text"] + return " ".join(t for t in parts if t).strip() or "[multimodal content]" + return decoded if isinstance(decoded, str) else "" + + +def _search_filter_clauses( + where: List[str], params: list, *, include_inactive: bool, source_filter: Optional[List[str]], + exclude_sources: Optional[List[str]], role_filter: Optional[List[str]], +) -> None: + """Append the visibility/source/role predicates every search route shares. + Live rows (active=1) AND compaction-archived rows (compacted=1) are + discoverable; only rewind/undo rows (active=0, compacted=0) are hidden.""" + if not include_inactive: + where.append("(m.active = 1 OR m.compacted = 1)") + if source_filter is not None: + where.append(f"s.source IN ({','.join('?' for _ in source_filter)})") + params.extend(source_filter) + if exclude_sources is not None: + where.append(f"s.source NOT IN ({','.join('?' for _ in exclude_sources)})") + params.extend(exclude_sources) + if role_filter: + where.append(f"m.role IN ({','.join('?' for _ in role_filter)})") + params.extend(role_filter) + + +class SessionSearchMixin: + """See module docstring — mixin for SessionDB (Search cluster).""" + + _SEARCH_MESSAGE_RESULT_FIELDS = ( + "id", "session_id", "role", "snippet", "timestamp", "tool_name", "source", "model", + "session_started", "context", + ) + + @classmethod + def _search_message_fields(cls, fields: Optional[Collection[str]]) -> Optional[Tuple[str, ...]]: + """Validate and canonically order an optional result projection.""" + if fields is None: + return None + if isinstance(fields, str): + raise TypeError("search fields must be a collection of field names, not a string") + requested = set(fields) + unknown = requested.difference(cls._SEARCH_MESSAGE_RESULT_FIELDS) + if unknown: + raise ValueError(f"unknown search result field(s): {', '.join(sorted(unknown))}") + return tuple(field for field in cls._SEARCH_MESSAGE_RESULT_FIELDS if field in requested) + + def _try_incremental_merge_fts(self) -> None: + """Run one bounded FTS5 merge pass without failing the completed write. + The canonical write is already committed: no maintenance failure (even + the bare SystemError CPython's sqlite3 layer can raise under + cross-thread errmsg scrambling) may make the caller replay an + ambiguous, possibly-durable write.""" + if not self._fts_enabled: + return + try: + self._merge_fts_incrementally(max_pages=self._FTS_MERGE_MAX_PAGES_PER_INDEX) + except Exception as exc: # noqa: BLE001 - post-commit maintenance + logger.warning("FTS incremental merge failed after commit: %s", exc) + + # ── Deferred rebuild engine (base + CJK backfills) ───────────────────── + + def fts_rebuild_status(self) -> Optional[Dict[str, Any]]: + """Deferred-rebuild progress ``{"pending", "total", "indexed", + "percent"}``, or None when no rebuild is pending. Reads via the pooled + reader (not get_meta, which takes self._lock) so search_messages never + blocks on the writer lock.""" + return self._rebuild_status("fts_rebuild") + + def fts_cjk_rebuild_status(self) -> Optional[Dict[str, Any]]: + """CJK-index backfill progress, or None when none is pending.""" + return self._rebuild_status("fts_cjk_rebuild") + + def _rebuild_status(self, prefix: str) -> Optional[Dict[str, Any]]: + rows = self._read_all( + "SELECT key, value FROM state_meta WHERE key IN (?, ?)", + (f"{prefix}_high_water", f"{prefix}_progress"), + ) + meta = {r["key"]: r["value"] for r in rows} + high_water = meta.get(f"{prefix}_high_water") + if high_water is None: + return None + progress = int(meta.get(f"{prefix}_progress") or 0) + total = int(high_water) + if total <= 0: + return None + pct = min(100, int(100 * progress / total)) + return {"pending": True, "total": total, "indexed": progress, "percent": pct} + + # Re-index rows in an id window the index is missing. docsize has one row + # per indexed doc, so the anti-join is exact. + _BOUNDARY_SWEEP_SQL = ( + "INSERT INTO {table}(rowid, content, tool_name, tool_calls) " + "SELECT m.id, m.content, m.tool_name, m.tool_calls " + "FROM messages m " + "WHERE m.id > ? AND m.id <= ? {extra}" + "AND NOT EXISTS (SELECT 1 FROM {table}_docsize d WHERE d.id = m.id)" + ) + _CHUNK_INSERT_SQL = ( + "INSERT INTO {table}(rowid, content, tool_name, tool_calls) " + "SELECT id, content, tool_name, tool_calls FROM messages " + "WHERE id > ? AND id <= ?{extra}" + ) + + def _fts_rebuild_finish(self) -> None: + """Finalize the deferred rebuild: boundary sweep + clear markers. + The sweep is cheap insurance against a write that slipped through the + migration-boundary instant (between high_water capture and trigger + activation). The trigram half is gated on ``_trigram_available``: + without the tokenizer/table an unconditional INSERT raises ``no such + table`` and aborts the whole rebuild (and optimize_fts_storage()).""" + sweeps = [self._BOUNDARY_SWEEP_SQL.format(table="messages_fts", extra="")] + if self._trigram_available: + sweeps.append(self._BOUNDARY_SWEEP_SQL.format(table="messages_fts_trigram", extra="AND m.role <> 'tool' ")) + self._rebuild_finish("fts_rebuild", sweeps) + logger.info("Deferred FTS rebuild complete — all messages indexed.") + + def _fts_cjk_rebuild_finish(self) -> None: + """Boundary sweep + clear the cjk markers; index becomes servable.""" + self._rebuild_finish("fts_cjk_rebuild", [ + self._BOUNDARY_SWEEP_SQL.format(table="messages_fts_cjk", extra="AND m.role <> 'tool' ") + ]) + self._fts_cjk_available = True + logger.info("CJK FTS index backfill complete — serving CJK search.") + + def _rebuild_finish(self, prefix: str, sweep_sqls: List[str]) -> None: + """Sweep a generous window around the high-water boundary, then clear + the ``{prefix}_high_water`` / ``{prefix}_progress`` markers.""" + def _do(conn): + hw_row = _meta_row(conn, f"{prefix}_high_water") + if hw_row is not None: + hw = int(hw_row[0]) + for sql in sweep_sqls: + conn.execute(sql, (hw - 1000, hw + 1000)) + _delete_meta(conn, f"{prefix}_high_water", f"{prefix}_progress") + self._execute_write(_do) + + def fts_rebuild_step(self) -> bool: + """Backfill one chunk of the deferred FTS rebuild; True while work + remains. Safe from any process: chunks are claimed atomically inside + the write transaction, so concurrent callers interleave instead of + duplicating rows.""" + if not self._fts_enabled: + return False + inserts = [self._CHUNK_INSERT_SQL.format(table="messages_fts", extra="")] + if self._trigram_available: + inserts.append(self._CHUNK_INSERT_SQL.format(table="messages_fts_trigram", extra=" AND role <> 'tool'")) + return self._rebuild_step( + "fts_rebuild", inserts, fail_msg="FTS rebuild chunk failed (will retry): %s", + finish=self._fts_rebuild_finish, + ) + + def fts_cjk_rebuild_step(self) -> bool: + """Backfill one chunk of the CJK index. True while work remains.""" + if not self._fts_enabled or not self._fts_cjk_loaded: + return False + return self._rebuild_step( + "fts_cjk_rebuild", + [self._CHUNK_INSERT_SQL.format(table="messages_fts_cjk", extra=" AND role <> 'tool'")], + fail_msg="CJK FTS rebuild chunk failed (will retry): %s", finish=self._fts_cjk_rebuild_finish, + ) + + def _rebuild_step(self, prefix: str, insert_sqls: List[str], *, fail_msg: str, finish) -> bool: + """Shared chunk engine for the base and CJK deferred backfills.""" + high_water_raw = self.get_meta(f"{prefix}_high_water") + if high_water_raw is None: + return False + high_water = int(high_water_raw) + chunk = self._FTS_REBUILD_CHUNK_ROWS + + def _do(conn): + # Re-reading progress inside the BEGIN IMMEDIATE held by + # _execute_write IS the claim: two workers cannot read the same value. + row = _meta_row(conn, f"{prefix}_progress") + if row is None: + return False # finished (or cleared) by another process + progress = int(row[0]) + if progress >= high_water: + return False + # Upper bound is an id, not a row count, so deleted-row gaps don't + # shrink chunks below the claimed range. + upper = min(progress + chunk, high_water) + for sql in insert_sqls: + conn.execute(sql, (progress, upper)) + # Progress lands in the same transaction as its rows (crash-atomic). + conn.execute("UPDATE state_meta SET value = ? WHERE key = ?", (str(upper), f"{prefix}_progress")) + return upper < high_water + + try: + more = self._execute_write(_do) + except sqlite3.OperationalError as exc: + logger.debug(fail_msg, exc) + return True # transient (lock contention) — caller retries + if more is False: + status = self._rebuild_status(prefix) + if status is not None and status["indexed"] >= status["total"]: + finish() + return False + return bool(more) + + def _fts_teardown_trash_step(self) -> bool: + """Tear down one chunk of a demoted v22 FTS shadow table; True while + work remains. + + Trash tables are PLAIN tables (their vtable parent was demoted), so no + FTS5 machinery is involved. Integer single-column-key tables drain with + a high-water marker so each chunk's scan is bounded (restarting the + scan was O(n²)); compound-key tables cannot use a scalar high-water and + keep the chunked ``LIMIT`` delete — they are small by construction.""" + with self._lock: + trash = [ + r[0] for r in self._conn.execute( + "SELECT name FROM sqlite_master WHERE type = 'table' " + "AND name LIKE ? ESCAPE '\\'", + (self._FTS_TRASH_PREFIX.replace("_", "\\_") + "%",), + ).fetchall() + ] + if not trash: + return False + tbl = trash[0] + + def _do(conn): + pk_info = [(r[1], (r[2] or "").upper()) for r in conn.execute(f"PRAGMA table_info({tbl})") if r[5] > 0] + pk_cols = [name for name, _typ in pk_info] + key = ", ".join(pk_cols) if pk_cols else "rowid" + if len(pk_cols) == 1 and (not pk_info or pk_info[0][1] == "INTEGER"): + # High-water drain; the marker is read/written in the same + # BEGIN IMMEDIATE as the DELETE so concurrent callers claim + # disjoint ranges. Only INTEGER pks anchor the comparison (the + # TEXT-pk config shadow table falls through below). + marker_key = f"fts_teardown_{tbl}_progress" + row = _meta_row(conn, marker_key) + high_water = int(row[0]) if row is not None else 0 + # Claim the LAST row of the LIMIT window so a full chunk goes per step. + upper_rows = conn.execute( + f"SELECT {key} FROM {tbl} WHERE {key} > ? " + f"ORDER BY {key} LIMIT {self._FTS_REBUILD_CHUNK_ROWS}", + (high_water,), + ).fetchall() + if not upper_rows: + return _drop(conn, marker_key) + upper = upper_rows[-1][0] + cur = conn.execute(f"DELETE FROM {tbl} WHERE {key} > ? AND {key} <= ?", (high_water, upper)) + if cur.rowcount > 0: + self.set_meta(marker_key, str(upper), cursor=conn) + return True + cur = conn.execute( + f"DELETE FROM {tbl} WHERE ({key}) IN " + f"(SELECT {key} FROM {tbl} LIMIT {self._FTS_REBUILD_CHUNK_ROWS})" + ) + if cur.rowcount == 0: + return _drop(conn) + return True # re-check: more trash tables / chunks may remain + + def _drop(conn, marker_key: Optional[str] = None) -> bool: + """Drained — the DROP is cheap now. True: re-check for more trash.""" + conn.execute(f"DROP TABLE IF EXISTS {tbl}") + if marker_key is not None: + _delete_meta(conn, marker_key) + logger.info("Old FTS shadow table %s torn down.", tbl) + return True + + try: + return bool(self._execute_write(_do)) + except sqlite3.OperationalError as exc: + logger.debug("FTS trash teardown chunk failed (will retry): %s", exc) + return True + + def _fts_cjk_reset_if_stale(self) -> None: + """From-scratch rebuild of a stale cjk index (triggers were dropped, + gap extent unknown): drop table + triggers, clear the breadcrumb, + recreate via ``_ensure_fts_cjk_schema`` (fresh backfill markers on a + populated DB). No-op when not stale.""" + if not self._fts_cjk_loaded: + return + + def _do(conn): + if _meta_row(conn, FTS_CJK_STALE_KEY) is None: + return False + for trig in _FTS_CJK_TRIGGERS: + conn.execute(f"DROP TRIGGER IF EXISTS {trig}") + conn.execute("DROP TABLE IF EXISTS messages_fts_cjk") + conn.execute("DROP VIEW IF EXISTS messages_fts_cjk_src") + _delete_meta(conn, FTS_CJK_STALE_KEY, "fts_cjk_rebuild_high_water", "fts_cjk_rebuild_progress") + return True + if self._execute_write(_do): + # Recreate OUTSIDE the write transaction: _ensure_fts_cjk_schema uses + # executescript(), which implicitly commits. + with self._lock: + self._ensure_fts_cjk_schema(self._conn) + self._conn.commit() + + def _fts_external_index_empty_with_messages(self, conn) -> bool: + """True when the base FTS table indexes nothing while ``messages`` has + rows (the post-demote empty-index shape). Caller holds ``self._lock``. + Healthy and mid-backfill installs never match. docsize is the + authoritative "is this rowid indexed" surface for external-content + FTS5; EXISTS not COUNT(*) because this runs on every writable open.""" + try: + if not conn.execute("SELECT EXISTS(SELECT 1 FROM messages)").fetchone()[0]: + return False + return not conn.execute("SELECT EXISTS(SELECT 1 FROM messages_fts_docsize)").fetchone()[0] + except sqlite3.OperationalError: + return False # table absent / FTS disabled mid-init — not this failure class + + def _fts_index_known_empty(self, conn) -> bool: + """True when the base external-content index holds no rows; a missing + table counts as empty (the schema ensure that follows creates it).""" + try: + return int(conn.execute("SELECT COUNT(*) FROM messages_fts_docsize").fetchone()[0]) == 0 + except sqlite3.OperationalError: + return True + + def _reset_fts_index_to_empty(self, conn) -> None: + """Truncate the v23 external-content tables via FTS5 ``'delete-all'``. + A plain DELETE is O(rows) on external-content FTS5 and corrupts the + index when indexed rows diverged from ``messages`` — exactly the shape + this repair handles. The backfill worker replays its id range with no + anti-join, so a replay from zero is only safe once the index is known + empty; this is how a partially indexed DB gets there.""" + for tbl in ("messages_fts", "messages_fts_trigram"): + try: + conn.execute(f"INSERT INTO {tbl}({tbl}) VALUES('delete-all')") + except sqlite3.OperationalError: + pass # table absent — already an empty surface + + def _reseed_missing_progress(self, conn) -> None: + """high_water without progress: fts_rebuild_step reads missing progress + as "done by another process" and optimize would no-op then stamp. + Reset a partially indexed DB to a known-empty surface (the chunk + worker replays without an anti-join) and re-seed progress.""" + if _meta_row(conn, "fts_rebuild_progress") is None: + if not self._fts_index_known_empty(conn): + self._reset_fts_index_to_empty(conn) + self.set_meta("fts_rebuild_progress", "0", cursor=conn) + + def _seed_fts_rebuild_markers(self, conn, *, force: bool = False) -> int: + """Write ``fts_rebuild_high_water`` / ``fts_rebuild_progress`` for a + full backfill; returns the high-water id. Without ``force`` and with + high_water already set, only repairs a missing progress key (see + ``_reseed_missing_progress`` for why a missing key must not read as + "done"). Caller holds the write transaction.""" + existing_hw = _meta_row(conn, "fts_rebuild_high_water") + if existing_hw is not None and not force: + self._reseed_missing_progress(conn) + return int(existing_hw[0]) + hw = conn.execute("SELECT COALESCE(MAX(id), 0) FROM messages").fetchone()[0] + self.set_meta("fts_rebuild_high_water", str(hw), cursor=conn) + self.set_meta("fts_rebuild_progress", "0", cursor=conn) + return int(hw) + + def _repair_optimize_bookkeeping(self) -> None: + """Heal interrupted demote/backfill bookkeeping before optimize runs: + orphan high_water-without-progress gets progress re-seeded; an empty + external index with messages and no markers (demote crash window / + premature stamp) gets a full backfill claim. Never invents markers on a + still-legacy inline DB — optimize would then skip demote and INSERT + against the inline table forever.""" + def _do(conn): + if _meta_row(conn, "fts_rebuild_high_water") is not None: + self._reseed_missing_progress(conn) + return + if self._db_has_legacy_inline_fts(conn): + return # demote owns marker creation + if self._fts_external_index_empty_with_messages(conn): + _delete_meta(conn, "fts_storage_version") + self._seed_fts_rebuild_markers(conn, force=True) + self._execute_write(_do) + + def fts_optimize_available(self) -> bool: + """True when `optimize_fts_storage()` has work: legacy inline FTS to + migrate, an interrupted optimize to resume (markers/trash remain), a + CJK-bigram backfill/rebuild on this tokenizer-capable host, or an + empty external index left without markers. False for fresh and + fully-optimized installs and when FTS5 is unavailable.""" + if not self._fts_enabled or self.read_only: + return False + with self._lock: + conn = self._conn + if self._db_has_legacy_inline_fts(conn): + return True + if _meta_row(conn, "fts_rebuild_high_water") is not None: + return True # interrupted optimize: demoted but unfinished + # CJK work is only offerable when THIS process can tokenize. + if self._fts_cjk_loaded and ( + _meta_row(conn, "fts_cjk_rebuild_high_water") is not None + or _meta_row(conn, FTS_CJK_STALE_KEY) is not None + ): + return True + if self._has_fts_trash(conn): + return True + return self._fts_external_index_empty_with_messages(conn) + + def _demote_legacy_fts_to_trash(self) -> int: + """Demote the legacy inline FTS vtables and stage their shadow tables + for chunked teardown; returns MAX(messages.id) as the rebuild high + water. O(1) schema surgery — the heavy delete is deferred. + + Markers are written in the same BEGIN IMMEDIATE as the demote, BEFORE + the empty v23 schema is created (``executescript`` implicitly COMMITs + and cannot run inside that transaction), closing the crash window + where trash + empty v23 tables exist with no backfill claim.""" + def _stage(conn): + self._drop_fts_triggers(conn) + conn.execute("DROP VIEW IF EXISTS messages_fts_trigram_src") + had = bool(conn.execute( + "SELECT 1 FROM sqlite_master WHERE type = 'table' " + "AND name IN ('messages_fts', 'messages_fts_trigram') " + "AND sql LIKE 'CREATE VIRTUAL TABLE%' LIMIT 1" + ).fetchone()) + if had: + conn.execute("PRAGMA writable_schema=ON") + conn.execute( + "DELETE FROM sqlite_master WHERE type = 'table' " + "AND name IN ('messages_fts', 'messages_fts_trigram') " + "AND sql LIKE 'CREATE VIRTUAL TABLE%'" + ) + conn.execute("PRAGMA writable_schema=RESET") + shadows = [ + r[0] for r in conn.execute( + "SELECT name FROM sqlite_master WHERE type = 'table' " + "AND (name LIKE 'messages_fts_%' ESCAPE '\\' " + "OR name LIKE 'messages_fts_trigram_%' ESCAPE '\\')" + ).fetchall() + ] + for sh in shadows: + conn.execute(f"ALTER TABLE {sh} RENAME TO fts_v22_trash_{sh}") + # Claim the backfill BEFORE the empty v23 tables exist so a crash before + # schema ensure resumes instead of stamping an empty index. + hw = self._seed_fts_rebuild_markers(conn, force=True) + _delete_meta(conn, "fts_optimize_available") + return hw + + hw = int(self._execute_write(_stage)) + # Outside the write transaction (executescript commits); markers are durable. + self._ensure_v23_fts_tables("failed to create v23 messages_fts during optimize-storage demote") + return hw + + def _ensure_v23_fts_tables(self, failure_message: str) -> None: + """Ensure the v23 base + trigram tables under the lock (IF NOT EXISTS, + cheap); raise *failure_message* without the base table, since the + backfill loop would otherwise retry "no such table" forever.""" + with self._lock: + base_ok = self._ensure_fts_schema(self._conn, "messages_fts", FTS_SQL) + trigram_ok = self._ensure_fts_schema(self._conn, "messages_fts_trigram", FTS_TRIGRAM_SQL) + self._trigram_available = bool(trigram_ok) + if not base_ok: + raise sqlite3.OperationalError(failure_message) + self._conn.commit() + + def _optimize_unsettled_reason(self, conn) -> Optional[str]: + """Refusal reason while optimize work remains, else None. Settling after + a no-op backfill meant permanent search-index loss for historical rows, + so an empty base index against non-empty messages also refuses.""" + if _meta_row(conn, "fts_rebuild_high_water") is not None: + return "backfill_incomplete" + if self._has_fts_trash(conn): + return "teardown_incomplete" + if self._fts_external_index_empty_with_messages(conn): + return "backfill_incomplete" + return None + + def _optimize_vacuum(self) -> bool: + """Phase 3: reclaim freed pages to the OS. False when VACUUM failed + (usually no free disk for its temp copy; a later VACUUM reclaims).""" + try: + with self._lock: + self._conn.execute("VACUUM") + vacuum_ok = True + except sqlite3.OperationalError as exc: + logger.warning("VACUUM after FTS optimize failed: %s", exc) + vacuum_ok = False + # Best-effort WAL fold-back, REFUSED (SQLITE_BUSY) while another + # connection holds a read-mark — so callers must size the result via + # logical_size_bytes, not stat(). PASSIVE, never TRUNCATE: a TRUNCATE + # reset from a transient CLI would race a live writer. + try: + with self._lock: + self._conn.execute("PRAGMA wal_checkpoint(PASSIVE)") + except Exception as exc: + logger.debug("WAL checkpoint (PASSIVE) after optimize VACUUM failed: %s", exc) + return vacuum_ok + + def _optimize_settle(self, conn) -> Optional[str]: + """Phase 4 (inside the write transaction, so a concurrent writer cannot + race a stamp past incomplete work): stamp the FTS layout — the source + of truth for "optimized" — clear the "available" flag, and advance + schema_version if pre-decoupling code left it behind. Returns a + refusal reason (nothing stamped) or None.""" + refusal = self._optimize_unsettled_reason(conn) + if refusal is not None: + return refusal + self.set_meta("fts_storage_version", str(FTS_STORAGE_VERSION), cursor=conn) + _delete_meta(conn, "fts_optimize_available") + conn.execute( + "UPDATE schema_version SET version = ? WHERE version < ?", + (SCHEMA_VERSION, SCHEMA_VERSION), + ) + return None + + def optimize_fts_storage( + self, *, progress_cb: Optional[Callable[[Dict[str, Any]], None]] = None, vacuum: bool = True + ) -> Dict[str, Any]: + """Migrate a legacy v22 inline-FTS DB to the v23 external-content + schema, foreground and to completion; re-running resumes an + interrupted attempt. ``progress_cb`` receives {"phase", "percent", + "indexed", "total"}. A missing trigram tokenizer is not fatal (CJK + falls back to LIKE, as at startup).""" + if not self._fts_enabled: + return {"ok": False, "reason": "fts5_unavailable"} + if self.read_only: + return {"ok": False, "reason": "read_only"} + + # Heal bookkeeping BEFORE deciding whether to demote again. + self._repair_optimize_bookkeeping() + with self._lock: + legacy = self._db_has_legacy_inline_fts(self._conn) + pending = self.get_meta("fts_rebuild_high_water") is not None + if legacy and not pending: + self._demote_legacy_fts_to_trash() + elif pending and not legacy: + # Resume mid-demote: the process may have died between the staged + # demote commit and schema ensure. + self._ensure_v23_fts_tables("failed to re-create v23 messages_fts on optimize-storage resume") + + # A stale CJK index can only be recovered from scratch; then ensure + # table + markers exist (a v23 DB gaining the cjk index for the first time). + self._fts_cjk_reset_if_stale() + if self._fts_cjk_loaded: + with self._lock: + self._ensure_fts_cjk_schema(self._conn) + self._conn.commit() + + def _emit(phase: str) -> None: + if progress_cb is None: + return + st = self.fts_rebuild_status() or self.fts_cjk_rebuild_status() + progress_cb({ + "phase": phase, "percent": st["percent"] if st else 100, + "indexed": st["indexed"] if st else 0, "total": st["total"] if st else 0, + }) + + def _drive(phase: str, step) -> None: + """Run *step* to completion; the inter-chunk sleep is the single + place the duty cycle is enforced — back-to-back BEGIN IMMEDIATE + chunks starve a live gateway/CLI out of its lock retries.""" + while True: + _t0 = time.monotonic() + if not step(): + break + _emit(phase) + time.sleep(max(self._FTS_REBUILD_MIN_PAUSE, (time.monotonic() - _t0) * self._FTS_REBUILD_DUTY_FACTOR)) + + # Phase 1: base backfill; 1b: CJK-bigram backfill (own marker pair). + _emit("backfill") + _drive("backfill", self.fts_rebuild_step) + _emit("backfill") + _drive("backfill", self.fts_cjk_rebuild_step) + # Phase 2: tear down the demoted legacy shadow tables in chunks. + _emit("teardown") + _drive("teardown", self._fts_teardown_trash_step) + + with self._lock: + still_pending = _meta_row(self._conn, "fts_rebuild_high_water") is not None + still_trash = self._has_fts_trash(self._conn) + empty_index = self._fts_external_index_empty_with_messages(self._conn) + if still_pending or still_trash or empty_index: + reason = "backfill_incomplete" if still_pending or empty_index else "teardown_incomplete" + logger.warning( + "FTS storage optimization did not settle (%s): pending=%s trash=%s empty_index=%s", + reason, still_pending, still_trash, empty_index, + ) + return {"ok": False, "reason": reason, "vacuumed": None} + + vacuum_ok = None + if vacuum: + _emit("vacuum") + vacuum_ok = self._optimize_vacuum() + refusal = self._execute_write(self._optimize_settle) + if refusal is not None: + # A concurrent process changed state since the pre-vacuum check; a re-run can still settle. + logger.warning("FTS storage optimization settle refused (%s)", refusal) + return {"ok": False, "reason": refusal, "vacuumed": vacuum_ok} + _emit("done") + logger.info("FTS storage optimization complete (layout v%d).", FTS_STORAGE_VERSION) + return {"ok": True, "vacuumed": vacuum_ok} + + # ── Read views ───────────────────────────────────────────────────────── + + def get_anchored_view( + self, session_id: str, around_message_id: int, window: int = 5, bookend: int = 3, + keep_roles: Optional[Tuple[str, ...]] = ("user", "assistant"), + ) -> Dict[str, Any]: + """Anchored window (``get_messages_around``) plus session bookends, so a + hit anywhere in a long session yields the goal and the resolution in + one call. ``window`` is filtered to ``keep_roles`` EXCEPT the anchor, + which is always kept; ``bookend_start`` / ``bookend_end`` are the + first/last ``bookend`` messages with ids strictly outside the window + (empty when the window already overlaps the head/tail), skipping + empty-content rows (tool-call-only turns) so they don't crowd out + prose. Empty slices + zero counts when the anchor isn't in the + session. ``keep_roles=None`` disables role filtering.""" + bookend = max(bookend, 0) + primitive = self.get_messages_around(session_id, around_message_id, window=window) + window_rows = primitive["window"] + if not window_rows: + return {"window": [], "messages_before": 0, "messages_after": 0, "bookend_start": [], "bookend_end": []} + + filtered_window = window_rows + if keep_roles is not None: + keep_set = set(keep_roles) + filtered_window = [m for m in window_rows if m.get("id") == around_message_id or m.get("role") in keep_set] + + bookend_start_rows: List[Any] = [] + bookend_end_rows: List[Any] = [] + if bookend > 0: + role_clause = "" + role_params: list = [] + if keep_roles is not None: + role_clause = f" AND role IN ({','.join('?' for _ in keep_roles)})" + role_params = list(keep_roles) + with self._read_ctx() as conn: + def _bookend(op: str, boundary_id: int, order: str): + return conn.execute( + f"SELECT * FROM messages " + f"WHERE session_id = ? AND id {op} ?{role_clause} " + f"AND length(content) > 0 " + f"ORDER BY id {order} LIMIT ?", + (session_id, boundary_id, *role_params, bookend), + ).fetchall() + bookend_start_rows = _bookend("<", window_rows[0]["id"], "ASC") + # End rows come back DESC for the LIMIT cap; flip to ASC. + bookend_end_rows = list(reversed(_bookend(">", window_rows[-1]["id"], "DESC"))) + + def _hydrate(row) -> Dict[str, Any]: + msg = dict(row) + if "content" in msg: + msg["content"] = self._decode_content(msg["content"]) + if msg.get("tool_calls"): + try: + msg["tool_calls"] = json.loads(msg["tool_calls"]) + except (json.JSONDecodeError, TypeError): + logger.warning("Failed to deserialize tool_calls in get_anchored_view, falling back to []") + msg["tool_calls"] = [] + if msg.get("display_metadata") is not None: + msg["display_metadata"] = self._decode_display_metadata(msg["display_metadata"]) + return msg + + return { + "window": filtered_window, "messages_before": primitive["messages_before"], + "messages_after": primitive["messages_after"], + "bookend_start": [_hydrate(r) for r in bookend_start_rows], + "bookend_end": [_hydrate(r) for r in bookend_end_rows], + } + + def list_recent_user_messages( + self, session_id: str, limit: int = 20, include_inactive: bool = False + ) -> List[Dict[str, Any]]: + """The *limit* most-recent real user turns, newest first, as + ``{id, timestamp, preview}`` (preview = first 80 chars, whitespace + collapsed). Used by /rewind and ``/undo [N]``. + + Bookkeeping timeline rows (``display_kind`` set) are excluded: no + client counts them as user turns, and including them made ``/undo`` + soft-delete from a marker instead of the last real turn. Legacy + standalone compaction handoffs are role='user' rows with NO + display_kind — invisible to SQL — so fetch with headroom and drop them + in the decode loop; otherwise ``/undo N`` pairs an in-memory count that + excludes handoffs with a DB pick that includes them.""" + active_clause = "" if include_inactive else " AND active = 1" + display_clause = " AND (display_kind IS NULL OR display_kind = '')" + fetch_limit = int(limit) * 2 + 5 + with self._lock: + rows = self._conn.execute( + "SELECT id, timestamp, content FROM messages " + "WHERE session_id = ? AND role = 'user'" + f"{active_clause}{display_clause} " + "ORDER BY id DESC LIMIT ?", + (session_id, fetch_limit), + ).fetchall() + + from agent.context_compressor import ContextCompressor + + result: List[Dict[str, Any]] = [] + for row in rows: + if len(result) >= int(limit): + break + decoded = self._decode_content(row["content"]) + if ContextCompressor._is_context_summary_content(decoded): + continue # compaction handoff — never a user-originated turn + if isinstance(decoded, str): + # A /skill turn embeds the whole skill body; show what was typed. + preview = describe_skill_invocation(decoded) or decoded + else: + preview = _flatten_text(decoded) + preview = " ".join(preview.split()) + if len(preview) > 80: + preview = preview[:77] + "..." + result.append({"id": row["id"], "timestamp": row["timestamp"], "preview": preview}) + return result + + # ── Query analysis ───────────────────────────────────────────────────── + + @staticmethod + def _sanitize_fts5_query(query: str) -> str: + """Sanitize user input for FTS5 MATCH (raw special characters raise + ``sqlite3.OperationalError``): preserve paired quoted phrases, strip + unmatched special characters, and quote hyphenated/dotted terms so + FTS5 matches them as phrases instead of splitting (``chat-send``, + ``P2.2``, ``my-app.config.ts``).""" + # Cap before any regex processing so adversarial input stays bounded. + query = query[:MAX_FTS5_QUERY_CHARS] + + # 1. Protect balanced quoted phrases via numbered placeholders. Linear + # scan, not regex, so pathological quote runs cannot backtrack. + _quoted_parts: list = [] + pieces: list[str] = [] + i = 0 + while i < len(query): + ch = query[i] + if ch != '"': + pieces.append(ch) + i += 1 + continue + end = query.find('"', i + 1) + if end == -1: + pieces.append(" ") # unmatched quote -> whitespace + i += 1 + continue + _quoted_parts.append(query[i:end + 1]) + pieces.append(f"\x00Q{len(_quoted_parts) - 1}\x00") + i = end + 1 + sanitized = "".join(pieces) + + # 2. Strip FTS5-special characters (an unquoted ``TODO: fix`` parses as + # ``column:term``). ``%`` is only spared for the CJK LIKE fallback. + sanitized = _FTS5_SPECIAL_RE.sub(" ", sanitized) + if "%" in sanitized and not SessionSearchMixin._contains_cjk(sanitized): + sanitized = sanitized.replace("%", " ") + # 3. Collapse repeated * and drop leading * (prefix needs a char). + sanitized = re.sub(r"\*+", "*", sanitized) + sanitized = re.sub(r"(^|\s)\*", r"\1", sanitized) + # 4. Drop dangling boolean operators at start/end (syntax errors). + sanitized = re.sub(r"(?i)^(AND|OR|NOT)\b\s*", "", sanitized.strip()) + sanitized = re.sub(r"(?i)\s+(AND|OR|NOT)\s*$", "", sanitized.strip()) + # 5. Quote dotted/hyphenated/underscored terms in ONE pass (sequential + # passes double-quote ``my-app.config``). + sanitized = re.sub(r"\b(\w+(?:[._-]\w+)+)\b", r'"\1"', sanitized) + # 6. Restore preserved quoted phrases. + for i, quoted in enumerate(_quoted_parts): + sanitized = sanitized.replace(f"\x00Q{i}\x00", quoted) + return sanitized.strip() + + # Unified Ideographs, Extension A, Extension B, CJK Symbols, Hiragana, Katakana, Hangul Syllables. + _CJK_RANGES = ( + (0x4E00, 0x9FFF), (0x3400, 0x4DBF), (0x20000, 0x2A6DF), (0x3000, 0x303F), (0x3040, 0x309F), + (0x30A0, 0x30FF), (0xAC00, 0xD7AF), + ) + + @staticmethod + def _is_cjk_codepoint(cp: int) -> bool: + return any(lo <= cp <= hi for lo, hi in SessionSearchMixin._CJK_RANGES) + + @staticmethod + def _contains_cjk(text: str) -> bool: + return any(SessionSearchMixin._is_cjk_codepoint(ord(ch)) for ch in text) + + @classmethod + def _count_cjk(cls, text: str) -> int: + return sum(1 for ch in text if cls._is_cjk_codepoint(ord(ch))) + + @classmethod + def _has_lone_cjk_run(cls, query: str) -> bool: + """True when any maximal CJK run in the query is a single char: the + cjk-bigram index stores unigrams only for isolated chars, so such a + term can't match inside longer runs — those queries keep LIKE.""" + run = 0 + for ch in query: + if cls._is_cjk_codepoint(ord(ch)): + run += 1 + else: + if run == 1: + return True + run = 0 + return run == 1 + + @staticmethod + def _trigram_eligible_tokens(query: str) -> bool: + """True when every non-operator token is >=3 chars: a shorter token + produces no trigrams, and with FTS5's implicit AND one such token + makes the whole MATCH return nothing.""" + tokens = [t for t in query.strip('"').strip().split() if t.upper() not in _FTS_OPERATORS] + return bool(tokens) and all(len(t) >= 3 for t in tokens) + + @classmethod + def _has_short_cjk_token(cls, raw_query: str) -> bool: + """True when any non-operator CJK token has fewer than 3 CJK chars — + the trigram tokenizer needs >=3 per token, so such a query returns + nothing there and must take the LIKE route.""" + return any( + cls._count_cjk(t) < 3 + for t in raw_query.split() + if t.upper() not in _FTS_OPERATORS and cls._contains_cjk(t) + ) + + def _trigram_route_ok(self, raw_query: str) -> bool: + """Per-token CJK length gate for the trigram index: ``广西 OR 桂林 OR + 漓江`` has 6 CJK chars total but 2 per token, so trigram returns 0.""" + return ( + self._count_cjk(raw_query) >= 3 + and not self._has_short_cjk_token(raw_query) + and self._trigram_available + ) + + def _describe_search_path(self, query: str) -> str: + """Best-effort name of the routing path a query takes (log-only).""" + try: + if self._fts_stale: + return "like_scan_fts_stale" + sanitized = self._sanitize_fts5_query(query or "") + if not sanitized: + return "empty" + if not self._contains_cjk(sanitized): + return "fts5" + raw = sanitized.strip('"').strip() + if self._fts_cjk_available and not self._has_lone_cjk_run(raw): + return "fts_cjk" + if self._trigram_route_ok(raw): + return "trigram" + return "like_scan" + except Exception: + return "unknown" + + # ── Query builders / runners ─────────────────────────────────────────── + + @staticmethod + def _fts_match_sql( + table: str, match_query: str, order_by_sql: str, *, include_inactive: bool, + source_filter: Optional[List[str]], exclude_sources: Optional[List[str]], + role_filter: Optional[List[str]], limit: int, offset: int, + ) -> Tuple[str, list]: + """MATCH query + params against one FTS5 index joined to messages/sessions.""" + where = [f"{table} MATCH ?"] + params: list = [match_query] + _search_filter_clauses( + where, params, include_inactive=include_inactive, source_filter=source_filter, + exclude_sources=exclude_sources, role_filter=role_filter, + ) + params.extend([limit, offset]) + sql = f""" + SELECT m.id, m.session_id, m.role, + snippet({table}, -1, '>>>', '<<<', '...', 40) AS snippet, + {_SEARCH_SELECT_TAIL} + FROM {table} + JOIN messages m ON m.id = {table}.rowid + JOIN sessions s ON s.id = m.session_id + WHERE {' AND '.join(where)} + {order_by_sql} + LIMIT ? OFFSET ? + """ + return sql, params + + def _match_rows( + self, table: str, match_query: str, order_by_sql: str, *, fail_open: Optional[str] = None, + operational_debug: Optional[str] = None, **kwargs, + ) -> Optional[List[Dict[str, Any]]]: + """Run one MATCH against *table*; ``None`` when the query cannot + execute (tokenizer unavailable / syntax) so the caller falls back. + + *fail_open* names the index for the substring-capable routes: a + corruption-class ``DatabaseError`` there detaches the derived indexes + (``_enter_fts_fail_open``) and answers from canonical rows — a live + search never performs the unbounded rebuild. Non-FTS corruption, or + any ``DatabaseError`` without *fail_open*, propagates.""" + sql, params = self._fts_match_sql(table, match_query, order_by_sql, **kwargs) + try: + return [dict(row) for row in self._read_all(sql, params)] + except sqlite3.OperationalError: + if operational_debug: + logger.debug(operational_debug, exc_info=True) + return None + except sqlite3.DatabaseError as exc: + if fail_open is None or not self._enter_fts_fail_open(exc): + raise + logger.warning( + "%s FTS search hit a corruption error (%s); detached FTS and falling back to canonical LIKE.", + fail_open, exc, + ) + return None + + def _like_rows(self, where: List[str], params: list, *, order_by: str, limit_sql: str) -> List[Dict[str, Any]]: + """Canonical-table LIKE scan; ``params[0]`` is the snippet anchor term.""" + sql = f""" + SELECT m.id, m.session_id, m.role, + {_LIKE_SNIPPET_SQL}, + {_SEARCH_SELECT_TAIL} + FROM messages m + JOIN sessions s ON s.id = m.session_id + WHERE {' AND '.join(where)} + {order_by} + {limit_sql} + """ + return [dict(row) for row in self._read_all(sql, params)] + + @staticmethod + def _compile_like_boolean_query(query: str) -> Tuple[str, List[Any], Optional[str]]: + """Compile the supported FTS boolean subset into LIKE predicates: + terms within an OR group are ANDed (FTS5's implicit conjunction) and + ``NOT`` negates the following term rather than being discarded.""" + groups: List[List[Tuple[str, bool]]] = [[]] + negate_next = False + for raw_token in _LIKE_TOKEN_RE.findall(query): + operator = raw_token.upper() + if operator == "OR": + if groups[-1]: + groups.append([]) + negate_next = False + continue + if operator in {"AND", "NEAR"}: + continue + if operator == "NOT": + negate_next = True + continue + term = raw_token.strip('"').strip("*").strip() + if term: + groups[-1].append((term, negate_next)) + negate_next = False + + compiled_groups: List[str] = [] + params: List[Any] = [] + snippet_term: Optional[str] = None + for group in groups: + if not group or not any(not negated for _, negated in group): + continue + clauses: List[str] = [] + for term, negated in group: + clauses.append(f"NOT {_LIKE_COALESCED_COLUMN_SQL}" if negated else _LIKE_COALESCED_COLUMN_SQL) + params.extend(_like_params(term)) + if snippet_term is None and not negated: + snippet_term = term + compiled_groups.append(f"({' AND '.join(clauses)})") + return " OR ".join(compiled_groups), params, snippet_term + + def _search_messages_like_fallback( + self, query: str, *, limit: int, offset: int, sort: Optional[str], **filters + ) -> List[Dict[str, Any]]: + """Search canonical messages while derived FTS state is stale.""" + predicate, params, snippet_term = self._compile_like_boolean_query(query) + if not predicate or snippet_term is None: + return [] + where = [f"({predicate})"] + _search_filter_clauses(where, params, **filters) + order = "ASC" if isinstance(sort, str) and sort.strip().lower() == "oldest" else "DESC" + return self._like_rows( + where, [snippet_term, *params, limit, offset], + order_by=f"ORDER BY m.timestamp {order}, m.id {order}", limit_sql="LIMIT ? OFFSET ?", + ) + + def _refresh_fts_stale_state(self) -> None: + """Observe fail-open initiated by another process sharing state.db.""" + if self._fts_stale or not self._fts_enabled: + return + try: + stale = self._read_one("SELECT 1 FROM state_meta WHERE key = ? LIMIT 1", (FTS_STALE_KEY,)) + except sqlite3.Error: + return + if stale is not None: + self._fts_stale = True + self._fts_enabled = False + self._trigram_available = False + self._fts_cjk_available = False + + def _finalize_search_matches( + self, matches: List[Dict[str, Any]], result_fields: Optional[Collection[str]] = None + ) -> List[Dict[str, Any]]: + """Attach neighboring messages (1 before + after, only when the + projection consumes ``context``) and trim full content. Each context + query takes its own read transaction, never a lock across N queries.""" + if result_fields is None or "context" in result_fields: + for match in matches: + try: + with self._read_ctx() as conn: + rows = conn.execute(_CONTEXT_WINDOW_SQL, (match["id"], match["id"])).fetchall() + match["context"] = [ + {"role": row["role"], "content": _flatten_text(self._decode_content(row["content"]))[:200]} + for row in rows + ] + except Exception: + match["context"] = [] + # No route selects full content; the pop guards any future one that does. for match in matches: match.pop("content", None) - if result_fields is not None: - matches = [ - {field: match[field] for field in result_fields if field in match} - for match in matches - ] - + matches = [{field: match[field] for field in result_fields if field in match} for match in matches] return matches + # ── search_messages ──────────────────────────────────────────────────── + + def search_messages( + self, query: str, source_filter: List[str] = None, exclude_sources: List[str] = None, + role_filter: List[str] = None, limit: int = 20, offset: int = 0, sort: str = None, + include_inactive: bool = False, fields: Optional[Collection[str]] = None, + ) -> List[Dict[str, Any]]: + """Instrumented wrapper around :meth:`_search_messages_impl`: logs one + line per slow search with the routing path taken so latency stays + attributable per query shape. Threshold HERMES_SEARCH_SLOW_MS + (default 1000; 0 logs every call).""" + started = time.time() + rows = None + try: + rows = self._search_messages_impl( + query, source_filter=source_filter, exclude_sources=exclude_sources, role_filter=role_filter, + limit=limit, offset=offset, sort=sort, include_inactive=include_inactive, fields=fields, + ) + return rows + finally: + try: + threshold = float(os.getenv("HERMES_SEARCH_SLOW_MS", "1000")) + except (TypeError, ValueError): + threshold = 1000.0 + elapsed_ms = (time.time() - started) * 1000.0 + if elapsed_ms >= threshold: + logger.info( + "slow session search: path=%s elapsed=%.0fms rows=%s query=%r", + self._describe_search_path(query), elapsed_ms, + len(rows) if rows is not None else "err", query[:200], + ) + def _search_messages_impl( - self, - query: str, - source_filter: List[str] = None, - exclude_sources: List[str] = None, - role_filter: List[str] = None, - limit: int = 20, - offset: int = 0, - sort: str = None, - include_inactive: bool = False, - fields: Optional[Collection[str]] = None, + self, query: str, source_filter: List[str] = None, exclude_sources: List[str] = None, + role_filter: List[str] = None, limit: int = 20, offset: int = 0, sort: str = None, + include_inactive: bool = False, fields: Optional[Collection[str]] = None, ) -> List[Dict[str, Any]]: """FTS5 search across session messages (keywords, ``"phrases"``, AND/OR/NOT, ``prefix*``). @@ -1425,13 +1154,10 @@ class SessionSearchMixin: Rewound rows (``active=0, compacted=0``) are excluded by default; compaction-archived rows (``compacted=1``) ARE included so the pre-compaction transcript stays discoverable. ``include_inactive`` - searches every row. - """ + searches every row.""" result_fields = self._search_message_fields(fields) - if not query or not query.strip(): return [] - query = self._sanitize_fts5_query(query) if not query: return [] @@ -1442,195 +1168,94 @@ class SessionSearchMixin: ) self._refresh_fts_stale_state() if self._fts_stale: - matches = self._search_messages_like_fallback( - query, limit=limit, offset=offset, sort=sort, **filters - ) + matches = self._search_messages_like_fallback(query, limit=limit, offset=offset, sort=sort, **filters) return self._finalize_search_matches(matches, result_fields=result_fields) if not self._fts_enabled: return [] - # Normalise sort; anything unknown falls back to rank-only so callers - # can pass through user input. - if isinstance(sort, str): - sort_norm = sort.strip().lower() - if sort_norm not in ("newest", "oldest"): - sort_norm = None - else: - sort_norm = None - - if sort_norm == "newest": - order_by_sql = "ORDER BY m.timestamp DESC, rank" - elif sort_norm == "oldest": - order_by_sql = "ORDER BY m.timestamp ASC, rank" - else: - order_by_sql = "ORDER BY rank" - - # CJK queries bypass the unicode61 table, whose tokenizer splits CJK - # into single characters ("大别山项目" -> "大 AND 别 AND ...": false - # positives, missed phrases). 3+ CJK chars -> trigram; shorter -> - # LIKE (trigram needs 9 UTF-8 bytes = 3 CJK chars). - matches: List[Dict[str, Any]] = [] + order_by_sql = _FTS_ORDER_BY.get(sort.strip().lower() if isinstance(sort, str) else None, "ORDER BY rank") + route = dict(order_by_sql=order_by_sql, limit=limit, offset=offset, **filters) + # Tool rows are excluded from the trigram/cjk indexes (see FTS_TRIGRAM_SQL). + wants_tool_rows = bool(role_filter) and "tool" in role_filter is_cjk = self._contains_cjk(query) if is_cjk: - raw_query = query.strip('"').strip() - _trigram_succeeded = False - # Tool rows are excluded from the trigram/cjk indexes (see - # FTS_TRIGRAM_SQL), so a role='tool' CJK query must use LIKE. - _wants_tool_rows = bool(role_filter) and "tool" in role_filter - - # CJK-bigram route: serves every CJK shape the legacy code split - # between trigram and LIKE full scans, except role='tool' queries - # and LONE 1-char CJK runs (the index stores bigrams for runs >=2, - # so a single-char term only matches isolated chars — LIKE is broader). - if ( - self._fts_cjk_available - and not _wants_tool_rows - and not self._has_lone_cjk_run(raw_query) - ): - cjk_sql, cjk_params = self._fts_match_sql( - "messages_fts_cjk", _quote_fts_tokens(raw_query), order_by_sql, - limit=limit, offset=offset, **filters, - ) - try: - matches = [dict(row) for row in self._read_all(cjk_sql, cjk_params)] - _trigram_succeeded = True - except sqlite3.OperationalError: - # Tokenizer missing / query syntax — trigram + LIKE still answer. - logger.debug( - "messages_fts_cjk query failed; falling back to " - "trigram/LIKE", exc_info=True, - ) - except sqlite3.DatabaseError as exc: - # A live search never performs the unbounded full rebuild: - # detach the derived indexes and answer from canonical rows. - # Non-FTS corruption is not safe to reinterpret here. - if not self._enter_fts_fail_open(exc): - raise - logger.warning( - "CJK-bigram FTS search hit a corruption error (%s); " - "detached FTS and falling back to canonical LIKE.", - exc, - ) - - # Per-token CJK length check: trigram needs >=3 CJK chars per - # token. "广西 OR 桂林 OR 漓江" has 6 CJK chars total but 2 per - # token — trigram returns 0, so such queries take LIKE. - if ( - not _trigram_succeeded - and self._count_cjk(raw_query) >= 3 - and not self._has_short_cjk_token(raw_query) - and self._trigram_available - and not _wants_tool_rows - ): - tri_sql, tri_params = self._fts_match_sql( - "messages_fts_trigram", _quote_fts_tokens(raw_query), order_by_sql, - limit=limit, offset=offset, **filters, - ) - try: - matches = [dict(row) for row in self._read_all(tri_sql, tri_params)] - _trigram_succeeded = True - except sqlite3.OperationalError: - # Trigram query failed at runtime — fall through to LIKE. - pass - except sqlite3.DatabaseError as exc: - # Same bounded recovery as the CJK/main paths; a non-FTS - # storage error stays fatal rather than hidden as a miss. - if not self._enter_fts_fail_open(exc): - raise - logger.warning( - "Trigram FTS search hit a corruption error (%s); " - "detached FTS and falling back to canonical LIKE.", - exc, - ) - if not _trigram_succeeded: - # LIKE substring fallback; one clause per non-operator token so - # "广西 OR 桂林 OR 漓江" matches each term independently. - non_op_tokens = [ - t for t in raw_query.split() if t.upper() not in _FTS_OPERATORS - ] or [raw_query] - like_params: list = [] - for tok in non_op_tokens: - like_params += [f"%{_escape_like(tok)}%"] * 3 - like_where = [ - f"({' OR '.join([_LIKE_ANY_COLUMN_SQL] * len(non_op_tokens))})" - ] - _search_filter_clauses(like_where, like_params, **filters) - # instr() for snippet uses first search token - matches = self._like_rows( - like_where, [non_op_tokens[0], *like_params, limit, offset], - order_by="ORDER BY m.timestamp DESC", limit_sql="LIMIT ? OFFSET ?", - ) + matches = self._search_cjk(query, wants_tool_rows, route) else: - sql, params = self._fts_match_sql( - "messages_fts", query, order_by_sql, limit=limit, offset=offset, **filters - ) + sql, params = self._fts_match_sql("messages_fts", query, **route) try: matches = [dict(row) for row in self._read_all(sql, params)] except sqlite3.OperationalError: - # FTS5 query syntax error despite sanitization — return empty - return [] + return [] # FTS5 syntax error despite sanitization except sqlite3.DatabaseError as exc: - # Corruption parent class (OperationalError is caught above). - # Live search must stay bounded: detach the derived indexes and - # answer from canonical rows; repair paths own the rebuild. + # Corruption parent class: detach the derived indexes and answer + # from canonical rows; repair paths own the rebuild. if not self._enter_fts_fail_open(exc): raise - matches = self._search_messages_like_fallback( - query, limit=limit, offset=offset, sort=sort, **filters - ) + matches = self._search_messages_like_fallback(query, limit=limit, offset=offset, sort=sort, **filters) # Deferred-rebuild supplement: while the backfill is pending the FTS # indexes miss the (progress, high_water] gap; top up with a bounded - # LIKE scan over that range so old messages never silently vanish - # mid-rebuild. The cost decays to zero as the backfill advances. - rebuild_status = self.fts_rebuild_status() - if rebuild_status is not None and len(matches) < limit: + # LIKE scan so old messages never vanish mid-rebuild. Cost decays to + # zero as the backfill advances. + if self.fts_rebuild_status() is not None and len(matches) < limit: try: - gap_matches = self._search_unindexed_gap( - query, limit - len(matches), **filters - ) + gap_matches = self._search_unindexed_gap(query, limit - len(matches), **filters) seen_ids = {m["id"] for m in matches} matches.extend(m for m in gap_matches if m["id"] not in seen_ids) except sqlite3.OperationalError as exc: logger.debug("Unindexed-gap supplement skipped: %s", exc) - # unicode61 puts no boundary between Latin and adjacent CJK - # ("修改youer服务端" is one token, so MATCH "youer" misses). On a - # zero-result Latin miss retry the substring-capable indexes: cjk - # first (splits Latin off CJK: exact ranked match), then trigram - # (needs >=3-char tokens). Gated on a miss so successful searches keep - # their ranking; trade-off: "cat" may then match "concatenate". - # Skipped for role='tool' (both indexes exclude tool rows). - if ( - not matches - and not is_cjk - and not (bool(role_filter) and "tool" in role_filter) - ): - _fb_query = query.strip('"').strip() - fb_kwargs = dict(order_by_sql=order_by_sql, limit=limit, offset=offset, **filters) + # unicode61 puts no boundary between Latin and adjacent CJK ("修改youer服务端" + # is one token, so MATCH "youer" misses). On a zero-result Latin miss retry + # the substring-capable indexes: cjk first (exact ranked match), then + # trigram (>=3-char tokens). Gated on a miss so hits keep their ranking + # ("cat" may then match "concatenate"). Skipped for role='tool' (both + # indexes exclude tool rows). + if not matches and not is_cjk and not wants_tool_rows: + fb_query = _quote_fts_tokens(query.strip('"').strip()) if self._fts_cjk_available: - matches = self._run_trigram_search( - _fb_query, table="messages_fts_cjk", **fb_kwargs - ) or matches - if ( - not matches - and self._trigram_available - and self._trigram_eligible_tokens(query) - ): - matches = self._run_trigram_search(_fb_query, **fb_kwargs) or matches - + matches = self._match_rows("messages_fts_cjk", fb_query, **route) or matches + if not matches and self._trigram_available and self._trigram_eligible_tokens(query): + matches = self._match_rows("messages_fts_trigram", fb_query, **route) or matches return self._finalize_search_matches(matches, result_fields=result_fields) - def _search_unindexed_gap( - self, - fts_query: str, - limit: int, - *, - include_inactive: bool = False, - source_filter: Optional[List[str]] = None, - exclude_sources: Optional[List[str]] = None, - role_filter: Optional[List[str]] = None, - ) -> List[Dict[str, Any]]: + def _search_cjk(self, query: str, wants_tool_rows: bool, route: Dict[str, Any]) -> List[Dict[str, Any]]: + """CJK routing: the unicode61 table splits CJK into single characters + ("大别山项目" -> "大 AND 别 AND ...": false positives, missed phrases). + + cjk-bigram serves every shape the legacy code split between trigram + and LIKE, except role='tool' queries and LONE 1-char CJK runs (the + index stores bigrams for runs >=2, so a single-char term only matches + isolated chars — LIKE is broader). Then trigram (>=3 CJK chars per + token), then a LIKE substring scan with one clause per non-operator + token so "广西 OR 桂林 OR 漓江" matches each term independently.""" + raw_query = query.strip('"').strip() + match_query = _quote_fts_tokens(raw_query) + if self._fts_cjk_available and not wants_tool_rows and not self._has_lone_cjk_run(raw_query): + matches = self._match_rows( + "messages_fts_cjk", match_query, fail_open="CJK-bigram", + operational_debug="messages_fts_cjk query failed; falling back to trigram/LIKE", **route, + ) + if matches is not None: + return matches + if self._trigram_route_ok(raw_query) and not wants_tool_rows: + matches = self._match_rows("messages_fts_trigram", match_query, fail_open="Trigram", **route) + if matches is not None: + return matches + non_op_tokens = [t for t in raw_query.split() if t.upper() not in _FTS_OPERATORS] or [raw_query] + like_params: list = [] + for tok in non_op_tokens: + like_params += _like_params(tok) + like_where = [f"({' OR '.join([_LIKE_ANY_COLUMN_SQL] * len(non_op_tokens))})"] + filters = {k: route[k] for k in ("include_inactive", "source_filter", "exclude_sources", "role_filter")} + _search_filter_clauses(like_where, like_params, **filters) + # instr() for the snippet uses the first search token. + return self._like_rows( + like_where, [non_op_tokens[0], *like_params, route["limit"], route["offset"]], + order_by="ORDER BY m.timestamp DESC", limit_sql="LIMIT ? OFFSET ?", + ) + + def _search_unindexed_gap(self, fts_query: str, limit: int, **filters) -> List[Dict[str, Any]]: """LIKE-scan ids in (fts_rebuild_progress, fts_rebuild_high_water] — the rows the deferred rebuild hasn't indexed yet. The FTS query is degraded to AND-joined substring terms (quoted phrases kept whole): @@ -1638,39 +1263,25 @@ class SessionSearchMixin: status = self.fts_rebuild_status() if status is None or limit <= 0: return [] - progress, high_water = status["indexed"], status["total"] - - terms: List[str] = [] - for raw_tok in re.findall(r'"[^"]+"|\S+', fts_query): - tok = raw_tok.strip('"').strip("*").strip() - if tok and tok.upper() not in {"AND", "OR", "NOT", "NEAR"}: - terms.append(tok) + terms = [ + tok for tok in (t.strip('"').strip("*").strip() for t in _LIKE_TOKEN_RE.findall(fts_query)) + if tok and tok.upper() not in _LIKE_SKIP_TOKENS + ] if not terms: return [] - where = ["m.id > ? AND m.id <= ?"] - params: list = [progress, high_water] + params: list = [status["indexed"], status["total"]] for term in terms: where.append(_LIKE_ANY_COLUMN_SQL) - params += [f"%{_escape_like(term)}%"] * 3 - _search_filter_clauses( - where, params, include_inactive=include_inactive, - source_filter=source_filter, exclude_sources=exclude_sources, - role_filter=role_filter, - ) + params += _like_params(term) + _search_filter_clauses(where, params, **filters) return self._like_rows( - where, [terms[0], *params, limit], - order_by="ORDER BY m.timestamp DESC", limit_sql="LIMIT ?", + where, [terms[0], *params, limit], order_by="ORDER BY m.timestamp DESC", limit_sql="LIMIT ?", ) def search_sessions_by_id( - self, - query: str, - limit: int = 20, - include_archived: bool = True, - source: str = None, - sources: List[str] = None, - exclude_sources: List[str] = None, + self, query: str, limit: int = 20, include_archived: bool = True, source: str = None, + sources: List[str] = None, exclude_sources: List[str] = None, ) -> List[Dict[str, Any]]: """Search surfaced sessions by exact/prefix/substring session id (paste an id from logs and jump to it). Also matches ``_lineage_root_id`` so @@ -1678,19 +1289,12 @@ class SessionSearchMixin: needle = (query or "").strip().lower() if not needle or limit <= 0: return [] - # list_sessions_rich pushes the id LIKE filter (own id + forward - # compression chain) into SQL; over-fetch so the in-Python - # exact/prefix/substring ranking has candidates, then truncate. + # compression chain) into SQL; over-fetch so the in-Python ranking has + # candidates, then truncate. candidates = self.list_sessions_rich( - source=source, - sources=sources, - exclude_sources=exclude_sources, - limit=max(limit * 4, limit), - offset=0, - include_archived=include_archived, - order_by_last_active=True, - id_query=needle, + source=source, sources=sources, exclude_sources=exclude_sources, limit=max(limit * 4, limit), + offset=0, include_archived=include_archived, order_by_last_active=True, id_query=needle, ) def score(row: Dict[str, Any]) -> int: @@ -1702,58 +1306,47 @@ class SessionSearchMixin: return 1 return 2 - ranked = sorted( - enumerate(candidates), - key=lambda item: (score(item[1]), item[0]), - ) + ranked = sorted(enumerate(candidates), key=lambda item: (score(item[1]), item[0])) return [row for _, row in ranked[:limit]] + # ── FTS maintenance commands ─────────────────────────────────────────── + def _fts_table_exists(self, name: str) -> bool: - """True if an FTS5 virtual table is queryable in this DB.""" + """True if an FTS5 virtual table is queryable in this DB ("no such + table" and "vtable constructor failed" — missing tokenizer / + mid-teardown — both count as not queryable).""" try: self._conn.execute(f"SELECT 1 FROM {name} LIMIT 0") return True except sqlite3.DatabaseError: - # "no such table", or "vtable constructor failed" (missing - # tokenizer / mid-teardown) — either way not queryable. return False def optimize_fts(self) -> int: """Merge fragmented FTS5 segments into one per index (``'optimize'``). - Pure maintenance: changes neither results nor ``snippet()`` output, only layout and speed; complementary to VACUUM, which then returns - the freed pages. Skips absent tables, so it is safe unconditionally. - Returns the number of indexes optimized. - """ + the freed pages. Skips absent tables. Returns the number optimized.""" optimized = 0 with self._lock: for tbl in self._FTS_TABLES: if not self._fts_table_exists(tbl): continue try: - self._conn.execute( - f"INSERT INTO {tbl}({tbl}) VALUES('optimize')" - ) + self._conn.execute(f"INSERT INTO {tbl}({tbl}) VALUES('optimize')") optimized += 1 except sqlite3.OperationalError as exc: - logger.warning( - "FTS optimize failed for %s: %s", tbl, exc - ) + logger.warning("FTS optimize failed for %s: %s", tbl, exc) return optimized def rebuild_fts(self) -> int: """Rebuild FTS5 indexes from ``messages`` (``'rebuild'``) — the documented recovery for a corrupt index that rejects writes while - reads succeed. - - A full structural rebuild must never run concurrently in two processes - sharing one state.db (that interleaving corrupted production DBs), so - this admits through ``fts_rebuild_admission`` and FAILS CLOSED, - returning 0 on deferral; callers treat 0 as "no progress" and fall - back to the stale-FTS breadcrumb path. Skips absent tables. Returns - the number of indexes rebuilt. - """ + reads succeed. A full structural rebuild must never run concurrently + in two processes sharing one state.db (that interleaving corrupted + production DBs), so this admits through ``fts_rebuild_admission`` and + FAILS CLOSED, returning 0 on deferral (callers treat 0 as "no + progress" and fall back to the stale-FTS breadcrumb path). Skips + absent tables; returns the number of indexes rebuilt.""" rebuilt = 0 with fts_rebuild_admission(self.db_path) as admitted: if not admitted: @@ -1767,41 +1360,28 @@ class SessionSearchMixin: if not self._fts_table_exists(tbl): continue try: - self._conn.execute( - f"INSERT INTO {tbl}({tbl}) VALUES('rebuild')" - ) + self._conn.execute(f"INSERT INTO {tbl}({tbl}) VALUES('rebuild')") self._conn.commit() rebuilt += 1 except sqlite3.OperationalError as exc: self._conn.rollback() - logger.warning( - "FTS rebuild failed for %s: %s", tbl, exc - ) + logger.warning("FTS rebuild failed for %s: %s", tbl, exc) return rebuilt - def _merge_fts_incrementally( - self, *, max_pages: int, max_commands: Optional[int] = None - ) -> int: + def _merge_fts_incrementally(self, *, max_pages: int, max_commands: Optional[int] = None) -> int: """Run bounded FTS5 ``'merge'`` commands against each present index. - A positive merge rank stops after ~that many output pages, so each - command holds the write lock for milliseconds regardless of index - size — unlike ``'optimize'`` (9-18 s per index on a 10 GB DB, enough - to exhaust a competing writer's lock-retry patience). - - - ``usermerge`` is lowered to its minimum of 2 (persisted in the - ``%_config`` shadow table, once per instance) so a positive merge - acts on ANY level with >= 2 segments; at the default 4 a fragmented - index cannot converge. - - Up to *max_commands* per index, stopping on the documented - no-progress signal: ``total_changes`` delta < 2 (the command's own - INSERT is 1 change). - - Each command is its own implicit transaction (``isolation_level=None``), - so competing processes interleave mid-pass. Missing tables are valid - variants (optimize_fts_storage drops + backfills them live) and are - skipped; other SQLite errors propagate. Returns commands executed. - """ + command holds the write lock for milliseconds regardless of index size + (``'optimize'`` takes 9-18 s per index on a 10 GB DB, exhausting a + competing writer's lock-retry patience). ``usermerge`` is lowered to + its minimum of 2 (persisted in ``%_config``, once per instance) so a + positive merge acts on ANY level with >= 2 segments; at the default 4 a + fragmented index cannot converge. Up to *max_commands* per index, + stopping on the no-progress signal ``total_changes`` delta < 2 (the + command's own INSERT is 1 change). Each command is its own implicit + transaction, so competing processes interleave mid-pass. Missing tables + are valid variants (optimize_fts_storage drops + backfills them live) + and are skipped; other SQLite errors propagate. Returns commands executed.""" if isinstance(max_pages, bool) or not isinstance(max_pages, int): raise TypeError("max_pages must be an integer") if max_pages <= 0: @@ -1818,19 +1398,11 @@ class SessionSearchMixin: for tbl in self._FTS_TABLES: if not self._fts_table_exists(tbl): continue - # One-time (per instance) usermerge floor; metadata-only write, - # persisted so future connections inherit it. if not self._fts_usermerge_floor_applied: - self._conn.execute( - f"INSERT INTO {tbl}({tbl}, rank) " - "VALUES('usermerge', 2)" - ) + self._conn.execute(f"INSERT INTO {tbl}({tbl}, rank) VALUES('usermerge', 2)") for _ in range(max_commands): before = self._conn.total_changes - self._conn.execute( - f"INSERT INTO {tbl}({tbl}, rank) VALUES('merge', ?)", - (max_pages,), - ) + self._conn.execute(f"INSERT INTO {tbl}({tbl}, rank) VALUES('merge', ?)", (max_pages,)) executed += 1 if self._conn.total_changes - before < 2: break diff --git a/hermes_state_telegram.py b/hermes_state_telegram.py index 2c8dbf8501..5419b0efe6 100644 --- a/hermes_state_telegram.py +++ b/hermes_state_telegram.py @@ -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) diff --git a/hermes_state_titles.py b/hermes_state_titles.py index 3d6dbea0f5..9404fa74ad 100644 --- a/hermes_state_titles.py +++ b/hermes_state_titles.py @@ -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}" diff --git a/hermes_state_usage.py b/hermes_state_usage.py index 9abae52aa7..f84455053e 100644 --- a/hermes_state_usage.py +++ b/hermes_state_usage.py @@ -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)} diff --git a/hermes_state_wal.py b/hermes_state_wal.py index a6a1ce9171..006135f85b 100644 --- a/hermes_state_wal.py +++ b/hermes_state_wal.py @@ -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.``; ``_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.``.""" + 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)