#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::missing_panics_doc,
// Test fixtures: every cast here is of a bounded loop counter into a byte, and the
// wrap is what makes the fill vary.
clippy::cast_possible_truncation
)]
use ant_node::storage::{ChunkStore, ChunkStoreConfig};
use std::path::Path;
use std::time::{Duration, Instant};
use tempfile::TempDir;
const DEFAULT_KEYS: usize = 100_000;
const SCAN_CEILING_PER_KEY: Duration = Duration::from_micros(50);
#[cfg(target_os = "linux")]
const SCAN_READ_CEILING: u64 = 64 * 1024;
fn key_count() -> usize {
std::env::var("ANT_SCALE_KEYS")
.ok()
.and_then(|raw| raw.parse().ok())
.unwrap_or(DEFAULT_KEYS)
}
fn plant_chunks(chunks_dir: &Path, count: usize) {
for shard in 0u16..256 {
std::fs::create_dir_all(chunks_dir.join(format!("{shard:02x}"))).expect("mkdir");
}
for n in 0..count {
let mut address = [0u8; 32];
address[..8].copy_from_slice(&(n as u64).to_le_bytes());
address[31] = (n % 256) as u8;
let path = chunks_dir
.join(format!("{:02x}", address[31]))
.join(hex::encode(address));
std::fs::write(path, b"x").expect("plant a chunk");
}
}
fn walk(chunks_dir: &Path, stat_each: bool) -> Duration {
let started = Instant::now();
let mut seen = 0usize;
if let Ok(shards) = std::fs::read_dir(chunks_dir) {
for shard in shards.flatten() {
let Ok(entries) = std::fs::read_dir(shard.path()) else {
continue;
};
for entry in entries.flatten() {
seen += entry.file_name().as_encoded_bytes().len();
if stat_each {
seen += usize::from(entry.metadata().is_ok());
}
}
}
}
assert!(seen > 0, "the control walk found nothing to walk");
started.elapsed()
}
#[cfg(target_os = "linux")]
fn resident_bytes() -> Option<u64> {
let status = std::fs::read_to_string("/proc/self/status").ok()?;
status
.lines()
.find_map(|line| line.strip_prefix("VmRSS:"))
.and_then(|value| value.split_whitespace().next()?.parse::<u64>().ok())
.map(|kb| kb * 1024)
}
#[cfg(not(target_os = "linux"))]
fn resident_bytes() -> Option<u64> {
None
}
#[tokio::test]
async fn opening_a_large_store_stays_quick() {
let keys = key_count();
let tmp = TempDir::new().expect("temp dir");
let root = tmp.path().join("node");
let chunks_dir = root.join("chunks");
std::fs::create_dir_all(&chunks_dir).expect("mkdir");
let planting = Instant::now();
plant_chunks(&chunks_dir, keys);
let planted = planting.elapsed();
let before = resident_bytes();
let opening = Instant::now();
let store = ChunkStore::new(ChunkStoreConfig {
root_dir: root.clone(),
verify_on_read: true,
disk_reserve: 0,
})
.await
.expect("open a store holding a large number of chunks");
let scan = opening.elapsed();
let after = resident_bytes();
let indexed = store.current_chunks().expect("count");
assert_eq!(
indexed as usize, keys,
"the scan must find every planted chunk"
);
let per_key_ns = scan.as_nanos() / keys.max(1) as u128;
let growth = match (before, after) {
(Some(before), Some(after)) => format!("{} KiB", after.saturating_sub(before) / 1024),
_ => "not measured on this platform".to_string(),
};
println!(
"scale: {keys} chunks planted in {planted:?}, scanned in {scan:?} \
({per_key_ns} ns/key), resident growth {growth}"
);
let ceiling = SCAN_CEILING_PER_KEY * u32::try_from(keys).unwrap_or(u32::MAX);
assert!(
scan < ceiling,
"scanning {keys} chunks took {scan:?} ({per_key_ns} ns/key), over the {ceiling:?} \
ceiling"
);
drop(store);
let mut scans = Vec::new();
let mut bare = Vec::new();
let mut stats = Vec::new();
for _ in 0..3 {
scans.push(time_a_scan(&root).await);
bare.push(walk(&chunks_dir, false));
stats.push(walk(&chunks_dir, true));
}
let scan = median(&mut scans);
let names_only = median(&mut bare);
let with_stat = median(&mut stats);
let midpoint = names_only + with_stat.saturating_sub(names_only) / 2;
println!(
"scale: medians of three, bare walk {names_only:?} names only, {with_stat:?} with a \
stat each, store scan {scan:?}, midpoint {midpoint:?}"
);
assert!(
scan < midpoint,
"the scan took {scan:?}, past the {midpoint:?} midpoint between a names-only walk \
({names_only:?}) and one that stats every entry ({with_stat:?}), so it is doing \
more per entry than reading a name"
);
}
async fn time_a_scan(root: &Path) -> Duration {
let started = Instant::now();
let store = ChunkStore::new(ChunkStoreConfig {
root_dir: root.to_path_buf(),
verify_on_read: true,
disk_reserve: 0,
})
.await
.expect("reopen the store");
let elapsed = started.elapsed();
drop(store);
elapsed
}
fn median(samples: &mut [Duration]) -> Duration {
samples.sort_unstable();
samples.get(samples.len() / 2).copied().unwrap_or_default()
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn the_in_memory_index_costs_a_bounded_amount_per_chunk() {
let keys = key_count();
let tmp = TempDir::new().expect("temp dir");
let root = tmp.path().join("node");
let chunks_dir = root.join("chunks");
std::fs::create_dir_all(&chunks_dir).expect("mkdir");
plant_chunks(&chunks_dir, keys);
let per_key = index_cost_in_a_fresh_process(&root, keys);
println!("scale: index costs {per_key} bytes per chunk, measured in its own process");
assert!(
per_key < 128,
"the index costs {per_key} bytes per chunk, which does not scale"
);
assert!(
per_key > 0,
"the index reported no cost at all, so nothing was measured"
);
}
#[cfg(target_os = "linux")]
fn index_cost_in_a_fresh_process(root: &Path, keys: usize) -> u64 {
let exe = std::env::current_exe().expect("this test binary");
let output = std::process::Command::new(exe)
.arg("--exact")
.arg("child_reports_index_memory")
.arg("--nocapture")
.arg("--ignored")
.env("ANT_SCALE_ROOT", root)
.env("ANT_SCALE_KEYS", keys.to_string())
.output()
.expect("spawn the child");
let said = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success(),
"the child failed: {said}{}",
String::from_utf8_lossy(&output.stderr)
);
said.lines()
.find_map(|line| line.strip_prefix(INDEX_BYTES_PER_KEY))
.and_then(|value| value.trim().parse().ok())
.unwrap_or_else(|| panic!("the child reported no measurement: {said}"))
}
#[cfg(target_os = "linux")]
const INDEX_BYTES_PER_KEY: &str = "INDEX_BYTES_PER_KEY=";
#[cfg(target_os = "linux")]
#[tokio::test]
#[ignore = "child process of the index memory measurement, not run on its own"]
async fn child_reports_index_memory() {
let root = std::path::PathBuf::from(
std::env::var("ANT_SCALE_ROOT").expect("the child needs a store to open"),
);
let keys = key_count();
let before = resident_bytes().expect("linux reports this");
let store = ChunkStore::new(ChunkStoreConfig {
root_dir: root,
verify_on_read: true,
disk_reserve: 0,
})
.await
.expect("open");
let after = resident_bytes().expect("linux reports this");
assert_eq!(store.current_chunks().expect("count") as usize, keys);
let grew = after.saturating_sub(before);
println!("{INDEX_BYTES_PER_KEY}{}", grew / keys.max(1) as u64);
drop(store);
}
#[tokio::test]
async fn each_chunk_the_store_writes_costs_one_directory_entry() {
let keys = 2_000;
let tmp = TempDir::new().expect("temp dir");
let root = tmp.path().join("node");
std::fs::create_dir_all(&root).expect("mkdir");
let store = ChunkStore::new(ChunkStoreConfig {
root_dir: root.clone(),
verify_on_read: true,
disk_reserve: 0,
})
.await
.expect("open");
for n in 0..keys {
let mut content = vec![0u8; 512];
content[..8].copy_from_slice(&(n as u64).to_le_bytes());
let address = ant_node::client::compute_address(&content);
store.put(&address, &content).await.expect("put");
}
store.wait_idle().await;
let entries = count_entries(&root.join("chunks"));
assert_eq!(
entries.files, keys,
"the store wrote {} files for {keys} chunks",
entries.files
);
assert!(
entries.dirs <= 256,
"the store made {} directories, which grows with the store",
entries.dirs
);
}
struct Entries {
files: usize,
dirs: usize,
}
fn count_entries(path: &Path) -> Entries {
let mut counted = Entries { files: 0, dirs: 0 };
let Ok(entries) = std::fs::read_dir(path) else {
return counted;
};
for entry in entries.flatten() {
match entry.file_type() {
Ok(kind) if kind.is_dir() => {
counted.dirs += 1;
let nested = count_entries(&entry.path());
counted.files += nested.files;
counted.dirs += nested.dirs;
}
Ok(_)
if entry.file_name() == ant_node::storage::chunk_store::LAYOUT_FILE_NAME
|| entry.file_name() == ".lock" => {}
Ok(_) => counted.files += 1,
Err(_) => {}
}
}
counted
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn the_startup_scan_does_not_read_chunk_contents() {
let keys = 3_000;
let chunk = 64 * 1024;
let tmp = TempDir::new().expect("temp dir");
let root = tmp.path().join("node");
plant_sized(&root.join("chunks"), keys, chunk);
let before = bytes_read().expect("linux reports this");
let store = ChunkStore::new(ChunkStoreConfig {
root_dir: root.clone(),
verify_on_read: true,
disk_reserve: 0,
})
.await
.expect("open");
let read = bytes_read()
.expect("linux reports this")
.saturating_sub(before);
let payload = (keys * chunk) as u64;
println!(
"scale: opening a store of {keys} chunks read {read} bytes, against {payload} \
bytes of chunk"
);
assert_eq!(store.current_chunks().expect("count") as usize, keys);
assert!(
read < SCAN_READ_CEILING,
"the scan read {read} bytes of a {payload} byte store, over the \
{SCAN_READ_CEILING} byte ceiling, so it is reading contents"
);
}
#[cfg(target_os = "linux")]
fn bytes_read() -> Option<u64> {
let io = std::fs::read_to_string("/proc/self/io").ok()?;
io.lines()
.find_map(|line| line.strip_prefix("rchar:"))
.and_then(|value| value.trim().parse().ok())
}
#[cfg(target_os = "linux")]
fn plant_sized(chunks_dir: &Path, count: usize, bytes: usize) {
for shard in 0u16..256 {
std::fs::create_dir_all(chunks_dir.join(format!("{shard:02x}"))).expect("mkdir");
}
let payload = vec![7u8; bytes];
for n in 0..count {
let mut address = [0u8; 32];
address[..8].copy_from_slice(&(n as u64).to_le_bytes());
address[31] = (n % 256) as u8;
let path = chunks_dir
.join(format!("{:02x}", address[31]))
.join(hex::encode(address));
std::fs::write(path, &payload).expect("plant a chunk");
}
}