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 best-practice 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 string literals under the default predicate allowlist (or every predicate, with predicates = []) 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 (predicate, literal) pair — the document identity includes the predicate, and subjects are never stored (a per-subject document would be a graph copy whose size is the text-triple count). The same literal under two predicates is two documents (waratah_text_index/src/schema.rs):

Field Tokenizer Content

term

bytes, fast

The encoded EncodedTerm; the candidate payload.

key

bytes, indexed

The (predicate, literal) identity, u32(predicate_len) ‖ predicate ‖ literal. add_batch deletes by it before adding, so a re-write upserts instead of duplicating.

predicate

bytes, indexed

The encoded predicate term; the query-side scoping dimension.

text

the configured analyzer

The full lexical, for text:query. Fieldnorms are off (the collector never scores).

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.

Writes are an upsert by key: delete_term(key) then add_document, one commit per batch. Tantivy’s delete is an opstamp tombstone that removes both the previously committed document and one added earlier in the same commit, so the last write wins and the index converges to one document per pair across chunks, restarts, and online inserts. The candidate drain dedups by term ordinal and streams the dictionary once (sorted), rather than seeking the dictionary per matching document.

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 predicates allowlist filters at write time, before the registry or axis work, so a literal under an excluded predicate never reaches the index. Absent applies the built-in DEFAULT_TEXT_PREDICATES list (RDFS/SKOS/DCTerms/Schema.org text, keywords, FOAF names); an explicit [] indexes every predicate. It is part of the fingerprint; changing it requires a rebuild.

The allowlist also defines the query-time universe, and every rewrite checks it. TextPlannerPlugin::text_index_applies walks the plan and asks for coverage evidence: at least one scan must bind the searched variable in an OBJECT slot under an allowed constant predicate, no object-slot scan may use any other (or a variable) predicate, and no property-path object, VALUES column, or BIND may bind the same variable — the candidate set is only a superset over the indexed universe, and a value from outside it survives only if a road happens to evaluate it locally, which the plan does not guarantee. Without that evidence (a variable bound only by VALUES/BIND, or only in a subject slot) the candidate injection is declined and the exact residual answers. text:query is scoped by the index by definition: its literal form searches the indexed universe (no fallback), and its subject form is a plan error when it names an unindexed predicate. The standard string functions cannot be redefined by configuration, so they keep exact SPARQL semantics and fall back rather than return a short answer.

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 rewrite strips the conjunct and joins a childless text_subjects op with the inner plan on the subject variable. The op carries the named predicate set, the query and the branch’s applied graph scope; the O partition searches the index once for the whole set (a single OR over the stored predicate terms, not one search per predicate), walks the OPSG rows of every matched literal at the query snapshot, and streams DISTINCT (subject, graph) rows. Compute never sees a literal carrier, and the join is a semi-join by construction: a subject with several matching values appears once.

One op is minted, in the window the FILTER’s own group names. A bare triple/path sibling at that level supplies the window — the dataset default wins over a GRAPH-block sibling, so a group that mixes a GRAPH pattern with a bare pattern resolves in the default graph. A single GRAPH block’s window is kept: lowering erases a fixed graph boundary, and a variable graph keeps its boundary node only when the variable is used inside, so a filter written outside a single block is indistinguishable from one written inside it. With no such pattern the graph is unbound and the resolve matches in every graph. A graph column is emitted only when the window binds a graph variable: then each solution’s graph is that one value and the join reconciles it; a ground window needs no column. GRAPH ?s { … } with text:query(?s, …) on the same variable is one variable taking one value: the op emits the subject alone and the resolve keeps only rows whose subject equals their graph. The resolve reads at the query snapshot, so visibility is the store’s — including the graph scope copied from the sibling scan (above).

The semi-join is built once per query. The planner marks the text:query conjunct as a candidate producer (TextPlannerPlugin::pins_through_optimizer), so the FILTER is pinned across the Sparopt roundtrip and restored at the lowest point that still covers the subject variable. Without the pin, the optimizer’s filter pushdown copies the FILTER into both inputs of every inner join that binds the subject and into every UNION arm, which turns one semi-join into one per binding site — on the t12-facets shape, nine copies and nine scans of the searched predicates' whole literal domain. The mechanism is described in the optimization catalog.

A subject or literal bound by a single-row VALUES column or a ground BIND is still rewritten: TextPlannerPlugin::keeps_variable_when_ground keeps the variable through the lowering’s ground-value substitution, which would otherwise fold the value into the call and leave no variable to join on. The plan then reads only that value — the subject resolve is pinned to that subject (the resolve still runs, memoized per window) or, for literal mode, a pinned membership test with no candidate drain — instead of failing with the unsupported-form error.

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, predicate allowlist). 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.

An existing index this build cannot adopt refuses startup and import outright, before the store is opened: a schema or fingerprint mismatch (TextIndex::check_adoptable — read-only, no writer lock) would not just fail text:query, it would fail every insert, because the text documents precede the axis writes. The index is never rebuilt automatically; the operator runs waratah text rebuild-index on a stopped data dir (it deletes a mismatched directory and rebuilds from the hexastore) or removes the directory and re-imports. A store with no index is untouched: the normal build path still creates it.

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 from the request’s mode and what the op carries, mirroring the geo executor. The op is purely value-typed: its variable is the literal variable — literal-mode text:query, or the string functions' candidate injection — so pushed keys are always the literal values the decision is about.

  1. Pinned — the driver binds the output variable to exactly one ground term: a seed mode evaluates that value locally; literal mode drains and tests it against the index’s match set.

  2. Direct evaluation — pushed keys, deduped, priced small by the break-even: seed modes evaluate every key locally, no candidate scan RPC at all. Literal mode never takes this road.

  3. Semi-join — pushed keys: one candidate drain, then keep only the candidates in the key set. Literal mode’s keyed road.

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

Literal mode (Fts) answers from the index on every road. Under the predicate allowlist, "this value matches the query" is no longer the same question as "the index returns this value" — the value may sit under a predicate the index does not hold — so a local evaluation would make the answer depend on which road the cost model picked. Draining and filtering makes the answer the index’s match set, unaffected by cardinality estimates. The seed modes keep their exact conjunct in the residual, so a local evaluation is a sound superset and may answer in-process.

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.

The subject resolve

text_subjects has no local evaluation and no literal table: one TextSubjectScan returns the whole answer. The executor’s only work is the pushed-column semi-join — the request has no subject pre-filter, so a probe-side execution drains once and keeps the rows whose subject, or bound graph, is in the driver’s exact key set. The engine names the pushed column, so a push on the graph variable is never misread as subject keys. Requests whose graph is the searched subject (the subject_equals_graph shape) carry one column and the partition does the row filter; merge_default_graph cannot be combined with that shape (the merge removes the graph identity the equality test needs) and the partition rejects the pair.

The resolve is memoized per request window (QueryCaches::text_subjects, keyed on the whole request plus snapshot and text epoch) as a TextSubjectWindow: subjects and graphs are interned into the query TermDict and stored as sorted TermId columns, four bytes per id. A probe page then answers each pushed subject with a dictionary peek plus a binary search over the sorted ids, and walks that subject’s contiguous graph ids, instead of scanning every resolved row. The admission budget is counted in interned ids — 16,777,216 per entry and 26,214,400 total (64 MiB / 100 MiB at four bytes per id), halved for the graph-column shape — and the planner stamps the same limit into the cost model’s probe_memo_entry_rows, so a window the cost model prices as one resolve is exactly a window the memo admits. As with the candidate drain, every minted request carries limit: 0; a request that ever arms the guard ERRORS on exceeding it rather than truncating, and a stream error after partial pages is fatal — a partial subject set would silently drop rows, and the subject form has no residual to answer them.

Road selection

For a seed mode, 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). Literal mode skips the choice: it always drains.

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 through the same schema, analyzer registration, query builder, and collector the partition index uses. This evaluator is now the in-memory twin of the index for tests: the executor does not call it for a literal-mode request, because a pushed value’s text matching the query does not mean the index holds it (the predicate allowlist scopes the index’s universe). Literal mode drains instead.

The request’s per-drain limit is ignored on the local seed roads — it guards candidate materialization on the sweep road, while those roads' 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.