diff --git a/src/promql/src/native/execute.rs b/src/promql/src/native/execute.rs index 3c06d24eeb1..8d87732830b 100644 --- a/src/promql/src/native/execute.rs +++ b/src/promql/src/native/execute.rs @@ -319,11 +319,13 @@ impl Emitted { .iter() .map(|field| occupied_runs(field, base)) .collect(); - // A series that produced no value at all owns nothing here: it hands out no sample under - // this label set, so recording it would refuse the next series that produces none either, - // and the answer to both is simply empty. Only a label set already holding values has to - // be marked closed when its last chunk arrives. - if occupied.iter().all(Vec::is_empty) && !self.sets.contains_key(&labels) { + // A chunk holding no value records nothing. If the label set is unknown or already closed, + // the series this chunk belongs to contributed no sample at all -- either it is the first + // such series, or a later one that also answers empty -- so there is nothing to report, + // nothing to merge and nothing to refuse. A label set still open is the other case: the + // chunk closes the series that *did* produce the values, so it falls through to close it. + let empty = occupied.iter().all(Vec::is_empty); + if empty && self.sets.get(&labels).is_none_or(|history| history.closed) { return Ok(()); } if let Some(history) = self.sets.get(&labels) { @@ -355,12 +357,13 @@ impl Emitted { history.fields.resize_with(fields, Vec::new); } for (index, runs) in occupied.into_iter().enumerate() { - for run in runs { - absorb(&mut history.fields[index], run); - } + absorb(&mut history.fields[index], &runs); } if chunk.is_last { history.closed = true; + // No later chunk reads these runs: a closed label set refuses every series that would + // use them. Keeping them charges the pool for a series that has already been answered. + history.fields = Vec::new(); } let after = history_bytes(history); history.bytes = after; @@ -424,21 +427,41 @@ fn occupied_runs(field: &Samples, base: usize) -> Vec { runs } -/// Adds `run` to `runs`, keeping them in position order and joining the ones that touch. +/// Merges `incoming` into `stored`, keeping the result in position order and joining the runs that +/// touch. /// -/// `runs` never holds two that overlap, so only adjacency is joined; joining is what keeps one -/// series arriving in many chunks from costing one run per chunk. -fn absorb(runs: &mut Vec, run: Run) { - let at = runs.partition_point(|stored| stored.start < run.start); - runs.insert(at, run); - let mut merged: Vec = Vec::with_capacity(runs.len()); - for run in runs.drain(..) { +/// Both sides are sorted and disjoint, so one pass merges them. Adding the runs one at a time and +/// rebuilding the whole array after each would cost the square of the runs a chunk yields: a chunk +/// of one hundred thousand positions alternating between values and nulls yields fifty thousand +/// runs, and re-merging after each is over a billion element moves for a single series. +fn absorb(stored: &mut Vec, incoming: &[Run]) { + if incoming.is_empty() { + return; + } + let mut merged: Vec = Vec::with_capacity(stored.len() + incoming.len()); + let (mut a, mut b) = (0, 0); + while a < stored.len() || b < incoming.len() { + let larger = match (stored.get(a), incoming.get(b)) { + (Some(left), Some(right)) if right.start < left.start => { + b += 1; + *right + } + (Some(left), _) => { + a += 1; + *left + } + (None, Some(right)) => { + b += 1; + *right + } + (None, None) => break, + }; match merged.last_mut() { - Some(last) if run.start <= last.end => last.end = last.end.max(run.end), - _ => merged.push(run), + Some(last) if larger.start <= last.end => last.end = last.end.max(larger.end), + _ => merged.push(larger), } } - *runs = merged; + *stored = merged; } /// What a map node applies. diff --git a/src/promql/src/native/execute/tests.rs b/src/promql/src/native/execute/tests.rs index 53c4a4cbd12..fe3efc4034d 100644 --- a/src/promql/src/native/execute/tests.rs +++ b/src/promql/src/native/execute/tests.rs @@ -1623,6 +1623,55 @@ fn the_emitted_charge_is_the_same_folded_in_as_walked() { } } +/// A series that produced values under a label set, followed by one that produced none under the +/// same label set, is not a collision: the second contributes no sample, so the answer is just the +/// first one's values. +/// +/// This is the other order of [`two_series_with_no_result_do_not_collide`], and the one that used to +/// fail: by the time the empty series arrives the label set is already closed, and refusing it +/// failed an execution whose answer was never in doubt. +#[test] +fn a_series_with_no_result_after_a_closed_one_is_passed_over() { + let map_grid = grid(0, 60_000, 1); + let tree = NativeTree::try_new(map( + evaluated_input(Arc::clone(&map_grid)), + vec![MathOp::Abs], + )) + .unwrap(); + let schema = evaluated_schema(Arc::clone(&map_grid)); + let mut execution = executor(&tree, pool(), &ExecutionPlanMetricsSet::new()); + + // `abs` drops the name, so both series arrive under the same label set. The first holds a + // value; the second holds none at all and has to be passed over rather than refused. + for (name, values) in [("a", vec![Some(-7.0)]), ("b", vec![None])] { + execution + .push_evaluated(evaluated_chunk_of( + &schema, + named_metric(name, "x"), + 0, + values, + true, + )) + .unwrap(); + } + + let mut handed = Vec::new(); + loop { + match execution.next_chunk() { + Ok(Some(chunk)) => handed.push(decided(&[chunk])), + Ok(None) => break, + Err(error) => panic!("an empty series after a closed one was refused: {error}"), + } + } + assert!( + handed + .iter() + .flatten() + .any(|(_, value)| *value == Some(7.0)), + "the first series' value is missing: {handed:?}" + ); +} + /// Two series that each produce no value at all are not a collision: both answer empty, and the /// node hands nothing on rather than refusing the second one. ///