Skip to main content

waratah/
import.rs

1//! Bulk RDF import: online (RPC) or offline (in-process RocksDB).
2//!
3//! - default: spawn S/P/O + registry, stream chunks over gRPC, flush, optional compact
4//! - `--connect`: attach to a running cluster; do not spawn or kill children
5//! - `--offline`: in-process hexastore WriteBatch load with deferred registry
6//!   SST runs (`RegistryStaging`); always flush + compact. The load open
7//!   attaches the stats collectors, so the flush writes `waratah.stats`
8//!   (including the temporal histogram on O). The end compact merges L0 and
9//!   skips the bottommost rewrite. A chunk's run is renamed into place only when
10//!   its SST write and hexastore apply both succeed. A write error ingests the
11//!   renamed runs and skips compaction; a killed import is recovered the next
12//!   time the registry opens. An import into an empty O store stamps the geo
13//!   and temporal index epochs to the import `commit_ts`.
14//!
15//! A parser thread fills a `sync_channel(1)` of [`waratah_compute::INSERT_QUAD_CHUNK`]
16//! quads so the next parse overlaps the current write.
17//!
18//! Online imports with the text plugin enabled establish trust BEFORE any
19//! batch: an untrusted index is pre-built against the running cluster
20//! (covering the store's pre-existing rows), a fingerprint mismatch
21//! refuses, and the bracket's finish stamps only when it began against a
22//! trusted index — an import's documents cover only the imported rows, so
23//! stamping over an untrusted begin would declare trust over the
24//! pre-existing rows the index never saw.
25
26use std::collections::BTreeMap;
27use std::fs;
28use std::path::{Path, PathBuf};
29use std::thread;
30use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
31
32#[cfg(test)]
33use std::cell::Cell;
34
35use waratah_compute::{
36    ComputeNode, HexastoreAdmin, HexastoreGeo, RdfParseOptions, RetryPolicy, join_rdf_parser,
37    spawn_rdf_parser,
38};
39use waratah_router::ClusterConfig;
40use waratah_stats::{
41    attach_catalog_stats_collector, attach_geo_stats_collector, attach_stats_collector,
42    attach_temporal_stats_collector,
43};
44use waratah_storage::{
45    CommitTs, EncodedTriplePattern, GByteFilter, HexastoreVersion, IndexPermutation,
46    MAIN_REPOSITORY_ID, PartitionAxis, Quad, REGISTRY_BLOCK_SIZE_BYTES, Registry,
47    RocksDbOptionsHooks, RocksDbTuning, SnapshotId, Storage, StorageOp, StrHash, VisibilityLabel,
48    catalog_graphs_from_versions, delete_partial_registry_sst_runs, encode_quad,
49    finished_registry_sst_runs, hexastore_data_dir, iterator_readahead_bytes,
50    prepare_hexastore_puts, registry_data_dir, registry_entries_for_quad, registry_sst_staging_dir,
51};
52
53// Test hook: `write_offline_chunk` returns before touching batch N
54// (`staging.runs.len()`). `None` disables it.
55#[cfg(test)]
56thread_local! {
57    static FAIL_BEFORE_OFFLINE_BATCH: Cell<Option<u64>> = const { Cell::new(None) };
58}
59
60use crate::dev::{Backend, DevOptions, SpawnedCluster};
61use crate::error::DevError;
62
63/// How often to print insert progress during a long import.
64const PROGRESS_INTERVAL: Duration = Duration::from_secs(30);
65
66/// Print an importer status line prefixed with the current UTC timestamp.
67macro_rules! status {
68    ($($arg:tt)*) => {{
69        println!("[{}] {}", crate::import::now_stamp(), format_args!($($arg)*));
70    }};
71}
72pub(crate) use status;
73
74/// UTC `YYYY-MM-DDTHH:MM:SS.mmmZ` for status lines.
75pub(crate) fn now_stamp() -> String {
76    let dur = SystemTime::now()
77        .duration_since(UNIX_EPOCH)
78        .unwrap_or_default();
79    let secs = dur.as_secs();
80    let millis = dur.subsec_millis();
81    let days = (secs / 86_400) as i64;
82    let rem = secs % 86_400;
83    let hour = rem / 3_600;
84    let min = (rem % 3_600) / 60;
85    let sec = rem % 60;
86    let (year, month, day) = civil_from_unix_days(days);
87    format!("{year:04}-{month:02}-{day:02}T{hour:02}:{min:02}:{sec:02}.{millis:03}Z")
88}
89
90/// Gregorian date for `days` since 1970-01-01 (Howard Hinnant `civil_from_days`).
91fn civil_from_unix_days(z: i64) -> (i32, u32, u32) {
92    let z = z + 719_468;
93    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
94    let doe = (z - era * 146_097) as u64;
95    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
96    let y = yoe as i64 + era * 400;
97    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
98    let mp = (5 * doy + 2) / 153;
99    let d = doy - (153 * mp + 2) / 5 + 1;
100    let m = if mp < 10 { mp + 3 } else { mp - 9 };
101    let y = if m <= 2 { y + 1 } else { y };
102    (y as i32, m as u32, d as u32)
103}
104
105/// Options for [`run`].
106pub struct ImportOptions {
107    /// Addresses of all five processes (online spawn / `--connect`).
108    pub config: ClusterConfig,
109    /// RocksDB parent directory. Required for spawn and `--offline`; ignored with `--connect`.
110    pub data_dir: Option<PathBuf>,
111    /// Directory holding `waratah-partition` and `waratah-registry`.
112    pub bin_dir: PathBuf,
113    /// RDF file to load (optionally `.gz`).
114    pub file: PathBuf,
115    /// Commit timestamp applied to every imported quad.
116    pub commit_ts: CommitTs,
117    /// Online: compact once after the final flush. Offline always compacts.
118    pub compact: bool,
119    /// In-process RocksDB load (no gRPC).
120    pub offline: bool,
121    /// Attach to a running cluster; do not spawn or kill children.
122    pub connect: bool,
123    /// Skip WAL on the offline ingest open (`--disable-wal`).
124    pub disable_wal: bool,
125    /// Stub: SST file ingest is not implemented.
126    pub direct_sst: bool,
127    /// Text plugin config (enabled = documents flow and the epoch stamps).
128    pub text_config: waratah_text::TextPluginConfig,
129}
130
131/// Spawn, connect, or load offline depending on [`ImportOptions`].
132pub async fn run(options: ImportOptions) -> Result<(), DevError> {
133    if options.direct_sst {
134        return Err(DevError::DirectSstNotImplemented);
135    }
136    if options.offline {
137        run_offline(&options)
138    } else if options.connect {
139        run_connect(&options).await
140    } else {
141        run_spawn(options).await
142    }
143}
144
145/// Online import text bracket: create/open the O partition's index with the
146/// The O partition's Describe — where the text-index trust covariates live.
147async fn describe_text(
148    compute: &ComputeNode,
149) -> Result<waratah_compute::HexastoreDescribe, DevError> {
150    compute
151        .queries()
152        .hexastore()
153        .describe(PartitionAxis::O)
154        .await
155        .map_err(|status| DevError::Backend(format!("text index describe: {status}")))
156}
157
158/// The trust rule the shells use: a stamped epoch AND the O partition's
159/// fingerprint matching this config, strictly.
160fn describe_is_trusted(describe: &waratah_compute::HexastoreDescribe, fingerprint: &str) -> bool {
161    describe.text_index_epoch.is_some() && describe.text_index_fingerprint == fingerprint
162}
163
164/// Ensure the running cluster's text index reads TRUSTED before an online
165/// import loads any data.
166///
167/// An import whose bracket stamps an epoch over documents covering only its
168/// own rows leaves every PRE-EXISTING literal silently missing from a
169/// TRUSTED index — the trusted-but-incomplete state the offline import's
170/// whole-store rule exists to prevent. Trusted → nothing to do. Untrusted →
171/// pre-build against the running cluster first (additive: the store's
172/// existing rows are exactly what the walk must cover). A fingerprint
173/// mismatch cannot be repaired live (re-analysis is an offline operation);
174/// the rebuild's begin rejects it and the error surfaces with the repair
175/// hint. A concurrent driver's lease is bounded-waited.
176async fn ensure_trusted_text_index(
177    compute: &ComputeNode,
178    config: &waratah_text::TextPluginConfig,
179) -> Result<(), DevError> {
180    let fingerprint = config.fingerprint();
181    if describe_is_trusted(&describe_text(compute).await?, &fingerprint) {
182        return Ok(());
183    }
184    status!("no trusted text index on the running database; building it before the load");
185    let allow = config.predicate_allowlist();
186    match waratah_text::drive_text_rebuild(
187        compute.queries().hexastore(),
188        compute.queries().registry(),
189        &config.analyzer,
190        config.seed_chars as u32,
191        &fingerprint,
192        allow.as_ref(),
193        // Additive: the store's existing rows are exactly what the walk
194        // must cover; a wipe would delete nothing useful and is not the
195        // import's decision to make.
196        false,
197    )
198    .await
199    {
200        Ok(Some(report)) if report.is_complete() => {
201            status!(
202                "text index pre-built and stamped before load ({}); restart the cluster \
203                 for text:query",
204                report.summary()
205            );
206            Ok(())
207        }
208        Ok(Some(report)) => Err(DevError::Backend(format!(
209            "the text-index pre-build left {} lexical(s) unresolved and {} above the \
210             indexed-lexical limit; the epoch was NOT stamped — run \
211             `waratah text rebuild-index` offline and retry the import",
212            report.unresolved, report.oversized
213        ))),
214        // Another driver holds the lease: bounded wait, then re-probe — the
215        // other driver's stamp (when its walk completes) establishes the
216        // same trust this import needs.
217        Ok(None) => match lease_wait_until_trusted(compute, &fingerprint).await? {
218            Some(()) => Ok(()),
219            None => Err(DevError::Backend(
220                "a concurrent text-index rebuild held the lease throughout the wait; \
221                 retry the import once it finishes"
222                    .to_owned(),
223            )),
224        },
225        Err(error) => Err(DevError::Backend(format!(
226            "the text-index pre-build failed: {error}"
227        ))),
228    }
229}
230
231/// Bounded wait for a concurrent rebuild's lease to end and its stamp to
232/// land: poll the O Describe every 5 s for up to 60 s. `Some(())` when the
233/// index reads trusted; `None` when the wait ran out.
234async fn lease_wait_until_trusted(
235    compute: &ComputeNode,
236    fingerprint: &str,
237) -> Result<Option<()>, DevError> {
238    const POLL: Duration = Duration::from_secs(5);
239    const ROUNDS: usize = 12;
240    for _ in 0..ROUNDS {
241        tokio::time::sleep(POLL).await;
242        if describe_is_trusted(&describe_text(compute).await?, fingerprint) {
243            return Ok(Some(()));
244        }
245    }
246    Ok(None)
247}
248
249/// One online import's text-index bracket: the rebuild lease token plus the
250/// trust snapshot the stamp gate needs.
251struct TextImportBracket {
252    lease_token: u64,
253    /// Whether the index read TRUSTED (stamped epoch + matching
254    /// fingerprint) when the bracket began. Only then may the finish stamp:
255    /// a begin against an untrusted index means the index does not cover
256    /// the store's PRE-EXISTING rows, and stamping after the load would
257    /// declare trust over exactly those rows — the trusted-but-incomplete
258    /// state (the offline import's whole-store rule, same hole).
259    trusted_at_begin: bool,
260    /// The lease-renewal keepalive task. Held so the bracket can stop it at
261    /// close: a detached task would keep ticking until its next renewal
262    /// fails against the released lease — up to one full interval past the
263    /// import.
264    keepalive: tokio::task::AbortHandle,
265}
266
267/// Take the online import's text rebuild lease (`waratah_text`'s import
268/// config; fingerprint-checked against any existing index by the
269/// partition's begin) so `PutTextIndex` frames have somewhere to land.
270///
271/// Returns the bracket; `None` when another driver already holds the lease
272/// (the import still loads — puts are only fenced during a WIPE lease —
273/// but the stamp must then be left to that driver). A no-op when the
274/// plugin is disabled.
275///
276/// The lease is renewed on a background task for the bracket's whole life:
277/// a large import can outlive the partition's one-hour lease deadline, and
278/// an expired lease means finish is rejected and a stale takeover may wipe
279/// under the import.
280async fn bracket_online_text_import(
281    compute: &ComputeNode,
282    config: &waratah_text::TextPluginConfig,
283) -> Result<Option<TextImportBracket>, DevError> {
284    if !config.enabled {
285        return Ok(None);
286    }
287    // The stamp gate's trust snapshot, taken BEFORE the load against the
288    // index as it stands. `ensure_trusted_text_index` normally makes this
289    // true before the bracket runs; the gate is the backstop that keeps
290    // the forbidden state unreachable even if a future path skips the
291    // ensure.
292    let trusted_at_begin =
293        describe_is_trusted(&describe_text(compute).await?, &config.fingerprint());
294    let hexastore = compute.queries().hexastore();
295    let (_started, _already, lease_token) = hexastore
296        .rebuild_text_index(
297            &config.analyzer,
298            config.seed_chars as u32,
299            &config.fingerprint(),
300            // Import writes documents before rows; a pre-existing index keeps
301            // them (wipe would only make sense when nothing is serving).
302            false,
303        )
304        .await
305        .map_err(|status| DevError::Backend(format!("text index begin: {status}")))?;
306    if lease_token == 0 {
307        return Ok(None);
308    }
309    // Keepalive well under the partition's one-hour lease: a renewal every
310    // five minutes keeps the deadline ahead of a multi-hour import. The
311    // abort handle rides the bracket so close_online_text_import stops the
312    // task at the finish — a detached task would keep ticking until its
313    // next renewal no longer matches the released lease, up to one full
314    // interval past the import.
315    let renews = compute.queries().hexastore().clone();
316    let keepalive = tokio::spawn(async move {
317        let mut interval = tokio::time::interval(std::time::Duration::from_secs(300));
318        interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
319        interval.tick().await; // the immediate first tick: skip it
320        loop {
321            interval.tick().await;
322            if renews.renew_text_rebuild_lease(lease_token).await.is_err() {
323                // The lease was lost (expired anyway, or taken over): stop
324                // renewing; the finish will be rejected and the import's
325                // stamp is the other driver's business now.
326                break;
327            }
328        }
329    })
330    .abort_handle();
331    status!("text index lease taken (token {lease_token}), keepalive running");
332    Ok(Some(TextImportBracket {
333        lease_token,
334        trusted_at_begin,
335        keepalive,
336    }))
337}
338
339/// Release the bracket ([`bracket_online_text_import`]). Stamps the epoch
340/// only when the load succeeded AND the index read trusted at begin: a
341/// begin against an untrusted index plus this load's documents is exactly
342/// a partial index, and stamping it would declare trust over the
343/// pre-existing rows the index never saw (the trusted-but-incomplete
344/// state). Untrusted → release without stamping; the next startup build
345/// owns the epoch. A FAILED import always releases without stamping — the
346/// index must not read trusted over an import that did not complete.
347async fn close_online_text_import(
348    compute: &ComputeNode,
349    bracket: Option<TextImportBracket>,
350    load_succeeded: bool,
351) -> Result<(), DevError> {
352    let Some(bracket) = bracket else {
353        return Ok(());
354    };
355    // Stop the keepalive BEFORE the finish: the finish carries the token
356    // itself and needs no renewal, and an aborted task must not fire after
357    // the lease is released (the failure path below still ends the task —
358    // the lease is gone either way).
359    bracket.keepalive.abort();
360    let stamp = load_succeeded && bracket.trusted_at_begin;
361    let hexastore = compute.queries().hexastore();
362    let epoch = hexastore
363        .finish_text_index_rebuild(bracket.lease_token, stamp)
364        .await
365        .map_err(|status| DevError::Backend(format!("text index finish: {status}")))?;
366    if stamp {
367        status!("stamped text index epoch at {epoch}");
368    } else {
369        status!(
370            "text index lease released without stamping — the index was not trusted \
371             when the import began; the next startup build owns the epoch"
372        );
373    }
374    Ok(())
375}
376
377async fn run_spawn(options: ImportOptions) -> Result<(), DevError> {
378    let data_dir = options
379        .data_dir
380        .as_ref()
381        .expect("clap requires --data-dir unless --connect");
382    fs::create_dir_all(data_dir)?;
383
384    let dev = DevOptions {
385        config: options.config.clone(),
386        backend: Backend::RocksDb(data_dir.clone()),
387        bin_dir: options.bin_dir.clone(),
388        load_demo: false,
389        query: None,
390        http: None,
391        debug: false,
392        standalone: false,
393        describe_mode: waratah_compute::DescribeMode::Star,
394        default_union: false,
395        seat_by_total_cost: false,
396        force_semi: false,
397        eager_scan_filter: true,
398        strict_sparql: false,
399        ingest_dir: PathBuf::from("ingest"),
400        queries_dir: None,
401        spill_dir: None,
402        notebooks: None,
403        ai: None,
404        ready_file: None,
405        debug_file: None,
406        pidfile: false,
407        text_config: (options
408            .text_config
409            .enabled
410            .then(|| options.text_config.clone())),
411    };
412    let mut cluster = SpawnedCluster::spawn(&dev)?;
413    let compute = ComputeNode::connect(&dev.config, RetryPolicy::default_dev()).await?;
414
415    status!(
416        "importing {} into {} (commit_ts={})",
417        options.file.display(),
418        data_dir.display(),
419        options.commit_ts.0
420    );
421
422    let text_enabled = options.text_config.enabled;
423    if text_enabled {
424        // Before any batch: an untrusted index plus this load's documents
425        // would be a partial index — establish trust first (pre-build) or
426        // refuse (mismatch / persistent lease contention).
427        ensure_trusted_text_index(&compute, &options.text_config).await?;
428    }
429    let lease = if text_enabled {
430        bracket_online_text_import(&compute, &options.text_config).await?
431    } else {
432        None
433    };
434    let loaded = load_online(&compute, &options.file, options.commit_ts).await;
435    // The bracket closes on success AND failure. A failed import releases
436    // the lease WITHOUT stamping — the index must not read trusted over an
437    // import that did not complete; the next import or startup build
438    // retries the walk.
439    let loaded = match loaded {
440        Ok(loaded) => {
441            close_online_text_import(&compute, lease, true).await?;
442            loaded
443        }
444        Err(error) => {
445            let _ = close_online_text_import(&compute, lease, false).await;
446            return Err(error);
447        }
448    };
449    status!(
450        "loaded {} quads ({} registry entries) in {} batch(es)",
451        loaded.quads,
452        loaded.registered,
453        loaded.batches
454    );
455    report_spike_reductions(loaded.spike_reductions);
456
457    compute.flush_memtables().await?;
458    status!("flushed memtables on S/P/O and registry");
459
460    if options.compact {
461        compact_online(&compute).await?;
462    }
463
464    cluster.shutdown();
465    Ok(())
466}
467
468async fn run_connect(options: &ImportOptions) -> Result<(), DevError> {
469    let compute = ComputeNode::connect(&options.config, RetryPolicy::default_dev()).await?;
470
471    status!(
472        "importing {} into running cluster (commit_ts={})",
473        options.file.display(),
474        options.commit_ts.0
475    );
476
477    let text_enabled = options.text_config.enabled;
478    if text_enabled {
479        // Before any batch: an untrusted index plus this load's documents
480        // would be a partial index — establish trust first (pre-build) or
481        // refuse (mismatch / persistent lease contention).
482        ensure_trusted_text_index(&compute, &options.text_config).await?;
483    }
484    let lease = if text_enabled {
485        bracket_online_text_import(&compute, &options.text_config).await?
486    } else {
487        None
488    };
489    let loaded = load_online(&compute, &options.file, options.commit_ts).await;
490    // Same bracket discipline as `run_spawn`: release on failure without
491    // stamping.
492    let loaded = match loaded {
493        Ok(loaded) => {
494            close_online_text_import(&compute, lease, true).await?;
495            loaded
496        }
497        Err(error) => {
498            let _ = close_online_text_import(&compute, lease, false).await;
499            return Err(error);
500        }
501    };
502    status!(
503        "loaded {} quads ({} registry entries) in {} batch(es)",
504        loaded.quads,
505        loaded.registered,
506        loaded.batches
507    );
508    report_spike_reductions(loaded.spike_reductions);
509
510    compute.flush_memtables().await?;
511    status!("flushed memtables on S/P/O and registry");
512
513    if options.compact {
514        compact_online(&compute).await?;
515    }
516    Ok(())
517}
518
519fn run_offline(options: &ImportOptions) -> Result<(), DevError> {
520    let data_dir = options
521        .data_dir
522        .as_ref()
523        .expect("clap requires --data-dir for --offline");
524    fs::create_dir_all(data_dir)?;
525
526    status!(
527        "importing {} into {} offline (commit_ts={}, disable_wal={})",
528        options.file.display(),
529        data_dir.display(),
530        options.commit_ts.0,
531        options.disable_wal
532    );
533
534    let mut stores = OfflineStores::open(data_dir, options.disable_wal)?;
535    // Offline text index over the O store's directory (created when missing).
536    // `open_or_create` ADOPTS an existing directory's stored config — it does
537    // not compare fingerprints, so a store whose index was built by other
538    // settings keeps that analysis and these documents are simply added
539    // under it. That index stays UNTRUSTED for compute (its fingerprint no
540    // longer matches the plugin config, and a non-empty store is never
541    // re-stamped here): `waratah text rebuild-index` recreates it with the
542    // requested config, which is the settings-change repair.
543    if options.text_config.enabled {
544        let dir = stores
545            .o
546            .text_index_dir()
547            .ok_or_else(|| DevError::Backend("offline import requires a data dir".to_owned()))?;
548        let opts = waratah_text_index::TextIndexOptions::new(
549            options.text_config.analyzer.clone(),
550            options.text_config.seed_chars,
551            options.text_config.fingerprint(),
552        );
553        let index =
554            waratah_text_index::TextIndex::open_or_create(&dir, &opts).map_err(|error| {
555                DevError::Backend(format!("text index open at {}: {error}", dir.display()))
556            })?;
557        stores.text = Some(index);
558    }
559    // Captured before any quad is written. A later non-empty store must not
560    // be treated as "this import built the indexes from scratch".
561    let index_epochs = index_epochs_to_stamp(&stores.o)?;
562    // Open already ingested finished runs left by a killed import. `create`
563    // refuses to delete any `run-*.sst` that ingest did not take.
564    let mut staging = RegistryStaging::create(data_dir)?;
565    let loaded = match load_offline(&mut stores, &mut staging, &options.file, options.commit_ts) {
566        Ok(loaded) => loaded,
567        Err(err) => return Err(abort_offline_import(&stores, &staging, err)),
568    };
569    status!(
570        "loaded {} quads ({} registry entries) in {} batch(es)",
571        loaded.quads,
572        loaded.registered,
573        loaded.batches
574    );
575    report_spike_reductions(loaded.spike_reductions);
576
577    stores.flush_all()?;
578    status!("flushed memtables on S/P/O and registry");
579
580    drop((stores.s, stores.p, stores.o));
581    // The hexastore compactions, the registry bulk ingest, and the blob
582    // index compaction touch separate RocksDB directories, so they run
583    // concurrently. All finish before this scope exits (scoping joins every
584    // thread), which is what preserves the "registry complete before the
585    // data dir is served" ordering at import granularity — nothing can read
586    // this data dir while the import holds it.
587    let registry = &stores.registry;
588    let staged_entries = staging.entries;
589    let staged_runs = staging.runs.len();
590    thread::scope(|scope| {
591        let hexastore = scope.spawn(|| compact_offline_hexastore(data_dir));
592        let registry_ingest = scope.spawn(move || staging.ingest(registry));
593        let blobs = scope.spawn(|| -> Result<(), DevError> {
594            stores.blobs_reg.compact_range()?;
595            Ok(())
596        });
597        let hexastore = join_compact(hexastore, "S/P/O")?;
598        let registry = join_compact(registry_ingest, "registry")?;
599        let blobs = join_compact(blobs, "blobs")?;
600        hexastore?;
601        registry?;
602        blobs
603    })?;
604    status!(
605        "ingested {} registry entries from {} SST run(s)",
606        staged_entries,
607        staged_runs
608    );
609    // After both tail threads succeed: a failed import leaves the epochs
610    // unset so the next startup still rebuilds from whatever landed.
611    if index_epochs.text
612        && let Some(index) = stores.text.as_ref()
613    {
614        index
615            .stamp(options.commit_ts.0)
616            .map_err(|error| DevError::Backend(format!("text epoch stamp: {error}")))?;
617        status!("stamped text index epoch at {}", options.commit_ts.0);
618    }
619    stamp_offline_index_epochs(data_dir, options.commit_ts, &index_epochs)?;
620    Ok(())
621}
622
623/// Flush finished chunks and ingest their renamed registry runs, then return
624/// `write_err`. Hexastore compaction and the epoch stamp are skipped: this
625/// import did not finish.
626///
627/// Flush comes first so `--disable-wal` does not drop the finished chunks'
628/// memtables when this function returns and the stores are closed. If the
629/// registry ingest fails, the renamed runs stay on disk and the next registry
630/// open tries again.
631fn abort_offline_import(
632    stores: &OfflineStores,
633    staging: &RegistryStaging,
634    write_err: DevError,
635) -> DevError {
636    status!("offline import failed; flushing finished chunks and ingesting renamed registry runs");
637    let flush_err = stores.flush_all().err();
638    let recover_err = staging.recover(&stores.registry).err();
639    match (flush_err, recover_err) {
640        (None, None) => {
641            status!("ingested finished registry SST runs; hexastore compaction skipped");
642            write_err
643        }
644        (Some(err), None) => DevError::OfflineImportCleanup {
645            write: write_err.to_string(),
646            during: "flushing finished hexastore chunks",
647            cleanup: err.to_string(),
648        },
649        (None, Some(err)) => DevError::OfflineImportCleanup {
650            write: write_err.to_string(),
651            during: "ingesting finished registry SST runs (left in place)",
652            cleanup: err.to_string(),
653        },
654        (Some(flush_err), Some(recover_err)) => DevError::OfflineImportCleanup {
655            write: write_err.to_string(),
656            during: "flushing finished chunks and ingesting registry SST runs (runs left in place)",
657            cleanup: format!("{flush_err}; {recover_err}"),
658        },
659    }
660}
661
662/// Which index epochs a successful offline import may stamp.
663///
664/// Both flags start false. [`index_epochs_to_stamp`] sets one only when the
665/// O store had no visible quad at open and that epoch is still unset.
666struct IndexEpochPlan {
667    geo: bool,
668    temporal: bool,
669    text: bool,
670}
671
672/// Decide whether this import may stamp the geo and temporal epochs.
673///
674/// The write plugins already append postings during the load. Startup
675/// rebuilds an index whose epoch is missing, which wipes those postings.
676/// Stamping is safe only when this import is the whole store: every quad,
677/// including every geometry and temporal literal, was written with the
678/// plugins on. An epoch that is already set is left alone — raising it
679/// would hide an index that older snapshots can still use. A store that
680/// already held triples keeps a missing epoch, so startup's auto-upgrade
681/// can still repair plugin-less literals from before this import.
682fn index_epochs_to_stamp(o: &Storage) -> Result<IndexEpochPlan, DevError> {
683    let empty = o.count_pattern_impl(
684        IndexPermutation::Opsg,
685        &EncodedTriplePattern::default(),
686        SnapshotId::latest(),
687        1,
688        GByteFilter::Unconstrained,
689        false,
690    )? == 0;
691    if !empty {
692        return Ok(IndexEpochPlan {
693            geo: false,
694            temporal: false,
695            text: false,
696        });
697    }
698    Ok(IndexEpochPlan {
699        geo: o.geo_index_epoch()?.is_none(),
700        temporal: o.temporal_index_epoch()?.is_none(),
701        text: true,
702    })
703}
704
705/// Stamp the epochs selected by [`index_epochs_to_stamp`] to `commit_ts`.
706///
707/// Reopens O after the compaction handle has been dropped. The value is the
708/// import `commit_ts` because that is the version on the postings just
709/// written: the planner trusts the index for snapshots at or after the epoch,
710/// which is when those postings become visible.
711fn stamp_offline_index_epochs(
712    data_dir: &Path,
713    commit_ts: CommitTs,
714    plan: &IndexEpochPlan,
715) -> Result<(), DevError> {
716    if !plan.geo && !plan.temporal {
717        return Ok(());
718    }
719    let o = open_hexastore(
720        hexastore_data_dir(data_dir, MAIN_REPOSITORY_ID, PartitionAxis::O),
721        PartitionAxis::O,
722        RocksDbTuning::bulk_ingest(false),
723        false,
724    )?;
725    if plan.geo {
726        o.set_geo_index_epoch(commit_ts.0)?;
727    }
728    if plan.temporal {
729        o.set_temporal_index_epoch(commit_ts.0)?;
730    }
731    let which = match (plan.geo, plan.temporal) {
732        (true, true) => "geo and temporal",
733        (true, false) => "geo",
734        (false, true) => "temporal",
735        (false, false) => unreachable!("checked above"),
736    };
737    status!("stamped {which} index epoch at {}", commit_ts.0);
738    Ok(())
739}
740
741/// Join a scoped compaction/ingest thread; a panic becomes [`DevError::OfflineWritePanic`].
742fn join_compact(
743    handle: thread::ScopedJoinHandle<'_, Result<(), DevError>>,
744    axis: &'static str,
745) -> Result<Result<(), DevError>, DevError> {
746    match handle.join() {
747        Ok(result) => Ok(result),
748        Err(_) => Err(DevError::OfflineWritePanic { axis }),
749    }
750}
751
752/// Unix milliseconds, or `1` if the clock is before the epoch.
753pub fn now_commit_ts() -> CommitTs {
754    let millis = SystemTime::now()
755        .duration_since(UNIX_EPOCH)
756        .map(|d| d.as_millis() as u64)
757        .unwrap_or(1);
758    CommitTs(millis.max(1))
759}
760
761struct LoadStats {
762    quads: u64,
763    registered: u64,
764    batches: u64,
765    spike_reductions: u64,
766}
767
768fn report_spike_reductions(count: u64) {
769    if count != 0 {
770        eprintln!(
771            "warning: reduced zero-area polygon spikes in {count} stored geo {}; original EWKB and STR output were preserved",
772            if count == 1 { "literal" } else { "literals" }
773        );
774    }
775}
776
777struct OfflineStores {
778    s: Storage,
779    p: Storage,
780    o: Storage,
781    registry: Registry,
782    /// Content-addressed blob store beside the registry dictionary (geo
783    /// EWKB payloads; the same `{data_dir}/{repository}/blobs` tree the
784    /// registry process serves over gRPC).
785    blobs_reg: waratah_registry::BlobStore,
786    /// Offline text index over the O store's Tantivy directory (`None`
787    /// when the plugin is disabled). C3 twin of the compute write path's
788    /// pre-insert flush: each chunk's documents commit before the chunk's
789    /// hexastore rows apply, so a visible row never lacks its document.
790    text: Option<waratah_text_index::TextIndex>,
791}
792
793impl OfflineStores {
794    fn open(data_dir: &Path, disable_wal: bool) -> Result<Self, DevError> {
795        let tuning = RocksDbTuning::bulk_ingest(disable_wal);
796        // Collectors on for this open: the final flush, and any memtable flush
797        // during the load, stamps `waratah.stats`. The O open also attaches
798        // the temporal histogram and geo cell-count collectors. The end
799        // compact can then skip the bottommost rewrite.
800        Ok(Self {
801            text: None,
802            s: open_hexastore(
803                hexastore_data_dir(data_dir, MAIN_REPOSITORY_ID, PartitionAxis::S),
804                PartitionAxis::S,
805                tuning,
806                true,
807            )?,
808            p: open_hexastore(
809                hexastore_data_dir(data_dir, MAIN_REPOSITORY_ID, PartitionAxis::P),
810                PartitionAxis::P,
811                tuning,
812                true,
813            )?,
814            o: open_hexastore(
815                hexastore_data_dir(data_dir, MAIN_REPOSITORY_ID, PartitionAxis::O),
816                PartitionAxis::O,
817                tuning,
818                true,
819            )?,
820            registry: Registry::open_rocksdb(
821                registry_data_dir(data_dir, MAIN_REPOSITORY_ID),
822                // Registry SSTs are written by bulk sorted walks, not point
823                // lookups: keep the big-block layout and the explicit
824                // iterator readahead from the start so the data does not
825                // need a re-compaction after import.
826                RocksDbTuning {
827                    block_size_bytes: REGISTRY_BLOCK_SIZE_BYTES,
828                    iterator_readahead_bytes: iterator_readahead_bytes(),
829                    ..tuning
830                },
831            )?,
832            blobs_reg: waratah_registry::BlobStore::open(waratah_storage::blob_store_dir(
833                data_dir,
834                MAIN_REPOSITORY_ID,
835            ))?,
836        })
837    }
838
839    fn flush_all(&self) -> Result<(), DevError> {
840        // S, P, O, and the registry are separate RocksDB directories: their
841        // flushes are independent and run concurrently. The blob index is a
842        // separate DB too, but it is small; flush it after the axes rather
843        // than adding a fifth thread.
844        thread::scope(|scope| {
845            let s_h = scope.spawn(|| self.s.flush_memtables());
846            let p_h = scope.spawn(|| self.p.flush_memtables());
847            let o_h = scope.spawn(|| self.o.flush_memtables());
848            let r_h = scope.spawn(|| self.registry.flush_memtables());
849            join_axis(s_h, "S")?;
850            join_axis(p_h, "P")?;
851            join_axis(o_h, "O")?;
852            join_axis(r_h, "registry")?;
853            Ok::<(), DevError>(())
854        })?;
855        self.blobs_reg.flush()?;
856        Ok(())
857    }
858}
859
860pub(crate) fn open_hexastore(
861    path: PathBuf,
862    axis: PartitionAxis,
863    tuning: RocksDbTuning,
864    attach_collector: bool,
865) -> Result<Storage, DevError> {
866    Ok(Storage::open_rocksdb_with_hooks(
867        path,
868        axis,
869        RocksDbOptionsHooks {
870            configure_cf: if attach_collector {
871                Some(&attach_stats_collector)
872            } else {
873                None
874            },
875            configure_catalog_cf: if attach_collector {
876                Some(&attach_catalog_stats_collector)
877            } else {
878                None
879            },
880            configure_temporal_cf: if attach_collector {
881                Some(&attach_temporal_stats_collector)
882            } else {
883                None
884            },
885            configure_geo_cf: if attach_collector {
886                Some(&attach_geo_stats_collector)
887            } else {
888                None
889            },
890            tuning,
891            ..Default::default()
892        },
893    )?)
894}
895
896/// Staged registry SST run files awaiting bulk ingest at the end of an offline import.
897///
898/// The offline path defers registry writes instead of applying one `WriteBatch`
899/// per chunk (the old serial dictionary choke): each chunk's deduped entries —
900/// already hash-sorted by the per-chunk `BTreeMap` — become one sorted SST run
901/// under `{data_dir}/{repository}/registry.sst-staging`, and every run is
902/// `IngestExternalFile`-ed into the registry CF in bulk at the end, concurrent
903/// with the hexastore compactions. Nothing reads the registry mid-import (this
904/// process holds the data dir exclusively), so deferring preserves the
905/// "registered before visible" invariant at import granularity. A run may
906/// overlap earlier runs on key ranges: a `StrHash` is a pure hash of its raw
907/// string, so a duplicate hash always carries the same value.
908///
909/// A chunk writes `run-N.sst.partial` at the same time as its hexastore apply.
910/// The file is renamed to `run-N.sst` only when both succeed. Ingest and
911/// recovery look only at the renamed files.
912struct RegistryStaging {
913    /// Run-file directory for this import.
914    dir: PathBuf,
915    /// One path per renamed run, in staging order.
916    runs: Vec<PathBuf>,
917    /// Total staged entries across all runs (status reporting).
918    entries: u64,
919}
920
921impl RegistryStaging {
922    /// Create the staging directory under `data_dir`.
923    ///
924    /// Finished `run-*.sst` files are not deleted. Registry open ingests those
925    /// before this is called; if any remain, ingest failed and wiping them
926    /// would drop the only copy of that dictionary. In-progress `.partial` files
927    /// are incomplete and are removed.
928    fn create(data_dir: &Path) -> Result<Self, DevError> {
929        let dir = registry_sst_staging_dir(registry_data_dir(data_dir, MAIN_REPOSITORY_ID));
930        let leftover = finished_registry_sst_runs(&dir)?;
931        if !leftover.is_empty() {
932            return Err(DevError::OfflineStagingNotRecovered {
933                dir,
934                count: leftover.len(),
935            });
936        }
937        delete_partial_registry_sst_runs(&dir)?;
938        if dir.exists() {
939            fs::remove_dir_all(&dir)?;
940        }
941        fs::create_dir_all(&dir)?;
942        Ok(Self {
943            dir,
944            runs: Vec::new(),
945            entries: 0,
946        })
947    }
948
949    /// Path of the in-progress SST for the next chunk. Not a finished run until
950    /// [`Self::commit_run`].
951    fn partial_path(&self) -> PathBuf {
952        self.dir
953            .join(format!("run-{:06}.sst.partial", self.runs.len()))
954    }
955
956    /// Rename a finished partial into `run-N.sst` and remember it.
957    fn commit_run(&mut self, partial: &Path, n_entries: u64) -> Result<(), DevError> {
958        let Some(name) = partial.file_name().and_then(|name| name.to_str()) else {
959            return Err(DevError::Io(std::io::Error::other(
960                "registry SST partial path has no file name",
961            )));
962        };
963        let Some(finished_name) = name.strip_suffix(".partial") else {
964            return Err(DevError::Io(std::io::Error::other(
965                "registry SST partial path is missing the .partial suffix",
966            )));
967        };
968        let finished = partial.with_file_name(finished_name);
969        fs::rename(partial, &finished)?;
970        self.entries += n_entries;
971        self.runs.push(finished);
972        Ok(())
973    }
974
975    /// Delete an in-progress partial. Missing is fine: the SST writer may not
976    /// have created it, or Finish may already have removed it.
977    fn discard_partial(partial: &Path) {
978        match fs::remove_file(partial) {
979            Ok(()) => {}
980            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
981            Err(err) => {
982                status!(
983                    "could not delete in-progress registry SST {}: {err}",
984                    partial.display()
985                );
986            }
987        }
988    }
989
990    /// Ingest renamed runs after a write error. Does not compact. Leaves the
991    /// runs on disk if the ingest fails.
992    fn recover(&self, registry: &Registry) -> Result<(), DevError> {
993        registry.recover_staged_sst_runs(&self.dir)?;
994        Ok(())
995    }
996
997    /// Ingest every staged run into the registry CF (hard-linked, no copy),
998    /// compact the registry once, and clean the staging directory.
999    fn ingest(self, registry: &Registry) -> Result<(), DevError> {
1000        registry.ingest_sst_runs(&self.runs)?;
1001        // Runs may sit at non-bottommost levels and may overlap each other or
1002        // pre-existing registry data; one full-range compact merges them and
1003        // rewrites the files with the registry's own table layout.
1004        registry.compact_range();
1005        if self.dir.exists() {
1006            fs::remove_dir_all(&self.dir)?;
1007        }
1008        Ok(())
1009    }
1010}
1011
1012fn compact_offline_hexastore(data_dir: &Path) -> Result<(), DevError> {
1013    status!("starting compaction of S/P/O");
1014    let started = Instant::now();
1015    let tuning = RocksDbTuning {
1016        disable_auto_compactions: true,
1017        disable_wal: false,
1018        ..RocksDbTuning::bulk_ingest(false)
1019    };
1020    // Open all three stores first, then compact concurrently: separate
1021    // RocksDB directories, so the full-range compactions share no locks (only
1022    // disk bandwidth). Collectors stay attached so an L0 merge stamps
1023    // `waratah.stats` on its outputs, including the temporal histogram.
1024    // Bottommost compaction is skipped: a trivial move keeps the blob written
1025    // at flush time, and forcing that rewrite would read and write the keys
1026    // again.
1027    let s = open_hexastore(
1028        hexastore_data_dir(data_dir, MAIN_REPOSITORY_ID, PartitionAxis::S),
1029        PartitionAxis::S,
1030        tuning,
1031        true,
1032    )?;
1033    let p = open_hexastore(
1034        hexastore_data_dir(data_dir, MAIN_REPOSITORY_ID, PartitionAxis::P),
1035        PartitionAxis::P,
1036        tuning,
1037        true,
1038    )?;
1039    let o = open_hexastore(
1040        hexastore_data_dir(data_dir, MAIN_REPOSITORY_ID, PartitionAxis::O),
1041        PartitionAxis::O,
1042        tuning,
1043        true,
1044    )?;
1045    thread::scope(|scope| {
1046        // Handles are intentionally not joined: `thread::scope` waits for all
1047        // spawned threads and rethrows any thread panic after they finish,
1048        // while `compact_range` itself has no Result (a backend failure
1049        // surfaces through the RocksDB log).
1050        let _handles = (
1051            scope.spawn(|| s.compact_range_skip_bottommost()),
1052            scope.spawn(|| p.compact_range_skip_bottommost()),
1053            scope.spawn(|| o.compact_range_skip_bottommost()),
1054        );
1055    });
1056    status!("compacted S/P/O in {} ms", started.elapsed().as_millis());
1057    Ok(())
1058}
1059
1060async fn load_online(
1061    compute: &ComputeNode,
1062    path: &Path,
1063    commit_ts: CommitTs,
1064) -> Result<LoadStats, DevError> {
1065    let pipeline = spawn_rdf_parser(path.to_path_buf(), RdfParseOptions::default());
1066    let mut stats = LoadStats {
1067        quads: 0,
1068        registered: 0,
1069        batches: 0,
1070        spike_reductions: 0,
1071    };
1072    let mut last_progress = Instant::now();
1073    for chunk in pipeline.rx {
1074        let quads = chunk?;
1075        let result = compute.insert_quads(&quads, commit_ts).await?;
1076        stats.quads += result.quads;
1077        stats.registered += result.registered;
1078        stats.spike_reductions += result.spike_reductions;
1079        stats.batches += 1;
1080        maybe_report_progress(&stats, &mut last_progress);
1081    }
1082    join_rdf_parser(pipeline.handle)?;
1083    Ok(stats)
1084}
1085
1086fn load_offline(
1087    stores: &mut OfflineStores,
1088    staging: &mut RegistryStaging,
1089    path: &Path,
1090    commit_ts: CommitTs,
1091) -> Result<LoadStats, DevError> {
1092    let pipeline = spawn_rdf_parser(path.to_path_buf(), RdfParseOptions::default());
1093    let mut stats = LoadStats {
1094        quads: 0,
1095        registered: 0,
1096        batches: 0,
1097        spike_reductions: 0,
1098    };
1099    let mut last_progress = Instant::now();
1100    for chunk in pipeline.rx {
1101        let quads = chunk?;
1102        // The chunk writes its SST run alongside the hexastore apply and
1103        // renames it only when both succeed. The renamed runs are
1104        // bulk-ingested after the load (see `RegistryStaging`).
1105        let (quads_n, registered_n, spike_reductions_n) =
1106            write_offline_chunk(stores, staging, &quads, commit_ts)?;
1107        stats.quads += quads_n;
1108        stats.registered += registered_n;
1109        stats.spike_reductions += spike_reductions_n;
1110        stats.batches += 1;
1111        maybe_report_progress(&stats, &mut last_progress);
1112    }
1113    join_rdf_parser(pipeline.handle)?;
1114    Ok(stats)
1115}
1116
1117/// Fail-closed lexical screen for the offline import's text documents
1118/// (offline twin of the write-path guard in `WriteFanout::insert_quads_rpc`):
1119/// the text plugin indexes every string literal, and the rebuild walk skips
1120/// lexicals above the limit and refuses to stamp — an oversized document
1121/// landing here would create a trusted index state the repair command can
1122/// never reproduce. The whole import fails loudly instead. The offline route
1123/// has no gRPC wire and no registry length check, so this screen is the only
1124/// guard on it.
1125fn screen_offline_text_docs(text_docs: &[waratah_storage::TextIndexDoc]) -> Result<(), DevError> {
1126    if let Some(doc) = text_docs
1127        .iter()
1128        .find(|doc| doc.lexical.len() > waratah_storage::text_index::MAX_INDEXED_LEXICAL_BYTES)
1129    {
1130        return Err(DevError::Backend(format!(
1131            "text index: a string literal's lexical is {} bytes, above the {} KiB \
1132             indexed-lexical limit; the import is rejected (offline import twin of \
1133             the compute write path's guard)",
1134            doc.lexical.len(),
1135            waratah_storage::text_index::MAX_INDEXED_LEXICAL_BYTES / 1024
1136        )));
1137    }
1138    Ok(())
1139}
1140
1141fn write_offline_chunk(
1142    stores: &mut OfflineStores,
1143    staging: &mut RegistryStaging,
1144    quads: &[Quad],
1145    commit_ts: CommitTs,
1146) -> Result<(u64, u64, u64), DevError> {
1147    #[cfg(test)]
1148    if FAIL_BEFORE_OFFLINE_BATCH.with(|slot| slot.get()) == Some(staging.runs.len() as u64) {
1149        return Err(DevError::Io(std::io::Error::other(
1150            "injected offline batch failure",
1151        )));
1152    }
1153    let mut encoded = Vec::with_capacity(quads.len());
1154    for quad in quads {
1155        encoded.push(encode_quad(quad)?);
1156    }
1157    let mut entries = Vec::new();
1158    let mut blob_puts: Vec<(waratah_storage::StrHash, std::sync::Arc<[u8]>)> = Vec::new();
1159    let mut geo_puts: Vec<waratah_storage::GeoIndexPut> = Vec::new();
1160    let mut temporal_puts: Vec<waratah_storage::TemporalIndexPut> = Vec::new();
1161    let mut text_docs: Vec<waratah_storage::TextIndexDoc> = Vec::new();
1162    let mut warnings: Vec<String> = Vec::new();
1163    let mut spike_reductions = 0_u64;
1164    // Write plugins run here too (offline twin of the fan-out): a sparse
1165    // object-rewrite overlay over the plain encoding, plus blob puts and
1166    // O-axis postings. Same all-plugins fold as
1167    // `WriteFanout::insert_quads_rpc`; a conflicting rewrite on one position
1168    // is an error, the same term twice is idempotent.
1169    let plugins = waratah_compute::plugin::process_plugins();
1170    if plugins.write_plugins().next().is_some() {
1171        let mut prepared = plugins.write_plugins().try_fold(
1172            waratah_compute::plugin::PreparedInsert::default(),
1173            |mut acc, plugin| {
1174                let mut part = plugin.prepare_insert(quads, commit_ts, StorageOp::Put)?;
1175                acc.blobs.append(&mut part.blobs);
1176                acc.geo_puts.append(&mut part.geo_puts);
1177                acc.temporal_puts.append(&mut part.temporal_puts);
1178                acc.text_docs.append(&mut part.text_docs);
1179                acc.warnings.append(&mut part.warnings);
1180                acc.spike_reductions += part.spike_reductions;
1181                for (index, term) in part.object_rewrites {
1182                    if index >= quads.len() {
1183                        return Err(waratah_compute::ComputeError::UnsupportedSparql(format!(
1184                            "write plugin rewrote quad index {index} of {}",
1185                            quads.len()
1186                        )));
1187                    }
1188                    if let Some(slot) = acc.object_rewrites.iter_mut().find(|(i, _)| *i == index) {
1189                        if slot.1 != term {
1190                            return Err(waratah_compute::ComputeError::UnsupportedSparql(format!(
1191                                "two write plugins rewrote quad {index} differently"
1192                            )));
1193                        }
1194                    } else {
1195                        acc.object_rewrites.push((index, term));
1196                    }
1197                }
1198                Ok::<_, waratah_compute::ComputeError>(acc)
1199            },
1200        )?;
1201        blob_puts.append(&mut prepared.blobs);
1202        geo_puts.append(&mut prepared.geo_puts);
1203        temporal_puts.append(&mut prepared.temporal_puts);
1204        text_docs.append(&mut prepared.text_docs);
1205        warnings.append(&mut prepared.warnings);
1206        spike_reductions = prepared.spike_reductions;
1207        for (index, term) in prepared.object_rewrites {
1208            encoded[index].object = term;
1209        }
1210    }
1211    // Fail-closed lexical bound — see `screen_offline_text_docs`: without
1212    // it, an oversized literal would land its document on a route with no
1213    // wire and no registry check, creating a trusted index state the repair
1214    // walk can never reproduce.
1215    screen_offline_text_docs(&text_docs)?;
1216    for (quad, item) in quads.iter().zip(&encoded) {
1217        entries.extend(registry_entries_for_quad(quad, item));
1218    }
1219    // Dedupe by hash (last write wins, same as the old per-chunk
1220    // `register_entries`); the `BTreeMap` iteration is hash-ascending, which
1221    // is exactly the sorted-run contract the SST writer below requires.
1222    entries = dedupe_registry_entries(entries);
1223    if !blob_puts.is_empty() {
1224        // One atomic index WriteBatch per chunk, before the hexastore rows
1225        // that reference these ids.
1226        stores.blobs_reg.put_blobs(&blob_puts)?;
1227    }
1228
1229    let versions: Vec<HexastoreVersion<'_>> = encoded
1230        .iter()
1231        .map(|quad| HexastoreVersion {
1232            quad,
1233            commit_ts,
1234            op: StorageOp::Put,
1235            visibility: VisibilityLabel::default(),
1236        })
1237        .collect();
1238    let s_puts = prepare_hexastore_puts(PartitionAxis::S, versions.iter().copied());
1239    let p_puts = prepare_hexastore_puts(PartitionAxis::P, versions.iter().copied());
1240    let o_puts = prepare_hexastore_puts(PartitionAxis::O, versions.iter().copied());
1241    let catalog_graphs = catalog_graphs_from_versions(versions.iter().copied());
1242
1243    let entry_count = entries.len() as u64;
1244    let partial = staging.partial_path();
1245    let OfflineStores {
1246        text,
1247        s,
1248        p,
1249        o,
1250        registry,
1251        blobs_reg: blobs,
1252    } = stores;
1253    let _ = blobs; // written above, before the hexastore apply
1254    // C3 (offline twin): the chunk's documents commit BEFORE the chunk's
1255    // hexastore rows apply. Sequential here — the offline loader has no
1256    // concurrent consumers, and the index commits per chunk.
1257    if let Some(index) = text
1258        && !text_docs.is_empty()
1259    {
1260        index
1261            .add_batch(&text_docs)
1262            .map_err(|error| DevError::Backend(format!("text index add_batch: {error}")))?;
1263    }
1264    let catalog = s.catalog_puts_for_insert(&catalog_graphs)?;
1265    // The SST file and the hexastore rows share this chunk. Both are joined
1266    // before the next chunk. The partial is renamed only when every apply
1267    // returned Ok.
1268    let applied = thread::scope(|scope| {
1269        let sst_h = if entries.is_empty() {
1270            None
1271        } else {
1272            Some(scope.spawn(|| registry.write_sorted_sst_run(&partial, &entries)))
1273        };
1274        let s_h = scope.spawn(|| s.apply_prepared_puts_with_catalog(&s_puts, &catalog));
1275        let p_h = scope.spawn(|| p.apply_prepared_puts(&p_puts));
1276        let o_h = scope.spawn(|| o.apply_prepared_puts(&o_puts));
1277        let g_h = scope.spawn(|| o.apply_geo_puts(&geo_puts));
1278        let t_h = scope.spawn(|| o.apply_temporal_puts(&temporal_puts));
1279        let s_r = join_axis(s_h, "S");
1280        let p_r = join_axis(p_h, "P");
1281        let o_r = join_axis(o_h, "O");
1282        let g_r = join_axis(g_h, "geo");
1283        let t_r = join_axis(t_h, "temporal");
1284        let sst_r = match sst_h {
1285            None => Ok(()),
1286            Some(handle) => join_axis(handle, "registry"),
1287        };
1288        s_r?;
1289        p_r?;
1290        o_r?;
1291        g_r?;
1292        t_r?;
1293        sst_r?;
1294        Ok(())
1295    });
1296    if let Err(err) = applied {
1297        if entry_count > 0 {
1298            RegistryStaging::discard_partial(&partial);
1299        }
1300        return Err(err);
1301    }
1302    if entry_count > 0
1303        && let Err(err) = staging.commit_run(&partial, entry_count)
1304    {
1305        RegistryStaging::discard_partial(&partial);
1306        return Err(err);
1307    }
1308
1309    for warning in warnings {
1310        eprintln!("warning: {warning}");
1311    }
1312    Ok((encoded.len() as u64, entry_count, spike_reductions))
1313}
1314
1315fn join_axis(
1316    handle: thread::ScopedJoinHandle<'_, Result<(), waratah_storage::StorageError>>,
1317    axis: &'static str,
1318) -> Result<(), DevError> {
1319    match handle.join() {
1320        Ok(result) => Ok(result?),
1321        Err(_) => Err(DevError::OfflineWritePanic { axis }),
1322    }
1323}
1324
1325fn dedupe_registry_entries(entries: Vec<(StrHash, String)>) -> Vec<(StrHash, String)> {
1326    let mut map = BTreeMap::new();
1327    for (hash, raw) in entries {
1328        map.insert(hash, raw);
1329    }
1330    map.into_iter().collect()
1331}
1332
1333fn maybe_report_progress(stats: &LoadStats, last_progress: &mut Instant) {
1334    if last_progress.elapsed() >= PROGRESS_INTERVAL {
1335        status!("inserted {} quads so far", stats.quads);
1336        *last_progress = Instant::now();
1337    }
1338}
1339
1340/// Compact S/P/O and the registry. The RPC returns when compaction has finished.
1341async fn compact_online(compute: &ComputeNode) -> Result<(), DevError> {
1342    status!("starting compaction of S/P/O");
1343    let started = Instant::now();
1344    compute.compact_range().await?;
1345    status!("compacted S/P/O in {} ms", started.elapsed().as_millis());
1346    Ok(())
1347}
1348
1349#[cfg(test)]
1350mod tests {
1351    use super::*;
1352
1353    use waratah_stats::STATS_USER_PROPERTY_KEY;
1354    use waratah_storage::{EncodedTriplePattern, SnapshotId};
1355
1356    #[test]
1357    fn unix_epoch_is_1970_01_01() {
1358        assert_eq!(civil_from_unix_days(0), (1970, 1, 1));
1359        assert_eq!(civil_from_unix_days(1), (1970, 1, 2));
1360        assert_eq!(civil_from_unix_days(31), (1970, 2, 1));
1361        assert_eq!(civil_from_unix_days(365), (1971, 1, 1));
1362    }
1363
1364    /// The offline-import opener must attach the geo cell-count collector:
1365    /// the offline path writes geo postings via `Storage::apply_geo_puts`
1366    /// (no partition service, no overlay) and relies entirely on the final
1367    /// flush stamping the SST blob. The pre-fix `open_hexastore` attached
1368    /// the temporal collector but not geo, so offline-built stores flushed
1369    /// blobless and their histogram stayed empty until a later
1370    /// collector-attached compaction.
1371    #[test]
1372    fn offline_opener_attaches_geo_collector_and_flush_stamps_blob() {
1373        let dir = tempfile::tempdir().unwrap();
1374        let o = open_hexastore(
1375            dir.path().to_path_buf(),
1376            PartitionAxis::O,
1377            RocksDbTuning::default(),
1378            true,
1379        )
1380        .unwrap();
1381        let put = waratah_storage::GeoIndexPut {
1382            // Face-0 level-30 leaf, bucket 0 — a posting the collector
1383            // derives purely from the key's cell id.
1384            cell_id: 1,
1385            term: vec![0xAB; 8],
1386            commit_ts: CommitTs(1),
1387            op: StorageOp::Put,
1388            visibility: VisibilityLabel::default(),
1389            envelope: None,
1390        };
1391        o.apply_geo_puts(std::slice::from_ref(&put)).unwrap();
1392        o.flush_memtables().unwrap();
1393        let blobs = o.stats_property_blobs(STATS_USER_PROPERTY_KEY).unwrap();
1394        let geo_mass: u64 = blobs
1395            .iter()
1396            .map(|blob| {
1397                waratah_stats::from_bytes(blob)
1398                    .unwrap()
1399                    .geo_cell_histogram
1400                    .total_bucket_mass()
1401            })
1402            .sum();
1403        assert_eq!(
1404            geo_mass, 1,
1405            "offline opener flush must stamp the geo histogram blob"
1406        );
1407    }
1408
1409    #[test]
1410    fn now_stamp_is_rfc3339_utc() {
1411        let stamp = now_stamp();
1412        assert_eq!(stamp.len(), 24, "{stamp}");
1413        assert!(stamp.as_bytes()[4] == b'-' && stamp.as_bytes()[7] == b'-');
1414        assert!(stamp.as_bytes()[10] == b'T' && stamp.ends_with('Z'));
1415    }
1416
1417    #[test]
1418    fn offline_import_roundtrips_and_writes_stats_ssts() {
1419        let dir = tempfile::tempdir().unwrap();
1420        let rdf_path = dir.path().join("tiny.ttl");
1421        std::fs::write(
1422            &rdf_path,
1423            "<http://ex/alice> <http://ex/name> \"Alice\" .\n\
1424             <http://ex/bob> <http://ex/name> \"Bob\" .\n",
1425        )
1426        .unwrap();
1427        let data_dir = dir.path().join("db");
1428
1429        let options = ImportOptions {
1430            config: ClusterConfig::local_dev(),
1431            data_dir: Some(data_dir.clone()),
1432            bin_dir: PathBuf::from("."),
1433            file: rdf_path,
1434            commit_ts: CommitTs(42),
1435            compact: true,
1436            offline: true,
1437            connect: false,
1438            disable_wal: true,
1439            direct_sst: false,
1440            text_config: waratah_text::TextPluginConfig::default(),
1441        };
1442        run_offline(&options).unwrap();
1443
1444        let store = Storage::open_rocksdb(
1445            hexastore_data_dir(&data_dir, MAIN_REPOSITORY_ID, PartitionAxis::S),
1446            PartitionAxis::S,
1447        )
1448        .unwrap();
1449        let rows = store
1450            .scan_pattern(&EncodedTriplePattern::default(), SnapshotId::latest())
1451            .unwrap();
1452        assert_eq!(rows.len(), 2);
1453
1454        let blobs = store.stats_property_blobs(STATS_USER_PROPERTY_KEY).unwrap();
1455        assert!(
1456            !blobs.is_empty(),
1457            "expected waratah.stats on live SSTs after offline compact"
1458        );
1459
1460        let alice = StrHash::new("http://ex/alice");
1461        let registry = Registry::open_rocksdb(
1462            registry_data_dir(&data_dir, MAIN_REPOSITORY_ID),
1463            RocksDbTuning::registry_node(),
1464        )
1465        .unwrap();
1466        assert_eq!(
1467            registry.lookup(alice).unwrap().as_deref(),
1468            Some("http://ex/alice")
1469        );
1470
1471        // Empty at open: both indexes were built by this import, so the
1472        // epochs are the import commit_ts and startup will not rebuild.
1473        let o = Storage::open_rocksdb(
1474            hexastore_data_dir(&data_dir, MAIN_REPOSITORY_ID, PartitionAxis::O),
1475            PartitionAxis::O,
1476        )
1477        .unwrap();
1478        assert_eq!(o.geo_index_epoch().unwrap(), Some(42));
1479        assert_eq!(o.temporal_index_epoch().unwrap(), Some(42));
1480        let o_blobs = o.stats_property_blobs(STATS_USER_PROPERTY_KEY).unwrap();
1481        assert!(
1482            !o_blobs.is_empty(),
1483            "expected waratah.stats on O after offline compact"
1484        );
1485    }
1486
1487    /// The load open attaches the temporal collector, and the end compact
1488    /// does not force a bottommost rewrite. A single flushed temporal SST
1489    /// can be trivial-moved and must still carry the histogram.
1490    #[test]
1491    fn offline_open_keeps_temporal_histogram_without_bottommost_rewrite() {
1492        use waratah_compute::plugin::WritePlugin;
1493        use waratah_storage::{GraphName, Literal, NamedNode, Term};
1494
1495        let dir = tempfile::tempdir().unwrap();
1496        let store = open_hexastore(
1497            dir.path().to_path_buf(),
1498            PartitionAxis::O,
1499            RocksDbTuning::bulk_ingest(true),
1500            true,
1501        )
1502        .unwrap();
1503        let quad = Quad::new(
1504            NamedNode::new_unchecked("http://ex/e"),
1505            NamedNode::new_unchecked("http://ex/observedAt"),
1506            Term::from(Literal::new_typed_literal(
1507                "2020-01-01T00:00:00Z",
1508                NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#dateTime"),
1509            )),
1510            GraphName::DefaultGraph,
1511        );
1512        let prepared = waratah_temporal::TemporalWritePlugin
1513            .prepare_insert(std::slice::from_ref(&quad), CommitTs(7), StorageOp::Put)
1514            .unwrap();
1515        assert!(!prepared.temporal_puts.is_empty());
1516        store.apply_temporal_puts(&prepared.temporal_puts).unwrap();
1517        store.flush_memtables().unwrap();
1518        store.compact_range_skip_bottommost();
1519        let blobs = store.stats_property_blobs(STATS_USER_PROPERTY_KEY).unwrap();
1520        let profile = waratah_stats::merge_sst_property_blobs(&blobs).unwrap();
1521        assert!(
1522            profile.temporal_histogram.total_postings() > 0,
1523            "temporal histogram must survive a compact that skips the bottommost rewrite"
1524        );
1525    }
1526
1527    #[test]
1528    fn offline_import_twice_ingests_overlapping_registry_runs() {
1529        let dir = tempfile::tempdir().unwrap();
1530        let rdf_path = dir.path().join("tiny.ttl");
1531        std::fs::write(
1532            &rdf_path,
1533            "<http://ex/alice> <http://ex/name> \"Alice\" .\n\
1534             <http://ex/bob> <http://ex/name> \"Bob\" .\n",
1535        )
1536        .unwrap();
1537        let data_dir = dir.path().join("db");
1538
1539        let options = || ImportOptions {
1540            config: ClusterConfig::local_dev(),
1541            data_dir: Some(data_dir.clone()),
1542            bin_dir: PathBuf::from("."),
1543            file: rdf_path.clone(),
1544            commit_ts: CommitTs(42),
1545            compact: true,
1546            offline: true,
1547            connect: false,
1548            disable_wal: true,
1549            direct_sst: false,
1550            text_config: waratah_text::TextPluginConfig::default(),
1551        };
1552
1553        run_offline(&options()).unwrap();
1554        // The second import's staged runs overlap the first import's
1555        // (already-ingested, compacted) registry SSTs on key ranges. A
1556        // `StrHash` is a pure hash of its raw string, so the same hash in
1557        // both always carries the same value and the ingest stays idempotent.
1558        // A later commit_ts must not raise epochs the first import already
1559        // stamped: older snapshots still trust that index.
1560        let mut later = options();
1561        later.commit_ts = CommitTs(99);
1562        run_offline(&later).unwrap();
1563
1564        let registry = Registry::open_rocksdb(
1565            registry_data_dir(&data_dir, MAIN_REPOSITORY_ID),
1566            RocksDbTuning::registry_node(),
1567        )
1568        .unwrap();
1569        assert_eq!(
1570            registry
1571                .lookup(StrHash::new("http://ex/alice"))
1572                .unwrap()
1573                .as_deref(),
1574            Some("http://ex/alice")
1575        );
1576        assert_eq!(
1577            registry
1578                .lookup(StrHash::new("http://ex/name"))
1579                .unwrap()
1580                .as_deref(),
1581            Some("http://ex/name")
1582        );
1583
1584        // The staging directory is cleaned up after a successful ingest.
1585        assert!(
1586            !registry_data_dir(&data_dir, MAIN_REPOSITORY_ID)
1587                .with_extension("sst-staging")
1588                .exists()
1589        );
1590
1591        let o = Storage::open_rocksdb(
1592            hexastore_data_dir(&data_dir, MAIN_REPOSITORY_ID, PartitionAxis::O),
1593            PartitionAxis::O,
1594        )
1595        .unwrap();
1596        assert_eq!(o.geo_index_epoch().unwrap(), Some(42));
1597        assert_eq!(o.temporal_index_epoch().unwrap(), Some(42));
1598    }
1599
1600    #[test]
1601    fn offline_import_into_nonempty_store_does_not_stamp_index_epochs() {
1602        let dir = tempfile::tempdir().unwrap();
1603        let data_dir = dir.path().join("db");
1604        let o_path = hexastore_data_dir(&data_dir, MAIN_REPOSITORY_ID, PartitionAxis::O);
1605        let prior = Storage::open_rocksdb(&o_path, PartitionAxis::O).unwrap();
1606        let quad = Quad::new(
1607            waratah_storage::NamedNode::new("http://ex/old").unwrap(),
1608            waratah_storage::NamedNode::new("http://ex/name").unwrap(),
1609            waratah_storage::NamedNode::new("http://ex/prior").unwrap(),
1610            waratah_storage::GraphName::DefaultGraph,
1611        );
1612        prior.insert_quad(&quad).unwrap();
1613        prior.flush_memtables().unwrap();
1614        drop(prior);
1615
1616        let rdf_path = dir.path().join("tiny.ttl");
1617        std::fs::write(
1618            &rdf_path,
1619            "<http://ex/alice> <http://ex/name> \"Alice\" .\n",
1620        )
1621        .unwrap();
1622        run_offline(&ImportOptions {
1623            config: ClusterConfig::local_dev(),
1624            data_dir: Some(data_dir),
1625            bin_dir: PathBuf::from("."),
1626            file: rdf_path,
1627            commit_ts: CommitTs(42),
1628            compact: true,
1629            offline: true,
1630            connect: false,
1631            disable_wal: true,
1632            direct_sst: false,
1633            text_config: waratah_text::TextPluginConfig::default(),
1634        })
1635        .unwrap();
1636
1637        // Pre-existing triples and a missing epoch: startup's auto-upgrade
1638        // is still the repair for literals this import did not write.
1639        let o = Storage::open_rocksdb(&o_path, PartitionAxis::O).unwrap();
1640        assert_eq!(o.geo_index_epoch().unwrap(), None);
1641        assert_eq!(o.temporal_index_epoch().unwrap(), None);
1642    }
1643
1644    #[test]
1645    fn staging_create_refuses_to_delete_finished_runs() {
1646        let dir = tempfile::tempdir().unwrap();
1647        let data_dir = dir.path().join("db");
1648        let staging = registry_sst_staging_dir(registry_data_dir(&data_dir, MAIN_REPOSITORY_ID));
1649        std::fs::create_dir_all(&staging).unwrap();
1650        let run = staging.join("run-000000.sst");
1651        std::fs::write(&run, b"not-ingested").unwrap();
1652
1653        let err = match RegistryStaging::create(&data_dir) {
1654            Err(err) => err,
1655            Ok(_) => panic!("create must not accept a staging dir that still holds a finished run"),
1656        };
1657        assert!(
1658            run.exists(),
1659            "create must not delete a finished run that was not ingested ({err})"
1660        );
1661        assert!(matches!(
1662            err,
1663            DevError::OfflineStagingNotRecovered { count: 1, .. }
1664        ));
1665    }
1666
1667    #[test]
1668    fn offline_text_screen_rejects_oversized_lexicals_fail_closed() {
1669        // The offline import has no gRPC wire and no registry length check,
1670        // so without this screen an oversized literal would land its
1671        // document AND stamp the epoch on an empty-store import — a trusted
1672        // index the rebuild walk (which skips oversized terms and refuses to
1673        // stamp) can never reproduce. The import must reject instead.
1674        let big = "x".repeat(waratah_storage::text_index::MAX_INDEXED_LEXICAL_BYTES + 1);
1675        let docs = vec![waratah_storage::TextIndexDoc::new(vec![1], big, None)];
1676        let err = screen_offline_text_docs(&docs).unwrap_err();
1677        assert!(
1678            err.to_string().contains("indexed-lexical limit"),
1679            "the rejection names the limit: {err}"
1680        );
1681        // A within-limit document passes, and an empty batch is a no-op.
1682        assert!(
1683            screen_offline_text_docs(&[waratah_storage::TextIndexDoc::new(
1684                vec![1],
1685                "small".to_owned(),
1686                None
1687            )])
1688            .is_ok()
1689        );
1690        assert!(screen_offline_text_docs(&[]).is_ok());
1691    }
1692
1693    #[test]
1694    fn offline_import_error_ingests_finished_registry_runs() {
1695        use std::io::Write;
1696
1697        let dir = tempfile::tempdir().unwrap();
1698        let rdf_path = dir.path().join("two-batches.ttl");
1699        let mut file = std::io::BufWriter::new(std::fs::File::create(&rdf_path).unwrap());
1700        for i in 0..waratah_compute::INSERT_QUAD_CHUNK {
1701            writeln!(file, "<http://ex/keep/{i}> <http://ex/p> \"k\" .").unwrap();
1702        }
1703        writeln!(file, "<http://ex/drop> <http://ex/p> \"d\" .").unwrap();
1704        file.flush().unwrap();
1705        drop(file);
1706
1707        let data_dir = dir.path().join("db");
1708        let mut options = ImportOptions {
1709            config: ClusterConfig::local_dev(),
1710            data_dir: Some(data_dir.clone()),
1711            bin_dir: PathBuf::from("."),
1712            file: rdf_path,
1713            commit_ts: CommitTs(42),
1714            compact: true,
1715            offline: true,
1716            connect: false,
1717            disable_wal: true,
1718            direct_sst: false,
1719            text_config: waratah_text::TextPluginConfig::default(),
1720        };
1721
1722        FAIL_BEFORE_OFFLINE_BATCH.with(|slot| slot.set(Some(1)));
1723        let err = run_offline(&options).unwrap_err();
1724        FAIL_BEFORE_OFFLINE_BATCH.with(|slot| slot.set(None));
1725        assert!(
1726            err.to_string().contains("injected offline batch failure"),
1727            "{err}"
1728        );
1729
1730        let staging = registry_sst_staging_dir(registry_data_dir(&data_dir, MAIN_REPOSITORY_ID));
1731        assert!(
1732            !staging.exists(),
1733            "finished runs are ingested on the error path and the staging dir is removed"
1734        );
1735
1736        let registry = Registry::open_rocksdb(
1737            registry_data_dir(&data_dir, MAIN_REPOSITORY_ID),
1738            RocksDbTuning::registry_node(),
1739        )
1740        .unwrap();
1741        assert_eq!(
1742            registry
1743                .lookup(StrHash::new("http://ex/keep/0"))
1744                .unwrap()
1745                .as_deref(),
1746            Some("http://ex/keep/0")
1747        );
1748        assert_eq!(
1749            registry.lookup(StrHash::new("http://ex/drop")).unwrap(),
1750            None
1751        );
1752        drop(registry);
1753
1754        let store = Storage::open_rocksdb_with_hooks(
1755            hexastore_data_dir(&data_dir, MAIN_REPOSITORY_ID, PartitionAxis::S),
1756            PartitionAxis::S,
1757            RocksDbOptionsHooks {
1758                // Leave the abort flush's L0 files where they are. A normal
1759                // open would background-compact them and hide the signal.
1760                tuning: RocksDbTuning {
1761                    disable_auto_compactions: true,
1762                    ..RocksDbTuning::default()
1763                },
1764                ..RocksDbOptionsHooks::default()
1765            },
1766        )
1767        .unwrap();
1768        let rows = store
1769            .scan_pattern(&EncodedTriplePattern::default(), SnapshotId::latest())
1770            .unwrap();
1771        assert_eq!(rows.len(), waratah_compute::INSERT_QUAD_CHUNK);
1772        let blobs = store.stats_property_blobs(STATS_USER_PROPERTY_KEY).unwrap();
1773        assert!(
1774            !blobs.is_empty(),
1775            "a failed import still flushes, so waratah.stats is stamped without a compact"
1776        );
1777        let level0 = store
1778            .hexastore_level0_files()
1779            .expect("rocksdb reports L0 file counts");
1780        assert!(
1781            level0 > 0,
1782            "a failed import must not compact the hexastore (L0 files={level0})"
1783        );
1784        drop(store);
1785
1786        let o = Storage::open_rocksdb(
1787            hexastore_data_dir(&data_dir, MAIN_REPOSITORY_ID, PartitionAxis::O),
1788            PartitionAxis::O,
1789        )
1790        .unwrap();
1791        assert_eq!(o.geo_index_epoch().unwrap(), None);
1792        assert_eq!(o.temporal_index_epoch().unwrap(), None);
1793        drop(o);
1794
1795        // The store already holds the first batch, so this import must not
1796        // stamp epochs, and it must not drop the dictionary recovered above.
1797        let later_path = dir.path().join("later.ttl");
1798        std::fs::write(&later_path, "<http://ex/later> <http://ex/p> \"L\" .\n").unwrap();
1799        options.file = later_path;
1800        options.commit_ts = CommitTs(99);
1801        run_offline(&options).unwrap();
1802
1803        let registry = Registry::open_rocksdb(
1804            registry_data_dir(&data_dir, MAIN_REPOSITORY_ID),
1805            RocksDbTuning::registry_node(),
1806        )
1807        .unwrap();
1808        assert_eq!(
1809            registry
1810                .lookup(StrHash::new("http://ex/keep/0"))
1811                .unwrap()
1812                .as_deref(),
1813            Some("http://ex/keep/0")
1814        );
1815        assert_eq!(
1816            registry.lookup(StrHash::new("http://ex/drop")).unwrap(),
1817            None
1818        );
1819        assert_eq!(
1820            registry
1821                .lookup(StrHash::new("http://ex/later"))
1822                .unwrap()
1823                .as_deref(),
1824            Some("http://ex/later")
1825        );
1826        drop(registry);
1827
1828        let o = Storage::open_rocksdb(
1829            hexastore_data_dir(&data_dir, MAIN_REPOSITORY_ID, PartitionAxis::O),
1830            PartitionAxis::O,
1831        )
1832        .unwrap();
1833        assert_eq!(o.geo_index_epoch().unwrap(), None);
1834        assert_eq!(o.temporal_index_epoch().unwrap(), None);
1835    }
1836}
1837
1838#[cfg(test)]
1839mod text_bracket_tests {
1840    //! Engine-level pins for the online import's text bracket: the pre-build
1841    //! that establishes trust before any batch loads, and the stamp gate
1842    //! that keeps a begin-against-untrusted-import from declaring trust
1843    //! over an index that does not cover the store's pre-existing rows.
1844
1845    use super::*;
1846    use oxrdf::{GraphName, Literal, NamedNode, Quad};
1847    use waratah_compute::{
1848        ComputeNode, HexastoreAdmin, HexastoreInsert, RetryPolicy, StringRegister,
1849    };
1850    use waratah_partition::PartitionService;
1851    use waratah_registry::RegistryService;
1852    use waratah_router::{ClusterConfig, RegistryNodeId};
1853    use waratah_storage::SnapshotId;
1854    use waratah_text::TextPluginConfig;
1855
1856    /// Distinct compute listen ports for this binary's async tests (the
1857    /// other test binaries use their own fixed ports).
1858    fn compute_port(port: u16) -> std::net::SocketAddr {
1859        std::net::SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), port)
1860    }
1861
1862    /// Live partition services (the O one text-enabled) plus a connected
1863    /// compute node, with the text plugin NOT installed unless the caller
1864    /// says so — the pre-existing rows of the B2 scenario must be inserted
1865    /// without documents.
1866    async fn cluster(port: u16) -> ComputeNode {
1867        let config = enabled_config();
1868        let options = waratah_text_index::TextIndexOptions::new(
1869            config.analyzer.clone(),
1870            config.seed_chars,
1871            config.fingerprint(),
1872        );
1873        let mut hexastore = Vec::new();
1874        for axis in PartitionAxis::ALL {
1875            let (incoming, addr) = waratah_partition::bind("127.0.0.1:0".parse().unwrap()).unwrap();
1876            let service = PartitionService::memory(axis);
1877            let service = if axis == PartitionAxis::O {
1878                service.with_text_self_create(Some(options.clone()))
1879            } else {
1880                service
1881            };
1882            tokio::spawn(async move {
1883                waratah_partition::serve(service, incoming).await.unwrap();
1884            });
1885            hexastore.push((axis, addr));
1886        }
1887        let (incoming, registry) = waratah_registry::bind("127.0.0.1:0".parse().unwrap()).unwrap();
1888        tokio::spawn(async move {
1889            waratah_registry::serve(RegistryService::default(), incoming)
1890                .await
1891                .unwrap();
1892        });
1893        let cluster_config = ClusterConfig::new(
1894            hexastore,
1895            [(RegistryNodeId(0), registry)],
1896            compute_port(port),
1897        )
1898        .unwrap();
1899        ComputeNode::connect(&cluster_config, RetryPolicy::default_dev())
1900            .await
1901            .unwrap()
1902    }
1903
1904    fn iri(local: &str) -> NamedNode {
1905        NamedNode::new(format!("http://ex/{local}")).unwrap()
1906    }
1907
1908    /// The bracket and the ensure step need an ENABLED config —
1909    /// `TextPluginConfig::default()` is disabled (the plugin is off by
1910    /// default everywhere), and a disabled config no-ops the bracket.
1911    fn enabled_config() -> TextPluginConfig {
1912        TextPluginConfig {
1913            enabled: true,
1914            // The bracket tests index arbitrary `http://ex/` predicates.
1915            predicates: Vec::new(),
1916            ..TextPluginConfig::default()
1917        }
1918    }
1919
1920    async fn insert(compute: &ComputeNode, quad: Quad) {
1921        compute.insert_quads(&[quad], CommitTs(1)).await.unwrap();
1922    }
1923
1924    /// Insert one quad through the RAW axis clients — the write path as it
1925    /// runs with the plugin OFF: plain axis versions plus registry
1926    /// entries, no text documents. Going through `ComputeNode::insert_quads`
1927    /// would consult the process plugin registry, which both POISONS the
1928    /// later composed install (the registry's once-guard) and would mint
1929    /// documents the B2 scenario must not have yet.
1930    async fn insert_without_plugins(compute: &ComputeNode, quad: &Quad) {
1931        let encoded = waratah_storage::encode_quad(quad).unwrap();
1932        let versions: Vec<waratah_proto::QuadVersion> = PartitionAxis::ALL
1933            .into_iter()
1934            .map(|_| waratah_proto::QuadVersion {
1935                quad: encoded.clone(),
1936                commit_ts: CommitTs(1),
1937                op: StorageOp::Put,
1938                visibility: waratah_storage::VisibilityLabel::default(),
1939            })
1940            .collect();
1941        for axis in PartitionAxis::ALL {
1942            compute
1943                .queries()
1944                .hexastore()
1945                .insert_quads(axis, &versions)
1946                .await
1947                .unwrap();
1948        }
1949        let entries = waratah_storage::registry_entries_for_quad(quad, &encoded);
1950        compute
1951            .queries()
1952            .registry()
1953            .register_strings(&entries)
1954            .await
1955            .unwrap();
1956    }
1957
1958    async fn text_epoch(compute: &ComputeNode) -> Option<u64> {
1959        compute
1960            .queries()
1961            .hexastore()
1962            .describe(PartitionAxis::O)
1963            .await
1964            .unwrap()
1965            .text_index_epoch
1966    }
1967
1968    /// The B2 scenario, end to end: pre-existing rows written while the
1969    /// plugin was off (no documents, no index), then the online import
1970    /// flow with the plugin on. The pre-build must cover the PRE-EXISTING
1971    /// rows, and the finished index must answer `text:query` over them —
1972    /// not only over the imported rows.
1973    #[tokio::test]
1974    async fn online_import_prebuild_covers_preexisting_rows() {
1975        // The composed install lands BEFORE any engine exists (production's
1976        // ordering rule: the engine's builtin custom-function install is
1977        // first-wins, so plugin functions must precede it). The pre-existing
1978        // rows still land without documents — they go through the raw axis
1979        // clients, which never consult the write-plugin registry.
1980        crate::test_support::install_composed();
1981        let mut compute = cluster(7012).await;
1982
1983        // Phase 1 — plugin OFF: the store accumulates rows without documents
1984        // (raw axis writes; `ComputeNode::insert_quads` would consult the
1985        // process plugin registry, which must stay uninstalled until the
1986        // import phase).
1987        insert_without_plugins(
1988            &compute,
1989            &Quad::new(
1990                iri("old"),
1991                iri("bio"),
1992                Literal::from("mountain pass"),
1993                GraphName::NamedNode(iri("g1")),
1994            ),
1995        )
1996        .await;
1997        assert_eq!(text_epoch(&compute).await, None, "no index yet");
1998
1999        // Phase 2 — the import process runs with the plugin on (the real
2000        // binary composes the plugin host for every command).
2001        crate::test_support::install_composed();
2002        let config = enabled_config();
2003
2004        // The pre-build walks the pre-existing rows and stamps.
2005        ensure_trusted_text_index(&compute, &config).await.unwrap();
2006
2007        // The bracket + load + close, exactly as run_connect drives them.
2008        let bracket = bracket_online_text_import(&compute, &config)
2009            .await
2010            .unwrap()
2011            .expect("no competing driver");
2012        assert!(bracket.trusted_at_begin, "the pre-build established trust");
2013        insert(
2014            &compute,
2015            Quad::new(
2016                iri("new"),
2017                iri("bio"),
2018                Literal::from("mountain lake"),
2019                GraphName::NamedNode(iri("g2")),
2020            ),
2021        )
2022        .await;
2023        close_online_text_import(&compute, Some(bracket), true)
2024            .await
2025            .unwrap();
2026        assert!(text_epoch(&compute).await.is_some(), "the gate stamps");
2027
2028        // Shell duty: refresh the engine's text state from the Describe.
2029        let describe = compute
2030            .queries()
2031            .hexastore()
2032            .describe(PartitionAxis::O)
2033            .await
2034            .unwrap();
2035        compute.set_text_index_state(
2036            describe.text_index_epoch,
2037            describe.text_index_fingerprint.clone(),
2038        );
2039
2040        let results = compute
2041            .query(
2042                "SELECT ?g ?s WHERE { \
2043                 GRAPH ?g { \
2044                 ?s <http://ex/bio> ?v . \
2045                 FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\")) \
2046                 } }",
2047                SnapshotId::from(CommitTs(1)),
2048            )
2049            .await
2050            .unwrap();
2051        assert_eq!(
2052            results.len(),
2053            2,
2054            "the PRE-EXISTING row and the imported row both answer: {results:?}"
2055        );
2056
2057        // The mismatch refusal: an index built by other settings cannot be
2058        // re-analyzed live — the import refuses with the repair hint.
2059        let mismatched = TextPluginConfig {
2060            seed_chars: 8,
2061            ..TextPluginConfig::default()
2062        };
2063        let error = ensure_trusted_text_index(&compute, &mismatched)
2064            .await
2065            .unwrap_err();
2066        assert!(
2067            error.to_string().contains("offline rebuild"),
2068            "the refusal names the repair: {error}"
2069        );
2070    }
2071
2072    /// The stamp gate: a bracket begun against an UNTRUSTED index must not
2073    /// stamp at finish, even on a successful load — the load's documents
2074    /// cover only the imported rows, and stamping would declare trust over
2075    /// the pre-existing rows the index never saw (the trusted-but-
2076    /// incomplete state). The epoch stays unset, so the next startup build
2077    /// owns it.
2078    #[tokio::test]
2079    async fn stamp_gate_refuses_an_untrusted_begin() {
2080        crate::test_support::install_composed();
2081        let compute = cluster(7013).await;
2082        let config = enabled_config();
2083
2084        assert_eq!(text_epoch(&compute).await, None, "untrusted at start");
2085        let bracket = bracket_online_text_import(&compute, &config)
2086            .await
2087            .unwrap()
2088            .expect("no competing driver");
2089        assert!(
2090            !bracket.trusted_at_begin,
2091            "no index existed: the gate must refuse the stamp"
2092        );
2093        close_online_text_import(&compute, Some(bracket), true)
2094            .await
2095            .unwrap();
2096        assert_eq!(
2097            text_epoch(&compute).await,
2098            None,
2099            "an untrusted begin never stamps"
2100        );
2101    }
2102}