diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 68eb458af05..4b043b90700 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -18,7 +18,7 @@ //! one tree builds independent executions. A caller registers the tree's per-node metric handles //! into its own metrics set once, before the execution starts. -use std::collections::{HashSet, VecDeque}; +use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::Arc; use common_query::promql_annotations::PromqlAnnotationCollector; @@ -200,86 +200,62 @@ fn sample_slice_bytes(fields: &SeriesFields) -> usize { .fold(0usize, usize::saturating_add) } -/// The Arrow allocations (values and validity bitmaps) `series`' samples live in that neither -/// `billed` nor this chunk has already listed, with their bytes: full capacity plus one identity -/// slot each. A retained slice keeps its whole allocation resident, so it is billed in full, once. +/// Every Arrow allocation (values and validity bitmaps) `series`' samples live in, once, with its +/// bytes: full capacity plus one identity slot. A retained slice keeps its whole allocation +/// resident, so it is billed in full. /// /// The identity is [`Buffer::data_ptr`], shared by every slice of one allocation; it stays unique -/// while remembered because the retained chunk keeps the allocation alive. The caller adds the -/// returned identities to `billed` after retaining the chunk. -pub(crate) fn unbilled_sample_buffers( - series: &Series, - billed: &HashSet, -) -> (Vec, usize) { - let mut fresh: Vec = Vec::new(); - let mut bytes = 0usize; +/// while remembered because the retained chunk keeps the allocation alive. +fn sample_allocations(series: &Series) -> Vec<(usize, usize)> { + let mut allocations = Vec::new(); for field in series.fields.iter() { for segment in field.segments() { match segment.dense() { - Some(DenseSamplesRef::Float(values)) => { - unbilled_array_buffers(values, &mut fresh, billed, &mut bytes) - } + Some(DenseSamplesRef::Float(values)) => array_allocations(values, &mut allocations), Some(DenseSamplesRef::Histogram(histograms)) => { - unbilled_array_buffers(histograms.indices(), &mut fresh, billed, &mut bytes) + array_allocations(histograms.indices(), &mut allocations) } Some(DenseSamplesRef::Mixed(mixed)) => { - unbilled_array_buffers(mixed.floats(), &mut fresh, billed, &mut bytes); - unbilled_array_buffers( - mixed.histograms().indices(), - &mut fresh, - billed, - &mut bytes, - ); + array_allocations(mixed.floats(), &mut allocations); + array_allocations(mixed.histograms().indices(), &mut allocations); } // `segments` hands out dense segments only, so a nested chunk never reaches here. None => {} } } } - (fresh, bytes) + allocations } -/// [`unbilled_buffer`] for a sample array's values and validity bitmap. -fn unbilled_array_buffers( +/// [`sample_allocations`] for a sample array's values and validity bitmap. +fn array_allocations( values: &PrimitiveArray, - fresh: &mut Vec, - billed: &HashSet, - bytes: &mut usize, + allocations: &mut Vec<(usize, usize)>, ) { - unbilled_buffer(values.values().inner(), fresh, billed, bytes); + buffer_allocation(values.values().inner(), allocations); if let Some(nulls) = values.nulls() { - unbilled_buffer(nulls.buffer(), fresh, billed, bytes); + buffer_allocation(nulls.buffer(), allocations); } } -/// Adds the allocation `buffer` is a slice of to `fresh` and `bytes`, once. -fn unbilled_buffer( - buffer: &Buffer, - fresh: &mut Vec, - billed: &HashSet, - bytes: &mut usize, -) { +/// Adds the allocation `buffer` is a slice of to `allocations`, once. +fn buffer_allocation(buffer: &Buffer, allocations: &mut Vec<(usize, usize)>) { let held = buffer_bytes(buffer); if held == 0 { return; } let identity = buffer.data_ptr().as_ptr() as usize; - if billed.contains(&identity) || fresh.contains(&identity) { + if allocations.iter().any(|(seen, _)| *seen == identity) { return; } - fresh.push(identity); - *bytes = bytes - .saturating_add(held) - .saturating_add(std::mem::size_of::()); + allocations.push((identity, held.saturating_add(std::mem::size_of::()))); } -/// The histogram tables `series` references that neither `billed` nor this chunk has already -/// listed, with their [`table_bytes`] plus one identity slot each. The identity is the `Arc`'s -/// address, unique while the retained chunk keeps the table alive. The caller adds the identities -/// to `billed` after retaining the chunk. -pub(crate) fn unbilled_tables(series: &Series, billed: &HashSet) -> (Vec, usize) { - let mut fresh: Vec = Vec::new(); - let mut bytes = 0usize; +/// Every histogram table `series` references, once, with its [`table_bytes`] plus one identity +/// slot. The identity is the `Arc`'s address, unique while the retained chunk keeps the table +/// alive. +fn table_allocations(series: &Series) -> Vec<(usize, usize)> { + let mut tables: Vec<(usize, usize)> = Vec::new(); for field in series.fields.iter() { for segment in field.segments() { let table = match segment.dense() { @@ -288,18 +264,47 @@ pub(crate) fn unbilled_tables(series: &Series, billed: &HashSet) -> (Vec< _ => continue, }; let identity = Arc::as_ptr(table) as usize; - if billed.contains(&identity) || fresh.contains(&identity) { + if tables.iter().any(|(seen, _)| *seen == identity) { continue; } - fresh.push(identity); - bytes = bytes - .saturating_add(table_bytes(table)) - .saturating_add(std::mem::size_of::()); + tables.push(( + identity, + table_bytes(table).saturating_add(std::mem::size_of::()), + )); } } + tables +} + +/// The entries of `allocations` not in `billed`, with their total bytes. +fn unbilled(allocations: Vec<(usize, usize)>, billed: &HashSet) -> (Vec, usize) { + let mut bytes = 0usize; + let fresh = allocations + .into_iter() + .filter(|(identity, _)| !billed.contains(identity)) + .map(|(identity, held)| { + bytes = bytes.saturating_add(held); + identity + }) + .collect(); (fresh, bytes) } +/// The [`sample_allocations`] of `series` that `billed` does not list, with their bytes. The +/// caller adds the returned identities to `billed` after retaining the chunk. +pub(crate) fn unbilled_sample_buffers( + series: &Series, + billed: &HashSet, +) -> (Vec, usize) { + unbilled(sample_allocations(series), billed) +} + +/// The [`table_allocations`] of `series` that `billed` does not list, with their bytes. The caller +/// adds the returned identities to `billed` after retaining the chunk. +pub(crate) fn unbilled_tables(series: &Series, billed: &HashSet) -> (Vec, usize) { + unbilled(table_allocations(series), billed) +} + /// A rough workspace estimate for merging fragments that hold `rows` rows between them. Values /// and histogram tables stay shared with the fragments and are not counted. pub(crate) fn merge_workspace_bytes(rows: usize, fragments: usize, fields: usize) -> usize { @@ -922,6 +927,98 @@ impl InstantRuntime { } } +/// The chunks a streaming node pulls while a dynamic scalar it needs is still pending. Queued at +/// the source, every slice would be billed its whole allocation; here each allocation is billed +/// once, and released when the last held chunk referencing it is handed on. +#[derive(Default)] +struct HeldInput { + /// In arrival order. + chunks: VecDeque, + /// Per sample allocation and histogram table: its bytes and how many held chunks reference it. + allocations: HashMap, + /// The deque's slots plus what each held chunk and each referenced allocation is billed. + bytes: usize, +} + +struct HeldChunk { + chunk: EvaluatedChunk, + /// The allocations and tables the chunk references. + references: Vec, + /// [`chunk_bytes_beside_samples`] plus the `references` list. + beside: usize, +} + +impl HeldInput { + /// Holds `chunk`, growing `buffer` first so a refused chunk leaves nothing behind. + fn hold(&mut self, chunk: EvaluatedChunk, buffer: &mut NodeBuffer) -> Result<()> { + let mut allocations = sample_allocations(&chunk.series); + allocations.extend(table_allocations(&chunk.series)); + let beside = chunk_bytes_beside_samples(&chunk.series).saturating_add( + allocations + .len() + .saturating_mul(std::mem::size_of::()), + ); + let fresh = allocations + .iter() + .filter(|(identity, _)| !self.allocations.contains_key(identity)) + .fold(0usize, |total, (_, held)| total.saturating_add(*held)); + let capacity = self.chunks.capacity(); + let target = if self.chunks.len() == capacity { + capacity.saturating_mul(2).max(4) + } else { + capacity + }; + let bytes = beside.saturating_add(fresh).saturating_add( + target + .saturating_sub(capacity) + .saturating_mul(std::mem::size_of::()), + ); + buffer.grow(bytes)?; + self.chunks + .try_reserve_exact(target.saturating_sub(self.chunks.len())) + .map_err(|error| { + DataFusionError::Execution(format!("cannot hold a pending input chunk: {error}")) + })?; + let mut references = Vec::with_capacity(allocations.len()); + for (identity, held) in allocations { + self.allocations.entry(identity).or_insert((held, 0)).1 += 1; + references.push(identity); + } + self.chunks.push_back(HeldChunk { + chunk, + references, + beside, + }); + self.bytes = self.bytes.saturating_add(bytes); + Ok(()) + } + + /// Hands out the oldest held chunk and stops billing it, and every allocation no other held + /// chunk references. Once the last one is out, [`Self::bytes`] is zero. + fn pop(&mut self) -> Option { + let held = self.chunks.pop_front()?; + let mut released = held.beside; + for identity in held.references { + if let Some((bytes, count)) = self.allocations.get_mut(&identity) { + *count -= 1; + if *count == 0 { + released = released.saturating_add(*bytes); + self.allocations.remove(&identity); + } + } + } + self.bytes = self.bytes.saturating_sub(released); + if self.chunks.is_empty() { + *self = Self::default(); + } + Some(held.chunk) + } + + fn is_empty(&self) -> bool { + self.chunks.is_empty() + } +} + /// An input a node reads whole before it computes (a binary operand, or the input of a vector /// operation). Chunks are assembled into one series per logical series once the input ends. #[derive(Default)] @@ -1748,6 +1845,8 @@ struct BroadcastRuntime { sample_schema: Arc, /// The bytes charged for a [`BroadcastScalar::Dynamic`] value. scalar_bytes: usize, + /// Vector chunks pulled before the dynamic value arrived. + held: HeldInput, annotations: Option, } @@ -1766,6 +1865,8 @@ struct ParameterizedMapRuntime { values: Vec>, /// The bytes charged for `values` and for the constant input's chunk. parameter_bytes: usize, + /// Input chunks pulled before every parameter arrived. + held: HeldInput, } impl ParameterizedMapRuntime { @@ -2865,6 +2966,7 @@ impl RuntimeNode { literals, values: vec![None; parameters.len()], parameter_bytes: 0, + held: HeldInput::default(), }, state, } @@ -3777,6 +3879,13 @@ impl RuntimeNode { } } if !operation.ready() { + while let Some(chunk) = input.pull(inputs, inputs_finished)? { + let chunk = expect_evaluated(chunk, "the map node reads")?; + operation + .held + .hold(chunk, &mut state.buffer) + .map_err(|error| state.context(error))?; + } // A parameter like `scalar(selector)` answers only after its input ends. if !inputs_finished || !parameters.iter().all(|parameter| parameter.settled(inputs)) @@ -3808,6 +3917,14 @@ impl RuntimeNode { .map_err(|error| state.context(error)) .map(|output| output.map(NativeChunk::Evaluated)); } + while let Some(chunk) = operation.held.pop() { + if let Some(output) = state + .parameterized_map(operation, chunk) + .map_err(|error| state.context(error))? + { + return Ok(Some(NativeChunk::Evaluated(output))); + } + } loop { let chunk = match input.pull(inputs, inputs_finished)? { Some(NativeChunk::Evaluated(chunk)) => chunk, @@ -3905,6 +4022,13 @@ impl RuntimeNode { } } if operation.awaits_scalar() { + while let Some(chunk) = vector.pull(inputs, inputs_finished)? { + let chunk = expect_evaluated(chunk, "the binary node broadcasts over")?; + operation + .held + .hold(chunk, &mut state.buffer) + .map_err(|error| state.context(error))?; + } if !inputs_finished || !scalar.settled(inputs) { return Ok(None); } @@ -3912,6 +4036,14 @@ impl RuntimeNode { "a broadcast scalar did not hand over its value".to_string(), )); } + while let Some(chunk) = operation.held.pop() { + if let Some(output) = state + .broadcast(operation, NativeChunk::Evaluated(chunk)) + .map_err(|error| state.context(error))? + { + return Ok(Some(NativeChunk::Evaluated(output))); + } + } // A chunk the operation empties entirely yields nothing; keep pulling. loop { let Some(chunk) = vector.pull(inputs, inputs_finished)? else { @@ -4017,7 +4149,14 @@ impl RuntimeNode { .map_err(|error| state.context(error))?; } let series = { + // While the parameter is pending, retain the input anyway: queued at the + // source, each slice is billed its whole allocation. if !parameter_node.settled(inputs) { + while let Some(chunk) = input.pull(inputs, inputs_finished)? { + state + .retain_vector(operation, chunk) + .map_err(|error| state.context(error))?; + } return Ok(None); } slot.ok_or_else(|| { @@ -4086,6 +4225,7 @@ impl RuntimeNode { state, } => { let operation = vector; + let mut pending = false; for index in 0..parameters.len() { if values[index].is_none() { let mut slot = None; @@ -4109,7 +4249,8 @@ impl RuntimeNode { state.hold_scalar(&mut parameter_bytes[index], &mut slot, chunk)?; } if !parameter.settled(inputs) { - return Ok(None); + pending = true; + continue; } } let series = slot.ok_or_else(|| { @@ -4156,10 +4297,17 @@ impl RuntimeNode { parameters[index] = None; } } + // A pending parameter's bytes are already reserved; `retain_vector` settles on + // `parameter_bytes`, so it must count them. + operation.parameter_bytes = parameter_bytes + .iter() + .copied() + .fold(0usize, usize::saturating_add); + // While a parameter is pending, retain the input anyway, as `ParameterizedTopK` does. while let Some(chunk) = input.pull(inputs, inputs_finished)? { state.retain_vector(operation, chunk)?; } - if !inputs_finished || !input.settled(inputs) { + if pending || !inputs_finished || !input.settled(inputs) { return Ok(None); } let collected = values @@ -4237,11 +4385,15 @@ impl RuntimeNode { } // What one side of a vector match answers at a point depends on the other side. RuntimeOp::Binary { binary, state, .. } => state.queued.is_empty() && binary.computed, + RuntimeOp::ParameterizedMap { map, state, .. } => { + state.queued.is_empty() && map.held.is_empty() + } + RuntimeOp::Broadcast { + broadcast, state, .. + } => state.queued.is_empty() && broadcast.held.is_empty(), RuntimeOp::Instant { state, .. } | RuntimeOp::Map { state, .. } - | RuntimeOp::ParameterizedMap { state, .. } - | RuntimeOp::Timestamp { state, .. } - | RuntimeOp::Broadcast { state, .. } => state.queued.is_empty(), + | RuntimeOp::Timestamp { state, .. } => state.queued.is_empty(), }; own && self.children().all(|(_, child)| child.settled(inputs)) } @@ -4618,7 +4770,8 @@ impl NodeState { let outcome = match outcome { Ok(outcome) => outcome, Err(error) => { - self.buffer.resize(map.parameter_bytes)?; + self.buffer + .resize(map.parameter_bytes.saturating_add(map.held.bytes))?; return Err(error); } }; @@ -4636,7 +4789,8 @@ impl NodeState { metrics.record_grid_points(output.series.time.len()); metrics.record_output(1, valid_values(output)); } - self.buffer.resize(map.parameter_bytes)?; + self.buffer + .resize(map.parameter_bytes.saturating_add(map.held.bytes))?; Ok(output) } @@ -4719,7 +4873,8 @@ impl NodeState { let output = match outcome { Ok(output) => output, Err(error) => { - self.buffer.resize(broadcast.scalar_bytes)?; + self.buffer + .resize(broadcast.scalar_bytes.saturating_add(broadcast.held.bytes))?; return Err(error); } }; @@ -4731,7 +4886,8 @@ impl NodeState { metrics.record_grid_points(output.series.time.len()); metrics.record_output(1, valid_values(output)); } - self.buffer.resize(broadcast.scalar_bytes)?; + self.buffer + .resize(broadcast.scalar_bytes.saturating_add(broadcast.held.bytes))?; Ok(output) } @@ -5687,6 +5843,17 @@ fn no_live_execution() -> DataFusionError { DataFusionError::Internal("the running native execution has no state".to_string()) } +/// The evaluated chunk a streaming node reads; `reader` names the node in the error. +fn expect_evaluated(chunk: NativeChunk, reader: &str) -> Result { + match chunk { + NativeChunk::Evaluated(chunk) => Ok(chunk), + other => Err(DataFusionError::Execution(format!( + "{reader} evaluated chunks, not {}", + other.describe() + ))), + } +} + /// The error for a node asked to evaluate a window without its evaluator. fn no_window() -> DataFusionError { DataFusionError::Execution("the node holds no window evaluator".to_string()) @@ -5771,6 +5938,7 @@ fn broadcast_runtime( op: broadcast_op(matching)?, sample_schema, scalar_bytes: 0, + held: HeldInput::default(), annotations: None, }) } diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index 8e871328aaa..e11dad3c4d2 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -14716,3 +14716,158 @@ fn grid_position_reports_a_timestamp_whose_offset_overflows_and_misses_the_latti let error = grid_position(&grid, i64::MAX).unwrap_err().to_string(); assert!(error.contains("is not a point of"), "{error}"); } + +/// While a dynamic scalar is pending, a broadcast, a parameterized map, a parameterized `topk` and +/// a parameterized histogram function pull their vector input instead of leaving it queued at the +/// source, where every slice of one allocation is billed that whole allocation. +#[test] +fn a_node_waiting_for_a_dynamic_scalar_bills_its_input_allocation_once() { + const POINTS: usize = 4096; + const SLICES: usize = 32; + const LEN: usize = POINTS / SLICES; + let grid = grid(0, 1_000, POINTS as u64); + let schema = evaluated_schema(Arc::clone(&grid)); + let vector = || evaluated_input(Arc::clone(&grid)); + let parameter = || scalar_of(evaluated_input_with_source_index(Arc::clone(&grid), 1)); + let topk = { + let input = vector(); + NativeNode { + output: input.output.clone(), + expr: NativeExpr::ParameterizedTopK { + input: Box::new(input), + op: BoundVectorOp::TopK { + k: 0.0, + top: true, + group: Grouping::By(Arc::from([])), + }, + parameter: Box::new(parameter()), + }, + } + }; + let histogram = { + let input = vector(); + NativeNode { + output: input.output.clone(), + expr: NativeExpr::ParameterizedHistogram { + input: Box::new(input), + op: BoundVectorOp::Histogram(HistogramFunction::Quantile(0.0)), + parameters: vec![parameter()], + }, + } + }; + let answers = |answer: fn(f64) -> f64| { + Some( + (0..POINTS) + .map(|at| Some(answer(at as f64))) + .collect::>(), + ) + }; + // `x * scalar(y)`, `clamp_min(x, scalar(y))`, `topk(scalar(y), x)` with `y` = 2, and + // `histogram_quantile(scalar(y), x)`, which has no histogram to answer from. + let cases = [ + ( + scalar_binary(vector(), parameter(), binary_matching(BinaryOp::Mul)), + answers(|x| x * 2.0), + ), + ( + parameterized(vector(), ParameterizedOp::ClampMin, vec![parameter()]), + answers(|x| x.max(2.0)), + ), + (topk, answers(|x| x)), + (histogram, None), + ]; + let values = Float64Array::from_iter_values((0..POINTS).map(|at| at as f64)); + let allocation = POINTS * std::mem::size_of::(); + for (root, expected) in cases { + let tree = NativeTree::try_new(root).unwrap(); + let pool = bounded_pool(64 << 20); + let mut execution = executor(&tree, Arc::clone(&pool)); + let x = execution.state().input_ids(0).next().unwrap(); + let y = execution.state().input_ids(1).next().unwrap(); + for slice in 0..SLICES { + let chunk = evaluated_array_chunk_of( + &schema, + named_metric("x", "a"), + slice * LEN, + values.slice(slice * LEN, LEN), + slice + 1 == SLICES, + ); + execution.push_evaluated(x, chunk).unwrap(); + assert!(execution.next_chunk().unwrap().is_none()); + } + // One slice per queued chunk would hold `SLICES` allocations. + assert!(pool.reserved() < 4 * allocation, "{}", pool.reserved()); + execution + .push_evaluated( + y, + evaluated_chunk_of( + &schema, + named_metric("y", "b"), + 0, + vec![Some(2.0); POINTS], + true, + ), + ) + .unwrap(); + let chunks = execution.finish().unwrap(); + let answered: Vec> = chunks.iter().flat_map(sample_values).collect(); + match expected { + Some(expected) => assert_eq!(answered, expected), + None => assert!(answered.iter().all(Option::is_none), "{answered:?}"), + } + drop(execution); + assert_eq!(pool.reserved(), 0); + } +} + +/// `sort(x * scalar(y))` over series in allocations of their own: a held chunk's allocation stops +/// being billed once the broadcast hands it on, so the input and the sort's copy of the output are +/// not both billed in full. Billing every held allocation until the last one is out needs about 76 +/// allocations here; the source queue releasing per chunk needed about 43. +#[test] +fn a_held_chunk_is_released_as_the_broadcast_hands_it_on() { + const SERIES: usize = 32; + const POINTS: usize = 1024; + let grid = grid(0, 1_000, POINTS as u64); + let schema = evaluated_schema(Arc::clone(&grid)); + let root = vector_op( + scalar_binary( + evaluated_input(Arc::clone(&grid)), + scalar_of(evaluated_input_with_source_index(Arc::clone(&grid), 1)), + binary_matching(BinaryOp::Mul), + ), + BoundVectorOp::Sort(SortOrder::Desc), + ); + let tree = NativeTree::try_new(root).unwrap(); + let pool = bounded_pool(56 * POINTS * std::mem::size_of::()); + let mut execution = executor(&tree, Arc::clone(&pool)); + let x = execution.state().input_ids(0).next().unwrap(); + let y = execution.state().input_ids(1).next().unwrap(); + for series in 0..SERIES { + let chunk = evaluated_chunk_of( + &schema, + named_metric("x", &format!("j{series}")), + 0, + vec![Some(series as f64); POINTS], + true, + ); + execution.push_evaluated(x, chunk).unwrap(); + assert!(execution.next_chunk().unwrap().is_none()); + } + execution + .push_evaluated( + y, + evaluated_chunk_of( + &schema, + named_metric("y", "b"), + 0, + vec![Some(2.0); POINTS], + true, + ), + ) + .unwrap(); + let chunks = execution.finish().unwrap(); + assert_eq!(chunks.len(), SERIES); + drop(execution); + assert_eq!(pool.reserved(), 0); +}