diff --git a/Cargo.lock b/Cargo.lock index 907537ee..0a7c80f3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -333,7 +333,7 @@ dependencies = [ [[package]] name = "asap-accuracy" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=39a25ee3f5d3029ed13bd725d730be1f4ca58cb7#39a25ee3f5d3029ed13bd725d730be1f4ca58cb7" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2#3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2" dependencies = [ "asap-types", "asap_sketchlib", @@ -344,7 +344,7 @@ dependencies = [ [[package]] name = "asap-cost" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=39a25ee3f5d3029ed13bd725d730be1f4ca58cb7#39a25ee3f5d3029ed13bd725d730be1f4ca58cb7" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2#3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2" dependencies = [ "asap-types", "asap_sketchlib", @@ -356,7 +356,7 @@ dependencies = [ [[package]] name = "asap-executor" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=39a25ee3f5d3029ed13bd725d730be1f4ca58cb7#39a25ee3f5d3029ed13bd725d730be1f4ca58cb7" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2#3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2" dependencies = [ "ahash", "arrow", @@ -376,7 +376,7 @@ dependencies = [ [[package]] name = "asap-frontend-common" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=39a25ee3f5d3029ed13bd725d730be1f4ca58cb7#39a25ee3f5d3029ed13bd725d730be1f4ca58cb7" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2#3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2" dependencies = [ "asap-types", "serde", @@ -386,7 +386,7 @@ dependencies = [ [[package]] name = "asap-frontend-metricsql" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=39a25ee3f5d3029ed13bd725d730be1f4ca58cb7#39a25ee3f5d3029ed13bd725d730be1f4ca58cb7" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2#3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2" dependencies = [ "asap-frontend-common", "asap-types", @@ -397,7 +397,7 @@ dependencies = [ [[package]] name = "asap-frontend-promql" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=39a25ee3f5d3029ed13bd725d730be1f4ca58cb7#39a25ee3f5d3029ed13bd725d730be1f4ca58cb7" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2#3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2" dependencies = [ "asap-frontend-common", "asap-types", @@ -407,7 +407,7 @@ dependencies = [ [[package]] name = "asap-frontend-sil" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=39a25ee3f5d3029ed13bd725d730be1f4ca58cb7#39a25ee3f5d3029ed13bd725d730be1f4ca58cb7" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2#3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2" dependencies = [ "asap-types", "serde", @@ -417,7 +417,7 @@ dependencies = [ [[package]] name = "asap-frontend-sql" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=39a25ee3f5d3029ed13bd725d730be1f4ca58cb7#39a25ee3f5d3029ed13bd725d730be1f4ca58cb7" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2#3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2" dependencies = [ "asap-frontend-common", "asap-sql-function-catalog", @@ -429,7 +429,7 @@ dependencies = [ [[package]] name = "asap-planner" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=39a25ee3f5d3029ed13bd725d730be1f4ca58cb7#39a25ee3f5d3029ed13bd725d730be1f4ca58cb7" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2#3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2" dependencies = [ "asap-accuracy", "asap-cost", @@ -452,12 +452,12 @@ dependencies = [ [[package]] name = "asap-sql-function-catalog" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=39a25ee3f5d3029ed13bd725d730be1f4ca58cb7#39a25ee3f5d3029ed13bd725d730be1f4ca58cb7" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2#3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2" [[package]] name = "asap-stage0-memo" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=39a25ee3f5d3029ed13bd725d730be1f4ca58cb7#39a25ee3f5d3029ed13bd725d730be1f4ca58cb7" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2#3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2" dependencies = [ "asap-types", ] @@ -465,7 +465,7 @@ dependencies = [ [[package]] name = "asap-stage1-pass1-per-computation-candidates" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=39a25ee3f5d3029ed13bd725d730be1f4ca58cb7#39a25ee3f5d3029ed13bd725d730be1f4ca58cb7" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2#3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2" dependencies = [ "asap-types", "thiserror 2.0.20", @@ -474,7 +474,7 @@ dependencies = [ [[package]] name = "asap-stage1-pass2-reuse-candidates" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=39a25ee3f5d3029ed13bd725d730be1f4ca58cb7#39a25ee3f5d3029ed13bd725d730be1f4ca58cb7" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2#3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2" dependencies = [ "asap-accuracy", "asap-types", @@ -484,7 +484,7 @@ dependencies = [ [[package]] name = "asap-stage2-physical-optimization" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=39a25ee3f5d3029ed13bd725d730be1f4ca58cb7#39a25ee3f5d3029ed13bd725d730be1f4ca58cb7" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2#3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2" dependencies = [ "asap-types", ] @@ -492,7 +492,7 @@ dependencies = [ [[package]] name = "asap-stage3-plan-selection" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=39a25ee3f5d3029ed13bd725d730be1f4ca58cb7#39a25ee3f5d3029ed13bd725d730be1f4ca58cb7" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2#3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2" dependencies = [ "asap-accuracy", "asap-cost", @@ -507,7 +507,7 @@ dependencies = [ [[package]] name = "asap-types" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=39a25ee3f5d3029ed13bd725d730be1f4ca58cb7#39a25ee3f5d3029ed13bd725d730be1f4ca58cb7" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2#3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2" dependencies = [ "asap_sketchlib", "serde", @@ -2511,7 +2511,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "metricsql_common" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=39a25ee3f5d3029ed13bd725d730be1f4ca58cb7#39a25ee3f5d3029ed13bd725d730be1f4ca58cb7" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2#3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2" dependencies = [ "chrono", ] @@ -2519,7 +2519,7 @@ dependencies = [ [[package]] name = "metricsql_parser" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=39a25ee3f5d3029ed13bd725d730be1f4ca58cb7#39a25ee3f5d3029ed13bd725d730be1f4ca58cb7" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2#3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2" dependencies = [ "ahash", "chrono", diff --git a/Cargo.toml b/Cargo.toml index d9c59b84..96b11851 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,8 +10,8 @@ version = "0.1.0" # The backend depends on two Planner crates, at one immutable revision: # `asap-planner` to plan and `asap-executor` to execute. Planner IR types # are reached through `asap_executor::planner`. -asap-planner = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "39a25ee3f5d3029ed13bd725d730be1f4ca58cb7" } -asap-executor = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "39a25ee3f5d3029ed13bd725d730be1f4ca58cb7" } +asap-planner = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2" } +asap-executor = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2" } # The sketch library the Planner's executor pins, for the byte encodings of # the sketch states the data plane persists; keep it at the Planner's rev # (draft: ASAPPlanner#1553 head, for SIL intents). diff --git a/data_plane/Cargo.toml b/data_plane/Cargo.toml index 2f4a7c5f..db77d2c6 100644 --- a/data_plane/Cargo.toml +++ b/data_plane/Cargo.toml @@ -39,7 +39,7 @@ form_urlencoded = "1" [dev-dependencies] # Parses SIL intents for the intent round loop's end-to-end test. -asap-frontend-sil = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "39a25ee3f5d3029ed13bd725d730be1f4ca58cb7" } +asap-frontend-sil = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "3f95d9eebbb43c4e0205af4b5b5e8af9d4f517e2" } # Paused time for the intent loop's latency and overrun tests. tokio = { workspace = true, features = ["test-util"] } control_plane.workspace = true diff --git a/data_plane/src/engine.rs b/data_plane/src/engine.rs index db24ddcf..8f9f0947 100644 --- a/data_plane/src/engine.rs +++ b/data_plane/src/engine.rs @@ -133,6 +133,11 @@ pub struct EngineOptions { /// reads too; 1: every run on its query worker alone. The answers are /// the same for any value. pub query_parallelism: usize, + /// Parts each precompute window run's grouped builds split into on the + /// query worker pool (built when `query_parallelism` is above 1); + /// default 1: each window runs on its precompute thread. Above 1 a + /// window commits sooner for more CPU (the pool's split overhead). + pub precompute_parallelism: usize, /// Threads of the query worker pool (rayon's global pool, sized once per /// process) that runs those parts. Ingest, precompute and persist /// threads share the same cores; leave them room on a busy server. @@ -238,6 +243,7 @@ impl Default for EngineOptions { run_memory_limit_bytes: 4 << 30, query_threads: std::thread::available_parallelism().map_or(1, usize::from), query_parallelism: std::thread::available_parallelism().map_or(1, usize::from), + precompute_parallelism: 1, query_pool_threads: std::thread::available_parallelism().map_or(1, usize::from), query_min_split_rows: None, share_one_evaluation_results: true, @@ -435,7 +441,9 @@ impl EngineHandle { // the query runs', counted apart. let ingestion_raw_reads = Arc::new(crate::store::RawReadCounts::default()); let precompute = Arc::new( - precompute.with_raw_reads(options.label_pushdown, ingestion_raw_reads.clone()), + precompute + .with_raw_reads(options.label_pushdown, ingestion_raw_reads.clone()) + .with_parallelism(options.precompute_parallelism), ); // Push mode: the groups the shards build by push. let push_groups: Vec> = match options.precompute_mode { @@ -1222,6 +1230,19 @@ fn serve_shard( continue; } ShardMessage::Flush => { + let routing = shared + .routing + .read() + .unwrap_or_else(|e| e.into_inner()) + .clone(); + // Compacting is append work; a flush with nothing to compact + // is not counted as a run. + if let Some(through) = routing.flush_seal_through(newest_ms) { + let timer = Timer::start(); + if Arc::make_mut(&mut raw_data).seal_through(through) { + shared.metrics.append.record(timer); + } + } // The raw data travels only with a flush, which a window // closing reads; the coordinator lets it go after its pass, // so appending rarely copies the pane lists it shares. diff --git a/data_plane/src/ingestion.rs b/data_plane/src/ingestion.rs index eb9114e9..ff5930a4 100644 --- a/data_plane/src/ingestion.rs +++ b/data_plane/src/ingestion.rs @@ -369,6 +369,7 @@ impl Ingestion { limits, label_pushdown: true, raw_read_counts: None, + parallelism: 1, }, )) } @@ -500,6 +501,7 @@ impl Ingestion { Routing { scanned_metrics: self.scanned_metrics.clone(), max_future_ms: millis(self.options.max_future_ms), + allowed_lateness_ms: millis(self.options.allowed_lateness_ms), cutoffs, late_through, groups_waiting: self.groups.iter().any(|g| g.refreshed_through.is_none()), @@ -720,6 +722,10 @@ pub struct Routing { /// Each scanned metric's samples at or before this are in a window /// every group scanning it has closed (`None`: no group closed one). views_closed_through: HashMap>, + /// The allowed lateness: a shard whose newest sample is at `t` + /// compacts the panes ending at or before `t` minus it when it flushes + /// ([`Self::flush_seal_through`]). + allowed_lateness_ms: i64, } /// One batch of samples routed by a shard. @@ -805,6 +811,16 @@ impl Routing { routed } + /// Where a shard whose newest sample is at `newest_ms` compacts its + /// panes when it flushes: through the watermark its own samples allow + /// (at most the watermark the flush's pass sets, which takes the + /// newest sample over every shard). The windows that pass closes then + /// read one chunk per pane instead of one per request; a sample that + /// arrives later for a compacted pane adds a chunk, as after any seal. + pub fn flush_seal_through(&self, newest_ms: Option) -> Option { + newest_ms.map(|newest| newest.saturating_sub(self.allowed_lateness_ms)) + } + /// Seals and evicts `raw_data` as the ingestion stands: compacts the /// panes the watermark has passed and drops the panes at or before /// each metric's cutoff. @@ -932,9 +948,21 @@ pub struct Precompute { label_pushdown: bool, /// Where the runs count their raw reads' rows; `None`: not counted. raw_read_counts: Option>, + /// Parts a run's grouped summary builds split into on the query + /// worker pool ([`RunContext::with_parallelism`]: the same states for + /// any value); 1 (the default) runs each window on its own thread. + parallelism: usize, } impl Precompute { + /// Splits each window run's grouped builds into `parallelism` parts on + /// the worker pool (which must exist when it is above 1), so a large + /// window commits sooner; the pool's CPU counts as the run's. + pub fn with_parallelism(mut self, parallelism: usize) -> Self { + self.parallelism = parallelism.max(1); + self + } + /// The runs' raw reads select series by the `Scan`'s label predicates /// when `label_pushdown`, and count their rows in `counts`. pub fn with_raw_reads(mut self, label_pushdown: bool, counts: Arc) -> Self { @@ -1004,9 +1032,13 @@ impl Precompute { window_end_ms: end, }, self.limits.clone(), - )?; - let outputs = block_on(instance.execute_ingestion(group.compiled.roots(), context)?)?; - outputs + )? + .with_parallelism(self.parallelism); + let outputs = + block_on(instance.execute_ingestion(group.compiled.roots(), context.clone())?); + // The pool's work on this run counts as this thread's phase CPU. + crate::metrics::add_offloaded_cpu_ns(context.parallel_cpu_ns()); + outputs? }; Ok(self.computed(window.group, missing, outputs)) } diff --git a/data_plane/src/main.rs b/data_plane/src/main.rs index 37a778a1..811dd26c 100644 --- a/data_plane/src/main.rs +++ b/data_plane/src/main.rs @@ -129,6 +129,11 @@ struct Args { /// per run. Answers are the same for any value. Default: the cores. #[arg(long, default_value_t = EngineOptions::default().query_parallelism)] query_parallelism: usize, + /// Parts each precompute window run's grouped summary builds split + /// into on the query worker pool (the stored states are the same for + /// any value): above 1, windows commit sooner for more CPU. Default 1. + #[arg(long, default_value_t = EngineOptions::default().precompute_parallelism)] + precompute_parallelism: usize, /// Threads of the query worker pool those parts run on. Ingest, /// precompute and persist threads share the cores. Default: the cores. #[arg(long, default_value_t = EngineOptions::default().query_pool_threads)] @@ -260,6 +265,7 @@ async fn main() -> anyhow::Result<()> { run_memory_limit_bytes: args.run_memory_limit_bytes, query_threads: args.query_threads, query_parallelism: args.query_parallelism, + precompute_parallelism: args.precompute_parallelism, query_pool_threads: args.query_pool_threads, share_one_evaluation_results: !args.no_shared_results, label_pushdown: !args.no_label_pushdown, diff --git a/data_plane/src/series_ids.rs b/data_plane/src/series_ids.rs index f3767d10..857e8880 100644 --- a/data_plane/src/series_ids.rs +++ b/data_plane/src/series_ids.rs @@ -30,9 +30,23 @@ pub struct Series { pub identity: Arc, /// Shared with every query result row of this series. labels: Arc>, + /// Each label's name ([`intern_name`]) and its value's process-wide id + /// (equal texts share one id), sorted by name: a raw-data read builds a label + /// column over the label's distinct values with no text lookup or copy + /// per series. + value_ids: Box<[(&'static str, u32)]>, } impl Series { + /// The id of this series' value of the label `name`, an interned name + /// ([`intern_name`]; compared by address); `None` without the label. + pub fn value_id(&self, name: &'static str) -> Option { + self.value_ids + .iter() + .find(|(n, _)| std::ptr::eq(*n, name)) + .map(|&(_, id)| id) + } + /// The label set, shared: a query result row of this series holds it /// without copying. pub fn labels(&self) -> &Arc> { @@ -86,6 +100,13 @@ struct Interner { /// back without parsing its JSON. by_identity: ahash::HashMap, u32>, series: Vec<&'static Series>, + /// Label value ids by text, over every label name: equal texts share + /// one id. Never forgets a value. + value_ids: ahash::HashMap, u32>, + /// One shared `metric` text per metric name, so the series of one + /// metric hold the same `Arc` and per-sample code compares it by + /// address. + metrics: ahash::HashMap, Arc>, } fn interner() -> &'static RwLock { @@ -151,14 +172,38 @@ pub fn intern_pairs, V: AsRef>(pairs: &[(N, V)]) -> &'static .map(|(n, v)| (n.to_string(), v.to_string())) .collect(); let id = u32::try_from(interner.series.len()).expect("fewer than 2^32 series"); + let value_ids: Box<[(&'static str, u32)]> = sorted + .iter() + .map(|(name, value)| { + let next = u32::try_from(interner.value_ids.len()).expect("fewer than 2^32 values"); + let value_id = match interner.value_ids.get(*value) { + Some(&known) => known, + None => { + interner.value_ids.insert((*value).into(), next); + next + } + }; + (intern_name(name), value_id) + }) + .collect(); + let name = labels.get("__name__").map_or("", String::as_str); + let metric = match interner.metrics.get(name) { + Some(shared) => shared.clone(), + None => { + let shared: Arc = name.into(); + interner.metrics.insert(name.into(), shared.clone()); + shared + } + }; // Never freed: the interner keeps every series. let series: &'static Series = Box::leak(Box::new(Series { id, - metric: labels.get("__name__").map_or("", String::as_str).into(), + metric, identity: serde_json::to_string(&labels) .expect("labels serialize") .into(), labels: Arc::new(labels), + value_ids, })); interner.series.push(series); interner.by_hash.entry(hash).or_default().push(id); diff --git a/data_plane/src/store.rs b/data_plane/src/store.rs index 75ac2dae..ec7b4ee1 100644 --- a/data_plane/src/store.rs +++ b/data_plane/src/store.rs @@ -90,8 +90,9 @@ struct Chunk { fields: Vec<(&'static str, TextColumn)>, /// Rows sorted by series, then time. sorted: bool, - /// The columns built from the series' labels (each a dictionary whose - /// keys are `codes`: one entry per series, no work per row), built by + /// The columns built from the series' labels (each a dictionary: a + /// label's over its distinct values, [`Self::label_column`]; the + /// series identity's keyed by `codes`, one entry per series), built by /// the first read that needs one and shared by every later read, for /// the chunk's life. built: Mutex>, @@ -278,9 +279,18 @@ impl Chunk { .values() .map( |column| match column.as_any().downcast_ref::() { - // The keys are `codes`, counted once. - Some(dictionary) => dictionary.values().get_array_memory_size(), - None => column.get_array_memory_size(), + // The series identity column's keys are `codes`, + // counted once; a label column has its own keys. + Some(dictionary) + if dictionary + .keys() + .values() + .inner() + .ptr_eq(self.codes.values().inner()) => + { + dictionary.values().get_array_memory_size() + } + _ => column.get_array_memory_size(), }, ) .sum(); @@ -434,6 +444,40 @@ impl Chunk { self.take(&rows).map(Arc::new) } + /// The label `name` of each row, as a dictionary over the label's + /// distinct values in this chunk (in order of first appearance; `''` + /// for a series without the label): one entry per value, not per + /// series, found through the series' value ids, so many series sharing + /// a value (a `service` over its nodes) cost one entry, and readers + /// grouping by the label look up each value once. + fn label_column(&self, name: &str) -> TextColumn { + const MISSING: u32 = u32::MAX; + let name = crate::series_ids::intern_name(name); + let mut entry_of_value: ahash::HashMap = ahash::HashMap::default(); + let mut texts: Vec<&str> = Vec::new(); + let entry_of_code: Vec = self + .series + .iter() + .map(|series| { + let value = series.value_id(name).unwrap_or(MISSING); + *entry_of_value.entry(value).or_insert_with(|| { + texts.push(series.get(name).map_or("", String::as_str)); + texts.len() as u32 - 1 + }) + }) + .collect(); + let keys: Vec = self + .codes + .values() + .iter() + .map(|&code| entry_of_code[code as usize]) + .collect(); + DictionaryArray::new( + UInt32Array::from(keys), + Arc::new(StringArray::from_iter_values(texts)), + ) + } + fn column(&self, kind: &ColumnKind) -> Result { let label = match kind { ColumnKind::Time => return Ok(Arc::new(self.time.clone())), @@ -448,19 +492,19 @@ impl Chunk { if let Some(column) = built.get(kind) { return Ok(column.clone()); } - // One entry per series: series sharing a value repeat it. - let texts: StringArray = match label { - Some(name) => StringArray::from_iter_values( - self.series - .iter() - .map(|series| series.get(name).map_or("", String::as_str)), + let column: ArrayRef = match label { + Some(name) => Arc::new(self.label_column(name)), + // One entry per series. + None => Arc::new( + DictionaryArray::try_new( + self.codes.clone(), + Arc::new(StringArray::from_iter_values( + self.series.iter().map(|s| &*s.identity), + )), + ) + .map_err(|e| Error::Invalid(e.to_string()))?, ), - None => StringArray::from_iter_values(self.series.iter().map(|s| &*s.identity)), }; - let column: ArrayRef = Arc::new( - DictionaryArray::try_new(self.codes.clone(), Arc::new(texts)) - .map_err(|e| Error::Invalid(e.to_string()))?, - ); built.insert(kind.clone(), column.clone()); Ok(column) } @@ -514,12 +558,30 @@ impl RawData { /// samples of a metric no `Scan` reads are not stored. pub fn append(&mut self, samples: &[RawSample]) { let mut by_pane: BTreeMap<(&str, i64), Vec<&RawSample>> = BTreeMap::new(); + // A request's samples come in runs of one metric and pane: a run + // collects into one list, found in the map once per run. + let mut run: Option<((&str, i64), Vec<&RawSample>)> = None; for sample in samples { - let pane_end = window_end(sample.timestamp_ms, self.pane_width_ms); - by_pane - .entry((&sample.labels.metric, pane_end)) - .or_default() - .push(sample); + let key = ( + &*sample.labels.metric, + window_end(sample.timestamp_ms, self.pane_width_ms), + ); + match &mut run { + Some((run_key, rows)) + if std::ptr::eq(run_key.0, key.0) && run_key.1 == key.1 || *run_key == key => + { + rows.push(sample) + } + _ => { + if let Some((run_key, rows)) = run.take() { + by_pane.entry(run_key).or_default().extend(rows); + } + run = Some((key, vec![sample])); + } + } + } + if let Some((run_key, rows)) = run { + by_pane.entry(run_key).or_default().extend(rows); } for ((metric, pane_end), rows) in by_pane { let Some(metric) = self.by_metric.get_mut(metric) else { @@ -537,16 +599,20 @@ impl RawData { /// Compacts each pane ending at or before `watermark_ms` into one chunk: /// no more samples are expected for it (a late one adds a chunk, which /// the next call compacts). - pub fn seal_through(&mut self, watermark_ms: i64) { + /// Whether it compacted any pane. + pub fn seal_through(&mut self, watermark_ms: i64) -> bool { + let mut compacted_any = false; for metric in self.by_metric.values_mut() { for (_, pane) in metric.panes.range_mut(..=watermark_ms) { let unsorted = |chunk: &Arc| !chunk.fields.is_empty() && !chunk.sorted; if pane.len() > 1 || pane.iter().any(unsorted) { let compacted = Chunk::compacted(pane); *pane = compacted.map(Arc::new).into_iter().collect(); + compacted_any = true; } } } + compacted_any } /// Evicts `metric`'s samples at or before `oldest_kept_ms`: no read @@ -3220,4 +3286,27 @@ mod tests { assert_eq!(results.len(), usize::from(!fails)); } } + + /// A label column holds one dictionary entry per distinct value of the + /// label in the chunk, not one per series, and a series without the + /// label reads `''`. + #[test] + fn a_label_column_has_one_entry_per_distinct_value() { + let series = [ + intern_pairs(&[("__name__", "m_label_entries"), ("job", "a"), ("i", "1")]), + intern_pairs(&[("__name__", "m_label_entries"), ("job", "a"), ("i", "2")]), + intern_pairs(&[("__name__", "m_label_entries"), ("job", "b"), ("i", "3")]), + intern_pairs(&[("__name__", "m_label_entries"), ("i", "4")]), + ]; + let chunk = + Chunk::new((0..12).map(|row| (series[row % 4], row as i64, row as f64))).unwrap(); + let column = chunk.column(&ColumnKind::Label("job".into())).unwrap(); + let dictionary = column.as_any().downcast_ref::().unwrap(); + assert_eq!(dictionary.values().len(), 3); + let texts: Vec<&str> = (0..12).map(|row| text_at(dictionary, row)).collect(); + assert_eq!( + texts, + ["a", "a", "b", "", "a", "a", "b", "", "a", "a", "b", ""] + ); + } }