diff --git a/Cargo.lock b/Cargo.lock index 06062facc..3071a1160 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -421,6 +421,8 @@ dependencies = [ "asap_sketchlib", "chrono", "futures", + "libc", + "rayon", "regex", "rmp-serde", "serde", @@ -933,6 +935,25 @@ dependencies = [ "libc", ] +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.21" @@ -2861,6 +2882,26 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + [[package]] name = "recursive" version = "0.1.1" diff --git a/crates/executor/Cargo.toml b/crates/executor/Cargo.toml index d9b4d9753..b5708910b 100644 --- a/crates/executor/Cargo.toml +++ b/crates/executor/Cargo.toml @@ -7,6 +7,8 @@ autotests = false [dependencies] arrow.workspace = true ahash.workspace = true +# Grouped builds and merges split by group key run on its worker threads. +rayon = "1.10" chrono = { version = "0.4.39", default-features = false, features = ["std"] } futures = "0.3" planner-types = { package = "asap-types", path = "../types" } @@ -19,6 +21,10 @@ regex = "1" xxhash-rust = { version = "0.8", features = ["xxh64"] } +# The per-thread CPU clock that charges a run for its worker-thread tasks. +[target.'cfg(unix)'.dependencies] +libc = "0.2" + [features] # Executor internals the Planner's own tests use (the PromQL row encoding, # the timing frontier, binding views in a compiled DAG); a deployment diff --git a/crates/executor/src/operators/group_table.rs b/crates/executor/src/operators/group_table.rs index abeacf54c..96c032dc6 100644 --- a/crates/executor/src/operators/group_table.rs +++ b/crates/executor/src/operators/group_table.rs @@ -435,6 +435,25 @@ impl GroupTable { groups } + /// Per group column, each part id's key bytes ([`Value::key`]). + pub(crate) fn part_keys(&self) -> Vec> { + self.parts + .iter() + .map(|column| { + let mut keys: Vec<&[u8]> = vec![&[]; column.first_values.len()]; + for (key, &part) in &column.part_of_key { + keys[part as usize] = key; + } + keys + }) + .collect() + } + + /// Group `group`'s part ids, one per group column. + pub(crate) fn parts_of(&self, group: u32) -> &[u32] { + &self.parts_of_group[group as usize] + } + /// The group columns of the groups `order`, in the input's types. pub(crate) fn label_arrays( &self, @@ -458,6 +477,33 @@ impl GroupTable { } } +/// The group columns of the groups `order` of several tables over the +/// same group columns, each `(table, group)`, in the input's types. +pub(crate) fn label_arrays_of( + tables: &[&GroupTable], + order: &[(usize, u32)], + input: &crate::values::SchemaRef, +) -> Result, Error> { + let Some(first) = tables.first() else { + return Ok(Vec::new()); + }; + first + .group_columns + .iter() + .enumerate() + .map(|(index, &column)| { + let FieldDataType::Plain(dtype) = &input.fields[column].dtype else { + return Err(Error::Invalid("group columns are plain".into())); + }; + let values = order + .iter() + .map(|&(table, group)| tables[table].label(group, index)) + .collect::>(); + arrow_columns::encode(dtype, ColumnDepth::BatchColumn, &values) + }) + .collect() +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/executor/src/operators/summary/mod.rs b/crates/executor/src/operators/summary/mod.rs index af69b86fb..df32ebd4f 100644 --- a/crates/executor/src/operators/summary/mod.rs +++ b/crates/executor/src/operators/summary/mod.rs @@ -8,6 +8,8 @@ use arrow::array::{Array, BooleanArray, UInt32Array}; use planner_types::summary_type::{MergeInputRule, SummaryTypeCapability}; use std::num::NonZeroU32; +mod partitioned; + /// What each input row adds to its item's count in a keyed summary build /// ([`Operator::per_group_keyed_summary_build`] or /// [`Operator::all_groups_summary_build`]). Produced by the physical planner @@ -630,7 +632,29 @@ struct PerGroupBuild<'a> { /// One state per group, updated row by row through the family's /// [`StateColumnUpdater`]; a run-local [`GroupTable`] numbers the groups. async fn build_per_group_summary( - mut input: Input<'_, Batch>, + input: Input<'_, Batch>, + build: PerGroupBuild<'_>, + input_schema: &SchemaRef, + output: &SchemaRef, + context: &RunContext, +) -> Result { + if partitioned::splits_build(&build, context)? { + return partitioned::build_per_group_summary_split( + input, + build, + input_schema, + output, + context, + ) + .await; + } + fold_build_input(input, build, input_schema, output, context).await +} + +/// [`build_per_group_summary`] on one thread, folding each input batch as +/// it arrives. +async fn fold_build_input>( + mut input: impl futures::Stream> + Unpin, build: PerGroupBuild<'_>, input_schema: &SchemaRef, output: &SchemaRef, @@ -660,53 +684,14 @@ async fn build_per_group_summary( // chunk's new groups, so one large batch cannot overshoot the limit // by more than a chunk's states. for batch in row_chunks(&whole) { - let groups = table.group_ids(&batch)?; - updater.ensure_groups(table.len())?; - workspace.set_bytes(updater.memory_bytes() + table.memory_bytes())?; - let mask = filter_mask(filter.as_deref(), &batch)?; - let times = build.time.map(|time| { - timestamp_array(batch.column(time)) - .expect("summary time columns are timestamps") - .clone() - }); - let time_at = |row: usize| times.as_ref().map_or(0, |times| times.value(row)); - let values = batch.column(build.value); - if let Some(values) = float64_array(values) { - for (row, &group) in groups.iter().enumerate() { - // SQL aggregates ignore NULL samples while retaining the group. - if !kept(&mask, row) || values.is_null(row) { - continue; - } - updater.update(group, values.value(row), time_at(row))?; - } - } else if let Some(values) = values.as_any().downcast_ref::() - { - // Int64 ids or numbers, without decoding the column. - for (row, &group) in groups.iter().enumerate() { - if !kept(&mask, row) || values.is_null(row) { - continue; - } - updater.update_value(group, &Value::Int64(values.value(row)), time_at(row))?; - } - } else { - // Typed values: Utf8 items of a distinct count (KMV, HLL) - // or of UnivMon, and Bool items of UnivMon. - let SummaryFamilyType::Plain(dtype) = &input_schema.fields[build.value].dtype - else { - return Err(invalid("summary values are plain")); - }; - let values = crate::values::arrow_columns::decode( - values.as_ref(), - dtype, - ColumnDepth::BatchColumn, - ); - for (row, &group) in groups.iter().enumerate() { - if !kept(&mask, row) || matches!(values[row], Value::Null) { - continue; - } - updater.update_value(group, &values[row], time_at(row))?; - } - } + fold_build_rows( + &mut table, + &mut updater, + &batch, + &build, + filter.as_deref(), + input_schema, + )?; work.checkpoint_rows(batch.num_rows()).await?; workspace.set_bytes(updater.memory_bytes() + table.memory_bytes())?; } @@ -714,6 +699,60 @@ async fn build_per_group_summary( grouped_states(&table, updater.seal(), input_schema, output) } +/// Fold `batch`'s rows into `table`'s groups and `updater`'s states, as a +/// per-group build does with each chunk of its input. +fn fold_build_rows( + table: &mut GroupTable, + updater: &mut StateColumnUpdater, + batch: &Batch, + build: &PerGroupBuild<'_>, + filter: Option<&Expression>, + input_schema: &SchemaRef, +) -> Result<(), Error> { + let groups = table.group_ids(batch)?; + updater.ensure_groups(table.len())?; + let mask = filter_mask(filter, batch)?; + let times = build.time.map(|time| { + timestamp_array(batch.column(time)) + .expect("summary time columns are timestamps") + .clone() + }); + let time_at = |row: usize| times.as_ref().map_or(0, |times| times.value(row)); + let values = batch.column(build.value); + if let Some(values) = float64_array(values) { + for (row, &group) in groups.iter().enumerate() { + // SQL aggregates ignore NULL samples while retaining the group. + if !kept(&mask, row) || values.is_null(row) { + continue; + } + updater.update(group, values.value(row), time_at(row))?; + } + } else if let Some(values) = values.as_any().downcast_ref::() { + // Int64 ids or numbers, without decoding the column. + for (row, &group) in groups.iter().enumerate() { + if !kept(&mask, row) || values.is_null(row) { + continue; + } + updater.update_value(group, &Value::Int64(values.value(row)), time_at(row))?; + } + } else { + // Typed values: Utf8 items of a distinct count (KMV, HLL) + // or of UnivMon, and Bool items of UnivMon. + let SummaryFamilyType::Plain(dtype) = &input_schema.fields[build.value].dtype else { + return Err(invalid("summary values are plain")); + }; + let values = + crate::values::arrow_columns::decode(values.as_ref(), dtype, ColumnDepth::BatchColumn); + for (row, &group) in groups.iter().enumerate() { + if !kept(&mask, row) || matches!(values[row], Value::Null) { + continue; + } + updater.update_value(group, &values[row], time_at(row))?; + } + } + Ok(()) +} + /// A `PerGroupKeyedSummaryBuild`'s parameters. struct KeyedBuild<'a> { family: &'a SummaryFamilyType, @@ -1304,7 +1343,46 @@ impl ObjectMerger { /// batch is folded into the groups' states as it arrives and then dropped, /// so the merge holds one input batch at a time plus its accumulators. async fn merge_summary_streaming( - mut input: Input<'_, Batch>, + input: Input<'_, Batch>, + state_column: usize, + groups: &[usize], + shape: MergeOutput<'_>, + input_schema: &SchemaRef, + output: &SchemaRef, + context: &RunContext, +) -> Result { + let family = &input_schema.fields[state_column].dtype; + if context.parallelism() < 2 + || groups.is_empty() + || !matches!(family, SummaryFamilyType::ExactAggregate(..)) + { + return fold_merge_input( + input, + state_column, + groups, + shape, + input_schema, + output, + context, + ) + .await; + } + partitioned::merge_exact_split( + input, + state_column, + groups, + shape, + input_schema, + output, + context, + ) + .await +} + +/// [`merge_summary_streaming`] on one thread, folding each input batch as +/// it arrives. +async fn fold_merge_input>( + mut input: impl futures::Stream> + Unpin, state_column: usize, groups: &[usize], shape: MergeOutput<'_>, diff --git a/crates/executor/src/operators/summary/partitioned.rs b/crates/executor/src/operators/summary/partitioned.rs new file mode 100644 index 000000000..9a0f05786 --- /dev/null +++ b/crates/executor/src/operators/summary/partitioned.rs @@ -0,0 +1,590 @@ +//! Grouped summary builds and merges split by group key over rayon's +//! worker threads ([`RunContext::with_parallelism`]). +//! +//! Each input batch is split into `P` parts by a hash of its rows' group +//! keys (order kept), and worker `i` folds part `i` of every batch, in input +//! order, into its own group table and states. A group's rows all land in +//! one part and are folded in their input order, so its state is the state +//! one thread builds (a compensated sum adds in the same order; a sketch +//! sees the same items in the same order). The parts' groups are disjoint; +//! they are combined into the order one thread emits (groups by key) and +//! sealed once. +use super::*; +use crate::operators::group_table::label_arrays_of; +use crate::values::arrow_columns::text_dictionary_array; +use arrow::array::{Int64Array, StringArray, TimestampMillisecondArray}; +use rayon::prelude::*; +use std::collections::BinaryHeap; + +/// Rows of input folded per round of partition tasks: memory is checked +/// and cancellation seen after each. +pub(super) const WAVE_ROWS: usize = 1 << 18; + +/// Bytes of input held per wave (as the run charges them: a batch whose +/// dictionary is shared with other batches is charged it in full each +/// time), so a wave never holds much more than one thread's fold does. +const WAVE_BYTES: usize = 64 << 20; + +fn hasher() -> ahash::RandomState { + ahash::RandomState::with_seeds(0x51_7cc1_b727_220a, 0x95ef_d7a0_1c2b_3e44, 7, 11) +} + +/// Each row's group key hash, mixed over `groups`; key-equal values (zero +/// signs, NaN payloads, `Value::key`) hash alike. +fn row_hashes(batch: &Batch, groups: &[usize]) -> Result, Error> { + let state = hasher(); + let rows = batch.num_rows(); + let mut hashes = vec![0u64; rows]; + for &column in groups { + let array = batch.column(column); + let mut mix = |row: usize, value: u64| { + hashes[row] = (hashes[row].rotate_left(23) ^ value).wrapping_mul(0x9e37_79b9_7f4a_7c15); + }; + if let Some(dictionary) = text_dictionary_array(array) { + let texts = dictionary + .values() + .as_any() + .downcast_ref::() + .expect("batch text columns are dictionaries over strings"); + // One hash per dictionary entry the batch uses (a stored view's + // windows share one large dictionary): a dense slot per entry, or + // a map when the dictionary is much larger than the batch, as + // `GroupTable` resolves entries. + let keys = dictionary.keys(); + let dense = crate::values::arrow_columns::dense_dictionary(texts.len(), rows); + let mut slots: Vec> = if dense { + vec![None; texts.len()] + } else { + Vec::new() + }; + let mut map: ahash::AHashMap = ahash::AHashMap::new(); + for row in 0..rows { + if keys.is_null(row) { + mix(row, 1); + continue; + } + let entry = keys.value(row); + let cached = if dense { + slots[entry as usize] + } else { + map.get(&entry).copied() + }; + let hash = match cached { + Some(hash) => hash, + None => { + let hash = state.hash_one(texts.value(entry as usize).as_bytes()); + if dense { + slots[entry as usize] = Some(hash); + } else { + map.insert(entry, hash); + } + hash + } + }; + mix(row, hash); + } + continue; + } + let any = array.as_any(); + if let Some(values) = any.downcast_ref::() { + for row in 0..rows { + let v = if values.is_null(row) { + 1 + } else { + state.hash_one(values.value(row)) + }; + mix(row, v); + } + } else if let Some(values) = any.downcast_ref::() { + for row in 0..rows { + let v = if values.is_null(row) { + 1 + } else { + state.hash_one(values.value(row)) + }; + mix(row, v); + } + } else if let Some(values) = float64_array(array) { + for row in 0..rows { + let v = if values.is_null(row) { + 1 + } else { + let value = values.value(row); + let bits = if value == 0. { + 0 + } else if value.is_nan() { + f64::NAN.to_bits() + } else { + value.to_bits() + }; + state.hash_one(bits) + }; + mix(row, v); + } + } else { + let SummaryFamilyType::Plain(dtype) = &batch.schema().fields[column].dtype else { + return Err(invalid("group columns are plain")); + }; + let values = crate::values::arrow_columns::decode( + array.as_ref(), + dtype, + ColumnDepth::BatchColumn, + ); + for (row, value) in values.iter().enumerate() { + mix(row, state.hash_one(value.key()?)); + } + } + } + Ok(hashes) +} + +/// `batch` split into `parts` batches by group key, each keeping the input +/// order; `None` for a part with no row. +fn split(batch: &Batch, groups: &[usize], parts: usize) -> Result>, Error> { + let hashes = row_hashes(batch, groups)?; + let mut indices: Vec> = vec![Vec::new(); parts]; + for (row, hash) in hashes.into_iter().enumerate() { + let part = (((hash >> 32) * parts as u64) >> 32) as usize; + indices[part].push(row as u32); + } + indices + .into_iter() + .map(|rows| { + if rows.is_empty() { + Ok(None) + } else if rows.len() == batch.num_rows() { + Ok(Some(batch.clone())) + } else { + batch.take(&UInt32Array::from(rows)).map(Some) + } + }) + .collect() +} + +/// Each batch of a wave split into `parts`; then `fold` runs once per part +/// on the worker threads, with that part of every batch in input order. +/// Charges the tasks and their worker threads' CPU time to `context`. +fn fold_wave( + wave: &[&Batch], + groups: &[usize], + workers: &mut [W], + context: &RunContext, + fold: impl Fn(&mut W, &Batch) -> Result<(), Error> + Sync, +) -> Result<(), Error> { + use crate::runtime::thread_cpu_ns; + let parts = workers.len(); + let splits = wave + .par_iter() + .map(|batch| { + let start = thread_cpu_ns(); + split(batch, groups, parts).map(|split| (split, thread_cpu_ns() - start)) + }) + .collect::, Error>>()?; + let split_ns: u64 = splits.iter().map(|(_, ns)| ns).sum(); + let fold_ns = workers + .par_iter_mut() + .enumerate() + .map(|(part, worker)| { + let start = thread_cpu_ns(); + splits + .iter() + .filter_map(|(split, _)| split[part].as_ref()) + .try_for_each(|batch| fold(worker, batch))?; + Ok(thread_cpu_ns() - start) + }) + .collect::, Error>>()? + .into_iter() + .sum::(); + context.count_parallel_tasks(wave.len() + parts, split_ns + fold_ns); + Ok(()) +} + +/// Up to [`WAVE_ROWS`] rows (and about [`WAVE_BYTES`]) of `input`, whole +/// batches; `done` once the input has ended. +async fn next_wave>( + input: &mut (impl futures::Stream> + Unpin), + done: &mut bool, +) -> Result<(Vec, usize), Error> { + let mut wave = Vec::new(); + let (mut rows, mut bytes) = (0, 0); + while rows < WAVE_ROWS && bytes < WAVE_BYTES { + match input.next().await { + Some(batch) => { + let batch = batch?; + rows += batch.num_rows(); + bytes += batch.memory_bytes(); + wave.push(batch); + } + None => { + *done = true; + break; + } + } + } + Ok((wave, rows)) +} + +/// Parts for an input whose first wave has `rows` rows: 1 (one thread) +/// below the run's `min_split_rows`, else at most its parallelism, with +/// at least `min_split_rows / 8` rows each. +fn part_count(context: &RunContext, rows: usize) -> usize { + let min_split_rows = context.min_split_rows(); + if rows == 0 || rows < min_split_rows { + return 1; + } + context + .parallelism() + .min(rows / (min_split_rows / 8).max(1)) + .max(1) +} + +/// Every part's groups, `(part, group)`, in the order one table over all +/// their rows lists them ([`GroupTable::groups_in_key_order`]): by each +/// group column's key bytes in turn. Groups of different parts never have +/// equal keys. +fn groups_in_key_order(tables: &[&GroupTable]) -> Vec<(usize, u32)> { + struct Head<'a> { + key: Vec<&'a [u8]>, + part: usize, + position: usize, + } + impl PartialEq for Head<'_> { + fn eq(&self, other: &Self) -> bool { + self.cmp(other).is_eq() + } + } + impl Eq for Head<'_> {} + impl PartialOrd for Head<'_> { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } + } + impl Ord for Head<'_> { + // Reversed: `BinaryHeap` pops the greatest. + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + other.key.cmp(&self.key).then(other.part.cmp(&self.part)) + } + } + let orders: Vec> = tables + .par_iter() + .map(|table| table.groups_in_key_order()) + .collect(); + let keys: Vec>> = tables.iter().map(|table| table.part_keys()).collect(); + let key_of = |part: usize, group: u32| -> Vec<&[u8]> { + tables[part] + .parts_of(group) + .iter() + .zip(&keys[part]) + .map(|(&id, column)| column[id as usize]) + .collect() + }; + let mut heap = BinaryHeap::with_capacity(tables.len()); + for (part, order) in orders.iter().enumerate() { + if let Some(&group) = order.first() { + heap.push(Head { + key: key_of(part, group), + part, + position: 0, + }); + } + } + let mut merged = Vec::with_capacity(orders.iter().map(Vec::len).sum()); + while let Some(Head { part, position, .. }) = heap.pop() { + merged.push((part, orders[part][position])); + if let Some(&group) = orders[part].get(position + 1) { + heap.push(Head { + key: key_of(part, group), + part, + position: position + 1, + }); + } + } + merged +} + +/// The output batch of parts' groups `order`: labels, then the state +/// column `states` whose state `i` is row `i`'s. +fn output_batch( + tables: &[&GroupTable], + order: &[(usize, u32)], + states: StateColumn, + input: &SchemaRef, + output: &SchemaRef, +) -> Result { + let mut arrays = label_arrays_of(tables, order, input)?; + let mut columns = vec![None; arrays.len()]; + arrays.push(Arc::new(UInt32Array::from_iter_values( + 0..order.len() as u32, + ))); + columns.push(Some(Arc::new(states))); + Batch::from_parts(output.clone(), arrays, columns, order.len()) +} + +/// One part of a split build: its groups and their open states. +struct BuildPart { + table: GroupTable, + updater: StateColumnUpdater, +} + +/// Whether a build may split by group key at `context`'s parallelism +/// (its input size decides: [`part_count`]). +pub(super) fn splits_build(build: &PerGroupBuild<'_>, context: &RunContext) -> Result { + if context.parallelism() < 2 || build.groups.is_empty() { + return Ok(false); + } + let updater = StateColumnUpdater::new(build.family, build.parameters)?; + Ok(updater.groups_are_independent()) +} + +/// [`build_per_group_summary`] split by group key over up to +/// `context.parallelism()` parts; a small input runs on one thread. +pub(super) async fn build_per_group_summary_split( + mut input: Input<'_, Batch>, + build: PerGroupBuild<'_>, + input_schema: &SchemaRef, + output: &SchemaRef, + context: &RunContext, +) -> Result { + let mut done = false; + let (first, first_rows) = next_wave(&mut input, &mut done).await?; + let parts = part_count(context, first_rows); + if parts < 2 { + let input = futures::stream::iter(first.into_iter().map(Ok)).chain(input); + return fold_build_input(input, build, input_schema, output, context).await; + } + let filter = build + .filter + .map(|filter| filter.at_evaluation_time(context)); + let filter = filter.as_deref(); + let mut workers = (0..parts) + .map(|_| { + Ok(BuildPart { + table: GroupTable::new(build.groups.to_vec()), + updater: StateColumnUpdater::new(build.family, build.parameters)?, + }) + }) + .collect::, Error>>()?; + let mut work = Cooperative::new(context); + let mut workspace = Workspace::new(context)?; + let mut wave = Some((first, first_rows)); + loop { + let (batches, rows) = match wave.take() { + Some(wave) => wave, + None if done => break, + None => next_wave(&mut input, &mut done).await?, + }; + if rows > 0 { + let refs: Vec<&Batch> = batches.iter().map(|batch| &**batch).collect(); + fold_wave(&refs, build.groups, &mut workers, context, |part, batch| { + fold_build_rows( + &mut part.table, + &mut part.updater, + batch, + &build, + filter, + input_schema, + ) + })?; + workspace.set_bytes( + workers + .iter() + .map(|part| part.updater.memory_bytes() + part.table.memory_bytes()) + .sum(), + )?; + work.checkpoint_rows(rows).await?; + } + } + let (tables, updaters): (Vec, Vec) = workers + .into_iter() + .map(|part| (part.table, part.updater)) + .unzip(); + let table_refs: Vec<&GroupTable> = tables.iter().collect(); + let order = groups_in_key_order(&table_refs); + let states = StateColumnUpdater::gather(updaters, &order)?.seal(); + output_batch(&table_refs, &order, states, input_schema, output) +} + +/// One part of a split exact merge: its groups and their merged records. +struct MergePart { + table: GroupTable, + merged: Vec>, +} + +impl MergePart { + fn memory_bytes(&self) -> usize { + self.table.memory_bytes() + + self.merged.len() + * std::mem::size_of::>() + } +} + +/// Whether every state of `batch`'s column `state_column` is an exact +/// record (not a keyed exact state, which merges as an object). +fn holds_exact_records(batch: &Batch, state_column: usize) -> Result { + use crate::summary_kernels::exact::ExactAccumulator; + use crate::values::StateStorage; + let (states, indices) = state_indices(batch, state_column)?; + Ok(match states.storage() { + StateStorage::Exact(_) => true, + _ => indices.values().iter().all(|&index| { + states + .state(index as usize) + .as_any() + .downcast_ref::() + .and_then(ExactAccumulator::scalar) + .is_some() + }), + }) +} + +/// The parts' groups so far as one batch of merged records, in key order. +fn merged_batch( + workers: &mut [MergePart], + family: &SummaryFamilyType, + input_schema: &SchemaRef, + output: &SchemaRef, +) -> Result { + let mut merged: Vec>> = workers + .iter_mut() + .map(|part| std::mem::take(&mut part.merged)) + .collect(); + let table_refs: Vec<&GroupTable> = workers.iter().map(|part| &part.table).collect(); + let order = groups_in_key_order(&table_refs); + let records = order + .iter() + .map(|&(part, group)| { + merged[part][group as usize] + .take() + .ok_or_else(|| invalid("every group has a row")) + }) + .collect::, Error>>()?; + output_batch( + &table_refs, + &order, + StateColumn::from_exact(family.clone(), records), + input_schema, + output, + ) +} + +/// A grouped merge of exact states split by group key over up to +/// `context.parallelism()` parts, wave by wave (each wave's batches are +/// held only while it is folded). A small input, and the rest of an input +/// once a state is not an exact record (a keyed exact state merges as an +/// object), run on one thread, after the groups merged so far: a group's +/// records fold in input order either way. +pub(super) async fn merge_exact_split( + mut input: Input<'_, Batch>, + state_column: usize, + groups: &[usize], + shape: MergeOutput<'_>, + input_schema: &SchemaRef, + output: &SchemaRef, + context: &RunContext, +) -> Result { + use crate::summary_kernels::exact::ExactAccumulator; + use crate::values::StateStorage; + let family = &input_schema.fields[state_column].dtype; + let mut done = false; + let (first, first_rows) = next_wave(&mut input, &mut done).await?; + let parts = part_count(context, first_rows); + let one_thread = |before: Vec, wave: Vec>, input| { + let shared = |batch: crate::runtime::SharedValue| Arc::new((*batch).clone()); + futures::stream::iter(before.into_iter().map(Arc::new).map(Ok)) + .chain(futures::stream::iter(wave.into_iter().map(shared).map(Ok))) + .chain(futures::StreamExt::map( + input, + move |batch: Result<_, Error>| batch.map(shared), + )) + }; + if parts < 2 { + let input = one_thread(Vec::new(), first, input); + return fold_merge_input( + input, + state_column, + groups, + shape, + input_schema, + output, + context, + ) + .await; + } + let mut workers: Vec = (0..parts) + .map(|_| MergePart { + table: GroupTable::new(groups.to_vec()), + merged: Vec::new(), + }) + .collect(); + let mut work = Cooperative::new(context); + let mut workspace = Workspace::new(context)?; + let mut wave = Some((first, first_rows)); + loop { + let (batches, rows) = match wave.take() { + Some(wave) => wave, + None if done => break, + None => next_wave(&mut input, &mut done).await?, + }; + if rows == 0 { + continue; + } + let refs: Vec<&Batch> = batches.iter().map(|batch| &**batch).collect(); + let all_records = refs + .par_iter() + .map(|batch| holds_exact_records(batch, state_column)) + .collect::, Error>>()? + .into_iter() + .all(|exact| exact); + if !all_records { + let so_far = merged_batch(&mut workers, family, input_schema, output)?; + drop(workspace); + let input = one_thread(vec![so_far], batches, input); + return fold_merge_input( + input, + state_column, + groups, + shape, + input_schema, + output, + context, + ) + .await; + } + fold_wave(&refs, groups, &mut workers, context, |part, batch| { + let ids = part.table.group_ids(batch)?; + part.merged.resize(part.table.len(), None); + let (states, indices) = state_indices(batch, state_column)?; + for (row, &group) in ids.iter().enumerate() { + let index = indices.value(row) as usize; + let record = match states.storage() { + StateStorage::Exact(records) => records.get(index), + _ => states + .state(index) + .as_any() + .downcast_ref::() + .and_then(ExactAccumulator::scalar) + .cloned() + .ok_or_else(|| invalid("exact merge input is not a record"))?, + }; + fold_record(&mut part.merged[group as usize], record)?; + } + Ok(()) + })?; + workspace.set_bytes(workers.iter().map(MergePart::memory_bytes).sum())?; + work.checkpoint_rows(rows).await?; + } + if workers.iter().all(|part| part.table.len() == 0) { + let input = one_thread(Vec::new(), Vec::new(), input); + return fold_merge_input( + input, + state_column, + groups, + shape, + input_schema, + output, + context, + ) + .await; + } + merged_batch(&mut workers, family, input_schema, output) +} diff --git a/crates/executor/src/runtime/context.rs b/crates/executor/src/runtime/context.rs index 8c0373d1c..d2ea18071 100644 --- a/crates/executor/src/runtime/context.rs +++ b/crates/executor/src/runtime/context.rs @@ -30,6 +30,11 @@ pub(super) struct Control { cancelled: Cell, bytes: Cell, peak: Cell, + /// Partition tasks the run's operators ran on worker threads + /// ([`RunContext::with_parallelism`]). + parallel_tasks: Cell, + /// CPU time those tasks used on the worker threads, in nanoseconds. + parallel_cpu_ns: Cell, pub(super) limits: Limits, waiters: RefCell>, } @@ -41,8 +46,18 @@ pub struct RunContext { /// later row of its series, in ms (`DataArrival`'s /// `max_out_of_order_ms`); `None` when undeclared. max_out_of_order_ms: Option, + /// How many partitions a grouped build or merge splits its rows into + /// by group key ([`Self::with_parallelism`]); 1: none. + parallelism: usize, + /// Inputs with fewer rows (in their first wave) than this stay on one + /// thread ([`Self::with_min_split_rows`]). + min_split_rows: usize, pub(super) control: Rc, } + +/// The default [`RunContext::with_min_split_rows`]: below it, a split's +/// per-part tables and dispatch cost more than they save. +pub const DEFAULT_MIN_SPLIT_ROWS: usize = 16_384; impl RunContext { pub fn new(scope: Scope, limits: Limits) -> Result { if limits.max_bytes == 0 { @@ -56,10 +71,14 @@ impl RunContext { scope, query_range: None, max_out_of_order_ms: None, + parallelism: 1, + min_split_rows: DEFAULT_MIN_SPLIT_ROWS, control: Rc::new(Control { cancelled: Cell::new(false), bytes: Cell::new(0), peak: Cell::new(0), + parallel_tasks: Cell::new(0), + parallel_cpu_ns: Cell::new(0), limits, waiters: RefCell::new(Vec::new()), }), @@ -98,6 +117,50 @@ impl RunContext { pub(crate) fn max_out_of_order_ms(&self) -> Option { self.max_out_of_order_ms } + /// Split the rows of each grouped summary build and merge into + /// `partitions` parts by a hash of the group key, folded on the + /// threads of rayon's global pool and combined in the order of one + /// part: the answer and every state are the same as with 1 (the + /// default), whatever `partitions` is. Builds and merges whose groups + /// share state (no group column, counters, HydraCMS) stay on the + /// calling thread. + pub fn with_parallelism(mut self, partitions: usize) -> Self { + self.parallelism = partitions.max(1); + self + } + pub(crate) fn parallelism(&self) -> usize { + self.parallelism + } + /// A grouped build or merge whose input has fewer than `rows` rows (in + /// its first wave of up to 262144) stays on one thread; each part gets + /// at least `rows / 8`. Default [`DEFAULT_MIN_SPLIT_ROWS`]; 0 splits + /// any input (tests). + pub fn with_min_split_rows(mut self, rows: usize) -> Self { + self.min_split_rows = rows; + self + } + pub(crate) fn min_split_rows(&self) -> usize { + self.min_split_rows + } + /// Partition tasks this run's operators ran on worker threads. + pub fn parallel_tasks(&self) -> usize { + self.control.parallel_tasks.get() + } + /// CPU time this run's partition tasks used on the worker threads, + /// in nanoseconds: work done for the run off its own thread, which a + /// caller measuring its thread's CPU adds to the run's. + pub fn parallel_cpu_ns(&self) -> u64 { + self.control.parallel_cpu_ns.get() + } + pub(crate) fn count_parallel_tasks(&self, tasks: usize, cpu_ns: u64) { + let control = &self.control; + control + .parallel_tasks + .set(control.parallel_tasks.get() + tasks); + control + .parallel_cpu_ns + .set(control.parallel_cpu_ns.get() + cpu_ns); + } /// This run's context, evaluated at `evaluation_time_ms` instead: the /// same limits, cancellation, query range and `max_out_of_order_ms`. pub(crate) fn at_evaluation_time(&self, evaluation_time_ms: i64) -> Self { diff --git a/crates/executor/src/runtime/mod.rs b/crates/executor/src/runtime/mod.rs index 3e5462f66..13fb806de 100644 --- a/crates/executor/src/runtime/mod.rs +++ b/crates/executor/src/runtime/mod.rs @@ -15,7 +15,24 @@ use std::{ task::{Context, Poll, Waker}, }; mod context; -pub use context::{Limits, Reservation, RunContext, Scope}; +pub use context::{Limits, Reservation, RunContext, Scope, DEFAULT_MIN_SPLIT_ROWS}; + +/// CPU time the calling thread has used, in nanoseconds (0 where the +/// platform has no per-thread clock). +pub fn thread_cpu_ns() -> u64 { + #[cfg(unix)] + { + let mut time = libc::timespec { + tv_sec: 0, + tv_nsec: 0, + }; + // SAFETY: `time` is a valid timespec to write. + if unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut time) } == 0 { + return time.tv_sec as u64 * 1_000_000_000 + time.tv_nsec as u64; + } + } + 0 +} pub type OutputStream<'a, V> = LocalBoxStream<'a, Result>; /// Every root's batches of an ingestion run, in the order of its roots. pub type IngestionOutputs = Vec>>; diff --git a/crates/executor/src/summary_kernels/state_column_updater/mod.rs b/crates/executor/src/summary_kernels/state_column_updater/mod.rs index 769b3a7d1..cb864113f 100644 --- a/crates/executor/src/summary_kernels/state_column_updater/mod.rs +++ b/crates/executor/src/summary_kernels/state_column_updater/mod.rs @@ -516,6 +516,111 @@ impl StateColumnUpdater { Ok(()) } + /// Whether each group's state is built and sealed independently of the + /// other groups': no counter reorder buffer and no grid shared by all + /// groups. Its groups can then be built by separate updaters and + /// gathered into one ([`Self::gather`]). + pub(crate) fn groups_are_independent(&self) -> bool { + self.counter.is_none() && !matches!(self.states, GroupStates::Hydra { .. }) + } + + /// One updater whose group `i` is `order[i]` = `(part, group)`: that + /// group of updater `parts[part]`. Every part has the same family and + /// θ and independent groups ([`Self::groups_are_independent`]); each + /// group is taken once. + pub(crate) fn gather(parts: Vec, order: &[(usize, u32)]) -> Result { + let mut parts = parts.into_iter(); + let Some(first) = parts.next() else { + return Err(Error::Invalid("no updater to gather".into())); + }; + let rest: Vec = parts.collect(); + if !first.groups_are_independent() + || rest.iter().any(|part| { + part.family != first.family + || part.parameters != first.parameters + || !part.groups_are_independent() + }) + { + return Err(Error::Invalid( + "only updaters of one family with independent groups gather".into(), + )); + } + let memory_bytes = + rest.iter().map(|part| part.memory_bytes).sum::() + first.memory_bytes; + let Self { + family, + parameters, + states, + key_types, + .. + } = first; + let mut all = vec![states]; + all.extend(rest.into_iter().map(|part| part.states)); + fn take(parts: Vec>, order: &[(usize, u32)]) -> Result, Error> { + let mut parts: Vec>> = parts + .into_iter() + .map(|part| part.into_iter().map(Some).collect()) + .collect(); + order + .iter() + .map(|&(part, group)| { + parts + .get_mut(part) + .and_then(|states| states.get_mut(group as usize)) + .and_then(Option::take) + .ok_or_else(|| Error::Invalid(format!("no group {group} in part {part}"))) + }) + .collect() + } + let states = match all.remove(0) { + GroupStates::Exact { empty, states } => { + let mut parts = vec![states]; + for other in all { + let GroupStates::Exact { states, .. } = other else { + unreachable!("one family has one kind of states") + }; + parts.push(states); + } + GroupStates::Exact { + empty, + states: take(parts, order)?, + } + } + GroupStates::Sketches(states) => { + let mut parts = vec![states]; + for other in all { + let GroupStates::Sketches(states) = other else { + unreachable!("one family has one kind of states") + }; + parts.push(states); + } + GroupStates::Sketches(take(parts, order)?) + } + GroupStates::Keyed { empty, states } => { + let mut parts = vec![states]; + for other in all { + let GroupStates::Keyed { states, .. } = other else { + unreachable!("one family has one kind of states") + }; + parts.push(states); + } + GroupStates::Keyed { + empty, + states: take(parts, order)?, + } + } + GroupStates::Hydra { .. } => unreachable!("checked: independent groups"), + }; + Ok(Self { + family, + parameters, + states, + counter: None, + memory_bytes, + key_types, + }) + } + /// Memory the open states hold, in bytes. pub fn memory_bytes(&self) -> usize { self.memory_bytes diff --git a/crates/executor/tests/main.rs b/crates/executor/tests/main.rs index 957963c5a..c0c0567a3 100644 --- a/crates/executor/tests/main.rs +++ b/crates/executor/tests/main.rs @@ -15,6 +15,7 @@ mod kernel_state_round_trip; mod keyed_summary_row_weight; mod multi_level_window_chains; mod node_ids; +mod parallel_execution; mod physical_dag; mod physical_semantics; mod plan_properties; diff --git a/crates/executor/tests/parallel_execution.rs b/crates/executor/tests/parallel_execution.rs new file mode 100644 index 000000000..7e38cb449 --- /dev/null +++ b/crates/executor/tests/parallel_execution.rs @@ -0,0 +1,437 @@ +//! Grouped summary builds and merges split by group key over worker threads +//! (`RunContext::with_parallelism`) answer exactly as one thread does: the +//! same groups in the same order, the same labels, bit-identical exact +//! records and the same sketch states. +use asap_executor::expressions::{CompiledExpression, Expression}; +use asap_executor::operators::Operator; +use asap_executor::plan::PhysicalDAG; +use asap_executor::planner::ir::schema::{DataType, Field, FieldDataType, Schema}; +use asap_executor::planner::summary_type::{ + ExactKind, ExactParams, SketchAlgorithm, SketchParams, SketchStatistic, +}; +use asap_executor::runtime::{Limits, RunContext, Scope}; +use asap_executor::values::{Batch, SchemaRef, Value}; +use asap_executor::Error; +use futures::{executor::block_on, StreamExt}; +use planner_types::ir::scalar::{CompareOpKind, ScalarValue}; +use planner_types::ir::ScalarExpr; +use planner_types::stages::Lifetime; +use std::sync::Arc; + +fn field(name: &str, dtype: DataType, nullable: bool) -> Field { + Field { + name: name.into(), + dtype: FieldDataType::Plain(dtype), + nullable, + } +} + +/// `(host Utf8, user Int64, ts, value Float64?, item Utf8, fkey Float64?)`. +fn input() -> SchemaRef { + Arc::new(Schema { + fields: vec![ + field("host", DataType::Utf8, false), + field("user", DataType::Int64, false), + field("ts", DataType::Timestamp, false), + field("value", DataType::Float64, true), + field("item", DataType::Utf8, false), + field("fkey", DataType::Float64, true), + ], + time_index: Some(2), + unique_keys: vec![], + closed: false, + }) +} + +/// `batches` batches of `rows` rows: ~`hosts` x 7 (host, user) groups with +/// skewed sizes; values, items, float keys with zero signs, NaN payloads and +/// NULLs. +fn rows(batches: usize, rows: usize, hosts: u64) -> Vec { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + let floats = [0.0, -0.0, f64::NAN, -f64::NAN, 1.5, 2.5]; + let mut time = 0; + (0..batches) + .map(|_| { + let rows = (0..rows) + .map(|_| { + time += 1; + let r = next(); + let host = (r % hosts) * (r % 3) / 2; + vec![ + Value::Utf8(format!("h{host}").into()), + Value::Int64((r >> 20) as i64 % 7), + Value::Timestamp(time), + if r % 97 == 0 { + Value::Null + } else { + Value::Float64(1.0 + ((r >> 8) % 100_000) as f64 / 7.0) + }, + Value::Utf8(format!("i{}", (r >> 30) % 500).into()), + if r % 53 == 0 { + Value::Null + } else { + Value::Float64(floats[((r >> 40) % 6) as usize]) + }, + ] + }) + .collect(); + Batch::try_new(input(), rows).unwrap() + }) + .collect() +} + +fn context(parallelism: usize, limits: Limits) -> RunContext { + RunContext::new( + Scope::Query { + evaluation_time_ms: 1_000_000, + }, + limits, + ) + .unwrap() + .with_parallelism(parallelism) +} + +/// `operator` over a source of `inputs` with `parallelism`: its batches, +/// the partition tasks the run ran and their worker-thread CPU (ns). +fn run_with( + operator: Operator, + inputs: Vec, + parallelism: usize, + limits: Limits, +) -> Result<(Vec, usize, u64), Error> { + let mut dag = PhysicalDAG::default(); + let schema = inputs[0].schema().clone(); + dag.add( + 0, + vec![], + Operator::source(schema, inputs).unwrap(), + Lifetime::None, + ) + .unwrap(); + dag.add(1, vec![0], operator, Lifetime::None).unwrap(); + let context = context(parallelism, limits); + block_on(async { + let mut output = dag.execute(&[1], context.clone())?.remove(0); + let mut batches = Vec::new(); + while let Some(batch) = output.next().await { + batches.push((*batch?).clone()); + } + Ok((batches, context.parallel_tasks(), context.parallel_cpu_ns())) + }) +} + +fn run(operator: Operator, inputs: Vec, parallelism: usize) -> (Vec, usize) { + let (batches, tasks, _) = + run_with(operator, inputs, parallelism, Limits { max_bytes: 1 << 30 }).unwrap(); + (batches, tasks) +} + +/// Every cell of every row, exactly: plain values with their float bits, +/// states by their view bytes (or, without a view layout, their +/// cardinality estimate's bits). +fn fingerprint(batches: &[Batch]) -> Vec> { + let mut out = Vec::new(); + for batch in batches { + let rows = batch.to_rows(); + for (row_index, row) in rows.iter().enumerate() { + out.push( + row.iter() + .enumerate() + .map(|(column, value)| match value { + Value::Float64(v) => format!("f{:016x}", v.to_bits()), + Value::Summary { state, .. } => { + let states = batch.state_column(column).unwrap(); + let index = batch + .column(column) + .as_any() + .downcast_ref::() + .unwrap() + .value(row_index) as usize; + match states.view_bytes(index) { + Some(bytes) => format!("s{:?}", bytes), + None => format!( + "e{:016x}", + state + .estimate(&SketchStatistic::Cardinality) + .unwrap() + .to_bits() + ), + } + } + other => format!("{other:?}"), + }) + .collect(), + ); + } + } + out +} + +fn exact(kind: ExactKind, params: ExactParams) -> FieldDataType { + FieldDataType::ExactAggregate(kind, params) +} + +/// (family, θ, value column) of every family the tests build. +fn families() -> Vec<(FieldDataType, Option, usize)> { + vec![ + (exact(ExactKind::Sum, ExactParams::Sum), None, 3), + (exact(ExactKind::Count, ExactParams::Count), None, 3), + (exact(ExactKind::Min, ExactParams::Min), None, 3), + (exact(ExactKind::Max, ExactParams::Max), None, 3), + ( + FieldDataType::Sketch(SketchAlgorithm::DDSketch), + Some(SketchParams::DDSketch { alpha: 0.01 }), + 3, + ), + ( + FieldDataType::Sketch(SketchAlgorithm::HLL), + Some(SketchParams::Hll { precision: 10 }), + 4, + ), + ] +} + +// 1. Per family and key set, a build split 2, 3 or 8 ways equals the +// one-thread build cell for cell, and ran partition tasks. +#[test] +fn grouped_builds_split_by_group_key_equal_the_sequential_build() { + let inputs = rows(3, 8000, 300); + for (family, params, value) in families() { + for groups in [vec![0], vec![0, 1], vec![1, 0]] { + let build = || { + Operator::per_group_summary_build( + input(), + family.clone(), + params.clone(), + value, + None, + groups.clone(), + ) + .unwrap() + }; + let (sequential, tasks) = run(build(), inputs.clone(), 1); + assert_eq!(tasks, 0); + let expected = fingerprint(&sequential); + assert!(expected.len() > 100, "{family:?} {groups:?}"); + for parallelism in [2, 3, 8] { + let (parallel, tasks) = run(build(), inputs.clone(), parallelism); + assert_eq!( + fingerprint(¶llel), + expected, + "{family:?} {groups:?} x{parallelism}" + ); + assert!(tasks > 0, "{family:?} {groups:?} x{parallelism}"); + } + } + } +} + +// 2. Exact states of six windows merged by one key and by both keys: split +// 2 or 8 ways equals one thread, bit for bit. +#[test] +fn grouped_merges_split_by_group_key_equal_the_sequential_merge() { + for (kind, params) in [ + (ExactKind::Sum, ExactParams::Sum), + (ExactKind::Count, ExactParams::Count), + (ExactKind::Max, ExactParams::Max), + ] { + let family = exact(kind, params); + let windows: Vec = rows(6, 6000, 3000) + .into_iter() + .map(|window| { + let build = Operator::per_group_summary_build( + input(), + family.clone(), + None, + 3, + None, + vec![0, 1], + ) + .unwrap(); + run(build, vec![window], 1).0.remove(0) + }) + .collect(); + let states = windows[0].schema().clone(); + for groups in [vec![1], vec![0, 1], vec![0]] { + let merge = || Operator::summary_merge(states.clone(), 2, groups.clone()).unwrap(); + let expected = fingerprint(&run(merge(), windows.clone(), 1).0); + for parallelism in [2, 8] { + let (parallel, tasks) = run(merge(), windows.clone(), parallelism); + assert_eq!(fingerprint(¶llel), expected, "{kind:?} {groups:?}"); + assert!(tasks > 0, "{kind:?} {groups:?}"); + } + } + } +} + +// 3. A filtered build over NULL values, grouped by a Float64 key holding +// zero signs, NaN payloads and NULL: the same groups, the same first-row +// labels (bits), the same states. +#[test] +fn partitioned_builds_keep_filters_nulls_and_first_labels() { + let schema = input(); + let predicate = ScalarExpr::Compare { + semantics: planner_types::ir::ExprSemantics::Sql, + left: Box::new(ScalarExpr::Column(3)), + op: CompareOpKind::Gt, + right: Box::new(ScalarExpr::Literal(ScalarValue::Float64(500.0))), + }; + let build = || { + Operator::per_group_summary_build( + schema.clone(), + exact(ExactKind::Sum, ExactParams::Sum), + None, + 3, + None, + vec![5, 0], + ) + .unwrap() + .with_row_filter(Expression::planner( + CompiledExpression::compile(&predicate, &schema).unwrap(), + )) + .unwrap() + }; + let inputs = rows(4, 5000, 50); + for groups_only_float in [false, true] { + let build = || { + if groups_only_float { + Operator::per_group_summary_build( + schema.clone(), + exact(ExactKind::Count, ExactParams::Count), + None, + 3, + None, + vec![5], + ) + .unwrap() + } else { + build() + } + }; + let expected = fingerprint(&run(build(), inputs.clone(), 1).0); + for parallelism in [2, 5] { + let (parallel, tasks) = run(build(), inputs.clone(), parallelism); + assert_eq!(fingerprint(¶llel), expected); + assert!(tasks > 0); + } + } +} + +// 4. Builds whose groups share state or order stay on one thread: no group +// column, and a counter. Same answer, no partition task. +#[test] +fn builds_that_cannot_split_by_group_stay_sequential() { + let inputs = rows(2, 2000, 30); + let builds: Vec Operator>> = vec![ + Box::new(|| { + Operator::per_group_summary_build( + input(), + exact(ExactKind::Sum, ExactParams::Sum), + None, + 3, + None, + vec![], + ) + .unwrap() + }), + Box::new(|| { + Operator::per_group_summary_build( + input(), + exact(ExactKind::Counter, ExactParams::Counter), + None, + 3, + Some(2), + vec![0], + ) + .unwrap() + }), + ]; + for build in builds { + let expected = fingerprint(&run(build(), inputs.clone(), 1).0); + let (parallel, tasks) = run(build(), inputs.clone(), 4); + assert_eq!(fingerprint(¶llel), expected); + assert_eq!(tasks, 0); + } +} + +// 5. A split build is charged its groups: over a small limit it fails. +#[test] +fn a_partitioned_build_over_the_memory_limit_fails() { + let build = Operator::per_group_summary_build( + input(), + FieldDataType::Sketch(SketchAlgorithm::DDSketch), + Some(SketchParams::DDSketch { alpha: 0.01 }), + 3, + None, + vec![0, 1], + ) + .unwrap(); + let result = run_with( + build, + rows(3, 8000, 300), + 4, + Limits { + max_bytes: 256 << 10, + }, + ); + assert!( + matches!(result, Err(Error::MemoryLimit)), + "{:?}", + result.err() + ); +} + +// 6. A small input stays on one thread: no partition task, same answer. +#[test] +fn small_inputs_stay_on_one_thread() { + let build = || { + Operator::per_group_summary_build( + input(), + exact(ExactKind::Sum, ExactParams::Sum), + None, + 3, + None, + vec![0, 1], + ) + .unwrap() + }; + let inputs = rows(2, 1000, 30); + let expected = fingerprint(&run(build(), inputs.clone(), 1).0); + let (parallel, tasks) = run(build(), inputs, 8); + assert_eq!(fingerprint(¶llel), expected); + assert_eq!(tasks, 0); +} + +// 7. The run is charged its partition tasks' worker-thread CPU, so a caller +// adding it to its own thread's CPU counts the work wherever it ran; an +// input of several waves equals one thread. +#[test] +fn split_runs_charge_worker_cpu_and_span_waves() { + let build = || { + Operator::per_group_summary_build( + input(), + exact(ExactKind::Sum, ExactParams::Sum), + None, + 3, + None, + vec![0, 1], + ) + .unwrap() + }; + // 300000 rows: two waves of the split. + let inputs = rows(3, 100_000, 3000); + let (sequential, _, sequential_cpu) = + run_with(build(), inputs.clone(), 1, Limits { max_bytes: 1 << 30 }).unwrap(); + assert_eq!(sequential_cpu, 0); + let (parallel, tasks, cpu) = + run_with(build(), inputs, 4, Limits { max_bytes: 1 << 30 }).unwrap(); + assert_eq!(fingerprint(¶llel), fingerprint(&sequential)); + assert!(tasks > 0); + assert!(cpu > 0, "worker CPU not charged"); +}