Skip to content
Closed
12 changes: 12 additions & 0 deletions hermes_cli/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3068,6 +3068,18 @@ def _ensure_hermes_home_managed(home: Path):
# GBs of disk on heavy users. Opt in only if you have an external
# tool that consumes the JSON files directly.
"write_json_snapshots": False,
# Secondary trigram FTS5 index over message content, used for
# substring and CJK (Chinese/Japanese/Korean) search. It stores
# its own full copy of every message plus a 3-character-gram index,
# so it is by far the largest object in state.db (3-5x the raw
# message text) and fires on every message INSERT. On heavy users
# it dominates DB size and slows writes enough to blow the
# write-lock retry budget ("database is locked"). When false, the
# index is dropped at startup and never recreated; substring/CJK
# search transparently falls back to a LIKE scan (the base
# ``messages_fts`` word index — used by recall and session search —
# is unaffected). Default true preserves current behavior.
"trigram_fts": True,
},

# Contextual first-touch onboarding hints (see agent/onboarding.py).
Expand Down
94 changes: 84 additions & 10 deletions hermes_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,15 @@ def _delete_delegate_children(conn, parent_ids: List[str]) -> List[str]:
"messages_fts_trigram_update",
)

# Subset of _FTS_TRIGGERS that feed the trigram index specifically. Dropped
# (leaving the base messages_fts triggers intact) when sessions.trigram_fts
# is disabled — see SessionDB._drop_trigram_fts.
_TRIGRAM_FTS_TRIGGERS = (
"messages_fts_trigram_insert",
"messages_fts_trigram_delete",
"messages_fts_trigram_update",
)


def _set_last_init_error(msg: Optional[str]) -> None:
"""Record (or clear) the most recent state.db init failure.
Expand Down Expand Up @@ -994,6 +1003,24 @@ def _connect_and_init():

# ── Core write helper ──

@staticmethod
def _trigram_fts_enabled() -> bool:
"""Read ``sessions.trigram_fts`` from config (default True).

Lazy import + best-effort: any config-load failure defaults to the
historical behavior (trigram enabled). Cheap enough to call once per
schema init; not on the message write hot path."""
try:
from hermes_cli.config import load_config

cfg = load_config()
sessions = cfg.get("sessions") if isinstance(cfg, dict) else None
if isinstance(sessions, dict) and "trigram_fts" in sessions:
return bool(sessions["trigram_fts"])
except Exception:
pass
return True

@staticmethod
def _is_fts5_unavailable_error(exc: sqlite3.OperationalError) -> bool:
err = str(exc).lower()
Expand Down Expand Up @@ -1058,6 +1085,35 @@ def _drop_fts_triggers(cursor: sqlite3.Cursor) -> None:
except sqlite3.OperationalError:
pass

@staticmethod
def _drop_trigram_fts(cursor: sqlite3.Cursor) -> bool:
"""Drop the trigram FTS5 index and its triggers. Returns True if the
virtual table existed and was removed (so the caller knows a VACUUM
would reclaim space). Used when ``sessions.trigram_fts`` is disabled:
the trigram index is the single largest object in state.db and fires
on every message INSERT, so a heavy user opts out to shrink the DB and
speed up writes. Substring/CJK search falls back to a LIKE scan; the
base ``messages_fts`` word index is untouched."""
for trigger in _TRIGRAM_FTS_TRIGGERS:
try:
cursor.execute(f"DROP TRIGGER IF EXISTS {trigger}")
except sqlite3.OperationalError:
pass

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Do not ignore failed trigram trigger drops

When sessions.trigram_fts is false and a transient database is locked hits one of these DROP TRIGGER statements but clears before the later DROP TABLE, this suppresses the failure and can still remove messages_fts_trigram. SQLite does not remove triggers that are defined on messages, so any surviving messages_fts_trigram_* trigger will fire on the next message insert/update and fail with no such table: main.messages_fts_trigram, breaking message persistence for that DB until the stale trigger is removed.

Useful? React with 👍 / 👎.

existed = False
try:
row = cursor.execute(
"SELECT 1 FROM sqlite_master "
"WHERE type = 'table' AND name = 'messages_fts_trigram'"
).fetchone()
existed = row is not None
cursor.execute("DROP TABLE IF EXISTS messages_fts_trigram")
except sqlite3.OperationalError:
# FTS5 module missing entirely, or the shadow tables are in a
# state we can't drop cleanly — leave it be; nothing queries it
# when the flag is off.
pass
Comment thread
exiao marked this conversation as resolved.
Resolved
return existed

@staticmethod
def _fts_trigger_count(cursor: sqlite3.Cursor) -> int:
placeholders = ",".join("?" for _ in _FTS_TRIGGERS)
Expand Down Expand Up @@ -1572,22 +1628,40 @@ def _init_schema(self):
# FTS5 setup. Run the DDL even when the virtual table exists so
# CREATE TRIGGER IF NOT EXISTS repairs trigger-only degradation from
# an earlier no-FTS5 runtime.
triggers_need_repair = self._fts_trigger_count(cursor) < len(_FTS_TRIGGERS)
trigram_wanted = self._trigram_fts_enabled()
# Expected trigger count depends on whether the trigram index is
# enabled: with it off we intentionally keep only the 3 base
# messages_fts triggers, so comparing against all 6 would falsely
# flag a repair (and rebuild base FTS) on every startup.
expected_trigger_count = (
len(_FTS_TRIGGERS) if trigram_wanted else len(_FTS_TRIGGERS) - len(_TRIGRAM_FTS_TRIGGERS)
)
triggers_need_repair = self._fts_trigger_count(cursor) < expected_trigger_count
Comment thread
exiao marked this conversation as resolved.
Resolved
Comment thread
exiao marked this conversation as resolved.
Resolved
self._fts_enabled = self._ensure_fts_schema(cursor, "messages_fts", FTS_SQL)

# Trigram FTS5 for CJK/substring search. This is optional relative
# to the main FTS table; if it cannot be created, CJK search falls
# back to LIKE.
# back to LIKE. When sessions.trigram_fts is disabled, drop it
# instead of creating it — it is the largest object in state.db and
# fires on every message INSERT. Search transparently falls back to
# LIKE (see search_messages / self._trigram_available).
if self._fts_enabled:
trigram_enabled = self._ensure_fts_schema(
cursor, "messages_fts_trigram", FTS_TRIGRAM_SQL
)
self._trigram_available = trigram_enabled
if triggers_need_repair:
self._rebuild_fts_indexes(
cursor,
include_trigram=trigram_enabled,
if trigram_wanted:
trigram_enabled = self._ensure_fts_schema(
cursor, "messages_fts_trigram", FTS_TRIGRAM_SQL
)
self._trigram_available = trigram_enabled
if triggers_need_repair:
self._rebuild_fts_indexes(
cursor,
include_trigram=trigram_enabled,
)
else:
self._drop_trigram_fts(cursor)
Comment thread
exiao marked this conversation as resolved.
Resolved
self._trigram_available = False
Comment thread
exiao marked this conversation as resolved.
Resolved
Comment thread
exiao marked this conversation as resolved.
Resolved
if triggers_need_repair:
# Base FTS only — trigram is intentionally absent.
self._rebuild_fts_indexes(cursor, include_trigram=False)

self._conn.commit()

Expand Down
53 changes: 53 additions & 0 deletions tests/test_hermes_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,59 @@ def test_is_trigram_unavailable_error(self):
assert SessionDB._is_trigram_unavailable_error(generic_err) is False
assert SessionDB._is_trigram_unavailable_error(fts5_err) is False

def test_trigram_fts_config_flag_false_drops_index(self, tmp_path, monkeypatch):
"""sessions.trigram_fts: false drops the trigram index + its triggers,
keeps base FTS + its triggers, and leaves word search working."""
db_path = tmp_path / "state.db"
# Build a DB WITH the trigram index (default flag = True).
monkeypatch.setattr(SessionDB, "_trigram_fts_enabled", staticmethod(lambda: True))
seeded = SessionDB(db_path=db_path)
try:
seeded.create_session(session_id="s1", source="cli")
seeded.append_message("s1", role="user", content="the quick brown fox")
assert seeded._trigram_available is True
assert seeded._fts_table_exists("messages_fts_trigram") is True
finally:
seeded.close()

# Reopen with the flag OFF — trigram must be dropped, base FTS intact.
monkeypatch.setattr(SessionDB, "_trigram_fts_enabled", staticmethod(lambda: False))
reopened = SessionDB(db_path=db_path)
try:
assert reopened._trigram_available is False
assert reopened._fts_table_exists("messages_fts_trigram") is False
assert reopened._fts_table_exists("messages_fts") is True
# Base triggers survive; trigram triggers are gone.
names = {
r[0]
for r in reopened._conn.execute(
"SELECT name FROM sqlite_master WHERE type='trigger' "
"AND name LIKE 'messages_fts%'"
).fetchall()
}
assert names == {
"messages_fts_insert",
"messages_fts_delete",
"messages_fts_update",
}
# Word search still works through the base index.
assert len(reopened.search_messages("quick")) == 1
# A new write does not resurrect the trigram index.
reopened.append_message("s1", role="assistant", content="lazy dog sleeps")
assert reopened._fts_table_exists("messages_fts_trigram") is False
assert len(reopened.search_messages("lazy")) == 1
finally:
reopened.close()

# Reopen again with the flag back ON — trigram is recreated.
monkeypatch.setattr(SessionDB, "_trigram_fts_enabled", staticmethod(lambda: True))
restored = SessionDB(db_path=db_path)
try:
assert restored._trigram_available is True
assert restored._fts_table_exists("messages_fts_trigram") is True
finally:
restored.close()

def test_db_initializes_without_trigram_tokenizer(self, tmp_path, monkeypatch):
"""SessionDB must not crash when FTS5 exists but trigram tokenizer is missing."""
real_connect = sqlite3.connect
Expand Down
Loading