Skip to content

The agent that grows with you

fix(state): narrow FTS UPDATE triggers with AFTER UPDATE OF + migration

Jasmine Naderidab7c8860400
diff --git a/hermes_state.py b/hermes_state.py
index 907ca56b3dc..02de79cc44f 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -1504,7 +1504,8 @@ BEGIN
VALUES ('delete', old.id, old.content, old.tool_name, old.tool_calls);
END;
-CREATE TRIGGER IF NOT EXISTS messages_fts_cjk_update AFTER UPDATE ON messages
+CREATE TRIGGER IF NOT EXISTS messages_fts_cjk_update
+AFTER UPDATE OF content, tool_name, tool_calls, role ON messages
WHEN (old.content IS NOT new.content
OR old.tool_name IS NOT new.tool_name
OR old.tool_calls IS NOT new.tool_calls
diff --git a/hermes_state_common.py b/hermes_state_common.py
index 73498465718..3228943fb63 100644
--- a/hermes_state_common.py
+++ b/hermes_state_common.py
@@ -419,7 +419,11 @@ BEGIN
VALUES ('delete', old.id, old.content, old.tool_name, old.tool_calls);
END;
-CREATE TRIGGER IF NOT EXISTS messages_fts_update AFTER UPDATE ON messages
+-- UPDATE OF skips the trigger entirely for non-content column writes
+-- (status/compacted/observed/etc.), which is stronger than the WHEN gate
+-- alone and avoids FTS I/O saturation on large state.db (#68858 / #73639).
+CREATE TRIGGER IF NOT EXISTS messages_fts_update
+AFTER UPDATE OF content, tool_name, tool_calls ON messages
WHEN (old.content IS NOT new.content
OR old.tool_name IS NOT new.tool_name
OR old.tool_calls IS NOT new.tool_calls)
@@ -487,7 +491,8 @@ BEGIN
VALUES ('delete', old.id, old.content, old.tool_name, old.tool_calls);
END;
-CREATE TRIGGER IF NOT EXISTS messages_fts_trigram_update AFTER UPDATE ON messages
+CREATE TRIGGER IF NOT EXISTS messages_fts_trigram_update
+AFTER UPDATE OF content, tool_name, tool_calls, role ON messages
WHEN (old.content IS NOT new.content
OR old.tool_name IS NOT new.tool_name
OR old.tool_calls IS NOT new.tool_calls
@@ -548,7 +553,8 @@ CREATE TRIGGER IF NOT EXISTS messages_fts_delete AFTER DELETE ON messages BEGIN
DELETE FROM messages_fts WHERE rowid = old.id;
END;
-CREATE TRIGGER IF NOT EXISTS messages_fts_update AFTER UPDATE ON messages BEGIN
+CREATE TRIGGER IF NOT EXISTS messages_fts_update
+AFTER UPDATE OF content, tool_name, tool_calls ON messages BEGIN
DELETE FROM messages_fts WHERE rowid = old.id;
INSERT INTO messages_fts(rowid, content) VALUES (
new.id,
@@ -575,7 +581,8 @@ CREATE TRIGGER IF NOT EXISTS messages_fts_trigram_delete AFTER DELETE ON message
DELETE FROM messages_fts_trigram WHERE rowid = old.id;
END;
-CREATE TRIGGER IF NOT EXISTS messages_fts_trigram_update AFTER UPDATE ON messages BEGIN
+CREATE TRIGGER IF NOT EXISTS messages_fts_trigram_update
+AFTER UPDATE OF content, tool_name, tool_calls ON messages BEGIN
DELETE FROM messages_fts_trigram WHERE rowid = old.id;
INSERT INTO messages_fts_trigram(rowid, content) VALUES (
new.id,
diff --git a/hermes_state_schema.py b/hermes_state_schema.py
index a93f0377705..f9d25208b9a 100644
--- a/hermes_state_schema.py
+++ b/hermes_state_schema.py
@@ -56,6 +56,91 @@ class SessionSchemaMixin:
).fetchone()
return int(row[0] if not isinstance(row, sqlite3.Row) else row[0])
+
+ @staticmethod
+ def _fts_update_trigger_needs_narrowing(sql: Optional[str]) -> bool:
+ """True when trigger SQL is missing AFTER UPDATE OF (still broad)."""
+ 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
+
+ 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`` will not replace an existing broad
+ trigger, so installs that already created ``AFTER UPDATE ON messages``
+ would keep firing on every messages row touch (status/compaction
+ writes included). Inspect ``sqlite_master``, drop any still-broad
+ UPDATE triggers, and re-apply the current DDL constants.
+
+ No FTS rebuild: content correctness was already gated by WHEN clauses
+ on modern installs; OF only skips unnecessary trigger evaluation.
+
+ Returns the number of triggers dropped (0 when already converged).
+ """
+ import re as _re
+
+ update_names = (
+ "messages_fts_update",
+ "messages_fts_trigram_update",
+ "messages_fts_cjk_update",
+ )
+ rows = cursor.execute(
+ "SELECT name, sql FROM sqlite_master "
+ "WHERE type = 'trigger' AND name IN (?, ?, ?)",
+ update_names,
+ ).fetchall()
+ to_drop = []
+ for row in rows:
+ name = row[0] if not isinstance(row, sqlite3.Row) else row["name"]
+ sql = row[1] if not isinstance(row, sqlite3.Row) else row["sql"]
+ if self._fts_update_trigger_needs_narrowing(sql):
+ to_drop.append(name)
+ if not to_drop:
+ return 0
+
+ for name in to_drop:
+ # Trigger names are from our fixed allowlist, not user input.
+ if not _re.fullmatch(r"[A-Za-z0-9_]+", name):
+ continue
+ 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.
+ if self._db_has_legacy_inline_fts(cursor):
+ self._ensure_fts_schema(cursor, "messages_fts", LEGACY_FTS_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
+ )
+ # CJK triggers live on the host SessionDB; only recreate if present.
+ if hasattr(self, "_ensure_fts_cjk_schema"):
+ try:
+ self._ensure_fts_cjk_schema(cursor)
+ except Exception:
+ logger.debug(
+ "CJK FTS re-ensure after UPDATE OF migration skipped",
+ exc_info=True,
+ )
+
+ logger.info(
+ "Migrated %d broad FTS UPDATE trigger(s) to AFTER UPDATE OF "
+ "(no rebuild required)",
+ len(to_drop),
+ )
+ return len(to_drop)
+
+
@staticmethod
def _rebuild_fts_indexes(
cursor: sqlite3.Cursor,
@@ -855,6 +940,11 @@ class SessionSchemaMixin:
# the surfaces above 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.
+ if getattr(self, "_fts_enabled", False):
+ self._migrate_broad_fts_update_triggers(cursor)
+
self._conn.commit()
def _backfill_gateway_metadata_from_sessions_json(
diff --git a/tests/test_fts_update_of_narrowing.py b/tests/test_fts_update_of_narrowing.py
new file mode 100644
index 00000000000..48c3e2e4d53
--- /dev/null
+++ b/tests/test_fts_update_of_narrowing.py
@@ -0,0 +1,96 @@
+"""FTS UPDATE OF narrowing + migration (#73639 retargeted onto split SessionDB)."""
+
+from __future__ import annotations
+
+import sqlite3
+import tempfile
+from pathlib import Path
+
+import pytest
+
+from hermes_state import SessionDB
+from hermes_state_schema import SessionSchemaMixin
+
+
+def _trigger_sql(conn: sqlite3.Connection, name: str) -> str | None:
+ row = conn.execute(
+ "SELECT sql FROM sqlite_master WHERE type='trigger' AND name=?",
+ (name,),
+ ).fetchone()
+ return row[0] if row else None
+
+
+def test_fresh_db_installs_update_of_triggers(tmp_path: Path):
+ db = SessionDB(db_path=tmp_path / "state.db")
+ try:
+ sql = _trigger_sql(db._conn, "messages_fts_update")
+ assert sql is not None
+ compact = " ".join(sql.split()).upper()
+ assert "AFTER UPDATE OF " in compact
+ assert "CONTENT" in compact
+ assert "TOOL_NAME" in compact
+ assert "TOOL_CALLS" in compact
+
+ tri = _trigger_sql(db._conn, "messages_fts_trigram_update")
+ if tri: # trigram may be unavailable on some builds
+ tcompact = " ".join(tri.split()).upper()
+ assert "AFTER UPDATE OF " in tcompact
+ finally:
+ db.close()
+
+
+def test_migrate_replaces_broad_update_trigger(tmp_path: Path):
+ path = tmp_path / "state.db"
+ db = SessionDB(db_path=path)
+ try:
+ # Force a broad trigger the way older installs had it.
+ db._conn.execute("DROP TRIGGER IF EXISTS messages_fts_update")
+ db._conn.execute(
+ """
+ CREATE TRIGGER messages_fts_update AFTER UPDATE ON messages
+ BEGIN
+ SELECT 1;
+ END
+ """
+ )
+ db._conn.commit()
+ before = _trigger_sql(db._conn, "messages_fts_update")
+ assert "AFTER UPDATE OF" not in " ".join(before.split()).upper()
+
+ dropped = db._migrate_broad_fts_update_triggers(db._conn)
+ db._conn.commit()
+ assert dropped >= 1
+
+ after = _trigger_sql(db._conn, "messages_fts_update")
+ assert after is not None
+ compact = " ".join(after.split()).upper()
+ assert "AFTER UPDATE OF " in compact
+ finally:
+ db.close()
+
+
+def test_needs_narrowing_helper():
+ assert SessionSchemaMixin._fts_update_trigger_needs_narrowing(
+ "CREATE TRIGGER t AFTER UPDATE ON messages BEGIN SELECT 1; END"
+ )
+ assert not SessionSchemaMixin._fts_update_trigger_needs_narrowing(
+ "CREATE TRIGGER t AFTER UPDATE OF content ON messages BEGIN SELECT 1; END"
+ )
+ assert not SessionSchemaMixin._fts_update_trigger_needs_narrowing(None)
+
+
+def test_status_only_update_does_not_require_content_change(tmp_path: Path):
+ """Smoke: DB opens and accepts message updates under narrowed triggers."""
+ db = SessionDB(db_path=tmp_path / "state.db")
+ try:
+ sid = "s1"
+ db.create_session(sid, source="test")
+ mid = db.append_message(sid, role="user", content="hello searchable")
+ db._conn.execute(
+ "UPDATE messages SET content = content WHERE id = ?",
+ (mid,),
+ )
+ db._conn.commit()
+ assert _trigger_sql(db._conn, "messages_fts_update")
+ finally:
+ db.close()