Skip to main content

waratah/
text.rs

1//! `waratah text` CLI: offline rebuild and status of the O-axis text index.
2//!
3//! The rebuild shell mirrors `waratah geo rebuild-index`: open the O store
4//! and registry in-process (the walk needs registry lexicals the partition
5//! cannot resolve), wipe, walk the six string-literal head prefixes, post
6//! documents, stamp `epoch = max commit_ts under the same prefixes`. The
7//! sidecar fingerprint comes from the resolved text config, so a config
8//! change lands as a fresh build rather than a silent mismatch.
9
10use std::path::Path;
11
12use waratah_storage::{
13    EncodedTerm, IndexPermutation, MAIN_REPOSITORY_ID, Registry, RocksDbTuning, SnapshotId,
14    registry_data_dir,
15};
16use waratah_text::TextPluginConfig;
17
18use crate::config_dir;
19use crate::error::DevError;
20use crate::import::open_hexastore;
21use waratah_storage::hexastore_data_dir;
22
23/// Status line printer (matches the geo CLI's plain format).
24fn status(message: impl std::fmt::Display) {
25    println!("text: {message}");
26}
27
28/// Print the predicate universe the resolved config indexes.
29///
30/// The sidecar carries only the fingerprint, which encodes the list as one
31/// long opaque value; the operator-facing answer to "what is in this index" is
32/// the configured list itself. `trusted` in the status line already says
33/// whether the stored fingerprint matches this config.
34fn status_predicates(config: &TextPluginConfig) {
35    let predicates = config.normalized_predicates();
36    if predicates.is_empty() {
37        status("predicates: every predicate (`predicates = []`)");
38        return;
39    }
40    status(format!("predicates: {} configured", predicates.len()));
41    for predicate in predicates {
42        status(format!("  {predicate}"));
43    }
44}
45
46/// Resolve the text config for a CLI invocation (its own `--config-dir`).
47fn resolve_config(config_dir: Option<&Path>) -> Result<TextPluginConfig, DevError> {
48    let file = config_dir::find(config_dir, config_dir::files::TEXT);
49    match file {
50        Some(path) => {
51            let text = std::fs::read_to_string(&path)?;
52            let config = TextPluginConfig::from_toml(&text)
53                .map_err(|error| DevError::Backend(format!("invalid text config: {error}")))?;
54            status(format!("config {}", path.display()));
55            Ok(config)
56        }
57        None => Ok(TextPluginConfig {
58            // The CLI without a config file enables the defaults: an
59            // operator running `waratah text rebuild-index` is explicitly
60            // asking for the index.
61            enabled: true,
62            ..TextPluginConfig::default()
63        }),
64    }
65}
66
67/// Fail fast when an existing text index cannot be adopted by this build.
68///
69/// The index is derived data, but this build never rebuilds it automatically:
70/// its documents precede every axis write, so a schema/fingerprint mismatch
71/// would not surface as a query error — it would fail **every insert** at the
72/// partition, long after startup looked healthy. The check is read-only and
73/// lock-free (it reads the Tantivy meta and the sidecar), so it runs before
74/// the cluster or an import opens the store. A store with no index is left to
75/// the normal build path; a `--with-text`-disabled process is not checked.
76pub fn preflight_index(config: &TextPluginConfig, data_dir: &Path) -> Result<(), DevError> {
77    if !config.enabled {
78        return Ok(());
79    }
80    let o_dir = hexastore_data_dir(
81        data_dir,
82        MAIN_REPOSITORY_ID,
83        waratah_storage::PartitionAxis::O,
84    );
85    let Some(dir) = waratah_storage::text_index_dir_beside(&o_dir) else {
86        return Ok(());
87    };
88    waratah_text_index::TextIndex::check_adoptable(&dir, &config.fingerprint()).map_err(|reason| {
89        DevError::Backend(format!(
90            "{reason}. This build does not rebuild the index automatically: stop the cluster \
91             and run `waratah text rebuild-index --data-dir <data-dir>` (it rebuilds from the \
92             hexastore), or remove the index directory and re-import"
93        ))
94    })
95}
96
97/// Offline rebuild: wipe, walk, post, stamp. Runs against a STOPPED data
98/// dir (the geo CLI's contract); the partition process must not be open on
99/// the same Tantivy directory.
100pub fn rebuild_offline(data_dir: &Path, config_dir: Option<&Path>) -> Result<(), DevError> {
101    let config = resolve_config(config_dir)?;
102    let o = open_hexastore(
103        hexastore_data_dir(
104            data_dir,
105            MAIN_REPOSITORY_ID,
106            waratah_storage::PartitionAxis::O,
107        ),
108        waratah_storage::PartitionAxis::O,
109        RocksDbTuning::default(),
110        true,
111    )?;
112    let registry = Registry::open_rocksdb(
113        registry_data_dir(data_dir, MAIN_REPOSITORY_ID),
114        RocksDbTuning::registry_node(),
115    )?;
116    let dir = o.text_index_dir().ok_or_else(|| {
117        DevError::Backend("the text index requires a RocksDB data dir".to_owned())
118    })?;
119    let options = waratah_text_index::TextIndexOptions::new(
120        config.analyzer.clone(),
121        config.seed_chars,
122        config.fingerprint(),
123    );
124    // Recreate on a fingerprint mismatch: `open_or_create` ADOPTS the stored
125    // sidecar, so a mismatched index would be wiped and re-stamped under its
126    // OLD fingerprint — the repair this command exists for (analyzer or
127    // seed_chars change) would still fail the trust check afterwards.
128    // Nothing is serving (the cluster is stopped), so deleting the directory
129    // is safe.
130    if let Some(meta) = waratah_text_index::meta::read_meta(&dir)
131        .map_err(|error| DevError::Backend(format!("text index sidecar read: {error}")))?
132        && meta.fingerprint != options.fingerprint
133    {
134        status(format!(
135            "sidecar fingerprint {} != requested {}; deleting the index directory",
136            meta.fingerprint, options.fingerprint
137        ));
138        std::fs::remove_dir_all(&dir)
139            .map_err(|error| DevError::Backend(format!("text index remove: {error}")))?;
140    }
141    let index = waratah_text_index::TextIndex::open_or_create(&dir, &options)
142        .map_err(|error| DevError::Backend(format!("text index open: {error}")))?;
143    index
144        .wipe()
145        .map_err(|error| DevError::Backend(format!("text index wipe: {error}")))?;
146    // Sketch collector for the population sketch (`waratah_stats::
147    // TextSeedSketch`), fed from the same documents the walk posts. A
148    // wipe ran above, so the finish below always builds FRESH — the
149    // sketch and the index cover exactly the same walk.
150    let mut seed_sketch = waratah_stats::TextSeedSketch::collector(config.seed_chars);
151
152    let prefixes = waratah_text::text_head_prefixes();
153    let allow = config.predicate_allowlist();
154    let started = std::time::Instant::now();
155    let mut report = waratah_text::RebuildReport::default();
156    let mut cursor: Option<EncodedTerm> = None;
157    loop {
158        let terms = o.scan_axis_head(
159            IndexPermutation::Opsg,
160            SnapshotId::latest(),
161            waratah_text::HEAD_PAGE,
162            cursor.as_ref(),
163            None,
164            &[],
165            false,
166            false,
167            &prefixes,
168        )?;
169        if terms.is_empty() {
170            break;
171        }
172        let hashes: Vec<waratah_storage::StrHash> =
173            terms.iter().flat_map(waratah_text::hashes_of).collect();
174        let resolved = if hashes.is_empty() {
175            Vec::new()
176        } else {
177            registry.lookup_many(&hashes)?
178        };
179        // Shared core with the startup driver (`assemble_batch`): document
180        // assembly and the indexed-lexical gate live in one place. The O-axis
181        // domain scan resolves the predicates that reference each object, so
182        // the document identity is `(predicate, literal)`.
183        let hits = o.scan_object_preds(
184            &terms,
185            SnapshotId::latest(),
186            0,
187            None,
188            None,
189            None,
190            &[],
191            false,
192        )?;
193        let predicates_by_object = waratah_text::group_predicates(&terms, &hits);
194        let batch =
195            waratah_text::assemble_batch(&terms, &predicates_by_object, &resolved, allow.as_ref());
196        report.terms_walked += terms.len() as u64;
197        report.docs_posted += batch.docs.len() as u64;
198        report.unresolved += batch.unresolved;
199        report.oversized += batch.oversized;
200        if !batch.docs.is_empty() {
201            // Feed the sketch from the same documents (its coverage must
202            // equal the index's).
203            for doc in &batch.docs {
204                seed_sketch.record(&doc.lexical);
205            }
206            index
207                .add_batch(&batch.docs)
208                .map_err(|error| DevError::Backend(format!("text index add_batch: {error}")))?;
209        }
210        cursor = terms.last().cloned();
211    }
212    // A walk that skipped terms WITHOUT documents must NOT stamp: a visible
213    // row without its document is the silently-missing-candidate state —
214    // both query forms would drop it from a TRUSTED index. That covers
215    // registry misses (unresolved) and lexicals above the indexed-lexical
216    // limit (oversized). Leave the epoch unset so the next rebuild retries
217    // the walk (the registry may have the missing lexicals by then).
218    if !report.is_complete() {
219        status(format!(
220            "rebuild INCOMPLETE: {} lexical(s) unresolved in the registry, \
221             {} above the indexed-lexical limit; epoch NOT stamped — the index \
222             stays untrusted and the next rebuild retries the walk",
223            report.unresolved, report.oversized
224        ));
225        return Ok(());
226    }
227    // Epoch: the max version ts under the same prefixes — the walk saw
228    // every visible version of every string literal, and the epoch only
229    // needs to cover the store the walk read.
230    let epoch = o.max_commit_ts_under_prefixes(IndexPermutation::Opsg, &prefixes)?;
231    index
232        .stamp(epoch)
233        .map_err(|error| DevError::Backend(format!("text epoch stamp: {error}")))?;
234    // The seed-population sketch: fresh build (the wipe above removed any
235    // prior sidecar), stamped with the SAME epoch as the index — the
236    // planner prices from it only while the epochs match. Persisted as the
237    // sidecar sibling the partition's lease path writes; a write failure
238    // degrades to the unpriced path, so it must not fail the rebuild.
239    let mut sketch = seed_sketch;
240    sketch.epoch = epoch;
241    let mut sketch_bytes = Vec::new();
242    sketch.encode_body(&mut sketch_bytes);
243    if let Err(error) = std::fs::write(dir.join(waratah_text_index::SKETCH_FILE), sketch_bytes) {
244        status(format!(
245            "seed sketch write failed ({error}); the planner keeps its unpriced estimate \
246             until the next rebuild"
247        ));
248    }
249    status(format!(
250        "rebuild done: {} term(s) walked, {} document(s) posted, \
251         {} unresolved, {} oversized, epoch {epoch}, {} doc(s), {} ms",
252        report.terms_walked,
253        report.docs_posted,
254        report.unresolved,
255        report.oversized,
256        index.doc_count(),
257        started.elapsed().as_millis()
258    ));
259    Ok(())
260}
261
262/// Read-only status: the sidecar's stored settings vs the resolved config,
263/// plus the live document count.
264pub fn status_offline(data_dir: &Path, config_dir: Option<&Path>) -> Result<(), DevError> {
265    let config = resolve_config(config_dir)?;
266    let o = open_hexastore(
267        hexastore_data_dir(
268            data_dir,
269            MAIN_REPOSITORY_ID,
270            waratah_storage::PartitionAxis::O,
271        ),
272        waratah_storage::PartitionAxis::O,
273        RocksDbTuning::default(),
274        false,
275    )?;
276    let dir = o.text_index_dir().ok_or_else(|| {
277        DevError::Backend("the text index requires a RocksDB data dir".to_owned())
278    })?;
279    let meta = waratah_text_index::meta::read_meta(&dir)
280        .map_err(|error| DevError::Backend(format!("text index metadata: {error}")))?;
281    match meta {
282        None => {
283            status(format!(
284                "no index at {} (enable the plugin and start, or run `waratah text rebuild-index`)",
285                dir.display()
286            ));
287            status_predicates(&config);
288        }
289        Some(meta) => {
290            let trusted =
291                meta.trusted_epoch().is_some() && config.fingerprint() == meta.fingerprint;
292            status(format!(
293                "{}: analyzer {}, seed_chars {}, fingerprint {}, epoch {:?}, trusted {trusted}",
294                dir.display(),
295                meta.analyzer,
296                meta.seed_chars,
297                meta.fingerprint,
298                meta.trusted_epoch()
299            ));
300            status_predicates(&config);
301            // Live count: READ-ONLY open — no writer lock, nothing created.
302            // The count comes from the committed segments on disk; unlike
303            // `open_or_create` this neither materializes an index where the
304            // Tantivy meta is missing nor contends with a live writer.
305            match waratah_text_index::TextIndex::open_doc_count_read_only(&dir) {
306                Ok(count) => status(format!("live documents: {count}")),
307                Err(error) => status(format!("index unopenable: {error}")),
308            }
309        }
310    }
311    Ok(())
312}