Skip to content
Draft
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
41 changes: 41 additions & 0 deletions Cargo.lock

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

6 changes: 6 additions & 0 deletions crates/executor/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand All @@ -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
Expand Down
46 changes: 46 additions & 0 deletions crates/executor/src/operators/group_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<&[u8]>> {
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,
Expand All @@ -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<Vec<ArrayRef>, 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::<Vec<_>>();
arrow_columns::encode(dtype, ColumnDepth::BatchColumn, &values)
})
.collect()
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
176 changes: 127 additions & 49 deletions crates/executor/src/operators/summary/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<Batch, Error> {
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<B: std::ops::Deref<Target = Batch>>(
mut input: impl futures::Stream<Item = Result<B, Error>> + Unpin,
build: PerGroupBuild<'_>,
input_schema: &SchemaRef,
output: &SchemaRef,
Expand Down Expand Up @@ -660,60 +684,75 @@ 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::<arrow::array::Int64Array>()
{
// 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())?;
}
}
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::<arrow::array::Int64Array>() {
// 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,
Expand Down Expand Up @@ -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<Batch, Error> {
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<B: std::ops::Deref<Target = Batch>>(
mut input: impl futures::Stream<Item = Result<B, Error>> + Unpin,
state_column: usize,
groups: &[usize],
shape: MergeOutput<'_>,
Expand Down
Loading