Skip to main content

waratah/
compact.rs

1//! `waratah compact`: offline flush + full-range compaction of an existing
2//! RocksDB data-dir.
3//!
4//! Opens each targeted storage brick in this process (like `import --offline`)
5//! and compacts it so the on-disk layout matches the current tuning:
6//! - hexastore axes open with the stats collectors attached, so `waratah.stats`
7//!   SST properties are re-collected from the compaction output;
8//! - the registry opens with the registry tuning (32 KiB SST blocks), so
9//!   existing files are rewritten at the new block size — existing files keep
10//!   their original block size until a compaction rewrites them.
11//!
12//! Targets run sequentially: one compaction saturates a spinning disk, and
13//! parallel full-range compactions would just interleave their streams.
14
15use std::fmt;
16use std::path::{Path, PathBuf};
17use std::time::Instant;
18
19use waratah_storage::{
20    COMPACTION_READAHEAD_BYTES, MAIN_REPOSITORY_ID, PartitionAxis, REGISTRY_BLOCK_SIZE_BYTES,
21    Registry, RocksDbTuning, blob_index_dir, blob_store_dir, hexastore_data_dir,
22    iterator_readahead_bytes, registry_data_dir,
23};
24
25use crate::error::DevError;
26use crate::import::{open_hexastore, status};
27
28/// One compaction target.
29#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
30pub enum CompactTarget {
31    /// S-axis hexastore (SPOG / SOPG + named-graph catalog).
32    #[value(alias = "S")]
33    S,
34    /// P-axis hexastore (PSOG / POSG).
35    #[value(alias = "P")]
36    P,
37    /// O-axis hexastore (OPSG + TSG).
38    #[value(alias = "O")]
39    O,
40    /// String registry dictionary (files rewritten at the registry block size).
41    #[value(alias = "Registry")]
42    Registry,
43}
44
45impl CompactTarget {
46    /// Human label for status lines.
47    fn label(self) -> &'static str {
48        match self {
49            Self::S => "S",
50            Self::P => "P",
51            Self::O => "O",
52            Self::Registry => "registry",
53        }
54    }
55}
56
57const CANONICAL_ORDER: [CompactTarget; 4] = [
58    CompactTarget::S,
59    CompactTarget::P,
60    CompactTarget::O,
61    CompactTarget::Registry,
62];
63
64/// Flush and compact targets of an existing data-dir, sequentially.
65///
66/// No targets (the default) means all of them in canonical order
67/// S, P, O, registry. Repeated targets are compacted once.
68pub fn run(data_dir: PathBuf, targets: &[CompactTarget]) -> Result<(), DevError> {
69    let selected: Vec<CompactTarget> = if targets.is_empty() {
70        CANONICAL_ORDER.to_vec()
71    } else {
72        CANONICAL_ORDER
73            .into_iter()
74            .filter(|target| targets.contains(target))
75            .collect()
76    };
77    if selected.is_empty() {
78        return Ok(());
79    }
80
81    status!(
82        "compacting {} on {} (compaction readahead {} MiB; registry query-time \
83         iterator readahead {} KiB, override with WARATAH_ITERATOR_READAHEAD_SIZE=<KiB>)",
84        selected
85            .iter()
86            .map(|target| target.label())
87            .collect::<Vec<_>>()
88            .join(", "),
89        data_dir.display(),
90        COMPACTION_READAHEAD_BYTES / (1024 * 1024),
91        iterator_readahead_bytes() / 1024,
92    );
93
94    for target in selected {
95        match target {
96            CompactTarget::S => compact_axis(&data_dir, PartitionAxis::S, "S")?,
97            CompactTarget::P => compact_axis(&data_dir, PartitionAxis::P, "P")?,
98            CompactTarget::O => compact_axis(&data_dir, PartitionAxis::O, "O")?,
99            CompactTarget::Registry => compact_registry(&data_dir)?,
100        }
101    }
102    status!("all targets compacted");
103    Ok(())
104}
105
106/// Flush + full-range compaction of one hexastore axis.
107///
108/// The stats collectors are attached, so the rewritten SSTs carry fresh
109/// `waratah.stats` properties for the planner.
110fn compact_axis(data_dir: &Path, axis: PartitionAxis, label: &str) -> Result<(), DevError> {
111    let path = hexastore_data_dir(data_dir, MAIN_REPOSITORY_ID, axis);
112    status!("{label} axis: opening (stats collectors attached)");
113    let tuning = RocksDbTuning {
114        disable_auto_compactions: true,
115        disable_wal: false,
116        ..RocksDbTuning::bulk_ingest(false)
117    };
118    let store = open_hexastore(path.clone(), axis, tuning, true)?;
119
120    status!("{label} axis: flushing memtables");
121    store.flush_memtables()?;
122    let before = SstStats::of(&path);
123
124    status!("{label} axis: compacting {before} (stats land in the new SSTs)");
125    let started = Instant::now();
126    store.compact_range();
127    let after = SstStats::of(&path);
128    status!(
129        "{label} axis: compacted in {:.1}s ({before} -> {after})",
130        started.elapsed().as_secs_f64()
131    );
132    Ok(())
133}
134
135/// Flush + full-range compaction of the string registry.
136///
137/// Opened with the registry tuning, whose 32 KiB block size applies to every
138/// SST the compaction writes: this is how an existing 4 KiB-block registry is
139/// migrated to the big-block layout.
140fn compact_registry(data_dir: &Path) -> Result<(), DevError> {
141    let path = registry_data_dir(data_dir, MAIN_REPOSITORY_ID);
142    status!(
143        "registry: opening (block size {} KiB; compaction rewrites files at this size)",
144        REGISTRY_BLOCK_SIZE_BYTES / 1024
145    );
146    let registry = Registry::open_rocksdb(&path, RocksDbTuning::registry_node())?;
147
148    status!("registry: flushing memtables");
149    registry.flush_memtables()?;
150    let before = SstStats::of(&path);
151
152    status!("registry: compacting {before} (transient free space of that order is needed)");
153    let started = Instant::now();
154    registry.compact_range();
155    let after = SstStats::of(&path);
156    status!(
157        "registry: compacted in {:.1}s ({before} -> {after})",
158        started.elapsed().as_secs_f64()
159    );
160
161    // The blob index is a separate RocksDB DB. It is append-only and small,
162    // but `--target registry` should leave its SSTs in the same tuned layout
163    // as the dictionary. Opening also enforces the legacy-layout check, so
164    // a data dir from a pre-two-tier build fails here instead of after the
165    // dictionary work.
166    let blob_root = blob_store_dir(data_dir, MAIN_REPOSITORY_ID);
167    if blob_root.exists() {
168        let blobs = waratah_registry::BlobStore::open(&blob_root)?;
169        status!("blobs: flushing the index memtable");
170        blobs.flush()?;
171        let blob_path = blob_index_dir(&blob_root);
172        let blob_before = SstStats::of(&blob_path);
173        status!("blobs: compacting {blob_before}");
174        let started = Instant::now();
175        blobs.compact_range()?;
176        let blob_after = SstStats::of(&blob_path);
177        status!(
178            "blobs: compacted in {:.1}s ({blob_before} -> {blob_after})",
179            started.elapsed().as_secs_f64()
180        );
181    }
182    Ok(())
183}
184
185/// On-disk SST summary for one store directory (before/after progress lines).
186#[derive(Debug, Clone, Copy, Default)]
187struct SstStats {
188    files: u64,
189    bytes: u64,
190}
191
192impl SstStats {
193    /// Sum `*.sst` file count and size under `dir` (missing dir = empty).
194    fn of(dir: &Path) -> Self {
195        let mut stats = Self::default();
196        let Ok(entries) = std::fs::read_dir(dir) else {
197            return stats;
198        };
199        for entry in entries.flatten() {
200            let Ok(meta) = entry.metadata() else {
201                continue;
202            };
203            if meta.is_file() && entry.file_name().to_string_lossy().ends_with(".sst") {
204                stats.files += 1;
205                stats.bytes += meta.len();
206            }
207        }
208        stats
209    }
210}
211
212impl fmt::Display for SstStats {
213    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214        const GIB: u64 = 1024 * 1024 * 1024;
215        const MIB: u64 = 1024 * 1024;
216        let size = if self.bytes >= GIB {
217            format!("{:.2} GiB", self.bytes as f64 / GIB as f64)
218        } else if self.bytes >= MIB {
219            format!("{:.1} MiB", self.bytes as f64 / MIB as f64)
220        } else {
221            format!("{} KiB", self.bytes / 1024)
222        };
223        write!(f, "{} SSTs / {size}", self.files)
224    }
225}