Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion plugins/memory/holographic/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,19 @@ def _clamp_trust(value: float) -> float:
return max(_TRUST_MIN, min(_TRUST_MAX, value))


def _fts5_safe_query(text: str) -> str:
"""Turn free text into a crash-proof FTS5 MATCH query.

User/LLM search strings routinely contain FTS5 query syntax — a stray
double-quote, a ``key:value`` colon, a bare ``AND``/``OR``/``NEAR``, or a
parenthesis — which otherwise raises ``sqlite3.OperationalError`` from
``MATCH``. Wrap each whitespace token in double quotes (escaping embedded
quotes) so every term is matched literally and AND-combined. Returns ``""``
when there are no usable tokens.
"""
return " ".join('"' + tok.replace('"', '""') + '"' for tok in text.split() if tok)


class MemoryStore:
"""SQLite-backed fact store with entity resolution and trust scoring."""

Expand Down Expand Up @@ -274,7 +287,18 @@ def search_facts(
LIMIT ?
"""

rows = self._conn.execute(sql, params).fetchall()
try:
rows = self._conn.execute(sql, params).fetchall()
except sqlite3.OperationalError:
# The raw text wasn't a valid FTS5 query (stray quote/colon/
# bare AND-OR-NEAR/paren). Retry with each token quoted as a
# literal phrase so the search degrades to a sane match instead
# of crashing the memory tool.
safe = _fts5_safe_query(query)
if not safe:
return []
params[0] = safe

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Current main now builds match_query through FactRetriever._sanitize_fts_query before this execution path (638d2e7). Please preserve that sanitizer when salvaging this guard: its raw fallback for all-discarded tokens is the remaining crash path.

rows = self._conn.execute(sql, params).fetchall()
results = [self._row_to_dict(r) for r in rows]

if results:
Expand Down
106 changes: 106 additions & 0 deletions tests/plugins/memory/test_holographic_store_search_fts5.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
"""MemoryStore.search_facts must not crash on FTS5 query syntax in user text.

The memory ``search`` action is exposed to the LLM, which routinely emits
queries containing FTS5 metasyntax — a stray double-quote, a ``key:value``
colon, a bare ``AND``/``OR``/``NEAR``, or a parenthesis. Passing those straight
to ``MATCH`` raised an unhandled ``sqlite3.OperationalError`` and crashed the
memory tool. search_facts now retries with each token quoted as a literal
phrase so the search degrades gracefully.
"""

import sqlite3

import pytest

from plugins.memory.holographic.store import MemoryStore, _fts5_safe_query


@pytest.fixture(autouse=True)
def _clean_shared_registry():
"""Each test starts and ends with an empty shared-connection registry."""
for entry in list(MemoryStore._shared.values()):
try:
entry["conn"].close()
except sqlite3.Error:
pass
MemoryStore._shared.clear()
yield
for entry in list(MemoryStore._shared.values()):
try:
entry["conn"].close()
except sqlite3.Error:
pass
MemoryStore._shared.clear()


@pytest.fixture
def store(tmp_path):
"""A MemoryStore backed by a per-test database file.

``MemoryStore`` resolves ``db_path`` before ``sqlite3.connect`` and keys its
process-wide shared-connection registry on the resolved path, so passing
``":memory:"`` yields a shared *on-disk* file rather than SQLite's in-memory
sentinel — leaking rows between tests. Use ``tmp_path`` and close the store,
matching ``test_holographic_store.py``.
"""
store = MemoryStore(tmp_path / "memory_store.db")
store.add_fact("Python is a programming language", category="tech")
store.add_fact("Rust is memory safe and fast", category="tech")
try:
yield store
finally:
store.close()


@pytest.mark.parametrize(
"query",
[
'"unterminated',
"foo:bar",
"AND",
"a OR",
"(python",
"memory:safe",
"C++ AND rust",
'say "hi',
"NEAR(",
],
)
def test_fts5_metasyntax_does_not_crash(store, query):
# Must return a list, never raise sqlite3.OperationalError.
result = store.search_facts(query)
assert isinstance(result, list)


def test_bare_boolean_operators_no_longer_crash(store):
# `_sanitize_fts_query` neutralises most metasyntax before MATCH (colons,
# stray quotes, parens, NEAR), but a bare boolean operator survives it and
# still reaches FTS5 as a syntax error — on an unguarded store,
# `search_facts("AND")` raises `fts5: syntax error near "AND"` and
# `search_facts("a OR")` raises `fts5: syntax error near ""`. These are the
# cases the quoted-phrase retry still has to absorb.
for query in ("AND", "a OR"):
assert isinstance(store.search_facts(query), list), query


def test_normal_query_unaffected(store):
results = store.search_facts("python")
assert any("Python" in r["content"] for r in results)


def test_prefix_query_still_works(store):
# A valid FTS5 prefix query must keep working (try-raw before fallback).
results = store.search_facts("rust*")
assert any("Rust" in r["content"] for r in results)


def test_empty_after_sanitization_returns_empty(store):
# A query that's only quotes -> no usable tokens -> [] (no crash).
assert store.search_facts('"') == []


def test_fts5_safe_query_helper():
assert _fts5_safe_query("foo:bar baz") == '"foo:bar" "baz"'
# An embedded double-quote is doubled (FTS5 phrase escaping).
assert _fts5_safe_query('a"b') == '"a""b"'
assert _fts5_safe_query(" ") == ""