use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::Instant;
use tsdb_reader::{BlockReader, ReaderOptions, SampleValue, TimeRange};
const SERIES_ALIGN: usize = 16;
#[derive(serde::Deserialize)]
struct ChunkFixture {
name: String,
encoding: String,
bytes_hex: String,
#[serde(default)]
floats: Vec<SampleGt>,
#[serde(default)]
hists: Vec<SampleGt>,
}
#[derive(serde::Deserialize)]
struct SampleGt {
t: i64,
}
struct Payload {
encoding: u8,
body: Vec<u8>,
samples: u64,
min_time: i64,
max_time: i64,
}
fn main() {
let cfg = Config::from_args();
if cfg.help {
println!("{}", Config::usage());
return;
}
let float = payload("XOR2").expect("XOR2 fixture");
let hist = payload("histogram").expect("histogram fixture");
let dir = std::env::temp_dir().join(format!("tsdb-reader-bench-{}", std::process::id()));
let build = Instant::now();
for i in 0..cfg.blocks {
write_block(&dir, i, &cfg, &float, &hist).expect("write block");
}
let build_secs = build.elapsed().as_secs_f64();
let rss_before = peak_rss_kb();
let start = Instant::now();
let mut samples = 0u64;
let mut floats = 0u64;
let mut histograms = 0u64;
let mut series_seen = 0u64;
let mut chunk_mib = 0.0f64;
let mut findings = 0usize;
let mut postings_entries = 0u32;
for i in 0..cfg.blocks {
let block = BlockReader::open(&dir.join(format!("block-{i:03}")), ReaderOptions::default())
.expect("open block");
series_seen += block.scan_stats().expect("scan stats").series;
chunk_mib += block.chunk_bytes() as f64 / (1024.0 * 1024.0);
if cfg.validate {
let report = block.validate().expect("validate block");
findings += report.findings.len();
for finding in &report.findings {
eprintln!(" block {i}: {finding:?}");
}
if let Some(stats) = report.postings {
postings_entries += stats.entries;
}
}
let mut iter = block.samples(TimeRange::all());
while let Some(sample) = iter.next_sample().expect("read sample") {
samples += 1;
match sample.value {
SampleValue::Float(_) => floats += 1,
SampleValue::IntHistogram(_) | SampleValue::FloatHistogram(_) => histograms += 1,
}
}
}
let secs = start.elapsed().as_secs_f64();
let rss_after = peak_rss_kb();
if cfg.json {
println!(
"{{\"blocks\":{},\"series\":{},\"samples\":{},\"floats\":{},\"histograms\":{},\
\"seconds\":{secs:.3},\"samples_per_second\":{:.0},\"chunk_mib\":{chunk_mib:.2},\
\"peak_rss_kb_before\":{rss_before},\"peak_rss_kb_after\":{rss_after},\
\"rss_delta_kb\":{},\"validate_findings\":{findings},\
\"postings_entries\":{postings_entries},\"build_seconds\":{build_secs:.3}}}",
cfg.blocks,
series_seen,
samples,
floats,
histograms,
samples as f64 / secs,
rss_after.saturating_sub(rss_before),
);
} else {
println!("blocks {}", cfg.blocks);
println!("series {series_seen}");
println!("samples {samples} ({floats} float, {histograms} histogram)");
println!("elapsed {secs:.2}s");
println!("throughput {:.0} samples/s", samples as f64 / secs);
println!("chunk payload {chunk_mib:.2} MiB");
if cfg.validate {
println!("validation {findings} finding(s), {postings_entries} postings entries");
}
println!("peak RSS before {rss_before} KiB");
println!("peak RSS after {rss_after} KiB");
println!(
"peak RSS delta {} KiB",
rss_after.saturating_sub(rss_before)
);
println!("(block build took {build_secs:.2}s)");
println!(
"per-series cost {:.1} KiB RSS",
(rss_after.saturating_sub(rss_before)) as f64 / series_seen.max(1) as f64
);
}
if cfg.keep {
println!("kept {}", dir.display());
} else {
let _ = std::fs::remove_dir_all(&dir);
}
}
fn payload(want: &str) -> Option<Payload> {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data/chunks.json");
let raw = std::fs::read_to_string(path).ok()?;
let fixtures: Vec<ChunkFixture> = serde_json::from_str(&raw).ok()?;
let fx = fixtures
.into_iter()
.find(|f| f.name.contains(want) || f.encoding == want)?;
let body: Vec<u8> = (0..fx.bytes_hex.len() / 2)
.map(|i| u8::from_str_radix(&fx.bytes_hex[i * 2..i * 2 + 2], 16).unwrap())
.collect();
let mut times: Vec<i64> = fx
.floats
.iter()
.chain(fx.hists.iter())
.map(|s| s.t)
.collect();
times.sort_unstable();
Some(Payload {
encoding: match fx.encoding.as_str() {
"XOR" => 1,
"histogram" => 2,
"floathistogram" => 3,
"XOR2" => 4,
"histogramST" => 5,
"floathistogramST" => 6,
other => panic!("unknown fixture encoding {other}"),
},
samples: times.len() as u64,
min_time: *times.first()?,
max_time: *times.last()?,
body,
})
}
struct Config {
blocks: usize,
series: usize,
chunk_mib: usize,
validate: bool,
json: bool,
keep: bool,
help: bool,
}
impl Config {
fn from_args() -> Self {
let mut cfg = Self {
blocks: 1,
series: 20_000,
chunk_mib: 16,
validate: true,
json: false,
keep: false,
help: false,
};
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--blocks" => cfg.blocks = parse(&mut args, "--blocks"),
"--series" => cfg.series = parse(&mut args, "--series"),
"--chunk-mib" => cfg.chunk_mib = parse(&mut args, "--chunk-mib"),
"--no-validate" => cfg.validate = false,
"--json" => cfg.json = true,
"--keep" => cfg.keep = true,
"--help" | "-h" => cfg.help = true,
"--bench" => {}
other => {
eprintln!("unknown argument {other}");
cfg.help = true;
}
}
}
cfg
}
fn usage() -> String {
[
"tsdb-reader read benchmark",
"",
" --blocks N blocks to generate (default 1)",
" --series N series per block (default 20000)",
" --chunk-mib N distinct chunk payload per block, MiB (default 16)",
" --no-validate skip BlockReader::validate on each block",
" --json emit one machine-readable line",
" --keep keep the generated blocks",
"",
"Every tenth series carries the integer histogram chunk, the rest the",
"XOR2 float chunk. Throughput is measured over a full SampleIterator",
"pass with tombstone filtering and default decode limits.",
]
.join("\n")
}
}
fn parse(args: &mut impl Iterator<Item = String>, flag: &str) -> usize {
args.next()
.and_then(|v| v.parse().ok())
.unwrap_or_else(|| panic!("{flag} expects a number"))
}
fn write_block(
root: &Path,
index: usize,
cfg: &Config,
float: &Payload,
hist: &Payload,
) -> std::io::Result<()> {
let dir = root.join(format!("block-{index:03}"));
std::fs::create_dir_all(dir.join("chunks"))?;
let target = cfg.chunk_mib * 1024 * 1024;
let copies = (target / (float.body.len() + hist.body.len()).max(1)).max(1);
let mut segment = Vec::new();
segment.extend_from_slice(&0x85BD_40DDu32.to_be_bytes());
segment.push(1);
segment.extend_from_slice(&[0, 0, 0]);
let mut float_offsets = Vec::with_capacity(copies);
let mut hist_offsets = Vec::with_capacity(copies);
for _ in 0..copies {
float_offsets.push(segment.len() as u64);
push_record(&mut segment, float);
hist_offsets.push(segment.len() as u64);
push_record(&mut segment, hist);
}
std::fs::write(dir.join("chunks/000001"), &segment)?;
let mut symbols: Vec<String> = Vec::new();
for s in 0..cfg.series {
symbols.push("__name__".to_string());
symbols.push(format!("bench_metric_{:04}", s % 50));
symbols.push("job".to_string());
symbols.push(format!("job-{}", s / 50));
symbols.push("instance".to_string());
symbols.push(format!("instance-{s:06}"));
}
symbols.sort();
symbols.dedup();
let mut file = Vec::new();
file.extend_from_slice(&0xBAAA_D700u32.to_be_bytes());
file.push(2);
let symbols_off = file.len();
let mut sym = Vec::new();
for name in &symbols {
put_uvarint(&mut sym, name.len() as u64);
sym.extend_from_slice(name.as_bytes());
}
file.extend_from_slice(&((sym.len() + 4) as u32).to_be_bytes());
file.extend_from_slice(&(symbols.len() as u32).to_be_bytes());
file.extend_from_slice(&sym);
let sym_crc = crc32c::crc32c(&file[symbols_off + 4..]);
file.extend_from_slice(&sym_crc.to_be_bytes());
while file.len() % 16 != 0 {
file.push(0);
}
let series_off = file.len();
let mut series_bytes = 0usize;
let mut postings: BTreeMap<(String, String), Vec<u32>> = BTreeMap::new();
for s in 0..cfg.series {
let metric = format!("bench_metric_{:04}", s % 50);
let job = format!("job-{}", s / 50);
let instance = format!("instance-{s:06}");
let labels = [
("__name__", metric.as_str()),
("job", job.as_str()),
("instance", instance.as_str()),
];
let (payload, offset) = if s % 10 == 0 {
(hist, hist_offsets[(s / 10) % copies])
} else {
(float, float_offsets[s % copies])
};
let mut body = Vec::new();
put_uvarint(&mut body, labels.len() as u64);
for (name, value) in labels {
put_uvarint(
&mut body,
symbols.binary_search(&name.to_string()).unwrap() as u64,
);
put_uvarint(
&mut body,
symbols.binary_search(&value.to_string()).unwrap() as u64,
);
}
put_uvarint(&mut body, 1); put_varint(&mut body, payload.min_time);
put_uvarint(&mut body, (payload.max_time - payload.min_time) as u64);
put_uvarint(&mut body, offset);
let record_off = file.len();
let reference = (record_off / SERIES_ALIGN) as u32;
put_uvarint(&mut file, body.len() as u64);
file.extend_from_slice(&body);
file.extend_from_slice(&crc32c::crc32c(&body).to_be_bytes());
while file.len() % 16 != 0 {
file.push(0);
}
series_bytes += body.len();
for (name, value) in labels {
postings
.entry((name.to_string(), value.to_string()))
.or_default()
.push(reference);
}
postings
.entry((String::new(), String::new()))
.or_default()
.push(reference);
}
let postings_off = file.len();
let mut table: Vec<(String, String, u64)> = Vec::with_capacity(postings.len());
for ((name, value), refs) in &postings {
while file.len() % 4 != 0 {
file.push(0);
}
let list_off = file.len() as u64;
let mut body = Vec::with_capacity(4 + refs.len() * 4);
body.extend_from_slice(&(refs.len() as u32).to_be_bytes());
for r in refs {
body.extend_from_slice(&r.to_be_bytes());
}
file.extend_from_slice(&(body.len() as u32).to_be_bytes());
file.extend_from_slice(&body);
file.extend_from_slice(&crc32c::crc32c(&body).to_be_bytes());
table.push((name.clone(), value.clone(), list_off));
}
let table_off = file.len();
let mut content = Vec::new();
content.extend_from_slice(&(table.len() as u32).to_be_bytes());
for (name, value, list_off) in &table {
put_uvarint(&mut content, 2);
put_uvarint(&mut content, name.len() as u64);
content.extend_from_slice(name.as_bytes());
put_uvarint(&mut content, value.len() as u64);
content.extend_from_slice(value.as_bytes());
put_uvarint(&mut content, *list_off);
}
let table_crc = crc32c::crc32c(&content);
file.extend_from_slice(&(content.len() as u32).to_be_bytes());
file.extend_from_slice(&content);
file.extend_from_slice(&table_crc.to_be_bytes());
let mut toc = Vec::new();
toc.extend_from_slice(&(symbols_off as u64).to_be_bytes());
toc.extend_from_slice(&(series_off as u64).to_be_bytes());
toc.extend_from_slice(&(postings_off as u64).to_be_bytes());
toc.extend_from_slice(&(table_off as u64).to_be_bytes());
toc.extend_from_slice(&(postings_off as u64).to_be_bytes());
toc.extend_from_slice(&(table_off as u64).to_be_bytes());
let toc_crc = crc32c::crc32c(&toc);
file.extend_from_slice(&toc);
file.extend_from_slice(&toc_crc.to_be_bytes());
std::fs::write(dir.join("index"), &file)?;
let hist_series = cfg.series.div_ceil(10);
let float_series = cfg.series - hist_series;
let min_time = float.min_time.min(hist.min_time);
let max_time = float.max_time.max(hist.max_time) + 1;
let meta = format!(
"{{\n\t\"ulid\": \"bench-{index:03}\",\n\t\"minTime\": {min_time},\n\t\"maxTime\": {max_time},\n\
\t\"stats\": {{\"numSamples\": {}, \"numFloatSamples\": {}, \"numHistogramSamples\": {},\
\"numSeries\": {}, \"numChunks\": {}}},\n\t\"compaction\": {{\"level\": 1}},\n\t\"version\": 1\n}}\n",
float_series as u64 * float.samples + hist_series as u64 * hist.samples,
float_series as u64 * float.samples,
hist_series as u64 * hist.samples,
cfg.series,
cfg.series,
);
std::fs::write(dir.join("meta.json"), meta)?;
let _ = series_bytes;
Ok(())
}
fn push_record(segment: &mut Vec<u8>, payload: &Payload) {
put_uvarint(segment, payload.body.len() as u64);
let start = segment.len();
segment.push(payload.encoding);
segment.extend_from_slice(&payload.body);
let crc = crc32c::crc32c(&segment[start..]);
segment.extend_from_slice(&crc.to_be_bytes());
}
fn put_uvarint(out: &mut Vec<u8>, mut v: u64) {
loop {
let mut b = (v & 0x7f) as u8;
v >>= 7;
if v != 0 {
b |= 0x80;
}
out.push(b);
if v == 0 {
break;
}
}
}
fn put_varint(out: &mut Vec<u8>, v: i64) {
put_uvarint(out, ((v << 1) ^ (v >> 63)) as u64);
}
fn peak_rss_kb() -> u64 {
#[cfg(unix)]
{
let mut usage: libc::rusage = unsafe { std::mem::zeroed() };
if unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut usage) } != 0 {
return 0;
}
let max = usage.ru_maxrss as u64;
if cfg!(target_os = "macos") {
max / 1024
} else {
max
}
}
#[cfg(not(unix))]
{
0
}
}