The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(state): contract the aligned projection; drop the removed boundary
Kelly Griffindb8b87991bc1
diff --git a/tests/hermes_state/test_fts_projection_integrity.py b/tests/hermes_state/test_fts_projection_integrity.pynew file mode 100644index 00000000000..ff583b14265--- /dev/null+++ b/tests/hermes_state/test_fts_projection_integrity.py@@ -0,0 +1,144 @@+"""Regression for the ``messages_fts`` external-content drift (issue #114169).++The base word index used to read its external content from the raw ``messages``+table while the triggers indexed only a bounded prefix of every long tool row+and the boundary itself moved with a ``state_meta`` high-water marker. FTS5's+strict ``rank=1`` integrity check re-reads the content source and compares it+with the stored token stream, so that construction could not stay consistent: a+long tool row was enough to make the check report ``fts5: checksum mismatch``,+and the delete/update commands sent full content for a truncated row, leaving+index tokens behind.++These are behaviour contracts on the projection, not on its shape: the strict+probe must survive arbitrary churn, and an index left reading raw ``messages``+must realign once, on open.+"""++import sqlite3++import pytest++from hermes_state import SessionDB+from hermes_state_common import FTS_STORAGE_VERSION, FTS_TOOL_CONTENT_PREFIX_CHARS++LONG_TOOL_ROW = "prefix " + ("padding " * ((FTS_TOOL_CONTENT_PREFIX_CHARS // 8) + 64)) + " tailtoken"+++def _strict_integrity_probe(db) -> None:+ """FTS5's strict check: re-reads the content source and compares it with the+ stored token stream. Raises ``sqlite3.DatabaseError`` when they disagree."""+ db._conn.execute(+ "INSERT INTO messages_fts(messages_fts, rank) VALUES('integrity-check', 1)"+ )+++def db(tmp_path):+ session_db = SessionDB(db_path=tmp_path / "state.db")+ if not session_db._fts_enabled:+ session_db.close()+ pytest.skip("SQLite FTS5 unavailable")+ session_db.create_session("session", source="cli")+ try:+ yield session_db+ finally:+ session_db.close()+++def test_strict_integrity_probe_survives_tool_row_churn(db):+ """Every write path must leave the index readable by FTS5's own checker.++ Pre-fix, the long-row assertion raises ``DatabaseError: fts5: checksum+ mismatch for table "messages_fts"``: the row was indexed as a prefix while+ ``content='messages'`` kept the full body, so the checker disagreed with the+ stored tokens. The UPDATE and DELETE legs are the triggers whose content+ command used to be re-evaluated against a moving mark.+ """+ _strict_integrity_probe(db)++ long_id = db.append_message(+ "session", role="tool", content=LONG_TOOL_ROW, tool_name="terminal"+ )+ _strict_integrity_probe(db)++ db._execute_write(+ lambda conn: conn.execute(+ "UPDATE messages SET content = ? WHERE id = ?", ("short body", long_id)+ )+ )+ _strict_integrity_probe(db)++ db.append_message("session", role="user", content="short user row")+ _strict_integrity_probe(db)++ db._execute_write(+ lambda conn: conn.execute("DELETE FROM messages WHERE id = ?", (long_id,))+ )+ _strict_integrity_probe(db)+++def test_tool_rows_keep_full_content_reachable_without_indexing_it(db):+ """Bounding the base index must not lose the explicit tool search path."""+ tool_id = db.append_message(+ "session", role="tool", content=LONG_TOOL_ROW, tool_name="terminal"+ )++ assert db.search_messages("tailtoken") == []+ assert [+ row["id"] for row in db.search_messages("tailtoken", role_filter=["tool"])+ ] == [tool_id]+ _strict_integrity_probe(db)+++def test_index_reading_raw_messages_realigns_once_on_open(tmp_path):+ """A store whose index still reads raw ``messages`` (the shipped shape for+ versions before the aligned projection) realigns on the next open, records+ the new storage version, and is consistent from then on."""+ path = tmp_path / "state.db"+ first = SessionDB(db_path=path)+ if not first._fts_enabled:+ first.close()+ pytest.skip("SQLite FTS5 unavailable")+ first.create_session("session", source="cli")+ row_id = first.append_message(+ "session", role="tool", content=LONG_TOOL_ROW, tool_name="terminal"+ )++ # Rewind to the pre-fix on-disk shape: the base index reads raw `messages`,+ # and its tokens were written from the bounded projection the triggers used+ # for tool rows. That mixture IS the drift: the checker re-reads the full+ # body and disagrees with the stored prefix.+ first._conn.execute("DROP TABLE messages_fts")+ first._conn.execute(+ "CREATE VIRTUAL TABLE messages_fts USING fts5("+ "content, tool_name, tool_calls, content='messages', content_rowid='id')"+ )+ first._conn.execute(+ "INSERT INTO messages_fts(rowid, content, tool_name, tool_calls) VALUES(?, ?, ?, ?)",+ (row_id, LONG_TOOL_ROW[:FTS_TOOL_CONTENT_PREFIX_CHARS], "terminal", None),+ )+ first._conn.execute(+ "INSERT INTO state_meta(key, value) VALUES('fts_storage_version', '2') "+ "ON CONFLICT(key) DO UPDATE SET value = '2'"+ )+ with pytest.raises(sqlite3.DatabaseError):+ _strict_integrity_probe(first)+ first.close()++ migrated = SessionDB(db_path=path)+ try:+ assert migrated.get_meta("fts_storage_version") == str(FTS_STORAGE_VERSION)+ _strict_integrity_probe(migrated)+ index_sql = migrated._conn.execute(+ "SELECT sql FROM sqlite_master WHERE name = 'messages_fts'"+ ).fetchone()[0]+ assert "messages_fts_src" in index_sql+ # The realigned index answers the prefix; the tail comes from the+ # explicit tool path, which reads stored content rather than the index.+ assert migrated.search_messages("prefix", role_filter=["tool"])+ assert [+ row["id"]+ for row in migrated.search_messages("tailtoken", role_filter=["tool"])+ ] == [row_id]+ finally:+ migrated.close()diff --git a/tests/hermes_state/test_fts_tool_write_bounds.py b/tests/hermes_state/test_fts_tool_write_bounds.pyindex fb38bd60d45..3e8158a1f43 100644--- a/tests/hermes_state/test_fts_tool_write_bounds.py+++ b/tests/hermes_state/test_fts_tool_write_bounds.py@@ -5,7 +5,6 @@ import pytestfrom hermes_state import SessionDBfrom hermes_state_common import (FTS_TOOL_CONTENT_PREFIX_CHARS,- FTS_TOOL_FULL_CONTENT_HIGH_WATER_KEY,LEGACY_FTS_SQL,_FTS_TRIGGERS,)@@ -55,70 +54,65 @@ def test_new_tool_rows_bound_fts_content_but_explicit_tool_search_is_complete(db]-def test_trigger_migration_preserves_historical_tool_tokens_without_rebuild(tmp_path):+def test_reopen_keeps_bounded_rows_consistent_without_a_marker(tmp_path):+ """The bounded projection is a fixed per-row function: reopening a store does+ not need a marker, and the redaction/delete paths that used to re-evaluate+ one keep the index consistent for both historical and new tool rows."""path = tmp_path / "state.db"first = SessionDB(db_path=path)if not first._fts_enabled:first.close()pytest.skip("SQLite FTS5 unavailable")first.create_session("session", source="cli")-- # Model the pre-migration trigger contract: every id through this artificial- # boundary receives full-content indexing.- first.set_meta(FTS_TOOL_FULL_CONTENT_HIGH_WATER_KEY, str(2**62))- old_id = first.append_message(+ historical_id = first.append_message("session",role="tool",- content=_long_message("old-prefix-token", "old-tail-token"),- )- assert [row["id"] for row in first.search_messages("old-tail-token")] == [old_id]- first._conn.execute(- "DELETE FROM state_meta WHERE key = ?",- (FTS_TOOL_FULL_CONTENT_HIGH_WATER_KEY,),+ content=_long_message("historical-prefix-token", "historical-tail-token"),)+ assert first.search_messages("historical-tail-token") == []first.close()- migrated = SessionDB(db_path=path)+ reopened = SessionDB(db_path=path)try:- assert int(migrated.get_meta(FTS_TOOL_FULL_CONTENT_HIGH_WATER_KEY)) == old_id- assert [- row["id"] for row in migrated.search_messages("old-tail-token")- ] == [old_id]-- new_id = migrated.append_message(+ assert reopened.get_meta("fts_storage_version") is not None+ new_id = reopened.append_message("session",role="tool",content=_long_message("new-prefix-token", "new-tail-token"),)- assert migrated.search_messages("new-tail-token") == []+ assert reopened.search_messages("new-tail-token") == []assert [row["id"]- for row in migrated.search_messages(+ for row in reopened.search_messages("new-tail-token", role_filter=["tool"])] == [new_id]- # Historical rows still use their full old token stream for the FTS5- # external-content delete command; redaction must remove the tail token.- migrated._execute_write(+ # Redaction must remove the tail token from the index as well.+ reopened._execute_write(lambda conn: conn.execute(- "UPDATE messages SET content = '' WHERE id = ?", (old_id,)+ "UPDATE messages SET content = '' WHERE id = ?", (historical_id,)))- assert migrated.search_messages("old-tail-token") == []+ assert reopened.search_messages("historical-tail-token") == []- # New bounded rows use the same prefix for delete as insert. A mismatch+ # Bounded rows use the same projection for insert and delete; a mismatch# corrupts external-content FTS and makes this delete or later write fail.- migrated._execute_write(+ reopened._execute_write(lambda conn: conn.execute("DELETE FROM messages WHERE id = ?", (new_id,)))- migrated.append_message("session", role="assistant", content="fts-still-healthy")- assert migrated.search_messages("fts-still-healthy")+ reopened.append_message("session", role="assistant", content="fts-still-healthy")+ assert reopened.search_messages("fts-still-healthy")+ reopened._conn.execute(+ "INSERT INTO messages_fts(messages_fts, rank) VALUES('integrity-check', 1)"+ )finally:- migrated.close()+ reopened.close()-def test_full_rebuild_moves_boundary_before_future_tool_writes(db):+def test_full_rebuild_keeps_every_tool_row_bounded(db):+ """A rebuild fills the index from the same stable projection as the triggers,+ so it cannot introduce full-content tokens for tool rows again."""before_id = db.append_message("session",role="tool",@@ -127,10 +121,7 @@ def test_full_rebuild_moves_boundary_before_future_tool_writes(db):assert db.search_messages("before-tail-token") == []assert db.rebuild_fts() >= 1- assert int(db.get_meta(FTS_TOOL_FULL_CONTENT_HIGH_WATER_KEY)) == before_id- assert [row["id"] for row in db.search_messages("before-tail-token")] == [- before_id- ]+ assert db.search_messages("before-tail-token") == []after_id = db.append_message("session",@@ -143,6 +134,10 @@ def test_full_rebuild_moves_boundary_before_future_tool_writes(db):for row in db.search_messages("after-tail-token", role_filter=["tool"])] == [after_id]+ db._conn.execute(+ "INSERT INTO messages_fts(messages_fts, rank) VALUES('integrity-check', 1)"+ )+def test_role_changes_switch_between_bounded_and_full_indexing(db):message_id = db.append_message(@@ -181,7 +176,7 @@ def test_legacy_inline_fts_also_bounds_new_tool_rows(tmp_path):initial._conn.executescript(LEGACY_FTS_SQL)initial._conn.execute("DELETE FROM state_meta WHERE key IN (?, 'fts_storage_version')",- (FTS_TOOL_FULL_CONTENT_HIGH_WATER_KEY,),+ ("fts_tool_full_content_high_water",),)initial.close()