diff --git a/src/promql/src/aggregate/state.rs b/src/promql/src/aggregate/state.rs index a4b4b10da47..82f14887aa6 100644 --- a/src/promql/src/aggregate/state.rs +++ b/src/promql/src/aggregate/state.rs @@ -25,8 +25,10 @@ //! gives the exact 1. Explicit NaN and infinite inputs follow the same rules as the serial fold. Where the serial fold keeps the first of two equal //! values, as `min` and `max` do for `0` and `-0`, a merge keeps the one merged first. +use std::collections::btree_map::Entry as BTreeEntry; use std::collections::hash_map::Entry; use std::collections::{BTreeMap, HashMap}; +use std::mem::size_of; use std::sync::Arc; use datafusion::error::{DataFusionError, Result}; @@ -34,8 +36,9 @@ use datatypes::series::SeriesLabels; use datatypes::series::samples::{SampleRef, Series, SeriesSchema}; use crate::aggregate::{ - AggregateOp, BLOCK_POINTS, Counts, FloatAggregator, FloatState, Group, LabelKey, count_series, - finish_groups, kahan_inc, label_key, + AggregateOp, BLOCK_POINTS, Counts, FloatAggregator, FloatState, Group, LabelKey, + btree_backing_bytes, count_series, finish_groups, finish_groups_budgeted, + hash_map_backing_bytes, kahan_inc, label_key, metric_bytes, next_hash_capacity, }; use crate::map::validate_float_series; @@ -99,28 +102,52 @@ pub struct PartialAggregate { impl FloatAggregator { /// The state folded so far, for a merge with the state of other partitions. pub fn finish_partial(self) -> PartialAggregate { + self.finish_partial_inner() + } + + /// [`Self::finish_partial`] that admits what it builds first: the fold state and the group, + /// point and state vectors, at the exact capacity [`Self::finish_partial_inner`] gives them. A + /// refusal consumes the aggregator, so the caller drops the execution. + pub(crate) fn finish_partial_budgeted( + self, + mut budget: impl FnMut(usize) -> Result<()>, + ) -> Result { let width = self.schema.fields.len(); - let groups = self - .groups - .into_iter() - .map(|group| { - let mut points = Vec::new(); - for (&block, states) in &group.blocks { - for (offset, point) in states.chunks_exact(width).enumerate() { - if point.iter().any(|state| state.seen) { - points.push(( - block * BLOCK_POINTS + offset, - point.iter().map(|state| state.partial()).collect(), - )); - } + let mut partial_bytes = self.groups.len().saturating_mul(size_of::()); + for group in &self.groups { + let points = seen_points(group, width); + partial_bytes = partial_bytes + .saturating_add(points.saturating_mul(size_of::())) + .saturating_add( + points + .saturating_mul(width) + .saturating_mul(size_of::>()), + ); + } + budget(self.state_bytes().saturating_add(partial_bytes))?; + Ok(self.finish_partial_inner()) + } + + fn finish_partial_inner(self) -> PartialAggregate { + let width = self.schema.fields.len(); + let mut groups: Vec = Vec::with_capacity(self.groups.len()); + for group in self.groups { + let mut points: Vec = Vec::with_capacity(seen_points(&group, width)); + for (&block, states) in &group.blocks { + for (offset, point) in states.chunks_exact(width).enumerate() { + if point.iter().any(|state| state.seen) { + points.push(( + block * BLOCK_POINTS + offset, + point.iter().map(|state| state.partial()).collect(), + )); } } - PartialGroup { - metric: group.metric, - points, - } - }) - .collect(); + } + groups.push(PartialGroup { + metric: group.metric, + points, + }); + } PartialAggregate { op: self.op, groups, @@ -128,6 +155,67 @@ impl FloatAggregator { } } +/// One point of a partial group: its grid position and one state per field. +type Point = (usize, Vec>); + +/// The points of `group` that carry a state: the ones a partial of it holds. +fn seen_points(group: &Group, width: usize) -> usize { + group.blocks.values().fold(0usize, |count, states| { + count.saturating_add( + states + .chunks_exact(width) + .filter(|point| point.iter().any(|state| state.seen)) + .count(), + ) + }) +} + +/// Bytes one partial group keeps: its labels and its point and state vectors at the capacity they +/// were built with, so spare capacity is paid for rather than skipped. +fn group_bytes(group: &PartialGroup) -> usize { + metric_bytes(&group.metric) + .saturating_add(group.points.capacity().saturating_mul(size_of::())) + .saturating_add(group.points.iter().fold(0usize, |bytes, (_, states)| { + bytes.saturating_add( + states + .capacity() + .saturating_mul(size_of::>()), + ) + })) +} + +/// Bytes a group's label key holds: a pair per capacity slot, and the `__name__` entry, whose +/// label and value `label_key` copies, each with its own `Arc` header. The other label strings are +/// the metric's, already counted with it. +fn key_bytes(key: &LabelKey) -> usize { + let name = key + .iter() + .find(|(label, _)| &**label == "__name__") + .map_or(0, |(label, value)| { + label + .len() + .saturating_add(value.len()) + .saturating_add(4 * size_of::()) + }); + key.capacity() + .saturating_mul(size_of::<(Arc, Arc)>()) + .saturating_add(name) +} + +/// Coarse bytes the key of `metric` holds while it is built: a pair per slot, the `__name__` label +/// and a copy of the metric name, each with its `Arc` header. +fn key_workspace_bytes(metric: &SeriesLabels) -> usize { + metric + .tags() + .len() + .saturating_add(1) + .saturating_mul(size_of::<(Arc, Arc)>()) + .saturating_add("__name__".len()) + .saturating_add(metric.name().map_or(0, str::len)) + .saturating_add(4 * size_of::()) + .saturating_add(size_of::()) +} + /// Merges the partial states of one aggregation into its result. Groups are identified by their /// full label set, already grouped by the partitions, and keep the order they first arrive in. pub struct FloatMerger { @@ -135,6 +223,7 @@ pub struct FloatMerger { op: AggregateOp, group_index: HashMap, groups: Vec, + retained: usize, } impl FloatMerger { @@ -149,12 +238,30 @@ impl FloatMerger { op, group_index: HashMap::new(), groups: Vec::new(), + retained: 0, }) } /// Merges the state of one partition. A partial that does not fit this merge, by its /// aggregation, field count or grid positions, fails and leaves the merge unchanged. pub fn merge(&mut self, partial: PartialAggregate) -> Result<()> { + self.merge_budgeted(partial, |_| Ok(())) + } + + /// Bytes this merge keeps: groups, labels, blocks, B-tree nodes, index table and its keys. Added + /// to by the allocations that change it, never recounted. + pub(crate) fn state_bytes(&self) -> usize { + self.retained + } + + /// [`Self::merge`] that admits each allocation before making it: the partial that stays live, + /// the key, and the group, index and block backing about to be reserved. A refusal leaves the + /// merge half applied, so a caller that budgets must drop it rather than merge into it again. + pub(crate) fn merge_budgeted( + &mut self, + partial: PartialAggregate, + mut budget: impl FnMut(usize) -> Result<()>, + ) -> Result<()> { let width = self.schema.fields.len(); let points = self .schema @@ -178,27 +285,140 @@ impl FloatMerger { } } } + let input_live = partial.groups.iter().fold( + partial + .groups + .capacity() + .saturating_mul(size_of::()), + |bytes, group| bytes.saturating_add(group_bytes(group)), + ); for group in partial.groups { - let index = match self.group_index.entry(label_key(&group.metric)) { - Entry::Occupied(entry) => *entry.get(), - Entry::Vacant(entry) => { - self.groups.push(Group { - metric: group.metric, - blocks: BTreeMap::new(), - }); - *entry.insert(self.groups.len() - 1) + let metric = group.metric; + // `label_key` copies the metric name into its own `Arc`, so the copy is admitted + // before it is made. A group that is already merged needs a key too, and its + // admission comes before anything else this call can allocate. + budget( + self.retained + .saturating_add(input_live) + .saturating_add(key_workspace_bytes(&metric)), + )?; + let key = label_key(&metric); + let live = input_live.saturating_add(key_bytes(&key)); + let index = match self.group_index.get(&key).copied() { + Some(index) => index, + None => self.open_group(metric, key, live, &mut budget)?, + }; + self.merge_points(index, group.points, live, &mut budget)?; + } + Ok(()) + } + + /// Adds a group and its key, admitting the group vector and index growth first. + fn open_group( + &mut self, + metric: SeriesLabels, + key: LabelKey, + live: usize, + budget: &mut impl FnMut(usize) -> Result<()>, + ) -> Result { + let capacity = self.groups.capacity(); + let next_capacity = if self.groups.len() == capacity { + capacity.saturating_mul(2).max(4) + } else { + capacity + }; + let map_capacity = self.group_index.capacity(); + let next_map_capacity = if self.group_index.len().saturating_add(1) > map_capacity { + next_hash_capacity(map_capacity) + } else { + map_capacity + }; + let key_live = key_bytes(&key); + let metric_live = metric_bytes(&metric); + // A realloc that cannot grow in place keeps both buffers alive while it copies, so a + // growing step admits the new buffer beside the old one, which `retained` already holds. + budget( + self.retained + .saturating_add(live) + .saturating_add(key_live) + .saturating_add(metric_live) + .saturating_add(if next_capacity > capacity { + next_capacity.saturating_mul(size_of::()) + } else { + 0 + }) + .saturating_add(if next_map_capacity > map_capacity { + hash_map_backing_bytes(next_map_capacity) + } else { + 0 + }), + )?; + self.groups.try_reserve(1).map_err(|error| { + DataFusionError::Execution(format!("cannot reserve aggregate groups: {error}")) + })?; + self.groups.push(Group { + metric, + blocks: BTreeMap::new(), + }); + let index = self.groups.len() - 1; + self.group_index.insert(key, index); + self.retained = self + .retained + .saturating_add( + self.groups + .capacity() + .saturating_sub(capacity) + .saturating_mul(size_of::()), + ) + .saturating_add( + hash_map_backing_bytes(self.group_index.capacity()) + .saturating_sub(hash_map_backing_bytes(map_capacity)), + ) + .saturating_add(metric_live) + .saturating_add(key_live); + Ok(index) + } + + /// Adds the points of one partial group to group `index`. A missing block is admitted with its + /// states and B-tree node before either is allocated; an existing one only merges state. + fn merge_points( + &mut self, + index: usize, + points: Vec, + live: usize, + budget: &mut impl FnMut(usize) -> Result<()>, + ) -> Result<()> { + let width = self.schema.fields.len(); + let block_bytes = BLOCK_POINTS + .saturating_mul(width) + .saturating_mul(size_of::()); + let blocks = &mut self.groups[index].blocks; + for (point, states) in points { + let block_index = point / BLOCK_POINTS; + let entries = blocks.len(); + let block = match blocks.entry(block_index) { + BTreeEntry::Occupied(entry) => entry.into_mut(), + BTreeEntry::Vacant(entry) => { + budget( + self.retained + .saturating_add(live) + .saturating_add(block_bytes) + .saturating_add(btree_backing_bytes(entries.saturating_add(1))), + )?; + self.retained = self + .retained + .saturating_add(block_bytes) + .saturating_add(btree_backing_bytes(entries.saturating_add(1))) + .saturating_sub(btree_backing_bytes(entries)); + entry.insert( + vec![FloatState::default(); BLOCK_POINTS * width].into_boxed_slice(), + ) } }; - let blocks = &mut self.groups[index].blocks; - for (point, states) in group.points { - let block = blocks.entry(point / BLOCK_POINTS).or_insert_with(|| { - vec![FloatState::default(); BLOCK_POINTS * width].into_boxed_slice() - }); - let offset = (point % BLOCK_POINTS) * width; - for (slot, state) in block[offset..offset + width].iter_mut().zip(states) { - if let Some(state) = state { - slot.merge(self.op, FloatState::from_partial(state)); - } + let offset = (point % BLOCK_POINTS) * width; + for (slot, state) in block[offset..offset + width].iter_mut().zip(states) { + if let Some(state) = state { + slot.merge(self.op, FloatState::from_partial(state)); } } } @@ -209,6 +429,15 @@ impl FloatMerger { pub fn finish(self) -> Result> { finish_groups(self.schema, self.op, self.groups) } + + /// [`Self::finish`] that admits the result it builds, on top of what the merge still holds. The + /// merge is consumed either way, so a caller that budgets drops it on a refusal. + pub(crate) fn finish_budgeted( + self, + budget: impl FnMut(usize) -> Result<()>, + ) -> Result> { + finish_groups_budgeted(self.schema, self.op, self.groups, self.retained, budget) + } } impl FloatState { diff --git a/src/promql/src/aggregate/tests.rs b/src/promql/src/aggregate/tests.rs index c529033ce01..0e04941632c 100644 --- a/src/promql/src/aggregate/tests.rs +++ b/src/promql/src/aggregate/tests.rs @@ -1446,6 +1446,247 @@ fn merged_and_serial(op: AggregateOp, partitions: &[&[f64]]) -> (f64, f64) { ) } +/// Runs `run` with a budget that admits everything, returning the largest figure it was asked +/// for: the pool a call needs to succeed. +fn peak_admission( + run: impl FnOnce( + &mut dyn FnMut(usize) -> Result<(), DataFusionError>, + ) -> Result<(), DataFusionError>, +) -> (usize, Result<(), DataFusionError>) { + let mut peak = 0usize; + let result = run(&mut |bytes| { + peak = peak.max(bytes); + Ok(()) + }); + (peak, result) +} + +#[test] +fn finish_partial_reserves_one_slot_per_seen_point() { + const SEEN: usize = 65_537; + let schema = schema_with_grid_len(&["value"], SEEN as u64); + let series = input(&schema, metric("m", &[]), 0, &[vec![Some(1.0); SEEN]]); + let mut aggregator = + FloatAggregator::try_new(&schema, AggregateOp::Sum, Grouping::By(&[])).unwrap(); + aggregator.update(&series).unwrap(); + let expected = aggregator + .state_bytes() + .saturating_add(std::mem::size_of::()) + .saturating_add( + SEEN.saturating_mul(std::mem::size_of::<(usize, Vec>)>()), + ) + .saturating_add(SEEN.saturating_mul(std::mem::size_of::>())); + let mut peak = 0usize; + let partial = aggregator + .finish_partial_budgeted(|bytes| { + peak = peak.max(bytes); + Ok(()) + }) + .unwrap(); + // The vector is reserved once, at the points that carry a state, so pushing does not double it. + assert_eq!(partial.groups[0].points.len(), SEEN); + assert_eq!(partial.groups[0].points.capacity(), SEEN); + assert_eq!(peak, expected); +} + +#[test] +fn merge_charges_the_capacity_of_an_input_partial() { + let schema = schema(&["value"]); + let series = input(&schema, metric("m", &[]), 0, &[vec![Some(1.0)]]); + let mut aggregator = + FloatAggregator::try_new(&schema, AggregateOp::Sum, Grouping::By(&[])).unwrap(); + aggregator.update(&series).unwrap(); + let partial = aggregator.finish_partial(); + assert_eq!(partial.groups[0].points.capacity(), 1); + let mut spare = partial.clone(); + let point = spare.groups[0].points.pop().unwrap(); + let mut points = Vec::with_capacity(1024); + points.push(point); + spare.groups[0].points = points; + let peak = |partial: PartialAggregate| { + let mut merger = FloatMerger::try_new(&schema, AggregateOp::Sum).unwrap(); + let (peak, result) = peak_admission(|budget| merger.merge_budgeted(partial, budget)); + result.unwrap(); + peak + }; + let slack = 1023 * std::mem::size_of::<(usize, Vec>)>(); + assert!( + peak(spare) >= peak(partial).saturating_add(slack), + "spare capacity was not admitted" + ); +} + +#[test] +fn merge_charges_one_block_per_new_block_not_per_point() { + let names: Vec = (0..64).map(|field| format!("f{field}")).collect(); + let labels: Vec<&str> = names.iter().map(String::as_str).collect(); + let schema = schema_with_grid_len(&labels, 64); + let fields: Vec>> = (0..64).map(|_| vec![Some(1.0); 64]).collect(); + let series = input(&schema, metric("m", &[]), 0, &fields); + let mut aggregator = + FloatAggregator::try_new(&schema, AggregateOp::Sum, Grouping::By(&[])).unwrap(); + aggregator.update(&series).unwrap(); + let partial = aggregator.finish_partial(); + assert_eq!(partial.groups[0].points.len(), 64); + let block = BLOCK_POINTS * 64 * std::mem::size_of::(); + let mut merger = FloatMerger::try_new(&schema, AggregateOp::Sum).unwrap(); + let (peak, result) = peak_admission(|budget| merger.merge_budgeted(partial, budget)); + result.unwrap(); + assert!( + peak < 8 * block, + "admitted {peak} for the one block of {block} the points share" + ); + assert_eq!( + values_of(&merger.finish().unwrap(), 0, 64).1, + [Some(1.0); 64] + ); +} + +#[test] +fn merge_admits_groups_and_blocks_before_it_inserts_them() { + let schema = schema(&["value"]); + let partial = |ids: std::ops::Range| PartialAggregate { + op: AggregateOp::Sum, + groups: ids + .map(|id| PartialGroup { + metric: metric("m", &[("i", &id.to_string())]), + points: Vec::new(), + }) + .collect(), + }; + let mut merger = FloatMerger::try_new(&schema, AggregateOp::Sum).unwrap(); + let (peak, result) = peak_admission(|budget| merger.merge_budgeted(partial(0..64), budget)); + result.unwrap(); + assert!(peak > 0 && merger.state_bytes() > 0); + // A refused group or block leaves nothing of itself behind; the caller drops the merge. + let retained = merger.state_bytes(); + let refused = |_| Err(DataFusionError::Execution("pool exhausted".into())); + assert!(merger.merge_budgeted(partial(100..108), refused).is_err()); + assert_eq!(merger.state_bytes(), retained); + let mut invalid = partial(200..201); + invalid.groups[0].points.push((256, Vec::new())); + assert!(merger.merge(invalid).is_err()); + assert_eq!(merger.state_bytes(), retained); + assert!( + merger + .finish_budgeted(|_| Err(DataFusionError::Execution("pool exhausted".into()))) + .is_err() + ); +} + +/// Building a label key copies the metric name, so the copy is admitted before it is made: a +/// refusal arrives before the merge touches anything, even for a group and block it already has. +#[test] +fn merge_admits_the_key_before_it_builds_it() { + let schema = schema(&["value"]); + let series = input(&schema, metric("m", &[("job", "a")]), 0, &[vec![Some(1.0)]]); + let partial = || { + let mut aggregator = + FloatAggregator::try_new(&schema, AggregateOp::Sum, Grouping::By(&[])).unwrap(); + aggregator.update(&series).unwrap(); + aggregator.finish_partial() + }; + let mut merger = FloatMerger::try_new(&schema, AggregateOp::Sum).unwrap(); + merger.merge(partial()).unwrap(); + let retained = merger.state_bytes(); + let mut calls = 0; + let result = merger.merge_budgeted(partial(), |_| { + calls += 1; + Err(DataFusionError::Execution("pool exhausted".into())) + }); + assert!(result.is_err()); + assert!(calls > 0, "the key was built without an admission"); + assert_eq!(merger.state_bytes(), retained, "a refused key was kept"); + + // An existing group and block allocate no block, but the key still is admitted. + let mut merger = FloatMerger::try_new(&schema, AggregateOp::Sum).unwrap(); + merger.merge(partial()).unwrap(); + let mut calls = 0; + merger + .merge_budgeted(partial(), |_| { + calls += 1; + Ok(()) + }) + .unwrap(); + assert!( + calls > 0, + "an existing group was merged without an admission" + ); +} + +/// The merge holds two allocations of the metric name: its group's labels, and the copy its label +/// key made. Only one of them is why a longer name costs twice as much. +#[test] +fn a_long_metric_name_is_held_by_the_group_and_by_its_key() { + let schema = schema(&["value"]); + let retained = |name: &str| { + let partial = PartialAggregate { + op: AggregateOp::Sum, + groups: vec![PartialGroup { + metric: metric(name, &[]), + points: Vec::new(), + }], + }; + let mut merger = FloatMerger::try_new(&schema, AggregateOp::Sum).unwrap(); + merger.merge(partial).unwrap(); + merger.state_bytes() + }; + const EXTRA: usize = 1000; + let long = format!("m{}", "x".repeat(EXTRA)); + let delta = retained(&long) - retained("m"); + assert_eq!( + delta, + 2 * EXTRA, + "the name is held once by the group and once by the key" + ); +} + +/// The budgeted partial path keeps the numbers of the public one: one partition, so the merged +/// result is the serial fold bit for bit, for every supported aggregation. +#[test] +fn budgeted_partial_state_merges_to_the_public_numbers() { + let schema = schema(&["value"]); + let series = input( + &schema, + metric("m", &[]), + 0, + &[vec![Some(1.0), None, Some(3.0), Some(-2.0)]], + ); + for op in [ + AggregateOp::Sum, + AggregateOp::Count, + AggregateOp::Avg, + AggregateOp::Min, + AggregateOp::Max, + AggregateOp::Group, + AggregateOp::Stddev, + AggregateOp::Stdvar, + ] { + let serial = aggregate_float( + &schema, + std::slice::from_ref(&series), + op, + Grouping::By(&[]), + ) + .unwrap(); + let expected = values_of(&serial, 0, 128); + let mut aggregator = FloatAggregator::try_new(&schema, op, Grouping::By(&[])).unwrap(); + aggregator.update(&series).unwrap(); + let partial = aggregator.finish_partial_budgeted(|_| Ok(())).unwrap(); + let mut merger = FloatMerger::try_new(&schema, op).unwrap(); + merger.merge_budgeted(partial.clone(), |_| Ok(())).unwrap(); + let merged = merger.finish_budgeted(|_| Ok(())).unwrap(); + assert_eq!(values_of(&merged, 0, 128), expected, "{op:?} budgeted"); + let mut plain = FloatMerger::try_new(&schema, op).unwrap(); + plain.merge(partial).unwrap(); + assert_eq!( + values_of(&plain.finish().unwrap(), 0, 128), + expected, + "{op:?}" + ); + } +} + /// Partial states merged in any partition and merge order give the serial result, within the /// rounding a regrouped fold may change: the same groups, points and fields, the same NaN and /// infinities. Each partial keeps only the components its aggregation declares, so the layout diff --git a/src/promql/src/extension_plan.rs b/src/promql/src/extension_plan.rs index baf57a275c8..9f7ddbc77dd 100644 --- a/src/promql/src/extension_plan.rs +++ b/src/promql/src/extension_plan.rs @@ -13,6 +13,8 @@ // limitations under the License. mod absent; +mod aggregate_exchange; +mod aggregate_finalize; mod empty_metric; mod fused_series; mod histogram_fold; @@ -27,6 +29,7 @@ mod test_util; mod union_distinct_on; pub use absent::{Absent, AbsentExec, AbsentStream}; +pub use aggregate_finalize::AggregateFinalize; use common_query::native_histogram::{SUM_FIELD, native_histogram_value_type}; use common_query::prometheus::is_prometheus_stale_nan; use datafusion::arrow::array::{Array, Float64Array, StructArray}; diff --git a/src/promql/src/extension_plan/aggregate_exchange.rs b/src/promql/src/extension_plan/aggregate_exchange.rs new file mode 100644 index 00000000000..7e75e7a2f87 --- /dev/null +++ b/src/promql/src/extension_plan/aggregate_exchange.rs @@ -0,0 +1,448 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The private Arrow layout of a partition's partial aggregate state, and the fold that writes it. +//! [`decode_state`] reads a batch back into the rows a `FloatMerger` merges. Only that producer and +//! that merge read [`state_schema`]: it is not a wire format, and has no serde or version. +//! +//! TODO(discord9): Replace this temporary state-row bridge with series frames emitted directly by +//! FusedSeries and consumed by native final aggregation, avoiding the extra state-row encoding, +//! decoding and reconstruction. This private layout is not the final intermediate representation. + +#[cfg(test)] +mod tests; + +use std::mem::size_of; +use std::sync::{Arc, Mutex}; + +use datafusion::arrow::array::{ + Array, ArrayRef, BooleanArray, Float64Array, StringArray, UInt32Array, UInt64Array, +}; +use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef}; +use datafusion::arrow::record_batch::RecordBatch; +use datafusion::error::{DataFusionError, Result as DfResult}; +use datafusion::execution::memory_pool::{MemoryConsumer, MemoryPool, MemoryReservation}; +use datatypes::series::samples::SeriesSchema; +use datatypes::series::{Label, SeriesLabels}; + +use crate::aggregate::{ + AccumulatorState, AggregateOp, FloatAggregator, Grouping, PartialAggregate, PartialGroup, +}; +use crate::evaluated::EvaluatedChunk; +use crate::grid_series::series_bytes; +use crate::native::plan::{ + AggregateKind, AggregateStage, BoundAggregate, Grouping as BoundGrouping, +}; + +/// Rows per encoded batch; the exchange has no session context to read a batch size from. +const BATCH_ROWS: usize = 4096; +/// One column's `ArrayRef`, its `Field` and its buffers are all well under this. +const COLUMN_OVERHEAD: usize = 256; +/// The value capacity a string column starts with, nulls or not (Arrow's `StringArray::from`). +const STRING_CAPACITY: usize = 1024; + +/// One state row: a group's labels, the point and field it is of, and its state. Label columns are +/// nullable, since absent and empty differ; `__name__` has the metric name's column. +pub(crate) fn state_schema(tags: &[String]) -> SchemaRef { + let mut fields = vec![Field::new("metric_name", DataType::Utf8, true)]; + let labels = ordinary_tags(tags).count(); + fields.extend((0..labels).map(|at| Field::new(format!("tag_{at}"), DataType::Utf8, true))); + fields.extend([ + Field::new("point", DataType::UInt64, false), + Field::new("field", DataType::UInt32, false), + ]); + for name in ["value", "mean", "compensation", "count"] { + fields.push(Field::new(name, DataType::Float64, false)); + } + fields.push(Field::new("incremental_mean", DataType::Boolean, false)); + Arc::new(Schema::new(fields)) +} + +/// The kernel a `Complete` aggregate binds; `quantile` and the other stages are not a fold. +pub(crate) fn aggregate_op(op: &BoundAggregate) -> DfResult { + if op.stage != AggregateStage::Complete { + return Err(DataFusionError::NotImplemented(format!( + "the aggregate state exchange folds only `Complete` aggregates, not `{:?}`", + op.stage + ))); + } + match op.kind { + AggregateKind::Sum => Ok(AggregateOp::Sum), + AggregateKind::Count => Ok(AggregateOp::Count), + AggregateKind::Avg => Ok(AggregateOp::Avg), + AggregateKind::Min => Ok(AggregateOp::Min), + AggregateKind::Max => Ok(AggregateOp::Max), + AggregateKind::Group => Ok(AggregateOp::Group), + AggregateKind::Stddev => Ok(AggregateOp::Stddev), + AggregateKind::Stdvar => Ok(AggregateOp::Stdvar), + AggregateKind::Quantile { quantile } => Err(DataFusionError::NotImplemented(format!( + "the aggregate state exchange does not carry `quantile {quantile}`" + ))), + } +} + +/// One partition's fold, and the state it encodes when its input ends. +pub(crate) struct PartialFold { + tags: Arc<[String]>, + pool: Arc, + /// What this fold holds beside the kernel's state, so each charge can be added to it. + held: usize, + reservation: MemoryReservation, + /// The plan's charge for exported batches, which live until its queue drains. + export_budget: Arc>>, + fold: Option, +} + +impl PartialFold { + /// Starts one partition's fold, its `export_budget` registered against `pool` at first export. + pub(crate) fn try_new( + op: BoundAggregate, + schema: Arc, + tags: Arc<[String]>, + export_budget: Arc>>, + pool: &Arc, + ) -> DfResult { + let kind = aggregate_op(&op)?; + let per_tag = size_of::() + size_of::() + size_of::(); + let held = tags.iter().map(|tag| tag.len() + per_tag).sum::() + 8 * per_tag; + let reservation = MemoryConsumer::new("AggregateExchangeState").register(pool); + reservation.try_resize(held)?; + // `__name__` has the metric name's column; a list without it is reused, not copied. + let tags: Arc<[String]> = if tags.iter().any(|tag| tag == "__name__") { + ordinary_tags(&tags) + .map(ToOwned::to_owned) + .collect::>() + .into() + } else { + tags + }; + // The grouping names are a scratch copy of the binding's list, which can be longer than the + // tag list, so they are admitted while the kernel is built and given back after. + let scratch = match &op.group { + BoundGrouping::By(names) | BoundGrouping::Without(names) => { + names.len() * size_of::<&str>() + } + }; + reservation.try_resize(held.saturating_add(scratch))?; + let fold = { + let names: Vec<&str> = match &op.group { + BoundGrouping::By(names) | BoundGrouping::Without(names) => { + names.iter().map(AsRef::as_ref).collect() + } + }; + let grouping = match &op.group { + BoundGrouping::By(_) => Grouping::By(&names), + BoundGrouping::Without(_) => Grouping::Without(&names), + }; + FloatAggregator::try_new_budgeted(&schema, kind, grouping, |total| { + reservation.try_resize(held.saturating_add(scratch).saturating_add(total)) + })? + }; + reservation.try_resize(held)?; + Ok(Self { + tags, + pool: Arc::clone(pool), + held, + reservation, + export_budget, + fold: Some(fold), + }) + } + + /// Folds one chunk, held while it is folded and dropped after. The kernel validates the chunk + /// against the schema this fold was built with before it charges anything. + pub(crate) fn update(&mut self, chunk: EvaluatedChunk) -> DfResult<()> { + let fold = self.fold.as_mut().ok_or_else(finished)?; + let pending = self.held + series_bytes(&chunk.series); + fold.update_budgeted(&chunk.series, |fold_bytes| { + self.reservation.try_resize(pending + fold_bytes) + })?; + drop(chunk); + self.reservation.try_resize(self.held + fold.state_bytes()) + } + + /// Encodes the fold's state once the caller has read the input to its end. The batches stay + /// charged to [`Self::export_budget`] after the states are given back, since they outlive them. + pub(crate) fn finish(&mut self) -> DfResult> { + let fold = self.fold.take().ok_or_else(finished)?; + let partial = + fold.finish_partial_budgeted(|total| self.reservation.try_resize(self.held + total))?; + let batches = self.encode(&partial)?; + drop(partial); + self.reservation.try_resize(self.held)?; + Ok(batches) + } + + /// Encodes `partial` as one row buffer, admitted in full before it allocates, and hands it over + /// as slices of at most [`BATCH_ROWS`] rows that share it. + fn encode(&self, partial: &PartialAggregate) -> DfResult> { + let mut rows = 0usize; + let mut label_bytes = 0usize; + for group in &partial.groups { + let labels = group.metric.name().map_or(0, str::len).saturating_add( + ordinary_tags(&self.tags) + .filter_map(|tag| group.metric.get(tag).map(|value| tag.len() + value.len())) + .sum::(), + ); + let present: usize = group + .points + .iter() + .map(|p| p.1.iter().flatten().count()) + .sum(); + rows += present; + label_bytes += labels * present; + } + if rows > 0 { + self.grow_export(export_bytes(rows, label_bytes, self.tags.len()))?; + } + let mut metric_name: Vec> = Vec::with_capacity(rows); + let mut tags: Vec> = self.tags.iter().map(|_| Vec::with_capacity(rows)).collect(); + let (mut point, mut field) = (Vec::with_capacity(rows), Vec::with_capacity(rows)); + let mut components: [Vec; 4] = std::array::from_fn(|_| Vec::with_capacity(rows)); + let mut incremental_mean: Vec = Vec::with_capacity(rows); + for group in &partial.groups { + for (at, states) in &group.points { + for (index, state) in states.iter().enumerate() { + let Some(state) = state else { + continue; + }; + metric_name.push(group.metric.name()); + for (column, tag) in tags.iter_mut().zip(self.tags.iter()) { + column.push(group.metric.get(tag)); + } + point.push(*at as u64); + field.push(index as u32); + components[0].push(state.value); + components[1].push(state.mean); + components[2].push(state.compensation); + components[3].push(state.count); + incremental_mean.push(state.incremental_mean); + } + } + } + let mut columns: Vec = Vec::with_capacity(8 + tags.len()); + columns.push(Arc::new(StringArray::from(metric_name))); + for values in tags { + columns.push(Arc::new(StringArray::from(values))); + } + columns.push(Arc::new(UInt64Array::from(point))); + columns.push(Arc::new(UInt32Array::from(field))); + for values in components { + columns.push(Arc::new(Float64Array::from(values))); + } + columns.push(Arc::new(BooleanArray::from(incremental_mean))); + let batch = RecordBatch::try_new(state_schema(&self.tags), columns)?; + Ok((0..rows) + .step_by(BATCH_ROWS) + .map(|offset| batch.slice(offset, BATCH_ROWS.min(rows - offset))) + .collect()) + } + + /// Admits `bytes` to the plan's export reservation, registered against this pool at first use. + fn grow_export(&self, bytes: usize) -> DfResult<()> { + let mut budget = self.export_budget.lock().unwrap_or_else(|e| e.into_inner()); + let consumer = MemoryConsumer::new("AggregateExchangeExport"); + budget + .get_or_insert_with(|| consumer.register(&self.pool)) + .try_grow(bytes) + } +} + +/// Reads one state batch back into the rows a `FloatMerger` merges. +/// +/// Rows of one group and point arrive together, so consecutive rows carrying the same labels and +/// point fill one state vector of the schema's width, and a change of either opens the next one. +/// Rows of one point split across batches stay separate groups, which the merge folds together. +pub(crate) fn decode_state( + batch: &RecordBatch, + schema: &Arc, + op: AggregateOp, + tags: &[String], + mut budget: impl FnMut(usize) -> DfResult<()>, +) -> DfResult { + // The expected layout builds a name and a field per column, so it is admitted before it is + // built, together with the column lookups below. + let mut total = (tags.len() + 9) + .saturating_mul(size_of::<&str>() + size_of::() + size_of::()); + budget(total)?; + let layout = state_schema(tags); + let batch_schema = batch.schema_ref(); + if batch_schema.as_ref() != layout.as_ref() { + return Err(DataFusionError::Execution(format!( + "not the layout {layout:?}" + ))); + } + let grid = schema.eval_grid.as_ref().ok_or_else(|| { + DataFusionError::Execution("aggregate state is indexed on an evaluated grid".into()) + })?; + let width = schema.fields.len(); + // The name list and the label column lookups are workspace, sized exactly and charged before + // either allocates. + total = total.saturating_add(tags.len() * (size_of::<&str>() + size_of::<&StringArray>())); + budget(total)?; + let mut names: Vec<&str> = Vec::with_capacity(tags.len()); + names.extend(ordinary_tags(tags)); + let metric_name: &StringArray = column(batch, "metric_name")?; + let mut tag_columns: Vec<&StringArray> = Vec::with_capacity(names.len()); + for at in 0..names.len() { + tag_columns.push(column(batch, &format!("tag_{at}"))?); + } + let point: &UInt64Array = column(batch, "point")?; + let field: &UInt32Array = column(batch, "field")?; + let value: &Float64Array = column(batch, "value")?; + let mean: &Float64Array = column(batch, "mean")?; + let compensation: &Float64Array = column(batch, "compensation")?; + let count: &Float64Array = column(batch, "count")?; + let incremental_mean: &BooleanArray = column(batch, "incremental_mean")?; + // A null in a state column is not a zero: that state was never folded. Only the label columns + // ahead of these are nullable. + for at in names.len() + 1..batch.num_columns() { + let nulls = batch.column(at).null_count(); + let name = batch_schema.field(at).name(); + if nulls > 0 { + return Err(DataFusionError::Execution(format!( + "the aggregate state column `{name}` holds {nulls} nulls, a state being a value" + ))); + } + } + let mut groups: Vec = Vec::new(); + for row in 0..batch.num_rows() { + let at = usize::try_from(point.value(row)).unwrap_or(usize::MAX); + let field = field.value(row) as usize; + if at >= grid.spec().len as usize || field >= width { + return Err(DataFusionError::Execution(format!( + "aggregate state row {row} is of point {at} of the grid's {} or of field {field} \ + of the aggregate's {width}", + grid.spec().len + ))); + } + // A row repeating the labels of the row before it, on the same point, is that point's next + // field; a change of either opens a group. + let differs = |column: &StringArray| { + column.is_null(row - 1) != column.is_null(row) + || (!column.is_null(row) && column.value(row - 1) != column.value(row)) + }; + let opens = row == 0 + || groups.last().is_none_or(|group| group.points[0].0 != at) + || differs(metric_name) + || tag_columns.iter().any(|column| differs(column)); + if opens { + // A push outgrowing the group vector doubles it, so the block it is about to allocate + // is admitted here; the point's tuple and state vector and the label scratch follow + // before either allocates, then what the labels carry once they are read. + let growth = if groups.len() == groups.capacity() { + groups.capacity().max(1) * 2 * size_of::() + } else { + 0 + }; + total = total.saturating_add( + growth + + size_of::<(usize, Vec>)>() + + width * size_of::>() + + (names.len() + 1) * size_of::<(&str, &str)>(), + ); + budget(total)?; + let name = (!metric_name.is_null(row)).then(|| metric_name.value(row)); + let mut carried: Vec<(&str, &str)> = Vec::with_capacity(names.len()); + for (column, label) in tag_columns.iter().zip(&names) { + if !column.is_null(row) { + carried.push((*label, column.value(row))); + } + } + // The label vector, the `Arc` header each name and value points at, and the bytes + // they hold. One extra pair is the metric name. + total = total.saturating_add( + (names.len() + 1) * (size_of::