diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 4b043b90700..95906847173 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -1269,17 +1269,25 @@ impl PairKernel { } } -fn side_name(index: usize) -> &'static str { - match index { - 0 => "left", - _ => "right", +#[derive(Clone, Copy)] +enum Side { + Left, + Right, +} + +impl Side { + fn name(self) -> &'static str { + match self { + Self::Left => "left", + Self::Right => "right", + } } } /// The owner of a [`RetainedInput`], named in its errors. #[derive(Clone, Copy)] enum Reader { - Operand { side: usize, node: &'static str }, + Operand { side: Side, node: &'static str }, Vector, } @@ -1293,18 +1301,13 @@ impl Reader { fn input(self) -> String { match self { - Self::Operand { side, .. } => format!("its {} operand", side_name(side)), + Self::Operand { side, .. } => format!("its {} operand", side.name()), Self::Vector => "its input".to_string(), } } } impl BinaryRuntime { - /// This node's evidence slot for a field. - fn slot(&self, field: usize) -> (usize, usize) { - (self.node_index, field) - } - fn new( kernel: PairKernel, schemas: [Arc; 2], @@ -1322,7 +1325,7 @@ impl BinaryRuntime { } } - fn reader(&self, side: usize) -> Reader { + fn reader(&self, side: Side) -> Reader { Reader::Operand { side, node: self.kernel.node(), @@ -1347,23 +1350,20 @@ impl BinaryRuntime { let [left, right] = &self.operands; let [left_schema, right_schema] = &self.schemas; Ok([ - left.assemble(left_schema, self.reader(0))?, - right.assemble(right_schema, self.reader(1))?, + left.assemble(left_schema, self.reader(Side::Left))?, + right.assemble(right_schema, self.reader(Side::Right))?, ]) } /// The bytes the chunk of `side` would add to that operand; see [`RetainedInput::pending`]. - fn pending(&self, side: usize, chunk: &EvaluatedChunk) -> Result { - self.operands - .get(side) - .map(|operand| operand.pending(chunk)) - .ok_or_else(invalid_binary_operand) + fn pending(&self, side: Side, chunk: &EvaluatedChunk) -> usize { + self.operands[side as usize].pending(chunk) } /// Refuses an operand that ended with a series still open. fn closed(&self) -> Result<()> { - for (side, operand) in self.operands.iter().enumerate() { - operand.ensure_closed(self.reader(side))?; + for side in [Side::Left, Side::Right] { + self.operands[side as usize].ensure_closed(self.reader(side))?; } Ok(()) } @@ -1371,24 +1371,20 @@ impl BinaryRuntime { /// Retains one chunk of the operand at `side`, after the kernel's own operand check. The bound /// tree is no proof of what a chunk carries: `Series` fields are public, so a struct-literal /// chunk can carry another field count or fewer samples than its axis places rows. - fn retain(&mut self, side: usize, chunk: EvaluatedChunk) -> Result<()> { - let Some(schema) = self.schemas.get(side) else { - return Err(invalid_binary_operand()); - }; - validate_binary_operand(schema.as_ref(), std::slice::from_ref(&chunk.series)).map_err( - |error| { - DataFusionError::Execution(format!( - "{} rejected its {} operand: {error}", - self.kernel.node(), - side_name(side) - )) - }, - )?; + fn retain(&mut self, side: Side, chunk: EvaluatedChunk) -> Result<()> { + validate_binary_operand( + self.schemas[side as usize].as_ref(), + std::slice::from_ref(&chunk.series), + ) + .map_err(|error| { + DataFusionError::Execution(format!( + "{} rejected its {} operand: {error}", + self.kernel.node(), + side.name() + )) + })?; let reader = self.reader(side); - let Some(operand) = self.operands.get_mut(side) else { - return Err(invalid_binary_operand()); - }; - operand.retain(chunk, reader) + self.operands[side as usize].retain(chunk, reader) } /// Runs the kernel over both assembled operands, or returns `None` if it already ran. @@ -1436,7 +1432,7 @@ impl BinaryRuntime { right_schema, right, evidence.map(|evidence| crate::vector_match::NodeEvidence { - node: self.slot(0).0, + node: self.node_index, evidence, }), self.annotations.as_ref(), @@ -2624,7 +2620,7 @@ impl NodeState { } } -/// Remaining stack below which [`RuntimeNode::build`] and [`RuntimeNode::pull`] grow it. Both +/// Remaining stack below which [`TreeBuilder::build`] and [`RuntimeNode::pull`] grow it. Both /// recurse once per tree level with large debug-build frames (about 140 KiB and 80 KiB, measured on /// a 100-term chain), and the tree has no depth limit, so an 8 MiB worker stack can overflow. const NATIVE_STACK_RED_ZONE: usize = 512 * 1024; @@ -2632,41 +2628,60 @@ const NATIVE_STACK_RED_ZONE: usize = 512 * 1024; /// Stack added per growth; holds several levels. const NATIVE_STACK_GROWTH: usize = 4 * 1024 * 1024; -impl RuntimeNode { +/// Builds the runtime nodes of one tree, numbering its inputs and pair nodes as it goes. +struct TreeBuilder<'a> { + pool: &'a Arc, + duplicate_evidence: Option>, + sources: &'a SourceFacts, + inputs: Vec, + pairs: usize, +} + +impl<'a> TreeBuilder<'a> { + fn new( + pool: &'a Arc, + duplicate_evidence: Option>, + sources: &'a SourceFacts, + ) -> Self { + Self { + pool, + duplicate_evidence, + sources, + inputs: Vec::new(), + pairs: 0, + } + } + /// Builds the runtime node for `node` and, recursively, for its inputs, growing the stack as it /// descends. - fn build( - node: &NativeNode, - pool: &Arc, - inputs: &mut Vec, - binary_before: &mut usize, - location: String, - duplicate_evidence: Option>, - sources: &SourceFacts, - ) -> Result { + fn build(&mut self, node: &NativeNode, location: String) -> Result { stacker::maybe_grow(NATIVE_STACK_RED_ZONE, NATIVE_STACK_GROWTH, || { - Self::build_within_stack( - node, - pool, - inputs, - binary_before, - location, - duplicate_evidence, - sources, - ) + self.build_within_stack(node, location) }) } - fn build_within_stack( - node: &NativeNode, - pool: &Arc, - inputs: &mut Vec, - binary_before: &mut usize, - location: String, - duplicate_evidence: Option>, - sources: &SourceFacts, - ) -> Result { + fn pair(&mut self, kernel: PairKernel, schemas: [&Arc; 2]) -> BinaryRuntime { + let node_index = self.pairs; + self.pairs += 1; + BinaryRuntime::new( + kernel, + schemas.map(Arc::clone), + node_index, + self.duplicate_evidence.clone(), + ) + } + + fn build_within_stack(&mut self, node: &NativeNode, location: String) -> Result { let metrics = Arc::new(NodeMetrics::default()); + let pool = self.pool; + let new_state = |kind: &str| { + NodeState::new( + format!("native.{kind} at {location}"), + Arc::clone(&metrics), + pool, + ) + }; + let at = |role: &str| format!("{location}.{role}"); let op = match &node.expr { NativeExpr::Input(bound) => { if bound.ordering == SeriesOrdering::Interleaved { @@ -2675,8 +2690,8 @@ impl RuntimeNode { bound.ordering ))); } - let id = InputId(inputs.len()); - inputs.push(InputSlot { + let id = InputId(self.inputs.len()); + self.inputs.push(InputSlot { source_index: bound.source_index, kind: LeafKind::of(&node.output)?, open_source_series: false, @@ -2694,9 +2709,7 @@ impl RuntimeNode { } NativeExpr::Scalar(_) => RuntimeOp::Scalar, NativeExpr::ScalarOf { input } => { - let input_schema = input.output.samples().cloned().ok_or_else(|| { - DataFusionError::Execution("scalar() consumes non-sample input".to_string()) - })?; + let input_schema = samples_of(&input.output, "scalar() consumes non-sample input")?; if input_schema.fields.len() != 1 { return Err(DataFusionError::NotImplemented( "the native runtime does not execute multi-field scalar()".into(), @@ -2705,26 +2718,13 @@ impl RuntimeNode { let grid = input_schema.eval_grid.clone().ok_or_else(|| { DataFusionError::Execution("scalar() consumes raw samples".to_string()) })?; - let child = Self::build( - input, - pool, - inputs, - binary_before, - format!("{location}.input"), - duplicate_evidence.clone(), - sources, - )?; RuntimeOp::ScalarOf { - input: Box::new(child), + input: Box::new(self.build(input, at("input"))?), input_schema, grid, retained: RetainedInput::default(), produced: false, - state: NodeState::new( - format!("native.scalar_of at {location}"), - Arc::clone(&metrics), - pool, - ), + state: new_state("scalar_of"), } } NativeExpr::EvalTime { date } => { @@ -2737,62 +2737,22 @@ impl RuntimeNode { grid: Arc::clone(grid), date: *date, produced: false, - state: NodeState::new( - format!("native.time at {location}"), - Arc::clone(&metrics), - pool, - ), - } - } - NativeExpr::VectorOf { input } => { - let schema = node.output.samples().cloned().ok_or_else(|| { - DataFusionError::Execution("vector() does not produce samples".to_string()) - })?; - let literal = match &input.expr { - NativeExpr::Scalar(BoundScalar { value }) => Some(*value), - _ => None, - }; - let child = Self::build( - input, - pool, - inputs, - binary_before, - format!("{location}.input"), - duplicate_evidence.clone(), - sources, - )?; - RuntimeOp::VectorOf { - input: Box::new(child), - literal, - produced: false, - schema, - state: NodeState::new( - format!("native.vector_of at {location}"), - Arc::clone(&metrics), - pool, - ), + state: new_state("time"), } } + NativeExpr::VectorOf { input } => RuntimeOp::VectorOf { + schema: samples_of(&node.output, "vector() does not produce samples")?, + literal: literal(input), + input: Box::new(self.build(input, at("input"))?), + produced: false, + state: new_state("vector_of"), + }, NativeExpr::Instant { input, op } => { - let child = Self::build( - input, - pool, - inputs, - binary_before, - format!("{location}.input"), - duplicate_evidence.clone(), - sources, - )?; - let input_schema = input.output.samples().cloned().ok_or_else(|| { - DataFusionError::Execution( - "instant selection consumes non-sample input".to_string(), - ) - })?; - let output_schema = node.output.samples().cloned().ok_or_else(|| { - DataFusionError::Execution( - "instant selection does not produce samples".to_string(), - ) - })?; + let child = self.build(input, at("input"))?; + let input_schema = + samples_of(&input.output, "instant selection consumes non-sample input")?; + let output_schema = + samples_of(&node.output, "instant selection does not produce samples")?; RuntimeOp::Instant { input: Box::new(child), instant: InstantRuntime::try_new( @@ -2801,63 +2761,26 @@ impl RuntimeNode { op, input_time_unit(input), )?, - state: { - NodeState::new( - format!("native.instant at {location}"), - Arc::clone(&metrics), - pool, - ) - }, - } - } - NativeExpr::Merge { input } => { - let child = Self::build( - input, - pool, - inputs, - binary_before, - format!("{location}.input"), - duplicate_evidence.clone(), - sources, - )?; - let schema = node.output.samples().cloned().ok_or_else(|| { - DataFusionError::Execution("merge does not produce samples".to_string()) - })?; - let state = NodeState::new( - format!("native.merge at {location}"), - Arc::clone(&metrics), - pool, - ); - RuntimeOp::Merge { - input: Box::new(child), - merge: Some(MergeInput::new(schema)), - state, + state: new_state("instant"), } } + NativeExpr::Merge { input } => RuntimeOp::Merge { + input: Box::new(self.build(input, at("input"))?), + merge: Some(MergeInput::new(samples_of( + &node.output, + "merge does not produce samples", + )?)), + state: new_state("merge"), + }, NativeExpr::Window { input, op } => { - let child = Self::build( - input, - pool, - inputs, - binary_before, - format!("{location}.input"), - duplicate_evidence.clone(), - sources, - )?; - let input_schema = input.output.samples().cloned().ok_or_else(|| { - DataFusionError::Execution("window consumes non-sample input".to_string()) - })?; + let child = self.build(input, at("input"))?; + let input_schema = samples_of(&input.output, "window consumes non-sample input")?; // Collect and merge fragments only when the input cannot prove its series keep // distinct label sets: the same check the canonical pass uses to place merges. let unification = - unifies_its_own_contributions(input, &sources.tags, &sources.metrics); + unifies_its_own_contributions(input, &self.sources.tags, &self.sources.metrics); let merge = matches!(unification, Some(false)) .then(|| MergeInput::new(Arc::clone(&input_schema))); - let state = NodeState::new( - format!("native.window at {location}"), - Arc::clone(&metrics), - pool, - ); RuntimeOp::Window { input: Box::new(child), window: Some( @@ -2870,50 +2793,23 @@ impl RuntimeNode { .with_raw_time_unit(input_time_unit(input)), ), merge, - state, - } - } - NativeExpr::Map { input, op } => { - let child = Self::build( - input, - pool, - inputs, - binary_before, - format!("{location}.input"), - duplicate_evidence.clone(), - sources, - )?; - let schema = node.output.samples().cloned().ok_or_else(|| { - DataFusionError::Execution("map does not produce samples".to_string()) - })?; - let state = NodeState::new( - format!("native.map at {location}"), - Arc::clone(&metrics), - pool, - ); - RuntimeOp::Map { - input: Box::new(child), - map: MapRuntime { - ops: Arc::clone(&op.ops), - schema, - }, - state, + state: new_state("window"), } } + NativeExpr::Map { input, op } => RuntimeOp::Map { + input: Box::new(self.build(input, at("input"))?), + map: MapRuntime { + ops: Arc::clone(&op.ops), + schema: samples_of(&node.output, "map does not produce samples")?, + }, + state: new_state("map"), + }, NativeExpr::ParameterizedMap { input, op, parameters, } => { - let child = Self::build( - input, - pool, - inputs, - binary_before, - format!("{location}.input"), - duplicate_evidence.clone(), - sources, - )?; + let child = self.build(input, at("input"))?; let schema = match &node.output { NativeType::Samples(schema) => Arc::clone(schema), NativeType::Scalar(grid) => Arc::new(scalar_schema(Arc::clone(grid))), @@ -2924,151 +2820,63 @@ impl RuntimeNode { )); } }; - let literals = parameters - .iter() - .map(|parameter| match ¶meter.expr { - NativeExpr::Scalar(BoundScalar { value }) => Some(*value), - _ => None, - }) - .collect(); - let input_literal = match &input.expr { - NativeExpr::Scalar(BoundScalar { value }) => Some(*value), - _ => None, - }; let nodes = parameters .iter() .enumerate() .map(|(index, parameter)| { - Self::build( - parameter, - pool, - inputs, - binary_before, - format!("{location}.parameter{index}"), - duplicate_evidence.clone(), - sources, - ) + self.build(parameter, format!("{location}.parameter{index}")) }) .collect::>>()?; - let state = NodeState::new( - format!("native.map at {location}"), - Arc::clone(&metrics), - pool, - ); RuntimeOp::ParameterizedMap { input: Box::new(child), parameters: nodes, map: ParameterizedMapRuntime { op: *op, schema, - input_literal, + input_literal: literal(input), input_produced: false, - literals, + literals: parameters.iter().map(literal).collect(), values: vec![None; parameters.len()], parameter_bytes: 0, held: HeldInput::default(), }, - state, - } - } - NativeExpr::Timestamp { input } => { - let child = Self::build( - input, - pool, - inputs, - binary_before, - format!("{location}.input"), - duplicate_evidence.clone(), - sources, - )?; - let schema = node.output.samples().cloned().ok_or_else(|| { - DataFusionError::Execution("timestamp does not produce samples".to_string()) - })?; - let state = NodeState::new( - format!("native.timestamp at {location}"), - Arc::clone(&metrics), - pool, - ); - RuntimeOp::Timestamp { - input: Box::new(child), - schema, - state, + state: new_state("map"), } } + NativeExpr::Timestamp { input } => RuntimeOp::Timestamp { + input: Box::new(self.build(input, at("input"))?), + schema: samples_of(&node.output, "timestamp does not produce samples")?, + state: new_state("timestamp"), + }, NativeExpr::Binary { left, right, matching, - } => { - let left_schema = left.output.samples(); - let right_schema = right.output.samples(); - let (binary, broadcast) = match (left_schema, right_schema) { - (Some(left_schema), Some(right_schema)) - if left_schema.eval_grid.is_some() && right_schema.eval_grid.is_some() => - { - let node_index = *binary_before; - *binary_before += 1; - ( - Some(BinaryRuntime::new( - PairKernel::Binary(Arc::new(matching.clone())), - [Arc::clone(left_schema), Arc::clone(right_schema)], - node_index, - duplicate_evidence.clone(), - )), - None, - ) - } - _ => (None, Some(broadcast_runtime(left, right, matching)?)), - }; - let left_node = Self::build( - left, - pool, - inputs, - binary_before, - format!("{location}.left"), - duplicate_evidence.clone(), - sources, - )?; - let right_node = Self::build( - right, - pool, - inputs, - binary_before, - format!("{location}.right"), - duplicate_evidence.clone(), - sources, - )?; - match (binary, broadcast) { - (Some(binary), None) => RuntimeOp::Binary { - left: Box::new(left_node), - right: Box::new(right_node), + } => match (left.output.samples(), right.output.samples()) { + (Some(left_schema), Some(right_schema)) + if left_schema.eval_grid.is_some() && right_schema.eval_grid.is_some() => + { + let binary = self.pair( + PairKernel::Binary(Arc::new(matching.clone())), + [left_schema, right_schema], + ); + RuntimeOp::Binary { + left: Box::new(self.build(left, at("left"))?), + right: Box::new(self.build(right, at("right"))?), binary, - state: NodeState::new( - format!("native.binary at {location}"), - Arc::clone(&metrics), - pool, - ), - }, - (None, Some(broadcast)) => { - let state = NodeState::new( - format!("native.binary at {location}"), - Arc::clone(&metrics), - pool, - ); - RuntimeOp::Broadcast { - left: Box::new(left_node), - right: Box::new(right_node), - broadcast, - state, - } - } - _ => { - return Err(DataFusionError::Internal( - "binary runtime build selected conflicting operation modes".to_string(), - )); + state: new_state("binary"), } } - } + _ => { + let broadcast = broadcast_runtime(left, right, matching)?; + RuntimeOp::Broadcast { + left: Box::new(self.build(left, at("left"))?), + right: Box::new(self.build(right, at("right"))?), + broadcast, + state: new_state("binary"), + } + } + }, NativeExpr::Set { left, right, op } => { let (Some(left_schema), Some(right_schema)) = (left.output.samples(), right.output.samples()) @@ -3077,41 +2885,12 @@ impl RuntimeNode { "a set operation consumes two vectors".to_string(), )); }; - let node_index = *binary_before; - *binary_before += 1; - let set = BinaryRuntime::new( - PairKernel::Set(op.clone()), - [Arc::clone(left_schema), Arc::clone(right_schema)], - node_index, - duplicate_evidence.clone(), - ); - let left_node = Self::build( - left, - pool, - inputs, - binary_before, - format!("{location}.left"), - duplicate_evidence.clone(), - sources, - )?; - let right_node = Self::build( - right, - pool, - inputs, - binary_before, - format!("{location}.right"), - duplicate_evidence.clone(), - sources, - )?; + let binary = self.pair(PairKernel::Set(op.clone()), [left_schema, right_schema]); RuntimeOp::Binary { - left: Box::new(left_node), - right: Box::new(right_node), - binary: set, - state: NodeState::new( - format!("native.set at {location}"), - Arc::clone(&metrics), - pool, - ), + left: Box::new(self.build(left, at("left"))?), + right: Box::new(self.build(right, at("right"))?), + binary, + state: new_state("set"), } } NativeExpr::Info { @@ -3126,41 +2905,15 @@ impl RuntimeNode { "info consumes two vectors".to_string(), )); }; - let node_index = *binary_before; - *binary_before += 1; - let runtime = BinaryRuntime::new( + let binary = self.pair( PairKernel::Info(selector.clone()), - [Arc::clone(base_schema), Arc::clone(info_schema)], - node_index, - duplicate_evidence.clone(), + [base_schema, info_schema], ); - let base_node = Self::build( - base, - pool, - inputs, - binary_before, - format!("{location}.base"), - duplicate_evidence.clone(), - sources, - )?; - let info_node = Self::build( - info, - pool, - inputs, - binary_before, - format!("{location}.info"), - duplicate_evidence.clone(), - sources, - )?; RuntimeOp::Binary { - left: Box::new(base_node), - right: Box::new(info_node), - binary: runtime, - state: NodeState::new( - format!("native.info at {location}"), - Arc::clone(&metrics), - pool, - ), + left: Box::new(self.build(base, at("base"))?), + right: Box::new(self.build(info, at("info"))?), + binary, + state: new_state("info"), } } NativeExpr::Aggregate { input, op } => { @@ -3172,23 +2925,10 @@ impl RuntimeNode { .ok_or_else(|| { DataFusionError::Execution("aggregate does not produce samples".to_string()) })?; - let mut state = NodeState::new( - format!("native.aggregate at {location}"), - Arc::clone(&metrics), - pool, - ); + let mut state = new_state("aggregate"); let aggregate = AggregateRuntime::new(op.clone(), schema, &mut state.buffer)?; - let child = Self::build( - input, - pool, - inputs, - binary_before, - format!("{location}.input"), - duplicate_evidence.clone(), - sources, - )?; RuntimeOp::Aggregate { - input: Box::new(child), + input: Box::new(self.build(input, at("input"))?), aggregate, state, } @@ -3208,32 +2948,12 @@ impl RuntimeNode { "a parameterized aggregate does not produce samples".into(), ) })?; - let mut state = NodeState::new( - format!("native.aggregate at {location}"), - Arc::clone(&metrics), - pool, - ); + let mut state = new_state("aggregate"); let aggregate = AggregateRuntime::new_parameterized(op.clone(), schema, &mut state.buffer)?; - let child = Self::build( - input, - pool, - inputs, - binary_before, - format!("{location}.input"), - duplicate_evidence.clone(), - sources, - )?; + let child = self.build(input, at("input"))?; // Input before parameter: the order the selector walk binds the two sources in. - let parameter = Self::build( - parameter, - pool, - inputs, - binary_before, - format!("{location}.parameter"), - duplicate_evidence.clone(), - sources, - )?; + let parameter = self.build(parameter, at("parameter"))?; RuntimeOp::ParameterizedAggregate { input: Box::new(child), parameter: Some(Box::new(parameter)), @@ -3246,44 +2966,21 @@ impl RuntimeNode { op, parameter, } => { - let schema = node.output.samples().cloned().ok_or_else(|| { - DataFusionError::Execution("parameterized topk does not produce samples".into()) - })?; - let one_field = schema.fields.len() == 1; - if !one_field { + let schema = + samples_of(&node.output, "parameterized topk does not produce samples")?; + if schema.fields.len() != 1 { return Err(DataFusionError::NotImplemented( "the native runtime does not execute multi-field vector operations".into(), )); } let vector = VectorRuntime::try_new(op.clone(), schema)?; - let child = Self::build( - input, - pool, - inputs, - binary_before, - format!("{location}.input"), - duplicate_evidence.clone(), - sources, - )?; - let parameter = Self::build( - parameter, - pool, - inputs, - binary_before, - format!("{location}.parameter"), - duplicate_evidence.clone(), - sources, - )?; - let state = NodeState::new( - format!("native.vector at {location}"), - Arc::clone(&metrics), - pool, - ); + let child = self.build(input, at("input"))?; + let parameter = self.build(parameter, at("parameter"))?; RuntimeOp::ParameterizedTopK { input: Box::new(child), parameter: Some(Box::new(parameter)), vector, - state, + state: new_state("vector"), } } NativeExpr::ParameterizedHistogram { @@ -3307,61 +3004,32 @@ impl RuntimeNode { "parameterized histogram has the wrong arity".into(), )); } - let literals = parameters - .iter() - .map(|parameter| match ¶meter.expr { - NativeExpr::Scalar(BoundScalar { value }) => Some(*value), - _ => None, - }) - .collect(); - let schema = node.output.samples().cloned().ok_or_else(|| { - DataFusionError::Execution( - "parameterized histogram does not produce samples".into(), - ) - })?; - let vector = VectorRuntime::try_new(op.clone(), schema)?; - let child = Self::build( - input, - pool, - inputs, - binary_before, - format!("{location}.input"), - duplicate_evidence.clone(), - sources, + let schema = samples_of( + &node.output, + "parameterized histogram does not produce samples", )?; - let mut built = Vec::with_capacity(parameters.len()); - for (index, parameter) in parameters.iter().enumerate() { - let runtime = Self::build( - parameter, - pool, - inputs, - binary_before, - format!("{location}.parameter{index}"), - duplicate_evidence.clone(), - sources, - )?; - built.push(Some(runtime)); - } + let vector = VectorRuntime::try_new(op.clone(), schema)?; + let child = self.build(input, at("input"))?; + let built = parameters + .iter() + .enumerate() + .map(|(index, parameter)| { + self.build(parameter, format!("{location}.parameter{index}")) + .map(Some) + }) + .collect::>>()?; RuntimeOp::ParameterizedHistogram { input: Box::new(child), parameter_bytes: vec![0; built.len()], values: vec![None; built.len()], parameters: built, - literals, + literals: parameters.iter().map(literal).collect(), vector, - state: NodeState::new( - format!("native.vector at {location}"), - Arc::clone(&metrics), - pool, - ), + state: new_state("vector"), } } NativeExpr::Vector { input, op } => { - let schema = node.output.samples().cloned().ok_or_else(|| { - DataFusionError::Execution( - "vector operation does not produce samples".to_string(), - ) - })?; + let schema = samples_of(&node.output, "vector operation does not produce samples")?; let one_field = matches!( op, BoundVectorOp::TopK { .. } @@ -3375,38 +3043,44 @@ impl RuntimeNode { )); } let mut vector = VectorRuntime::try_new(op.clone(), schema)?; - let child = Self::build( - input, - pool, - inputs, - binary_before, - format!("{location}.input"), - duplicate_evidence.clone(), - sources, - )?; - let limitk = matches!(op, BoundVectorOp::LimitK { .. }); - if limitk + let child = self.build(input, at("input"))?; + vector.merge_input = matches!(op, BoundVectorOp::LimitK { .. }) && matches!( - unifies_its_own_contributions(input, &sources.tags, &sources.metrics), + unifies_its_own_contributions( + input, + &self.sources.tags, + &self.sources.metrics + ), Some(false) - ) - { - vector.merge_input = true; - } + ); RuntimeOp::Vector { input: Box::new(child), vector, - state: NodeState::new( - format!("native.vector at {location}"), - Arc::clone(&metrics), - pool, - ), + state: new_state("vector"), } } }; - Ok(Self { metrics, op }) + Ok(RuntimeNode { metrics, op }) } +} +/// The sample schema of `output`, or an execution error saying `message`. +fn samples_of(output: &NativeType, message: &str) -> Result> { + output + .samples() + .cloned() + .ok_or_else(|| DataFusionError::Execution(message.to_string())) +} + +/// The value of a constant scalar node. +fn literal(node: &NativeNode) -> Option { + match &node.expr { + NativeExpr::Scalar(BoundScalar { value }) => Some(*value), + _ => None, + } +} + +impl RuntimeNode { /// The node's direct children, each with the role its metrics are named by. `children_mut` /// yields the same nodes in the same order. fn children(&self) -> impl Iterator { @@ -3981,12 +3655,12 @@ impl RuntimeNode { // whole. while let Some(chunk) = left.pull(inputs, inputs_finished)? { state - .retain_binary(operation, 0, chunk) + .retain_binary(operation, Side::Left, chunk) .map_err(|error| state.context(error))?; } while let Some(chunk) = right.pull(inputs, inputs_finished)? { state - .retain_binary(operation, 1, chunk) + .retain_binary(operation, Side::Right, chunk) .map_err(|error| state.context(error))?; } // An empty pull is not the end: a collecting window below may not have flushed. @@ -4540,17 +4214,9 @@ impl NativeExecutionState { duplicate_evidence: Option>, sources: &SourceFacts, ) -> Result { - let mut inputs = Vec::new(); - let mut binary_before = 0usize; - let root = RuntimeNode::build( - tree.root(), - &pool, - &mut inputs, - &mut binary_before, - "root".to_string(), - duplicate_evidence.clone(), - sources, - )?; + let mut builder = TreeBuilder::new(&pool, duplicate_evidence, sources); + let root = builder.build(tree.root(), "root".to_string())?; + let inputs = builder.inputs; let scalar_root = match (&tree.root().expr, &tree.root().output) { (NativeExpr::Scalar(BoundScalar { value }), NativeType::Scalar(grid)) => Some(( Arc::clone(grid), @@ -5019,7 +4685,7 @@ impl NodeState { fn retain_binary( &mut self, binary: &mut BinaryRuntime, - side: usize, + side: Side, chunk: NativeChunk, ) -> Result<()> { let NativeChunk::Evaluated(chunk) = chunk else { @@ -5028,7 +4694,7 @@ impl NodeState { binary.kernel.node() ))); }; - let pending = binary.pending(side, &chunk)?; + let pending = binary.pending(side, &chunk); let positions = chunk.series.time.len(); self.buffer.grow(pending)?; let metrics = Arc::clone(&self.buffer.metrics); @@ -5834,11 +5500,6 @@ fn no_input(inputs: usize, input: InputId) -> DataFusionError { )) } -/// A binary operation was asked to read an operand other than its two inputs. -fn invalid_binary_operand() -> DataFusionError { - DataFusionError::Internal("invalid binary operand index".to_string()) -} - fn no_live_execution() -> DataFusionError { DataFusionError::Internal("the running native execution has no state".to_string()) } @@ -5886,10 +5547,6 @@ fn broadcast_runtime( right: &NativeNode, matching: &BinaryMatching, ) -> Result { - let literal = |node: &NativeNode| match &node.expr { - NativeExpr::Scalar(BoundScalar { value }) => Some(*value), - _ => None, - }; let (vector_left, sample_schema) = match (&left.output, &right.output) { (NativeType::Samples(vector), NativeType::Scalar(_)) if vector.eval_grid.is_some() => { (true, Arc::clone(vector)) diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index e11dad3c4d2..0d65bc8724a 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -44,9 +44,9 @@ fn is_resources_exhausted(error: &DataFusionError) -> bool { use super::{ BinaryRuntime, InputId, InputSlot, InstantRuntime, NativeChunk, NativeExecutionState, - NativeExecutor, NodeState, PairKernel, Reader, RetainedInput, RuntimeNode, RuntimeOp, - SourceFacts, buffered_fields, buffered_time, evaluated_bytes, grid_chunk_bytes, grid_end_ms, - grid_position, map_chunk, map_workspace_bytes, raw_bytes, vector_series_with_k, + NativeExecutor, NodeState, PairKernel, Reader, RetainedInput, RuntimeNode, RuntimeOp, Side, + SourceFacts, TreeBuilder, buffered_fields, buffered_time, evaluated_bytes, grid_chunk_bytes, + grid_end_ms, grid_position, map_chunk, map_workspace_bytes, raw_bytes, vector_series_with_k, vector_workspace_bytes, }; use crate::evaluated::EvaluatedChunk; @@ -416,18 +416,9 @@ fn window_and_limitk_collect_only_unified_contributions() { let build_with = |node: NativeNode, sources: &SourceFacts| { let tree = NativeTree::try_new(node).unwrap(); - let mut inputs = Vec::new(); - let mut binary_before = 0; - RuntimeNode::build( - tree.root(), - &pool(), - &mut inputs, - &mut binary_before, - "root".to_string(), - None, - sources, - ) - .unwrap() + TreeBuilder::new(&pool(), None, sources) + .build(tree.root(), "root".to_string()) + .unwrap() }; let build = |node: NativeNode| build_with(node, &SourceFacts::none()); @@ -931,10 +922,18 @@ fn binary_charge( ) -> (usize, usize) { let (mut state, mut binary) = binary_runtime(&pool(), schema); state - .retain_binary(&mut binary, 0, NativeChunk::Evaluated(left.clone())) + .retain_binary( + &mut binary, + Side::Left, + NativeChunk::Evaluated(left.clone()), + ) .unwrap(); state - .retain_binary(&mut binary, 1, NativeChunk::Evaluated(right.clone())) + .retain_binary( + &mut binary, + Side::Right, + NativeChunk::Evaluated(right.clone()), + ) .unwrap(); let retained = state.buffer.reservation.size(); let assembly = binary @@ -7679,10 +7678,10 @@ fn a_binary_operand_reserves_what_it_retains() { let pool = bounded_pool(rows + descriptors); let (mut state, mut binary) = binary_runtime(&pool, &schema); state - .retain_binary(&mut binary, 0, NativeChunk::Evaluated(first)) + .retain_binary(&mut binary, Side::Left, NativeChunk::Evaluated(first)) .unwrap(); state - .retain_binary(&mut binary, 0, NativeChunk::Evaluated(second)) + .retain_binary(&mut binary, Side::Left, NativeChunk::Evaluated(second)) .unwrap(); assert!( state.buffer.reservation.size() >= rows, @@ -7705,10 +7704,10 @@ fn a_binary_operand_reserves_what_it_retains() { // one reserved for and then retained leaves the operand exactly where the reservation put it. let own = evaluated_chunk(&schema, 0, vec![1.0, 2.0], true); let (mut own_state, mut own_binary) = binary_runtime(&pool, &schema); - let pending = own_binary.pending(0, &own).unwrap(); + let pending = own_binary.pending(Side::Left, &own); let before = own_state.buffer.reservation.size(); own_state - .retain_binary(&mut own_binary, 0, NativeChunk::Evaluated(own)) + .retain_binary(&mut own_binary, Side::Left, NativeChunk::Evaluated(own)) .unwrap(); assert_eq!( own_state.buffer.reservation.size() - before, @@ -7769,12 +7768,12 @@ fn a_binary_operand_bills_each_histogram_table_it_retains() { let (mut state, mut binary) = binary_runtime(&pool, &schema); let before = state.buffer.reservation.size(); state - .retain_binary(&mut binary, 0, NativeChunk::Evaluated(first)) + .retain_binary(&mut binary, Side::Left, NativeChunk::Evaluated(first)) .unwrap(); let first_cost = state.buffer.reservation.size() - before; let before = state.buffer.reservation.size(); state - .retain_binary(&mut binary, 0, NativeChunk::Evaluated(second)) + .retain_binary(&mut binary, Side::Left, NativeChunk::Evaluated(second)) .unwrap(); let second_cost = state.buffer.reservation.size() - before; @@ -7822,12 +7821,12 @@ fn a_binary_operand_bills_a_shared_histogram_table_once() { let (mut state, mut binary) = binary_runtime(&pool, &schema); let before = state.buffer.reservation.size(); state - .retain_binary(&mut binary, 0, NativeChunk::Evaluated(first)) + .retain_binary(&mut binary, Side::Left, NativeChunk::Evaluated(first)) .unwrap(); let first_cost = state.buffer.reservation.size() - before; let before = state.buffer.reservation.size(); state - .retain_binary(&mut binary, 0, NativeChunk::Evaluated(second)) + .retain_binary(&mut binary, Side::Left, NativeChunk::Evaluated(second)) .unwrap(); let second_cost = state.buffer.reservation.size() - before; @@ -7891,7 +7890,11 @@ fn a_pool_that_holds_one_histogram_table_refuses_a_second() { // anything; the pool below is sized from it and half a table. let (mut probe_state, mut probe_binary) = binary_runtime(&pool(), &schema); probe_state - .retain_binary(&mut probe_binary, 0, NativeChunk::Evaluated(first.clone())) + .retain_binary( + &mut probe_binary, + Side::Left, + NativeChunk::Evaluated(first.clone()), + ) .unwrap(); let one_chunk = probe_state.buffer.reservation.size(); let budget = one_chunk + bytes / 2; @@ -7902,12 +7905,16 @@ fn a_pool_that_holds_one_histogram_table_refuses_a_second() { refused_state .retain_binary( &mut refused_binary, - 0, + Side::Left, NativeChunk::Evaluated(first.clone()), ) .unwrap(); let error = refused_state - .retain_binary(&mut refused_binary, 0, NativeChunk::Evaluated(second_own)) + .retain_binary( + &mut refused_binary, + Side::Left, + NativeChunk::Evaluated(second_own), + ) .unwrap_err(); assert!( is_resources_exhausted(&error), @@ -7922,10 +7929,18 @@ fn a_pool_that_holds_one_histogram_table_refuses_a_second() { // The second slice of the one table the operand holds does fit. let (mut shared_state, mut shared_binary) = binary_runtime(&bounded_pool(budget), &schema); shared_state - .retain_binary(&mut shared_binary, 0, NativeChunk::Evaluated(first)) + .retain_binary( + &mut shared_binary, + Side::Left, + NativeChunk::Evaluated(first), + ) .unwrap(); shared_state - .retain_binary(&mut shared_binary, 0, NativeChunk::Evaluated(second_shared)) + .retain_binary( + &mut shared_binary, + Side::Left, + NativeChunk::Evaluated(second_shared), + ) .unwrap(); assert!( shared_state.buffer.reservation.size() > one_chunk, @@ -8200,11 +8215,11 @@ fn an_assembly_bound_covers_the_capacity_its_flatten_grows_to() { let (mut state, mut binary) = binary_runtime(&pool, &schema); for chunk in [first, second.clone()] { state - .retain_binary(&mut binary, 0, NativeChunk::Evaluated(chunk)) + .retain_binary(&mut binary, Side::Left, NativeChunk::Evaluated(chunk)) .unwrap(); } state - .retain_binary(&mut binary, 1, NativeChunk::Evaluated(second)) + .retain_binary(&mut binary, Side::Right, NativeChunk::Evaluated(second)) .unwrap(); let assembly = binary.assembly_bytes().unwrap(); assert!( @@ -8248,10 +8263,18 @@ fn an_assembly_the_pool_cannot_hold_is_refused_before_it_allocates() { let pool = bounded_pool(retained + assembly - 1); let (mut state, mut binary) = binary_runtime(&pool, &schema); state - .retain_binary(&mut binary, 0, NativeChunk::Evaluated(left.clone())) + .retain_binary( + &mut binary, + Side::Left, + NativeChunk::Evaluated(left.clone()), + ) .unwrap(); state - .retain_binary(&mut binary, 1, NativeChunk::Evaluated(right.clone())) + .retain_binary( + &mut binary, + Side::Right, + NativeChunk::Evaluated(right.clone()), + ) .unwrap(); assert_eq!(state.buffer.reservation.size(), retained); let error = state.compute_binary(&mut binary).unwrap_err(); @@ -8274,10 +8297,10 @@ fn an_assembly_the_pool_cannot_hold_is_refused_before_it_allocates() { let pool = bounded_pool(retained + assembly); let (mut state, mut binary) = binary_runtime(&pool, &schema); state - .retain_binary(&mut binary, 0, NativeChunk::Evaluated(left)) + .retain_binary(&mut binary, Side::Left, NativeChunk::Evaluated(left)) .unwrap(); state - .retain_binary(&mut binary, 1, NativeChunk::Evaluated(right)) + .retain_binary(&mut binary, Side::Right, NativeChunk::Evaluated(right)) .unwrap(); let assembled = binary.assemble().unwrap(); assert_eq!(assembled[0].len(), 1, "one closed series is one series"); @@ -8353,7 +8376,11 @@ fn a_mixed_nested_operand_assembles_into_one_series_with_its_holes() { let (mut state, mut binary) = binary_runtime(&pool, &schema); for chunk in [&left_a, &left_b] { state - .retain_binary(&mut binary, 0, NativeChunk::Evaluated(chunk.clone())) + .retain_binary( + &mut binary, + Side::Left, + NativeChunk::Evaluated(chunk.clone()), + ) .unwrap(); } let assembled = binary.assemble().unwrap(); diff --git a/src/promql/src/native/plan.rs b/src/promql/src/native/plan.rs index 5f241bf54ce..6fc96b79526 100644 --- a/src/promql/src/native/plan.rs +++ b/src/promql/src/native/plan.rs @@ -1638,7 +1638,7 @@ impl<'de> serde::Deserialize<'de> for NativeTree { /// Whether the native runtime builds `tree`. /// /// The native route asks this before committing a statement, because a refusal raised during -/// physical planning cannot fall back. It mirrors what `RuntimeNode::build` and +/// physical planning cannot fall back. It mirrors what `TreeBuilder::build` and /// `NativeExecutionState::try_new` refuse beyond [`NativeNode::validate`]: /// /// - a root of raw samples;