A RAG search tool accepts a string, passes it to SQLite with a placeholder, and returns matching documents. The SQL review looks fine:
con.execute("SELECT rowid FROM docs WHERE docs MATCH ?", (query,))
Now give it rollback OR payroll. SQLite FTS5 interprets OR as a search operator. The caller has supplied a query expression, even though the SQL statement uses a bound parameter correctly.
I would make that choice explicit in the tool contract. A field described as “text to find” should not quietly grant control over Boolean operators, column filters and prefix expansion. A field described as “FTS5 expression” may grant exactly that control, but then its errors, resource limits and evaluation cases need to reflect it.
The distinction is reproducible without an LLM. The download below uses eight synthetic documents in an in-memory database. It makes no network requests and does not demonstrate a tenant-access bypass. It demonstrates a mismatch between the search interface’s promise and the language the backend executes.
The SQL value contains another language
Python’s SQLite documentation recommends placeholders for binding values rather than assembling SQL from strings. Keep doing that. It prevents the supplied value from becoming SQL syntax in this statement.
The FTS5 query syntax documentation defines a separate grammar inside the value passed to MATCH. That grammar includes AND, OR, NOT, phrases and column specifications. SQL binding does not turn those operators into ordinary search terms.
In the fixture, row 1 contains rollback guide, row 2 contains payroll guide, and row 3 contains rollback OR payroll. Other rows contain a quoted mention of rollback and a payroll reference. The bound raw expression returns all five matching rows:
SQL-bound raw FTS: [1, 2, 3, 4, 6]
SQL-bound token phrase: [3]
Both paths use the same SQL statement and a parameter tuple. The second path first encodes the supplied text as one FTS phrase. It therefore requires the token sequence rollback, or, payroll, rather than accepting either of the two outer words.
This can happen accidentally. An agent may copy a product name with punctuation, quote a passage with an unmatched quotation mark, or use a capitalised word that the search grammar reserves. Treating every such case as an attack would obscure an ordinary interface defect. The caller and the adapter need to agree on what the string means.
Encode a phrase before binding it
SQLite’s FTS5 string rules allow double-quoted strings and specify that embedded double quotes are escaped by doubling them. The fixture uses that rule:
def phrase(text):
# The complete download validates type, length and characters first.
return '"' + text.replace('"', '""') + '"'
rows = con.execute(
"SELECT rowid FROM docs WHERE docs MATCH ? ORDER BY rowid",
(phrase(query),),
)
Do not replace the parameter tuple with string interpolation after adding the FTS encoding. The encoder handles the inner query language. The placeholder still handles the SQL value.
The complete function accepts nonblank strings of at most 1,024 Unicode code points. It refuses ASCII control characters, DEL and surrogate code points. These are application constraints chosen for the example, not FTS5 requirements. A punctuation-only input such as *** passes those checks but produces no tokens and returns no matches in the configured fixture.
The tests also exercise rollback" OR "payroll. Doubling the embedded quotes prevents them from ending the enclosing phrase and exposing an OR operator. With the fixture’s tokenizer, the remaining words still form the phrase found in row 3. Returning that row is expected; the safety property is that the caller cannot break out into query syntax.
A token phrase is not an exact substring
Calling this helper escape_exact_text would make another false promise. FTS5 tokenises each phrase before searching. The configured tokenizer determines which characters become tokens and how it normalises them.
The fixture explicitly selects unicode61. Under its default options, the query release check matches the document release-check procedure. The query CAFE matches café handbook. Quoting has disabled query operators; it has not made punctuation, case or accents byte-exact.
Phrase order and adjacency still apply. rollback guide matches row 1. guide rollback does not. Nor does rollback payroll match row 3, because the intervening OR is a token in the document.
If a user needs every word anywhere in a document, this whole-phrase policy will be too restrictive. Design that as a separate contract: a validated list of terms that the application combines with a fixed operator, using the target engine’s encoding rules. If a user needs an exact quotation, verify the retrieved source text after candidate retrieval using a declared normalisation policy. A keyword index alone does not prove exact textual equality.
That is related to the citation-offset problem: a retrieval match and an evidence span have different contracts. Do not use a successful phrase search as proof that a particular byte range contains the quoted text.
Run the counterexample and its regressions
Download and inspect rag-fts-query-boundary.py. It requires Python 3.9 or later with SQLite FTS5 support. It creates only an in-memory database and closes the connection when finished.
python3 rag-fts-query-boundary.py
python3 rag-fts-query-boundary.py --test
python3 -O rag-fts-query-boundary.py --test
The demonstration above ran against SQLite 3.51.0. Ten unique tests passed in normal and optimised Python mode. The suite uses unittest checks rather than removable Python assert statements.
The tests retain the raw-expression path so the broader result set remains reproducible. They also cover unmatched and embedded quotes, column syntax, prefix syntax, phrase order, punctuation-only input, input limits and tokenizer normalisation. One test submits SQL-looking text and confirms that the table remains present. That check is a small regression case, not a general security certification.
For example, raw body:payroll selects documents containing payroll in the body column. The encoded phrase instead searches for the token sequence body payroll. Raw roll* expands a prefix; the encoded phrase passes the asterisk to the tokenizer and searches for roll, which is absent from these documents. Those differences are documented search semantics, not engine bugs.
If your Python build lacks FTS5, database creation fails visibly. Do not substitute a fake matcher and report the SQLite behaviour as tested. Run the fixture against a build with the extension, then retain the reported SQLite version with your adapter’s test results.
Keep search syntax separate from authority and cost
Encoding a phrase does not authorise a document. Apply the caller’s tenant and access constraints independently of any model-generated search expression. A document containing an allowed term can still belong to another user. The earlier RAG authorisation and top-k article addresses that retrieval boundary; today’s encoder does not implement it.
Nor does a short phrase guarantee a cheap query. A common term may match a large corpus. The example’s input-length bound limits what enters the parser, but it supplies no production query deadline, concurrency limit or relevance benchmark. Its sorted row IDs make tests deterministic; they are not relevance-ranked results.
For a richer agent search tool, expose the mode in the schema. Keep plain-text phrase search distinct from an advanced-expression operation. Validate the selected mode, retain independently enforced access constraints, and measure expensive cases against a representative index. A prompt asking the model to avoid operators cannot enforce the parser boundary.
For the wider approach to tool contracts and bounded agent work, see my Claude Code book, available as a Kindle edition on Amazon UK.
Add OR, an unmatched quote and a hyphenated product name to your search adapter’s tests. Specify the expected document IDs for each supported mode. That gives the next adapter change a concrete contract to preserve.