use std::path::{Path, PathBuf};
use regolith::{Db, Options};
const PATTERN: u8 = 0xC5;
const PAINT_CHUNK: usize = 1024;
const PAINT_LEVELS: usize = 128;
const MEASURE_THREAD_STACK: usize = 8 * 1024 * 1024;
const FINDING_THRESHOLD: usize = 4 * 1024;
const CALIBRATION_BYTES: usize = 64 * 1024;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let dir: PathBuf = std::env::args()
.nth(1)
.ok_or("usage: stack_depth <scratch-dir>")?
.into();
std::fs::create_dir_all(&dir)?;
let db_dir = dir.join("db");
if cfg!(debug_assertions) {
println!("WARNING: debug build. Frames are much larger than the shipped");
println!(" release profile. Re-run with --release.\n");
}
build_fixture(&db_dir)?;
let handle = std::thread::Builder::new()
.name("regolith-stack-probe".to_string())
.stack_size(MEASURE_THREAD_STACK)
.spawn(move || run_probes(&db_dir))?;
let results = handle.join().map_err(|_| "measuring thread panicked")??;
println!("regolith stack depth, {} profile", profile_name());
println!(
" method paint 0x{PATTERN:02X}, {PAINT_LEVELS} x {PAINT_CHUNK} B window, gap-cancelled diff"
);
println!(" build {}", build_profile());
println!(
" host {} / {}",
std::env::consts::ARCH,
std::env::consts::OS
);
println!();
let overhead = results
.iter()
.find(|r| r.is_calibration)
.map(|c| c.bytes.saturating_sub(CALIBRATION_BYTES))
.unwrap_or(0);
println!(" {:<40} {:>8} {:>8} verdict", "path", "raw", "net");
println!(" {}", "-".repeat(76));
let mut findings = 0usize;
let mut measured = 0usize;
for r in &results {
let net = r.bytes.saturating_sub(overhead);
let verdict = if r.is_calibration {
format!("harness overhead {overhead} B")
} else {
measured += 1;
if r.saturated {
format!("SATURATED (> {} B window)", PAINT_LEVELS * PAINT_CHUNK)
} else if net > FINDING_THRESHOLD {
findings += 1;
format!("FINDING: over {FINDING_THRESHOLD} B")
} else {
"within 4 KiB".to_string()
}
};
println!(" {:<40} {:>8} {:>8} {}", r.label, r.bytes, net, verdict);
}
println!();
let peak = results
.iter()
.filter(|r| !r.is_calibration)
.map(|r| r.bytes.saturating_sub(overhead))
.max();
match peak {
Some(p) => println!(
" peak across measured paths {p} B ({:.1} KiB)",
p as f64 / 1024.0
),
None => println!(" peak across measured paths not measured"),
}
println!(" paths over {FINDING_THRESHOLD} B {findings} of {measured}");
println!(
" calibration measured {} B for a known {CALIBRATION_BYTES} B frame",
results
.iter()
.find(|r| r.is_calibration)
.map(|c| c.bytes)
.unwrap_or(0)
);
Ok(())
}
fn profile_name() -> &'static str {
"embedded"
}
fn build_profile() -> &'static str {
if cfg!(debug_assertions) {
"debug (numbers not representative)"
} else {
"release"
}
}
fn build_fixture(db_dir: &Path) -> Result<(), Box<dyn std::error::Error>> {
let _ = std::fs::remove_dir_all(db_dir);
let db = Db::open(db_dir, Options::embedded())?;
let mut value = vec![0u8; 128];
for i in 0..40_000u64 {
value[..8].copy_from_slice(&i.to_le_bytes());
db.put(&key(i), &value)?;
}
db.compact_range(None, None)?;
for i in (0..40_000u64).step_by(3) {
value[..8].copy_from_slice(&i.to_le_bytes());
db.put(&key(i), &value)?;
}
for i in 0..200u64 {
value[..8].copy_from_slice(&i.to_le_bytes());
db.put(&key(i), &value)?;
}
println!("fixture: {}", level_shape(&db));
db.close()?;
Ok(())
}
fn level_shape(db: &Db) -> String {
let mut parts = Vec::new();
for level in 0..7 {
let name = format!("regolith.num-files-at-level{level}");
if let Some(n) = db.get_int_property(&name)
&& n > 0
{
parts.push(format!("L{level}={n}"));
}
}
if parts.is_empty() {
"no SSTables".to_string()
} else {
parts.join(" ")
}
}
fn key(i: u64) -> Vec<u8> {
format!("key{i:013}").into_bytes()
}
struct Probe {
label: String,
bytes: usize,
saturated: bool,
is_calibration: bool,
}
fn run_probes(db_dir: &Path) -> Result<Vec<Probe>, String> {
let mut out = Vec::new();
out.push(measure("calibration (known 64 KiB frame)", true, || {
consume_64k();
}));
let mut opened: Option<Db> = None;
out.push(measure(
"Db::open (multi-level + WAL replay)",
false,
|| {
opened = Db::open(db_dir, Options::embedded()).ok();
},
));
let db = opened.ok_or_else(|| "Db::open failed inside the probe".to_string())?;
println!("opened: {}", level_shape(&db));
let hit = key(20_001);
let miss = key(9_999_999);
out.push(measure("point read, key present", false, || {
let _ = std::hint::black_box(db.get(std::hint::black_box(&hit)));
}));
out.push(measure(
"point read, key absent (bloom miss)",
false,
|| {
let _ = std::hint::black_box(db.get(std::hint::black_box(&miss)));
},
));
let seek_target = key(12_345);
out.push(measure("iterator seek + 50-entry walk", false, || {
let mut it = db.iter();
it.seek(std::hint::black_box(&seek_target));
let mut n = 0;
while it.valid() && n < 50 {
let _ = std::hint::black_box(it.key());
it.next();
n += 1;
}
}));
out.push(measure("scan_page of 1000 rows", false, || {
let _ = std::hint::black_box(db.scan_page(None, None, 1000));
}));
let mut value = vec![7u8; 128];
out.push(measure(
"8000 puts crossing a flush boundary",
false,
|| {
for i in 100_000u64..108_000 {
value[..8].copy_from_slice(&i.to_le_bytes());
if db.put(&key(i), &value).is_err() {
return;
}
}
},
));
out.push(measure("compaction merge (compact_range)", false, || {
let _ = std::hint::black_box(db.compact_range(None, None));
}));
let _ = db.close();
Ok(out)
}
#[inline(never)]
fn consume_64k() {
let buf = [0u8; CALIBRATION_BYTES];
std::hint::black_box(&buf);
}
#[inline(never)]
fn paint(levels: usize) -> usize {
let mut buf = [PATTERN; PAINT_CHUNK];
let here = buf.as_mut_ptr() as usize;
if levels <= 1 {
std::hint::black_box(buf.as_mut_ptr());
return here;
}
let deepest = paint(levels - 1);
std::hint::black_box(buf.as_mut_ptr());
deepest
}
#[inline(never)]
fn snapshot(low: usize, top: usize) -> Vec<u8> {
let len = top - low;
let mut out = vec![0u8; len];
for (i, slot) in out.iter_mut().enumerate() {
*slot = unsafe { std::ptr::read_volatile((low + i) as *const u8) };
}
out
}
fn measure<F: FnOnce()>(label: &str, is_calibration: bool, workload: F) -> Probe {
let anchor: u8 = 0;
let top = std::hint::black_box(&anchor) as *const u8 as usize;
let low = paint(PAINT_LEVELS);
let before = snapshot(low, top);
let low_again = paint(PAINT_LEVELS);
assert_eq!(
low, low_again,
"paint frames moved between runs; the measurement would be invalid"
);
workload();
let after = snapshot(low, top);
let first_diff = before
.iter()
.zip(after.iter())
.position(|(b, a)| b != a)
.unwrap_or(before.len());
Probe {
label: label.to_string(),
bytes: top - (low + first_diff),
saturated: first_diff == 0,
is_calibration,
}
}