From 2febb5823c0ec187971f78547b38d63d01ba5d6d Mon Sep 17 00:00:00 2001 From: kshitijk4poor <82637225+kshitijk4poor@users.noreply.github.com> Date: Sun, 2 Aug 2026 19:55:22 +0530 Subject: [PATCH] perf(state): probe empty FTS index with EXISTS instead of COUNT(*) _fts_external_index_empty_with_messages runs on every writable open via the _init_schema fts_storage_version stamp condition. COUNT(*) is a full b-tree scan on both messages and messages_fts_docsize (~100ms per open on a 2M-row DB, measured); the function only ever compares against zero, so EXISTS(SELECT 1 ...) gives the identical boolean in O(1). --- hermes_state_search.py | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/hermes_state_search.py b/hermes_state_search.py index 680bda6893..986e0d85a2 100644 --- a/hermes_state_search.py +++ b/hermes_state_search.py @@ -366,16 +366,21 @@ class SessionSearchMixin: never match. """ try: - n_msg = conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0] - if int(n_msg) <= 0: + 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; COUNT(*) on the virtual table itself is - # not reliable across SQLite builds. - n_fts = conn.execute( - "SELECT COUNT(*) FROM messages_fts_docsize" + # external-content FTS5; probing the virtual table itself is + # not reliable across SQLite builds. EXISTS instead of COUNT(*): + # this runs on every writable open via the _init_schema stamp + # condition, and COUNT(*) is a full b-tree scan (~100ms on a + # 2M-row table) while EXISTS is O(1). + has_fts = conn.execute( + "SELECT EXISTS(SELECT 1 FROM messages_fts_docsize)" ).fetchone()[0] - return int(n_fts) == 0 + return not has_fts except sqlite3.OperationalError: # Table absent / FTS disabled mid-init — not this failure class. return False