Skip to main content

waratah_exp/
main.rs

1//! Local experiments for SST `waratah.stats` collection and compaction cost.
2//!
3//! Run:
4//! `cargo run -p waratah_exp --release -- --quads 1000000`
5
6use std::path::{Path, PathBuf};
7use std::process::ExitCode;
8use std::time::Instant;
9
10use clap::Parser;
11use rand::Rng;
12use rand::SeedableRng;
13use rand::rngs::StdRng;
14use waratah_partition::{PartitionService, RocksDbOpenOptions};
15use waratah_proto::QuadVersion;
16use waratah_storage::{
17    BlankNode, CommitTs, GraphName, Literal, NamedNode, NamedOrBlankNode, PartitionAxis, Quad,
18    StorageOp, Term, VisibilityLabel, encode_quad,
19};
20
21const AXIS: PartitionAxis = PartitionAxis::S;
22const BATCH: usize = 256;
23
24#[derive(Parser, Debug)]
25#[command(
26    name = "waratah-exp",
27    about = "SPOG partition stats/compaction experiments"
28)]
29struct Args {
30    /// Unique random quads to ingest (experiments 1 and 2).
31    #[arg(long, default_value_t = 1_000_000)]
32    quads: u64,
33    /// Identical Put count for the duplicate-key experiment.
34    #[arg(long, default_value_t = 1_000)]
35    duplicates: u64,
36    /// RocksDB parent directory (a temp dir is used when omitted).
37    #[arg(long)]
38    dir: Option<PathBuf>,
39    /// RNG seed for term-type mix and predicate vocabulary.
40    #[arg(long, default_value_t = 1)]
41    seed: u64,
42}
43
44fn main() -> ExitCode {
45    let args = Args::parse();
46    match run(args) {
47        Ok(()) => ExitCode::SUCCESS,
48        Err(error) => {
49            eprintln!("waratah-exp: {error}");
50            ExitCode::FAILURE
51        }
52    }
53}
54
55fn run(args: Args) -> Result<(), Box<dyn std::error::Error>> {
56    let temp = args.dir.is_none().then(tempfile::tempdir).transpose()?;
57    let root = match &args.dir {
58        Some(dir) => {
59            std::fs::create_dir_all(dir)?;
60            dir.as_path()
61        }
62        None => temp.as_ref().expect("tempdir").path(),
63    };
64
65    println!(
66        "waratah-exp root={} quads={} duplicates={} seed={}",
67        root.display(),
68        args.quads,
69        args.duplicates,
70        args.seed
71    );
72
73    exp_ingest_until_compaction(root, args.quads, args.seed)?;
74    exp_compact_timing(root, args.quads, args.seed)?;
75    exp_duplicate_puts(root, args.duplicates)?;
76    Ok(())
77}
78
79/// Experiment 1: ingest unique random quads with auto-compaction on; note first compaction.
80fn exp_ingest_until_compaction(
81    root: &Path,
82    quads: u64,
83    seed: u64,
84) -> Result<(), Box<dyn std::error::Error>> {
85    println!("\n== experiment 1: ingest until first auto-compaction (collector on) ==");
86    let path = root.join("ingest");
87    let service = PartitionService::open_rocksdb(
88        &path,
89        AXIS,
90        RocksDbOpenOptions {
91            attach_collector: true,
92            disable_auto_compactions: false,
93        },
94    )?;
95
96    let start = Instant::now();
97    let mut first_compaction_at = None;
98    ingest_random_quads(&service, quads, seed, |written| {
99        if first_compaction_at.is_none() && service.compaction_event_count() > 0 {
100            first_compaction_at = Some(written);
101        }
102    })?;
103
104    let elapsed_ms = start.elapsed().as_millis();
105    match first_compaction_at {
106        Some(n) => println!("first compaction after {n} writes"),
107        None => println!("no auto-compaction during {quads} writes"),
108    }
109    println!(
110        "wrote {quads} quads in {elapsed_ms} ms; flush_events={} compaction_events={}",
111        service.flush_event_count(),
112        service.compaction_event_count()
113    );
114    println!(
115        "open_puts (estimated, unflushed overlay)={}",
116        service.open_total_puts()?
117    );
118    drop(service);
119    Ok(())
120}
121
122/// Experiment 2: time a full-range compact with vs without the stats collector.
123fn exp_compact_timing(
124    root: &Path,
125    quads: u64,
126    seed: u64,
127) -> Result<(), Box<dyn std::error::Error>> {
128    println!("\n== experiment 2: compact_range with vs without collector ==");
129
130    let with_ms = timed_compact(root.join("compact-with"), quads, seed, true)?;
131    let without_ms = timed_compact(root.join("compact-without"), quads, seed, false)?;
132    let delta = with_ms as i128 - without_ms as i128;
133    println!("compact_range with collector:    {with_ms} ms");
134    println!("compact_range without collector: {without_ms} ms");
135    println!("difference (with - without):     {delta} ms");
136    Ok(())
137}
138
139fn timed_compact(
140    path: PathBuf,
141    quads: u64,
142    seed: u64,
143    attach_collector: bool,
144) -> Result<u128, Box<dyn std::error::Error>> {
145    let service = PartitionService::open_rocksdb(
146        &path,
147        AXIS,
148        RocksDbOpenOptions {
149            attach_collector,
150            disable_auto_compactions: true,
151        },
152    )?;
153    ingest_random_quads(&service, quads, seed, |_| {})?;
154    service.flush_memtables()?;
155    let start = Instant::now();
156    service.compact_range()?;
157    let ms = start.elapsed().as_millis();
158    drop(service);
159    Ok(ms)
160}
161
162/// Experiment 3: 1000 identical Puts (same key + ts) vs SST-collected cardinality.
163fn exp_duplicate_puts(root: &Path, duplicates: u64) -> Result<(), Box<dyn std::error::Error>> {
164    println!("\n== experiment 3: {duplicates} identical Puts, then flush + GetStatsProfile ==");
165    let path = root.join("dup");
166    let service = PartitionService::open_rocksdb(
167        &path,
168        AXIS,
169        RocksDbOpenOptions {
170            attach_collector: true,
171            disable_auto_compactions: true,
172        },
173    )?;
174
175    let quad = encode_quad(&Quad::new(
176        NamedNode::new("http://ex/dup/s")?,
177        NamedNode::new("http://ex/dup/p")?,
178        Literal::from("same"),
179        GraphName::DefaultGraph,
180    ))?;
181    let version = QuadVersion {
182        quad,
183        commit_ts: CommitTs(1),
184        op: StorageOp::Put,
185        visibility: VisibilityLabel::default(),
186    };
187    for _ in 0..duplicates {
188        service.apply_versions(Some(AXIS), std::slice::from_ref(&version))?;
189    }
190
191    let open_puts = service.open_total_puts()?;
192    println!("open_puts after {duplicates} identical Puts: {open_puts}");
193    if open_puts != duplicates {
194        eprintln!("warning: expected open_puts={duplicates}, got {open_puts}");
195    }
196
197    service.flush_memtables()?;
198    let profile = service.shard_profile()?;
199    println!(
200        "GetStatsProfile after flush: total_puts={} (1 means RocksDB kept a single key)",
201        profile.total_puts
202    );
203    if profile.total_puts != 1 {
204        eprintln!(
205            "warning: expected SST stats total_puts=1 after identical-key Puts, got {}",
206            profile.total_puts
207        );
208    }
209    drop(service);
210    Ok(())
211}
212
213fn ingest_random_quads(
214    service: &PartitionService,
215    quads: u64,
216    seed: u64,
217    mut after_batch: impl FnMut(u64),
218) -> Result<(), Box<dyn std::error::Error>> {
219    let mut rng = StdRng::seed_from_u64(seed);
220    let mut batch = Vec::with_capacity(BATCH);
221    let mut written = 0u64;
222    while written < quads {
223        batch.clear();
224        let remaining = (quads - written) as usize;
225        let n = remaining.min(BATCH);
226        for j in 0..n {
227            let i = written + j as u64;
228            let encoded = encode_quad(&random_quad(i, &mut rng))?;
229            batch.push(QuadVersion {
230                quad: encoded,
231                commit_ts: CommitTs(i.saturating_add(1)),
232                op: StorageOp::Put,
233                visibility: VisibilityLabel::default(),
234            });
235        }
236        service.apply_versions(Some(AXIS), &batch)?;
237        written += n as u64;
238        after_batch(written);
239        let prev = written - n as u64;
240        if written == quads || prev / 100_000 != written / 100_000 {
241            eprintln!("  ingested {written}/{quads}");
242        }
243    }
244    Ok(())
245}
246
247fn random_quad(i: u64, rng: &mut StdRng) -> Quad {
248    let subject: NamedOrBlankNode = if rng.random_bool(0.5) {
249        NamedNode::new(format!("http://ex/s/{i}"))
250            .expect("iri")
251            .into()
252    } else {
253        BlankNode::new(format!("b{i}")).expect("bnode").into()
254    };
255    let predicate =
256        NamedNode::new(format!("http://ex/p/{}", rng.random_range(0..128u32))).expect("pred iri");
257    let object: Term = match rng.random_range(0..3u8) {
258        0 => NamedNode::new(format!("http://ex/o/{i}"))
259            .expect("obj iri")
260            .into(),
261        1 => BlankNode::new(format!("ob{i}")).expect("obj bnode").into(),
262        _ => Literal::from(format!("lit-{i}")).into(),
263    };
264    Quad::new(subject, predicate, object, GraphName::DefaultGraph)
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270
271    #[test]
272    fn duplicate_puts_collapse_to_one_sst_stat() {
273        let dir = tempfile::tempdir().unwrap();
274        exp_duplicate_puts(dir.path(), 50).unwrap();
275    }
276
277    #[test]
278    fn compact_timing_smoke_runs() {
279        let dir = tempfile::tempdir().unwrap();
280        exp_compact_timing(dir.path(), 200, 1).unwrap();
281    }
282}