Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions data_plane/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ asap-planner.workspace = true
asap-executor.workspace = true
asap_sketchlib.workspace = true
serde_bytes = "0.11"
# Each view fragment is compressed (segment.rs).
zstd = "0.13"
ahash = "0.8"
# The per-thread series cache of the Remote Write decoder (a table of
# indices hashed by the keys they point to).
Expand Down
65 changes: 49 additions & 16 deletions data_plane/examples/view_read_bench.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
//! Cold view reads, `mmap` versus `pread` (docs/design/tiered-view-storage.md,
//! B3): writes `WINDOWS` windows of `SERIES` rows of one view (KLL states of
//! `SAMPLES` samples each, a series identity and a value) to a segment,
//! seals it, then decodes every window both ways, with the page cache warm
//! and after dropping it, and prints ns per window and per row, and the
//! process's `RssAnon`/`RssFile`.
//! B3): writes `WINDOWS` windows of `SERIES` rows of one view (states of
//! `SAMPLES` samples each of `FAMILY`, `kll` (default), `ddsketch` (alpha
//! 0.02) or `counter` (exact); a series identity and a value) to a
//! segment, timing the writes, seals it, then decodes every window both
//! ways, with the page cache warm and after dropping it, and prints ns per
//! window and per row, and the process's `RssAnon`/`RssFile`.
//!
//! `cargo run --release -p data_plane --example view_read_bench -- [SERIES] [WINDOWS] [SAMPLES] [DIR]`
//! `cargo run --release -p data_plane --example view_read_bench -- [SERIES] [WINDOWS] [SAMPLES] [DIR] [FAMILY]`

#[global_allocator]
static ALLOCATOR: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
Expand All @@ -17,8 +18,9 @@ use std::time::{Duration, Instant};
use asap_executor::planner::ir::schema::{
DataType, Field, FieldDataType, Schema, PROMQL_SERIES_IDENTITY,
};
use asap_executor::planner::summary_type::SketchAlgorithm;
use asap_executor::summary_kernels::DatasketchesKLLAccumulator;
use asap_executor::planner::summary_type::{ExactKind, ExactParams, SketchAlgorithm};
use asap_executor::summary_kernels::exact::ExactAccumulator;
use asap_executor::summary_kernels::{DDSketchAccumulator, DatasketchesKLLAccumulator};
use asap_executor::values::{Batch, Value};
use asap_executor::AggregateCore;
use data_plane::persist::{ViewFiles, ViewRead};
Expand All @@ -29,9 +31,15 @@ fn main() {
let windows: i64 = args.get(2).map_or(40, |a| a.parse().unwrap());
let samples: usize = args.get(3).map_or(15, |a| a.parse().unwrap());
let dir = PathBuf::from(args.get(4).map_or("view-read-bench", String::as_str));
let family_name = args.get(5).map_or("kll", String::as_str);
let _ = std::fs::remove_dir_all(&dir);

let family = FieldDataType::Sketch(SketchAlgorithm::Kll);
let family = match family_name {
"kll" => FieldDataType::Sketch(SketchAlgorithm::Kll),
"ddsketch" => FieldDataType::Sketch(SketchAlgorithm::DDSketch),
"counter" => FieldDataType::ExactAggregate(ExactKind::Counter, ExactParams::Counter),
other => panic!("unknown family {other}: kll, ddsketch or counter"),
};
let schema = Arc::new(Schema::with_time_index(
vec![
Field::plain("ts", DataType::Timestamp, false),
Expand All @@ -44,14 +52,35 @@ fn main() {
));
let mut files = ViewFiles::open(&dir, 1, Duration::from_secs(5)).unwrap();
let mut locations = Vec::new();
let mut write = Duration::ZERO;
for window in 0..windows {
let end = (window + 1) * 15_000;
let rows = (0..series)
.map(|s| {
let mut kll = DatasketchesKLLAccumulator::new(132);
for i in 0..samples {
kll.update(((s * 31 + i * 7 + window as usize) % 1000) as f64);
}
let sample = |i: usize| ((s * 31 + i * 7 + window as usize) % 1000) as f64;
let state: Arc<dyn AggregateCore> = match family_name {
"kll" => {
let mut kll = DatasketchesKLLAccumulator::new(132);
(0..samples).for_each(|i| kll.update(sample(i)));
Arc::new(kll)
}
"ddsketch" => {
let mut dd = asap_sketchlib::DdSketch::new(0.02);
(0..samples).for_each(|i| dd.add(&sample(i)));
Arc::new(DDSketchAccumulator::restore_from_disk(dd).unwrap())
}
_ => {
let mut counter = ExactAccumulator::new(family.clone(), false).unwrap();
(0..samples).for_each(|i| {
counter.update(
None,
(window as usize * samples + i) as f64,
end - 15_000 + i as i64 * 100,
)
});
Arc::new(counter)
}
};
vec![
Value::Timestamp(end),
Value::Utf8(
Expand All @@ -64,15 +93,17 @@ fn main() {
Value::Float64(s as f64),
Value::Summary {
family: family.clone(),
state: Arc::new(kll) as Arc<dyn AggregateCore>,
state,
},
]
})
.collect();
let batch = Batch::try_new(schema.clone(), rows).unwrap();
let started = Instant::now();
let written = files
.append(0, (end - 15_000, end), &[(1, std::slice::from_ref(&batch))])
.unwrap();
write += started.elapsed();
let location = written
.locations
.into_iter()
Expand All @@ -84,8 +115,10 @@ fn main() {
files.seal(0).unwrap();
let bytes: u64 = locations.iter().map(|l| u64::from(l.len())).sum();
println!(
"{windows} windows x {series} rows, {samples} samples per KLL: {:.1} MiB of fragments",
bytes as f64 / 1048576.0
"{windows} windows x {series} rows, {samples} samples per {family_name} state: {:.1} MiB of fragments, {:.1} B per row; write {:.0} ns per row",
bytes as f64 / 1048576.0,
bytes as f64 / (windows as f64 * series as f64),
write.as_nanos() as f64 / (windows as f64 * series as f64)
);
// pread first: a mapped page cannot be dropped from the page cache.
for how in [ViewRead::Pread, ViewRead::Mmap] {
Expand Down
1 change: 1 addition & 0 deletions data_plane/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ pub mod remote_write;
pub mod result_cache;
pub mod segment;
pub mod series_ids;
mod state_codec;
pub mod store;
pub mod window_cache;

Expand Down
126 changes: 84 additions & 42 deletions data_plane/src/persist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1105,12 +1105,13 @@ mod tests {
// docs/design/tiered-view-storage.md, tests V2, V3, V9, V12, V13,
// V18, V19. They fail until the segment format is implemented.

use asap_executor::arrow::array::{DictionaryArray, Float64Array};
use asap_executor::arrow::array::DictionaryArray;
use asap_executor::arrow::datatypes::UInt32Type;
use asap_executor::planner::ir::schema::{
DataType, Field, FieldDataType, Schema, PROMQL_SERIES_IDENTITY,
};
use asap_executor::planner::summary_type::{ExactKind, ExactParams, SketchAlgorithm};
use asap_executor::values::state_view_bytes;

/// A fresh directory for one test's segments.
fn segment_dir(test: &str) -> PathBuf {
Expand Down Expand Up @@ -1314,6 +1315,59 @@ mod tests {
out
}

/// One 1 s pane of 1,000 series, ten samples each, in a DDSketch at
/// alpha 0.02 (the demo's finest quantile view): the window's stored
/// fragment, with its series and label columns.
fn ten_sample_ddsketch_window() -> Batch {
// Samples uniform in [50, 100), full precision (xorshift).
let mut seed = 0x9e37_79b9_7f4a_7c15u64;
let mut sample = move || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
50.0 + 50.0 * (seed >> 11) as f64 / (1u64 << 53) as f64
};
let states = (0..1000)
.map(|_| {
let mut sketch = DdSketch::new(0.02);
for _ in 0..10 {
sketch.add(&sample());
}
Arc::new(DDSketchAccumulator::restore_from_disk(sketch).unwrap())
as Arc<dyn AggregateCore>
})
.collect();
window_batch(
1_000,
FieldDataType::Sketch(SketchAlgorithm::DDSketch),
states,
)
}

/// The window of [`ten_sample_ddsketch_window`] takes 30.2 kB on disk
/// (30 B a series, most of it the full-precision sum, min and max), not
/// the 126 kB of the mapped layout (106 kB of DDSketch views alone).
#[test]
fn a_ten_sample_ddsketch_window_is_stored_compact() {
let dir = segment_dir("dd-bytes");
let batch = ten_sample_ddsketch_window();
let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap();
let written = files
.append(0, (0, 1_000), &[(1, std::slice::from_ref(&batch))])
.unwrap();
let views: usize = batch
.to_rows()
.iter()
.map(|row| match &row[4] {
Value::Summary { state, .. } => state_view_bytes(state.as_ref()).unwrap().len(),
_ => unreachable!(),
})
.sum();
assert_eq!(views, 106_176);
assert_eq!(location_of(&written, 1).len(), 30_196);
let _ = std::fs::remove_dir_all(&dir);
}

/// V2. A cold window decodes, from its columnar fragment, to the rows
/// that were committed, read from the active segment (by `pread`) and
/// again once the segment is sealed (mapped), and with `ViewRead::Pread`.
Expand Down Expand Up @@ -1404,25 +1458,28 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}

/// V18. Reading a sealed segment borrows the text keys and plain
/// columns from the mapping, and every window of the segment shares one
/// dictionary; `ViewRead::Pread` copies them and reads the same rows.
/// A cold read rebuilds a KLL column (no compact form) in the mapped
/// layout in buffers of its own and reports their bytes, which the
/// batch's own memory count leaves out; every window of a segment
/// shares one dictionary of texts; `ViewRead::Pread` reads the same rows.
#[test]
fn mapped_reads_borrow_fixed_width_columns() {
let dir = segment_dir("borrow");
fn cold_reads_report_state_bytes_and_share_one_dictionary() {
let dir = segment_dir("cold-read");
let (_, a, b) = states().remove(1);
let (a, b): (Arc<dyn AggregateCore>, Arc<dyn AggregateCore>) = (Arc::from(a), Arc::from(b));
let kll = FieldDataType::Sketch(SketchAlgorithm::Kll);
let rows = |end| {
window_batch(
end,
kll.clone(),
(0..1000)
.map(|i| if i % 2 == 0 { a.clone() } else { b.clone() })
.collect(),
)
};
let (first, second) = (rows(10), rows(20));
let states: Vec<Arc<dyn AggregateCore>> = (0..1000)
.map(|i| if i % 2 == 0 { a.clone() } else { b.clone() })
.collect();
let held = 4 * (states.len() + 1)
+ states
.iter()
.map(|s| state_view_bytes(s.as_ref()).unwrap().len().div_ceil(8) * 8)
.sum::<usize>();
let (first, second) = (
window_batch(10, kll.clone(), states.clone()),
window_batch(20, kll, states),
);
let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap();
let w1 = files
.append(0, (0, 10), &[(1, std::slice::from_ref(&first))])
Expand All @@ -1432,9 +1489,11 @@ mod tests {
.unwrap();
files.seal(0).unwrap();
let (l1, l2) = (location_of(&w1, 1), location_of(&w2, 1));
let r1 = l1.read(first.schema(), ViewRead::Mmap).unwrap().0;
let r2 = l2.read(second.schema(), ViewRead::Mmap).unwrap().0;
let (r1, state_bytes) = l1.read(first.schema(), ViewRead::Mmap).unwrap();
let (r2, _) = l2.read(second.schema(), ViewRead::Mmap).unwrap();
assert_same_rows(&first, &r1, "mapped");
assert_eq!(state_bytes, held);
assert_eq!(r1.state_column(4).unwrap().state_memory_bytes(), 0);
let identity = |batch: &Batch| {
batch
.column(1)
Expand All @@ -1443,34 +1502,15 @@ mod tests {
.expect("a cold text column is a dictionary over the segment's texts")
.clone()
};
let keys = identity(&r1).keys().values().as_ptr() as usize;
assert!(l1.maps(keys), "text keys are copied, not borrowed");
let values = r1
.column(3)
.as_any()
.downcast_ref::<Float64Array>()
.unwrap();
assert!(
l1.maps(values.values().as_ptr() as usize),
"values are copied, not borrowed"
);
// The KLL states are read in place (a mapped column, charged
// nothing), not rebuilt as objects.
let states = r1.state_column(4).expect("a state column");
assert_eq!(states.state_memory_bytes(), 0);
assert!(
Arc::ptr_eq(identity(&r1).values(), identity(&r2).values()),
"one dictionary per segment"
);
let copied = l1.read(first.schema(), ViewRead::Pread).unwrap().0;
let (copied, copied_state_bytes) = l1.read(first.schema(), ViewRead::Pread).unwrap();
assert_same_rows(&first, &copied, "pread");
// The mapped states' bytes, which the batch does not count, are
// The rebuilt states' bytes, which the batch does not count, are
// reported for the window's charge, mapped or copied alike.
let (_, mapped_state_bytes) = l1.read(first.schema(), ViewRead::Mmap).unwrap();
let (_, copied_state_bytes) = l1.read(first.schema(), ViewRead::Pread).unwrap();
assert!(mapped_state_bytes > (first.num_rows() + 1) * 4);
assert_eq!(mapped_state_bytes, copied_state_bytes);
assert!(!l1.maps(identity(&copied).keys().values().as_ptr() as usize));
assert_eq!(copied_state_bytes, state_bytes);
let _ = std::fs::remove_dir_all(&dir);
}

Expand Down Expand Up @@ -1551,7 +1591,9 @@ mod tests {
let (l1, l2) = (location_of(&written, 1), location_of(&written, 2));
// `job` (other) is stored in view 2 only; `region` and `zone` in
// neither.
assert_eq!(l2.len() - l1.len(), series as u32 * 4);
// (Fragments are compressed: only the order of their lengths is
// fixed.)
assert!(l2.len() > l1.len());
for (location, batch, what) in [(&l1, &labeled, "labels"), (&l2, &other, "other")] {
let active = location.read(batch.schema(), ViewRead::Mmap).unwrap().0;
assert_same_rows(batch, &active, &format!("{what}, active segment"));
Expand Down Expand Up @@ -1794,7 +1836,7 @@ mod tests {
files.seal(0).unwrap();
assert!(locations[4].is_cold(), "sealing (60, 80] cools (40, 60]");
assert!(!locations[6].is_cold());
let read = locations[0].read(batch.schema(), ViewRead::Mmap).unwrap().0;
let (read, _) = locations[0].read(batch.schema(), ViewRead::Mmap).unwrap();
assert_same_rows(&batch, &read, "a cold segment");
let _ = std::fs::remove_dir_all(&dir);
}
Expand Down
Loading
Loading