Text search plugin internals

This page explains how the text search plugin works end to end: the Tantivy sidecar index, the planner walk that rewrites text filters, the trust gate, and the execute-time roads of the text_scan operator. It is written for engine developers; the user-facing view is the how-to page and the feature overview.

The normative cross-crate reference is ARCH.md section 7c at the repo root (not part of this site). Where this page and the code disagree, the code is authoritative.

The moving pieces

Crate Role

waratah_storage::text_index

Shared vocabulary: TextIndexDoc, TextSearchRequest, TextCandidateMode, the analyzer menu. Compute builds requests and the partition executes them; neither has to link Tantivy to name a mode.

waratah_text_index

The partition-side Tantivy engine: schema, document builder, candidate queries, the RAM scratch evaluator the compute side reuses.

waratah_text

The plugin: planner rewrites (plan.rs), executor roads (exec.rs), offline rebuild driver (rebuild.rs), configuration fingerprint (config.rs).

waratah_compute

The seam: PutTextIndex / TextCandidateScan RPCs in clients.rs, the C3 write ordering in fanout.rs, the drain memo in query/custom_op.rs.

The plugin is installed at startup only when enabled (--with-text, or {config-dir}/text.toml in the config directory). Disabled by default: unlike geo/temporal, whose cost is scoped to their own datatypes, this plugin indexes every string literal up to the indexed-lexical limit (1 MiB; longer literals fail the write), so always-on would change the write latency and disk baseline of every deployment.

The index schema and the seed fields

One Tantivy document per distinct string-literal term (waratah_text_index/src/schema.rs):

Field Tokenizer

Content

term

bytes, fast

The encoded EncodedTerm; the candidate payload.

text

the configured analyzer

The full lexical, for text:query.

text_begin

raw

The first seed_chars characters of the lexical.

text_end

raw

The LAST seed_chars characters of the lexical, REVERSED.

lang

raw

The language tag, or the _none sentinel.

The bounded seed fields back the string-function family. text_end stores the reversed suffix so a suffix query is a prefix query over the reversed seed, which the FST term dictionary can seek; without the reversal a suffix query would walk the whole dictionary. Both seeds truncate on char boundaries, never bytes. seed_chars defaults to 16 (largest accepted value 64) and is part of the config fingerprint.

The analyzer menu (waratah_storage/src/text_index.rs) maps config values to Waratah-owned registered tokenizers — simple, en_stem, whitespace — so a Tantivy upgrade cannot silently change the analysis of an existing store.

One bound applies to the whole document: a lexical above MAX_INDEXED_LEXICAL_BYTES (1 MiB) is rejected fail-closed rather than indexed — see [text-lexical-limit].

The planner walk: FILTER descent and the belt

The plugin’s planner hook (TextPlannerPlugin in waratah_text/src/plan.rs) runs once over the lowered plan. Every FILTER it visits is split into && conjuncts; each conjunct is matched against the plugin’s rewrite shapes.

The descent list

The walk descends into every node a lowered FILTER can hide under: Join, Union, LeftJoin, CustomNode children, Extend (BIND), Slice (LIMIT/OFFSET), Distinct, Sort, Group (GROUP BY), JoinGraphVar (GRAPH ?g), and SubSelect.inner. The geo planner’s list is the model, with one deliberate divergence: geo skips SubSelect because a missed geo filter still evaluates exactly per-row (slow, not wrong), while text:query has no per-row implementation — a missed filter there is a WRONG answer, so the text descent must be exhaustive.

The belt

The rewriter consumes only bare top-level conjuncts. A text:query call nested inside ||, !, IF, or COALESCE can never be rewritten by any descent list, and its per-row evaluation is the custom function’s error backstop — a FILTER error DROPS THE ROW, so a trusted index would silently answer zero rows (the forbidden trusted-but-empty state). After every rewrite attempt, the belt (ensure_no_surviving_text_query) scans the surviving early and residual expressions — and an OPTIONAL’s early_filter / residual_filter condition slots — with full Expression recursion, and fails the plan naming the supported shape. The descent and the belt cover disjoint sets: the descent makes the walk reach filters, the belt catches the shapes no descent can rewrite.

Graph-scope tracking

The walk threads a scope track: every Scan stamps the track with its own four applied-graph fields (ScanOp::applied_graph — ground truth for its position), deduplicated by a CONSERVATIVE comparison (ground graph names by encoded bytes, graph variables by name, filters by allocation identity — two structurally equal filters from different allocations count as distinct, which costs duplicate arms the union’s Distinct folds, never a wrong answer); JoinGraphVar and SubSelect are boundaries that save and restore the outer track. A branch can legitimately hold scans from DIFFERENT windows (GRAPH <g1> { … } beside a bare dataset-scope pattern), so a subject-mode rewrite searches EVERY distinct stamp: one candidate arm per (scope, predicate), unioned. A single last-stamp-wins copy would search one window and silently drop the subjects whose matching text lived in the other — the union keeps the promise that the injected scans see exactly the graphs the rest of the query sees. With no sibling scan in the branch, the dataset’s default window is the fallback (applied_default_graph); inside a GRAPH subtree with no pattern to stamp from, the scope is unguessable and the plan fails.

The branch boundary is the group-graph-pattern boundary, mirrored in the lowered plan: Join children share the track (both are elements of the same enclosing group — the mixed-scope group above relies on it), while Union arms and LeftJoin (OPTIONAL) bodies are INDEPENDENT group patterns and start stamp-free — stamps never cross the boundary in either direction. A stamp leaking across a union boundary would inject a candidate arm scoped to a sibling arm’s graphs, and since subject mode strips the conjunct (no residual to refine candidates), the extra rows would be final wrong answers; isolated arms keep the enclosing in_graph_scope flag so an arm inside a GRAPH ?g block with no scans of its own still fails the plan instead of answering from the dataset window.

The two rewrites

Argument shape selects the form (no role inference): two arguments with a literal query is literal mode; a named-node second argument is subject mode.

Literal mode — text:query(?lit, "q" [, "lang:xx"])

The conjunct is STRIPPED and a childless text_scan operator is joined on the variable. The op emits the distinct string terms the index matched, so the join is 1:1 per distinct value and the strip is sound: the op is the complete answer. A searched variable the branch never binds answers the EMPTY TABLE instead: a FILTER expression that errors on a solution removes that solution, and text:query on an unbound argument errors on every solution — joining the candidate op on a key the inner side does not carry would die at runtime (join key arity). Subject mode needs no counterpart: its unbound-argument shape answers 0 rows through the same SPARQL error semantics today.

The string functions ride the same machinery differently: STRSTARTS, STRENDS, and anchored REGEX keep their conjunct (strip: false) and inject a candidate producer in Prefix / Suffix mode. The candidates are a superset of the exact answers within the seed length — the exact residual decides the row. An anchored REGEX rewrites only ^literal or .*literal$ shapes whose body contains no regex metacharacters: a metacharacter is read as syntax by the regex engine but would be sent to the index as literal text, excluding values the regex matches.

Subject mode — text:query(?s, <field>+, "q" [, "lang:xx"])

The semi-join shape Distinct ?s (Union_i (scan_i ⋈ candidates_i)), built from existing executable nodes: per predicate, a real triple scan on the predicate joined against the candidate op on a gensym’d carrier variable — unguessable, a fresh 16-char random token per rewrite (same mechanism as the sub-SELECT scope token), so a user __text_h… variable in the same scope cannot collide — the arms unioned and distinct-projected on every variable the arm shares with the inner plan (the subject, plus the graph slot when GRAPH ?g binds one — a subject-only key would collapse a multi-graph subject to one arbitrary graph and the join’s soft-pair reconciliation would drop the rest), then joined with the inner plan on the subject variable. A subject with several matching values appears once; the scans read at the query snapshot, so visibility is the store’s — including the graph scope copied from the sibling scan (above).

Contradiction checks are plan errors naming the other form: literal mode over a subject-slot-only variable (the Jena reflex), subject mode over an object-slot-only variable. The slot evidence covers scans, property-path endpoints (the endpoint binds its slot’s kind), VALUES ground rows (each row’s term kind), and ground BIND expressions — a variable bound only by any of these fires the same diagnostics instead of rewriting to a silent zero-row join. A text:query used as a graph-pattern predicate (the IRI in a scan’s predicate slot) is also a plan error.

The trust gate

Trusted = the sidecar epoch is stamped AND the partition’s fingerprint matches the plugin config (TextPluginConfig::fingerprint() — prefix, analyzer, seed length). No snapshot comparison: unlike the geo index, text postings are never rewritten, so a pre-epoch snapshot only sees extra candidates that join nothing. Untrusted degradation is ASYMMETRIC:

  • The string functions fall back to the exact residual — slow, correct.

  • text:query FAILS the query with the waratah text rebuild-index hint. It has no residual to fall back on, and returning zero rows from an unusable index is the forbidden trusted-but-empty state.

Candidate pricing: the seed sketch

candidate_estimate prices a PREFIX / SUFFIX drain from the hierarchical Count-Min seed sketch (waratah_stats::text_seed_sketch::TextSeedSketch) instead of the flat UNPRICED_DRAIN_SEAT_ESTIMATE stamp. The sketch: two directions (forward seeds over text_begin, reversed trailing seeds over text_end) x 8 depth levels x 3 rows x 19,000 u32 counters — a FIXED 3,648,014-byte frame at any corpus scale (10M or 1B unique strings encode the identical section, one gRPC message). Estimates never under-estimate: adds saturate, point queries take the row minimum, and an estimate is the minimum over the pattern’s available prefix levels (a SUPER-SEED pattern — longer than the depth — prices from its deepest stored prefix, an upper bound on the drain, the conservative direction for seating).

Collection runs under the rebuild lease on the O partition — a wipe rebuild builds fresh (exact distinct terms), an additive rebuild delta-merges into the surviving sidecar (waratah-text-sketch.bin; with NO surviving sidecar the finish writes NOTHING and the store stays unpriced until the next full rebuild — a delta-only population must never claim the fresh epoch). Deletes never retract: counts are postings, the same over-count contract as the geo histogram. The sketch is epoch-gated against the index’s trusted epoch — a stale or absent sketch keeps the flat stamp, never a wrong price.

Execute-time: the four roads of text_scan

The executor (TextExecutorPlugin in waratah_text/src/exec.rs) picks one of four roads per execution, mirroring the geo executor. The op is purely value-typed: its variable is the literal variable in literal-mode rewrites and the hidden carrier in subject-mode rewrites, so pushed keys are always the literal values the decision is about — the op never sees subjects.

  1. Pinned — the driver binds the output variable to exactly one ground term: evaluate that value locally, no candidate scan.

  2. Direct evaluation — pushed keys, deduped, priced small by the break-even: evaluate every key locally, no candidate scan RPC at all.

  3. Semi-join — pushed keys priced large: one candidate drain, then keep only the candidates in the key set. One scan call, all compute-side.

  4. Driver sweep — no pushed keys: one candidate drain, emit every candidate.

The candidate drain behind the semi-join and driver-sweep roads is UNBOUNDED in v1: every minted request carries limit: 0 (no caller arms the guard), so a broad FTS query materializes its whole distinct candidate set in one partition-side allocation — memoized once per (request, snapshot, text epoch) window, but unbounded within that window. The CandidateLimitExceeded arm in TextIndex::search is therefore unreachable in v1; it exists so arming a real limit later is a one-line change at the request constructors, not a new error path. Arming a limit needs a policy for the error reaching the client — "refine the query" is not always actionable — so the unbounded drain is the documented contract, not an oversight.

Road selection

take_direct_road prices direct evaluation (keys × per_key_unit) against drain + semi-join (drain_rows + min(keys, sweep) × per_key_unit) from the stamped CustomOpCost; ties go to direct. Text values all price alike — the geo executor’s inline-point discount does not apply. An op without a stamp falls back to a legacy deduped-count limit of 500 (TEXT_DIRECT_EVALUATE_LIMIT).

Direct evaluation

The pushed keys ARE the strings, so every value is decidable in-process (waratah_text_index/src/scratch.rs):

  • Seed modes are pure string tests over the bounded seeds — the exact match the index performs on its stored text_begin / text_end fields, expressed as starts_with over the (seed-truncated) pattern and value seeds.

  • FTS builds a scratch in-memory index (TextIndex::create_in_ram) over the pushed values and runs it through the same schema, analyzer registration, query builder, and collector the partition index uses. Tantivy matching is per-document boolean — nothing in the match decision depends on index-global state — so the scratch answer equals the index answer, and no second query implementation exists to drift. Language tags decode off the pushed EncodedTerm into the scratch document’s lang field, so lang:xx requests match identically.

Direct evaluation equals index membership because these roads only run inside a plan rewritten under the trust gate: a trusted index contains every string literal in the store, so "this value matches" and "the index returns this value" coincide. The request’s per-drain limit is ignored on these roads — it guards candidate materialization on the sweep road, while the direct road’s universe is the pushed set itself, already in memory.

The drain memo

Roads 3 and 4 drain through PluginEnv::text_candidates, which memoizes one candidate list per (request, snapshot, text epoch) window in QueryCaches::text_drains — the candidate list is key-invariant, so the semi-join road’s "one drain" holds across the driver’s whole page sequence. The whole-result CustomOp memo covers repeats only for childless, unpinned, keyless executions; the drain memo below the plugin boundary covers every other repeat of the same window.

The write path (C3)

PutTextIndex runs BEFORE the three axis InsertQuads calls (waratah_compute/src/fanout.rs). The ordering is deliberately opposite to the geo/temporal posting order: a document committed ahead of its row leaves a harmless phantom, while a visible row without its document is the silently-missing-candidate state no rebuild can distinguish from a search miss. Delete batches discard documents before the rows go. A retry adds a duplicate document; search deduplicates by term bytes.

The indexed-lexical limit (fail-closed)

The wire payload of a PutTextIndex document carries the full lexical, so a string literal larger than the plugin’s indexed-lexical limit — MAX_INDEXED_LEXICAL_BYTES, 1 MiB, defined in waratah_storage/src/text_index.rs — could never become a valid document. Rather than fail a transport error mid-frame or silently skip the document (the silently-missing-candidate state), the limit is enforced fail-closed at three points:

  • The compute write path rejects any document whose lexical exceeds the limit after the insert’s registry/blob RPCs, but BEFORE the text frames and the three axis writes (waratah_compute/src/fanout.rs, WriteFanout::insert_quads_rpc). The whole insert errors, naming the limit and the escape; no axis write happens, and the oversized string at worst sits in the registry dictionary as a harmless phantom entry.

  • The O partition re-checks the same bound in apply_text (waratah_partition/src/lib.rs) — the partition is the authority, so a misbehaving client cannot land an unindexable document.

  • Both rebuild paths (the waratah text rebuild-index CLI and the startup driver, waratah_text/src/rebuild.rs) skip such terms, count them as oversized, and REFUSE to stamp the epoch while any term lacks its document — the index stays untrusted and the walk retries on the next startup, exactly like unresolved registry misses.

The refusal is deliberate: with a trusted index, a missing document is a dropped candidate for both text:query and the string-function rewrites. Fail-closed keeps the trust invariant honest at the cost of write availability.

The 1 MiB number is deliberately the string registry’s MAX_REGISTERED_STRING_BYTES (waratah_registry/src/lib.rs): on a clustered store, RegisterStrings precedes the text document write in the insert path, so the registry rejects these strings first — plugin on or off — and this guard only binds on in-process paths (waratah standalone, import --offline), where the registry performs no length check. The offline import carries the same guard before its per-chunk add_batch, so a document the repair walk could never reproduce cannot land on any route. A store that must hold literals above 1 MiB is therefore an in-process store with the text plugin disabled; string functions then answer exactly via the residual, at scan speed.