1use 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#[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
63const PROGRESS_INTERVAL: Duration = Duration::from_secs(30);
65
66macro_rules! status {
68 ($($arg:tt)*) => {{
69 println!("[{}] {}", crate::import::now_stamp(), format_args!($($arg)*));
70 }};
71}
72pub(crate) use status;
73
74pub(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
90fn 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
105pub struct ImportOptions {
107 pub config: ClusterConfig,
109 pub data_dir: Option<PathBuf>,
111 pub bin_dir: PathBuf,
113 pub file: PathBuf,
115 pub commit_ts: CommitTs,
117 pub compact: bool,
119 pub offline: bool,
121 pub connect: bool,
123 pub disable_wal: bool,
125 pub direct_sst: bool,
127 pub text_config: waratah_text::TextPluginConfig,
129}
130
131pub 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
145async 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
158fn describe_is_trusted(describe: &waratah_compute::HexastoreDescribe, fingerprint: &str) -> bool {
161 describe.text_index_epoch.is_some() && describe.text_index_fingerprint == fingerprint
162}
163
164async 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 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 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
231async 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
249struct TextImportBracket {
252 lease_token: u64,
253 trusted_at_begin: bool,
260 keepalive: tokio::task::AbortHandle,
265}
266
267async 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 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 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 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; loop {
321 interval.tick().await;
322 if renews.renew_text_rebuild_lease(lease_token).await.is_err() {
323 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
339async 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 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 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 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 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 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 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 let index_epochs = index_epochs_to_stamp(&stores.o)?;
562 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 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 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
623fn 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
662struct IndexEpochPlan {
667 geo: bool,
668 temporal: bool,
669 text: bool,
670}
671
672fn 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
705fn 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
741fn 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
752pub 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 blobs_reg: waratah_registry::BlobStore,
786 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 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 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 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
896struct RegistryStaging {
913 dir: PathBuf,
915 runs: Vec<PathBuf>,
917 entries: u64,
919}
920
921impl RegistryStaging {
922 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 fn partial_path(&self) -> PathBuf {
952 self.dir
953 .join(format!("run-{:06}.sst.partial", self.runs.len()))
954 }
955
956 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 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 fn recover(&self, registry: &Registry) -> Result<(), DevError> {
993 registry.recover_staged_sst_runs(&self.dir)?;
994 Ok(())
995 }
996
997 fn ingest(self, registry: &Registry) -> Result<(), DevError> {
1000 registry.ingest_sst_runs(&self.runs)?;
1001 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 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 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 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
1117fn 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 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 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 entries = dedupe_registry_entries(entries);
1223 if !blob_puts.is_empty() {
1224 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; 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 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
1340async 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 #[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 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 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 #[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 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 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 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 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 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 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 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 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 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 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 fn enabled_config() -> TextPluginConfig {
1912 TextPluginConfig {
1913 enabled: true,
1914 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 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 #[tokio::test]
1974 async fn online_import_prebuild_covers_preexisting_rows() {
1975 crate::test_support::install_composed();
1981 let mut compute = cluster(7012).await;
1982
1983 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 crate::test_support::install_composed();
2002 let config = enabled_config();
2003
2004 ensure_trusted_text_index(&compute, &config).await.unwrap();
2006
2007 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 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 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 #[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}