Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(store): bound FTS query text before the parser sees it

Victor Alencarb72d0df3c51b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index da1fca12..8a766b9a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -114,6 +114,13 @@ version in [`docs/changelog/`](docs/changelog/):
page, aligning belief input aggregation with the lint's resolved/stale split.
([#1386](https://github.com/akitaonrails/ai-memory/pull/1386))
- Kept the previous backup or OKF export intact when an archive download is interrupted, and publish completed downloads atomically. Successful downloads replace destination symlinks with private files rather than changing their targets or inheriting their permissions. ([#1381](https://github.com/akitaonrails/ai-memory/pull/1381))
+- Bounded free-text search before the FTS5 parser sees it. A query of 100k
+ distinct terms spent ~17.5 s in query preparation alone (and a ~500 KB
+ document ~59 s end to end), and a NUL byte reached the phrase parser as
+ end-of-input, surfacing `sqlite: unterminated string` as an internal error
+ instead of a result. Query text is now folded (NUL becomes a space) and cut
+ to the first 4 KiB on a UTF-8 boundary; ordinary queries are unchanged.
+ ([#1434](https://github.com/akitaonrails/ai-memory/issues/1434))
## [3.1.1] - 2026-10-17
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 446df4b7..e241163e 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -2693,6 +2693,9 @@ impl AiMemoryServer {
followed by a bounded kind/tier/pinned/tag source-authority adjustment. \
Returns up to `limit` pages with HTML-marked snippets and a rank \
score (lower rank = better match). Only latest page versions. \
+ Query text is folded (a NUL becomes a space) and bounded to the \
+ first 4 KiB before parsing, so pasting a whole document searches \
+ only its opening. \
Set `explain=true` to attach per-stream ranks, matched entities, raw \
scores, RRF contributions, graph provenance, and the authority multiplier to \
project/scopes hits; it also returns `streams_active` and per-stream \
diff --git a/crates/ai-memory-mcp/tests/suite/retrieval_via_tools.rs b/crates/ai-memory-mcp/tests/suite/retrieval_via_tools.rs
index 2013e0a2..64add3a2 100644
--- a/crates/ai-memory-mcp/tests/suite/retrieval_via_tools.rs
+++ b/crates/ai-memory-mcp/tests/suite/retrieval_via_tools.rs
@@ -16,6 +16,9 @@
//! `page_evidence` reaches explain output (P2 / V63).
//! 4. `memory_briefing(settled_first=true)` — standing rule/decision pages,
//! ordered by evidence then recency (P4).
+//! 5. `memory_query` input bounds — a NUL byte and a document-sized query
+//! stay inside the FTS5 parser's contract instead of surfacing an
+//! internal SQLite error or parsing term by term.
//!
//! The `[retrieval] query_intent` / `abstract_vectors` opt-in ranking signals
//! are deliberately NOT retested here: they are driven by process-level
@@ -469,3 +472,63 @@ async fn memory_briefing_settled_first_orders_by_evidence_then_recency() {
Some("rule")
);
}
+
+/// 5. Pathological query text stays bounded at the tool boundary. A NUL byte
+/// used to reach FTS5's phrase parser as end-of-input and come back as
+/// `sqlite: unterminated string` (an internal error), and a document-sized
+/// query was parsed term by term — the parser is superlinear, so 100k terms
+/// spent ~17 s in preparation alone. Both are input bounds, not retrieval
+/// features, but only the tool call proves the surface actually reaches them.
+#[tokio::test]
+async fn memory_query_bounds_pathological_queries() {
+ let h = harness().await;
+ h.store
+ .writer
+ .upsert_page(page(
+ h.ws,
+ h.proj,
+ "notes/bounded.md",
+ "Bounded",
+ "sendable marker",
+ ))
+ .await
+ .unwrap();
+
+ // Control: the seeded term answers through the same path.
+ let control = call(&h.router, "memory_query", query_args("sendable", json!({}))).await;
+ assert!(
+ hit_for(&control, "notes/bounded.md").is_some(),
+ "control query must hit the seeded page: {control}"
+ );
+
+ // A NUL is neutralised, not returned as an internal error. The rest of
+ // the token stays searchable, so the page still answers.
+ let nul = call(
+ &h.router,
+ "memory_query",
+ query_args("\u{0}sendable", json!({})),
+ )
+ .await;
+ assert!(
+ hit_for(&nul, "notes/bounded.md").is_some(),
+ "a NUL must not break the query: {nul}"
+ );
+
+ // 100k distinct terms is far past any real query. Unbounded, this took
+ // tens of seconds; bounded, the tool answers promptly. The timeout is the
+ // assertion: pre-fix it expires, post-fix the work is microseconds.
+ let oversized = (0..100_000)
+ .map(|i| format!("w{i}"))
+ .collect::<Vec<_>>()
+ .join(" ");
+ let answer = tokio::time::timeout(
+ std::time::Duration::from_secs(15),
+ call(&h.router, "memory_query", query_args(&oversized, json!({}))),
+ )
+ .await
+ .expect("an oversized query must be bounded, not parsed for tens of seconds");
+ assert!(
+ hits(&answer).is_empty(),
+ "no page contains those terms: {answer}"
+ );
+}
diff --git a/crates/ai-memory-store/src/fts_query.rs b/crates/ai-memory-store/src/fts_query.rs
index f4050184..4e28193b 100644
--- a/crates/ai-memory-store/src/fts_query.rs
+++ b/crates/ai-memory-store/src/fts_query.rs
@@ -6,6 +6,7 @@
//! exist on the FTS tables. Unknown bare column syntax is neutralised without
//! discarding deliberate FTS operators such as `OR`.
+use std::borrow::Cow;
use std::collections::HashSet;
use std::sync::Arc;
@@ -113,8 +114,14 @@ impl Default for FtsStopwords {
///
/// `stopwords` is the operator-configured set (default: [`FtsStopwords::default`],
/// the built-in English list; `FtsStopwords::none()` disables filtering).
+///
+/// The input is bounded first: a NUL byte is folded to a space, and anything
+/// past the 4 KiB cap is dropped, because FTS5's parser is superlinear in the
+/// expression it is handed (see `bounded_query_text`).
#[must_use]
pub fn prepare_fts5_query(raw: &str, stopwords: &FtsStopwords) -> String {
+ let bounded = bounded_query_text(raw);
+ let raw = bounded.as_ref();
let explicit_syntax = raw.contains('"')
|| raw.contains('(')
|| raw.contains(')')
@@ -178,6 +185,34 @@ pub fn prepare_fts5_query(raw: &str, stopwords: &FtsStopwords) -> String {
.join(" OR ")
}
+/// Upper bound (bytes) on the untrusted search text this module tokenises.
+///
+/// FTS5's query parser is superlinear in the expression it is handed:
+/// measured here, 10k distinct terms spent ~60 ms inside
+/// [`prepare_fts5_query`], 40k ~1.9 s and 100k ~17.5 s — before the real
+/// `MATCH` ran. Search text is a phrase, not a document, so the tail of
+/// anything longer is dropped instead of parsed.
+const MAX_FTS_QUERY_BYTES: usize = 4_096;
+
+/// Bound untrusted search text before anything parses it.
+///
+/// A NUL cannot appear in indexed text, but it used to reach the FTS5 parser,
+/// which reads a quoted phrase as a C string: `"\0"` fails as an unterminated
+/// string, so `memory_query` surfaced `sqlite: unterminated string` as an
+/// internal error instead of a result. Folding NUL to a space keeps the rest
+/// of the token searchable. Past [`MAX_FTS_QUERY_BYTES`] the text is cut on a
+/// UTF-8 boundary; a cut that lands inside a phrase or paren leaves invalid
+/// FTS5 syntax, which [`fts5_query_parses`] already degrades to the quoted
+/// bag of words. Borrows when neither applies, so the common query path
+/// allocates nothing.
+fn bounded_query_text(raw: &str) -> Cow<'_, str> {
+ let bounded = &raw[..raw.floor_char_boundary(MAX_FTS_QUERY_BYTES)];
+ if !bounded.contains('\0') {
+ return Cow::Borrowed(bounded);
+ }
+ Cow::Owned(bounded.replace('\0', " "))
+}
+
/// Whether FTS5's own parser accepts `query`. Uses a throwaway in-memory
/// table (microseconds; search-path frequency, not ingest-path) so the
/// judgement is the engine's, not a re-implementation of its grammar.
@@ -344,6 +379,70 @@ mod tests {
assert!(prepared.contains("Civilizations"));
}
+ /// A NUL byte cannot appear in indexed text, but it used to reach the
+ /// FTS5 query parser: a token that starts with one is quoted (`"\0x"`),
+ /// and the parser reads the phrase as end-of-input — `sqlite:
+ /// unterminated string` came back from `memory_query` as an internal
+ /// error. This module's contract is that MATCH never errors on user text.
+ #[test]
+ fn nul_bytes_never_reach_the_match_expression() {
+ for raw in ["\0", "\0x", "x\0", "\0 \0", "(\0)", "a\0b", "title:\0x"] {
+ let prepared = prepare_fts5_query(raw);
+ assert!(!prepared.contains('\0'), "NUL survived into {prepared:?}");
+ if !prepared.is_empty() {
+ assert_parses(&prepared);
+ }
+ }
+ }
+
+ /// The FTS5 query parser is superlinear in the number of terms: 100k
+ /// distinct terms spent ~17 s inside `prepare_fts5_query` alone, before
+ /// the real MATCH ran. Search text is a phrase, not a document, so the
+ /// tail of an oversized query must be dropped before the parser sees it.
+ #[test]
+ fn oversized_query_text_is_bounded_before_parsing() {
+ let raw = (0..100_000)
+ .map(|i| format!("w{i}"))
+ .collect::<Vec<_>>()
+ .join(" ");
+ let prepared = prepare_fts5_query(&raw);
+ assert!(
+ prepared.len() <= 32 * 1024,
+ "prepared expression is not bounded: {} bytes",
+ prepared.len()
+ );
+ assert_parses(&prepared);
+ }
+
+ /// The bound must not touch an ordinary query: this is the exact
+ /// expression every search has produced since the OR-join landed.
+ #[test]
+ fn ordinary_query_text_is_untouched_by_the_bound() {
+ assert_eq!(
+ prepare_fts5_query("cross project search strategy"),
+ "cross OR project OR search OR strategy"
+ );
+ }
+
+ /// 4 KiB lands mid-character for a 3-byte code point (4096 % 3 != 0); the
+ /// cut has to move back to a UTF-8 boundary instead of panicking.
+ #[test]
+ fn the_bound_cuts_on_a_character_boundary() {
+ let raw = "日".repeat(2_000);
+ assert!(raw.len() > MAX_FTS_QUERY_BYTES);
+ let prepared = prepare_fts5_query(&raw);
+ assert_parses(&prepared);
+ }
+
+ /// Truncation can land inside a quoted phrase; whatever the cut leaves,
+ /// the prepared expression must still parse and MATCH without error.
+ #[test]
+ fn truncated_explicit_syntax_stays_parseable() {
+ let raw = format!("\"unclosed {}", "w ".repeat(3_000));
+ let prepared = prepare_fts5_query(&raw);
+ assert_parses(&prepared);
+ }
+
#[test]
fn hostile_operator_soup_never_errors() {
for raw in [