Skip to main content

promql/
vector_match.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Vector–vector binary and set operations over evaluated series on one grid.
16//!
17//! Semantics follow Prometheus `VectorBinop`, `VectorAnd`, `VectorOr` and `VectorUnless`
18//! evaluated at every grid point. Series are processed whole, over their own grid ranges, and
19//! the cardinality rules are checked per point: series sharing a match group only conflict at
20//! points where both are present. Each field is matched on its own, as if the operands held
21//! only that field; the results of all fields with one label set form one series.
22
23use std::collections::hash_map::Entry;
24use std::collections::{HashMap, HashSet};
25use std::sync::Arc;
26
27use common_query::promql_annotations::PromqlAnnotationCollector;
28use datafusion::error::{DataFusionError, Result};
29use datafusion::execution::memory_pool::{MemoryConsumer, MemoryPool, MemoryReservation};
30use datatypes::series::histogram::{CounterResetHint, HistogramBatchBuilder, HistogramView};
31use datatypes::series::samples::{
32    DenseSamplesRef, FieldSpec, RowCursor, SampleRef, Series, SeriesSchema,
33};
34use datatypes::series::time::{EvalGrid, GridRunPair, GridSpan, TimeAxis};
35use datatypes::series::{Label, SeriesLabels};
36
37use crate::functions::{NativeHistogramAdd, NativeHistogramSub};
38use crate::grid_series::{GridSample, GridSeriesBuilder, METADATA_LABELS, external, owned};
39use crate::histogram_eval::float_histogram::FloatHistogram;
40use crate::map::{ArithmeticOp, ComparisonOp};
41
42#[cfg(test)]
43mod tests;
44
45// How many candidate pairs the binary kernel visited on this thread.
46//
47// Test-only, and per thread: the pairs a query considers are what says whether a series delivered in
48// many chunks is still one candidate, and that is not visible in the result. A thread of its own
49// keeps one test's chunks out of another test's figure, and the counter is compiled out of the
50// kernel otherwise.
51#[cfg(test)]
52thread_local! {
53    static VISITED_PAIRS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
54}
55
56/// Resets the candidate-pair counter of this thread to zero.
57#[cfg(test)]
58pub(crate) fn reset_visited_pairs() {
59    VISITED_PAIRS.with(|visited| visited.set(0));
60}
61
62/// The candidate pairs the binary kernel has visited on this thread since the last
63/// [`reset_visited_pairs`].
64///
65/// A pair is visited once per one-side candidate the kernel looks up for a many-side series, before
66/// the pairing's label set and axis intersection are built, so the count is what the kernel actually
67/// does rather than what its operands' sizes imply it would.
68#[cfg(test)]
69pub(crate) fn visited_pairs() -> usize {
70    VISITED_PAIRS.with(std::cell::Cell::get)
71}
72
73/// A PromQL binary operator between two instant vectors.
74#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
75pub enum BinaryOp {
76    Add,
77    Sub,
78    Mul,
79    Div,
80    Mod,
81    Pow,
82    Atan2,
83    Eq,
84    Ne,
85    Gt,
86    Lt,
87    Ge,
88    Le,
89}
90
91/// What a [`BinaryOp`] computes: arithmetic over two values or a comparison of them.
92#[derive(Clone, Copy, Debug)]
93pub enum BinaryKind {
94    Arithmetic(ArithmeticOp),
95    Comparison(ComparisonOp),
96}
97
98impl BinaryOp {
99    /// The kernel operation this operator names. Every path that evaluates a binary operator over
100    /// two floats, the broadcast of a scalar and a constant fold included, reads it from here, so
101    /// they cannot disagree about which operator is which or about what it computes.
102    #[inline]
103    pub fn kind(self) -> BinaryKind {
104        match self {
105            Self::Add => BinaryKind::Arithmetic(ArithmeticOp::Add),
106            Self::Sub => BinaryKind::Arithmetic(ArithmeticOp::Subtract),
107            Self::Mul => BinaryKind::Arithmetic(ArithmeticOp::Multiply),
108            Self::Div => BinaryKind::Arithmetic(ArithmeticOp::Divide),
109            Self::Mod => BinaryKind::Arithmetic(ArithmeticOp::Modulo),
110            Self::Pow => BinaryKind::Arithmetic(ArithmeticOp::Power),
111            Self::Atan2 => BinaryKind::Arithmetic(ArithmeticOp::Atan2),
112            Self::Eq => BinaryKind::Comparison(ComparisonOp::Equal),
113            Self::Ne => BinaryKind::Comparison(ComparisonOp::NotEqual),
114            Self::Gt => BinaryKind::Comparison(ComparisonOp::Greater),
115            Self::Lt => BinaryKind::Comparison(ComparisonOp::Less),
116            Self::Ge => BinaryKind::Comparison(ComparisonOp::GreaterEqual),
117            Self::Le => BinaryKind::Comparison(ComparisonOp::LessEqual),
118        }
119    }
120
121    pub fn is_comparison(self) -> bool {
122        matches!(self.kind(), BinaryKind::Comparison(_))
123    }
124
125    /// The value and whether a comparison holds, as Prometheus `vectorElemBinop` computes them.
126    #[inline]
127    fn apply(self, lhs: f64, rhs: f64) -> (f64, bool) {
128        match self.kind() {
129            BinaryKind::Arithmetic(op) => (op.calculate(lhs, rhs), true),
130            BinaryKind::Comparison(op) => (lhs, op.apply(lhs, rhs)),
131        }
132    }
133}
134
135/// The labels two series are matched by.
136#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
137pub enum MatchingLabels {
138    /// `on(...)`: only these labels, `__name__` included when listed.
139    On(Vec<Arc<str>>),
140    /// `ignoring(...)`, and the default with no labels: every label except these and
141    /// `__name__`.
142    Ignoring(Vec<Arc<str>>),
143}
144
145/// How many series of each side may share a match group.
146#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
147pub enum Cardinality {
148    OneToOne,
149    /// `group_left(...)`: the right side is the "one" side; the listed labels are copied from it.
150    ManyToOne(Vec<Arc<str>>),
151    /// `group_right(...)`: the left side is the "one" side; the listed labels are copied from it.
152    OneToMany(Vec<Arc<str>>),
153}
154
155/// A vector–vector binary operation with its modifiers.
156#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
157pub struct BinaryMatching {
158    pub op: BinaryOp,
159    /// `bool`: comparisons return 1 or 0 instead of filtering.
160    pub return_bool: bool,
161    pub labels: MatchingLabels,
162    pub cardinality: Cardinality,
163    pub fill: FillValues,
164}
165
166/// The values of `fill`, `fill_left` and `fill_right`, which stand in for a sample that has no
167/// match on the other side: `lhs` for a missing left-hand sample and `rhs` for a missing
168/// right-hand one, as the query writes them, `group_right` included (prometheus/prometheus#19939).
169#[derive(Clone, Copy, Debug, Default, serde::Serialize, serde::Deserialize)]
170pub struct FillValues {
171    pub lhs: Option<f64>,
172    pub rhs: Option<f64>,
173}
174
175// Compared by bits: a NaN fill equals itself, and `fill(-0)` differs from `fill(0)` (`1 / fill`).
176impl PartialEq for FillValues {
177    fn eq(&self, other: &Self) -> bool {
178        let bits = |value: Option<f64>| value.map(f64::to_bits);
179        bits(self.lhs) == bits(other.lhs) && bits(self.rhs) == bits(other.rhs)
180    }
181}
182
183impl Eq for FillValues {}
184impl std::hash::Hash for FillValues {
185    fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
186        std::hash::Hash::hash(&self.lhs.map(f64::to_bits), h);
187        std::hash::Hash::hash(&self.rhs.map(f64::to_bits), h);
188    }
189}
190
191/// A PromQL set operator between two instant vectors.
192#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
193pub enum SetOp {
194    And,
195    Or,
196    Unless,
197}
198
199/// The schema of `binary_vectors` output: fields paired by position, named after the left side.
200pub fn binary_output_schema(lhs: &SeriesSchema, rhs: &SeriesSchema) -> Result<Arc<SeriesSchema>> {
201    let grid = same_grid(lhs, rhs)?;
202    let fields = lhs.fields.len().min(rhs.fields.len());
203    Ok(Arc::new(SeriesSchema {
204        fields: lhs.fields[..fields].to_vec().into(),
205        eval_grid: Some(grid),
206    }))
207}
208
209/// Applies `matching` to every pair of matched series at every grid point.
210///
211/// Fields are paired by position. Arithmetic and `bool` comparisons drop `__name__`, `__type__`
212/// and `__unit__`; comparisons without `bool` keep the left value where they hold. Native
213/// histograms support `+`, `-`, `==` and `!=` with each other, `*` with a float on either side
214/// and `/` by a float; Prometheus skips any other pairing of a histogram. A fill value pairs a
215/// sample that has no match with a float sample labelled with its match group.
216pub fn binary_vectors(
217    matching: &BinaryMatching,
218    lhs_schema: &SeriesSchema,
219    lhs: &[Series],
220    rhs_schema: &SeriesSchema,
221    rhs: &[Series],
222) -> Result<Vec<Series>> {
223    binary_vectors_inner(matching, lhs_schema, lhs, rhs_schema, rhs, None, None, None)
224}
225
226/// [`binary_vectors`], handing the live workspace it holds to `reserve` as it allocates.
227///
228/// What the operation will allocate cannot be known before it allocates: which series match each
229/// other, where their axes overlap and which rows the operator keeps all come out of the operands
230/// as they are read. So `reserve` receives the **total** live workspace the operation holds, and it
231/// is asked at the three granularities [`Budget`] describes: where a long-lived result buffer grows,
232/// once per phase, and in the blocks a growing result buffer is reserved in. It is never asked per
233/// grid point or per row. A total `reserve` refuses ends the operation with that error, and what it
234/// admitted stays the caller's to release.
235#[derive(Clone, Copy)]
236pub(crate) struct NodeEvidence<'a> {
237    pub(crate) node: usize,
238    pub(crate) evidence: &'a DuplicateEvidence,
239}
240
241struct FieldEvidence<'a> {
242    node: usize,
243    field: usize,
244    evidence: &'a DuplicateEvidence,
245}
246
247#[allow(clippy::too_many_arguments)]
248pub(crate) fn binary_vectors_with_reservation(
249    matching: &BinaryMatching,
250    lhs_schema: &SeriesSchema,
251    lhs: &[Series],
252    rhs_schema: &SeriesSchema,
253    rhs: &[Series],
254    evidence: Option<NodeEvidence<'_>>,
255    annotations: Option<&PromqlAnnotationCollector>,
256    reserve: &mut dyn FnMut(usize) -> Result<()>,
257) -> Result<Vec<Series>> {
258    let mut budget = Budget::new(reserve);
259    binary_vectors_inner(
260        matching,
261        lhs_schema,
262        lhs,
263        rhs_schema,
264        rhs,
265        evidence,
266        annotations,
267        Some(&mut budget),
268    )
269}
270
271/// The one binary kernel: one walk, one lookup and one error order, whether or not a caller
272/// accounts for the workspace. Every figure is reserved only when `budget` is held.
273#[allow(clippy::too_many_arguments)]
274fn binary_vectors_inner(
275    matching: &BinaryMatching,
276    lhs_schema: &SeriesSchema,
277    lhs: &[Series],
278    rhs_schema: &SeriesSchema,
279    rhs: &[Series],
280    evidence: Option<NodeEvidence<'_>>,
281    annotations: Option<&PromqlAnnotationCollector>,
282    mut budget: Option<&mut Budget<'_>>,
283) -> Result<Vec<Series>> {
284    // The grid both operands are evaluated on, checked before anything is reserved for them.
285    let grid = same_grid(lhs_schema, rhs_schema)?;
286    // The fields paired by position and the descriptors they are handed back in: one result table
287    // per field, the field list both the results and the output schema keep, and the schema itself.
288    // The schema is what these bytes cover, so they are reserved before it is built.
289    let width = lhs_schema.fields.len().min(rhs_schema.fields.len());
290    if let Some(budget) = budget.as_deref_mut() {
291        budget.hold(output_bytes(width))?;
292    }
293    let output = binary_output_schema(lhs_schema, rhs_schema)?;
294    let mut errors = Vec::new();
295    let mut fields = Vec::with_capacity(width);
296    for field in 0..width {
297        let lhs = Operand::try_new(lhs_schema, lhs, field)?;
298        let rhs = Operand::try_new(rhs_schema, rhs, field)?;
299        let field_evidence = evidence.map(|evidence| FieldEvidence {
300            node: evidence.node,
301            field,
302            evidence: evidence.evidence,
303        });
304        let results = binary_field(
305            matching,
306            &grid,
307            &lhs,
308            &rhs,
309            &mut errors,
310            field_evidence,
311            annotations,
312            budget.as_deref_mut(),
313        )?;
314        // The field's flags, tables and sort are destroyed with its frame, so its phase ends here:
315        // what the field filed is what stays live, and the next field's phase is charged on its own.
316        if let Some(budget) = budget.as_deref_mut() {
317            budget.phase(0)?;
318        }
319        fields.push(results);
320    }
321    earliest_error(errors)?;
322    // The merge is the operation's last phase: it enters its own figure from the results the fields
323    // filed, which is where every term of it is read.
324    merge_fields(fields, output, budget)
325}
326
327/// The capacity a fresh `Vec` holds: a first push allocates four entries, and a full one doubles.
328const VEC_MIN_CAPACITY: usize = 4;
329
330/// One label of a match key, charged twice because `group_key` grows its `Vec` by doubling.
331const KEY_LABEL_BYTES: usize = 2 * std::mem::size_of::<(Arc<str>, Arc<str>)>();
332
333/// One name of [`MatchingLabels`], which `result_metric` collects into a reference vector. The
334/// vector is collected from an exact-size iterator, so its buffer holds one `&str` per name.
335const MATCHING_NAME_BYTES: usize = std::mem::size_of::<&str>();
336
337/// One entry of a match-group table, with the control byte and spare capacity it keeps.
338const GROUP_SLOT_BYTES: usize = 2 * std::mem::size_of::<(GroupKey, Vec<usize>)>();
339
340/// One entry of the one-to-one match set, charged the same way.
341const MATCH_SLOT_BYTES: usize = 2 * std::mem::size_of::<(usize, usize)>();
342
343/// One entry of a field's result table, charged the same way.
344const RESULT_SLOT_BYTES: usize = 2 * std::mem::size_of::<(GroupKey, ResultRows)>();
345
346/// One row of a field's results: its point, its match group and its value. The three vectors grow
347/// together, so one slot of each is what a row takes, and a block of the vectors is charged a row's
348/// bytes per slot it grew by.
349const RESULT_ROW_BYTES: usize =
350    2 * std::mem::size_of::<usize>() + std::mem::size_of::<Option<GridSample>>();
351
352/// One row while a label set is sorted: the old and the new copy of its point, group and value
353/// vectors, and the row order the sort reads. The sort copies a label set's rows when they are not
354/// already in order, so this is what one row costs while it runs.
355const SORT_ROW_BYTES: usize =
356    4 * std::mem::size_of::<usize>() + 2 * std::mem::size_of::<Option<GridSample>>();
357
358/// One row of the merge's table, charged the same way.
359const MERGE_SLOT_BYTES: usize =
360    2 * std::mem::size_of::<(GroupKey, (SeriesLabels, Vec<(usize, usize, GridSample)>))>();
361
362/// One row of the builder's histogram table: the scalar columns and the seven list offsets.
363pub(crate) const HISTOGRAM_ROW_BYTES: usize = 4 * std::mem::size_of::<f64>()
364    + 2 * std::mem::size_of::<i32>()
365    + std::mem::size_of::<i64>()
366    + 7 * std::mem::size_of::<i32>();
367
368/// The fixed text of one error message, around the label set it renders.
369const ERROR_TEXT_BYTES: usize = 256;
370
371/// The bytes the operation's own descriptors cost: one result table per paired field, the field
372/// list the results and the output schema each keep, and the schema struct.
373fn output_bytes(fields: usize) -> usize {
374    fields
375        .saturating_mul(std::mem::size_of::<Results>() + 2 * std::mem::size_of::<FieldSpec>())
376        .saturating_add(std::mem::size_of::<SeriesSchema>())
377}
378
379/// The live workspace a binary, set or `info` operation admits as it allocates, at three
380/// granularities.
381///
382/// A resource limit belongs at an allocation boundary, not at a value:
383///
384/// - [`Budget::hold`]: what the results keep until the operation returns -- rows, the label sets they
385///   are filed under, the values boxed along them, the messages an error reports. Each is charged
386///   where its container grows.
387/// - [`Budget::phase`]: one figure for the workspace of one walk, read from the operands before it
388///   allocates and replacing the phase before it, so the total is the phase being run beside what is
389///   held and never the sum of every phase.
390/// - [`Budget::grow`]: a block a container of that phase took when it outgrew what it held.
391///
392/// It exists because the caller is handed a *total*, and this turns those figures into that total.
393pub(crate) struct Budget<'a> {
394    /// Admits the live workspace, or refuses it.
395    reserve: &'a mut dyn FnMut(usize) -> Result<()>,
396    /// The bytes the results keep until the operation returns.
397    held: usize,
398    /// The bytes of the phase being run, beside what is held.
399    phase: usize,
400    /// The total handed to `reserve` last, so an unchanged one is not asked for twice.
401    requested: Option<usize>,
402}
403
404impl<'a> Budget<'a> {
405    pub(crate) fn new(reserve: &'a mut dyn FnMut(usize) -> Result<()>) -> Self {
406        Self {
407            reserve,
408            held: 0,
409            phase: 0,
410            requested: None,
411        }
412    }
413
414    /// Retains `bytes` of results, which stay live until the operation returns.
415    pub(crate) fn hold(&mut self, bytes: usize) -> Result<()> {
416        self.held = self.held.saturating_add(bytes);
417        self.admit()
418    }
419
420    /// Admits `bytes` as the whole workspace of the phase being run, replacing the phase before it.
421    pub(crate) fn phase(&mut self, bytes: usize) -> Result<()> {
422        self.phase = bytes;
423        self.admit()
424    }
425
426    /// Adds `bytes` to the phase for a container of it that has outgrown what was reserved.
427    pub(crate) fn grow(&mut self, bytes: usize) -> Result<()> {
428        self.phase = self.phase.saturating_add(bytes);
429        self.admit()
430    }
431
432    /// Hands the live total to `reserve` when it differs from the last one. It falls as well as
433    /// rises, and only a repeated figure is left out.
434    fn admit(&mut self) -> Result<()> {
435        let total = self.held.saturating_add(self.phase);
436        if self.requested != Some(total) {
437            self.requested = Some(total);
438            (self.reserve)(total)?;
439        }
440        Ok(())
441    }
442}
443
444/// The figures one field's phases are charged from, read once from its operands.
445#[derive(Default)]
446struct FieldMetadata {
447    /// The presence flags and the one side's match groups.
448    tables: usize,
449    /// The allowance for the messages the field can report, which its sort reserves before it knows
450    /// which of them it appends; only the ones it writes are kept.
451    errors: usize,
452    /// The largest key a row of the field is filed under.
453    largest_key: usize,
454    /// The widest pairing's label set and the histogram workspace one row of the walk reads.
455    pairing: usize,
456}
457
458/// The figures one field's phases are charged from.
459///
460/// The presence of each side and of the points both are present at are three flags per grid point;
461/// the one side's groups are a key, the values `on(...)` matching copies and a member list per
462/// series; one series of the many side is looked up by a key of its own; and a field reports at most
463/// three messages, each a fixed frame around one rendering. The duplicate scan's list is not part of
464/// these tables: a group of one member collects nothing, and a wider group's list is charged by
465/// [`overlap`] as it grows. The pairing's own terms are read from the widest series of each side
466/// rather than from every pair, since one pairing's label set replaces the one before it.
467fn field_metadata_bytes(
468    matching: &BinaryMatching,
469    include: &[Arc<str>],
470    points: usize,
471    many: &Operand<'_>,
472    one: &Operand<'_>,
473) -> FieldMetadata {
474    let mut bytes = points.saturating_mul(3);
475    let mut largest_key = 0usize;
476    for series in one.series {
477        bytes = bytes
478            .saturating_add(match_key_bytes(&series.metric, &matching.labels))
479            .saturating_add(2 * std::mem::size_of::<usize>())
480            .saturating_add(GROUP_SLOT_BYTES)
481            .saturating_add(2 * std::mem::size_of::<&GroupKey>())
482            .saturating_add(2 * std::mem::size_of::<(&GroupKey, usize)>());
483        largest_key = largest_key.max(result_key_bytes(&series.metric));
484    }
485    let mut lookup = 0usize;
486    for series in many.series {
487        lookup = lookup.max(match_key_bytes(&series.metric, &matching.labels));
488        largest_key = largest_key.max(result_key_bytes(&series.metric));
489    }
490    // A result label set carries the many side's labels and the `group_*` ones copied into it, so
491    // the widest rendering over both operands bounds the text an error writes.
492    let include_text = include.iter().fold(0usize, |bytes, name| {
493        bytes.saturating_add(name.len()).saturating_add(6)
494    });
495    let text = many
496        .series
497        .iter()
498        .chain(one.series)
499        .fold(include_text, |bytes, series| {
500            bytes.max(label_text_bytes(&series.metric).saturating_add(include_text))
501        });
502    // The widest series of each side: one pairing's label set replaces the one before it, so the
503    // widest is what the phase holds at its peak.
504    let pairing = widest_metric(many)
505        .zip(widest_metric(one))
506        .map_or(0, |(many, one)| pair_bytes(many, one, matching, include));
507    FieldMetadata {
508        tables: bytes.saturating_add(lookup),
509        errors: 3usize.saturating_mul(ERROR_TEXT_BYTES.saturating_add(text)),
510        largest_key: largest_key.saturating_add(include.len().saturating_mul(KEY_LABEL_BYTES)),
511        pairing: pairing.saturating_add(histogram_phase_bytes(many, one)),
512    }
513}
514
515/// The series of `operand` with the most labels: the widest label set one pairing of its field can
516/// build.
517fn widest_metric<'a>(operand: &'a Operand<'_>) -> Option<&'a SeriesLabels> {
518    operand
519        .series
520        .iter()
521        .map(|series| &series.metric)
522        .max_by_key(|metric| metric.tags().len())
523}
524
525/// The bytes one pairing allocates before it files a row: the result label set `result_metric`
526/// rewrites, the `group_*` labels it copies in, the reference vector it collects the matching label
527/// names into, and the key its rows are looked up by.
528///
529/// Each rewrite filters the tag list into a `Vec` and turns that into a shared slice, so the list it
530/// replaces is alive while two copies of the new one are built, and an included label the many side
531/// does not carry is inserted, which costs its descriptor too. The matching names are collected into
532/// a reference vector of their own before the rewrite, for `on(...)` and `ignoring(...)` alike and
533/// whether or not the series carries them. This is one pairing's scratch: the next pairing replaces
534/// it, and a pairing whose axes share no position still pays it, because the label set is built
535/// before the axes are intersected.
536fn pair_bytes(
537    many: &SeriesLabels,
538    one: &SeriesLabels,
539    matching: &BinaryMatching,
540    include: &[Arc<str>],
541) -> usize {
542    // The label list each rewrite builds and the one it replaces, then the key `key_of` builds for
543    // a row: every label with a value and the name, each charged twice for the growth of the key's
544    // `Vec`, and the name string it copies.
545    let labels = 3usize
546        .saturating_mul(many.tags().len().saturating_add(include.len()))
547        .saturating_mul(std::mem::size_of::<Label>());
548    let key = many
549        .tags()
550        .len()
551        .saturating_add(include.len())
552        .saturating_add(1)
553        .saturating_mul(KEY_LABEL_BYTES)
554        .saturating_add(many.name().map_or(0, str::len));
555    // Only a one-to-one match rewrites the label list by its matching labels, and it collects their
556    // names first; `group_left` and `group_right` copy the included labels instead.
557    let names = match (&matching.cardinality, &matching.labels) {
558        (Cardinality::OneToOne, MatchingLabels::On(names))
559        | (Cardinality::OneToOne, MatchingLabels::Ignoring(names)) => {
560            names.len().saturating_mul(MATCHING_NAME_BYTES)
561        }
562        _ => 0,
563    };
564    labels
565        .saturating_add(copied_bytes(one, include))
566        .saturating_add(key)
567        .saturating_add(names)
568}
569
570/// The label text `result_metric` copies from the one side: the value of every included label it
571/// sets, and the name of a label it inserts, since `SeriesLabels::set` copies that as well.
572fn copied_bytes(one: &SeriesLabels, include: &[Arc<str>]) -> usize {
573    include
574        .iter()
575        .fold(0usize, |bytes, name| match one.get(name) {
576            Some(value) if !value.is_empty() => {
577                bytes.saturating_add(value.len()).saturating_add(name.len())
578            }
579            _ => bytes,
580        })
581}
582
583/// The key `key_of` files a result label set under: every label with a value and the name, each
584/// charged twice for the growth of the key's `Vec`, plus the name string it copies.
585fn result_key_bytes(metric: &SeriesLabels) -> usize {
586    metric
587        .tags()
588        .len()
589        .saturating_add(1)
590        .saturating_mul(KEY_LABEL_BYTES)
591        .saturating_add(metric.name().map_or(0, str::len))
592}
593
594/// The bytes one result label set keeps once a row is filed under it: the label list and the
595/// copied strings `result_metric` leaves behind, its key and its entry in the result table.
596fn result_set_bytes(metric: &SeriesLabels, one: &SeriesLabels, include: &[Arc<str>]) -> usize {
597    metric
598        .tags()
599        .len()
600        .saturating_mul(std::mem::size_of::<Label>())
601        .saturating_add(copied_bytes(one, include))
602        .saturating_add(result_key_bytes(metric))
603        .saturating_add(RESULT_SLOT_BYTES)
604}
605
606/// The bytes the merge of every field's results and the builder writing them out allocate.
607///
608/// The merge files every kept triple under its label set and hands one series per label set to a
609/// builder, so the triples, the table, the row it fills, the output vector and the builder's own
610/// buffers are alive together: one triple of a label set's samples, the span a run may start with, a
611/// row of the histogram table per histogram and the heap its buckets are copied to. Every term counts
612/// a value a field actually kept or a label set it filed, so a pair the operator filtered costs its
613/// label set -- the table holds one without a value -- and no row at all. What grows with the output
614/// rows is the builder's columns, which [`merge_fields`] reserves in blocks as it pushes them.
615fn merge_bytes(
616    kept: usize,
617    sets: usize,
618    fields: usize,
619    histograms: usize,
620    histogram_heap: usize,
621) -> usize {
622    // One kept triple, charged twice for the capacity its vector ends at, one slot of the row the
623    // builder reads and the span it may start.
624    let row = (2 * std::mem::size_of::<(usize, usize, GridSample)>())
625        .saturating_add(2 * std::mem::size_of::<usize>())
626        .saturating_add(2 * std::mem::size_of::<GridSpan>());
627    kept.saturating_mul(row)
628        // One label set's entry in the merge table and the series it is written out as.
629        .saturating_add(
630            sets.saturating_mul(MERGE_SLOT_BYTES.saturating_add(2 * std::mem::size_of::<Series>())),
631        )
632        // The row the builder reads its pushes from.
633        .saturating_add(2 * fields.saturating_mul(std::mem::size_of::<Option<GridSample>>()))
634        // The histogram table of every field that carries one: the builders of its columns, the
635        // scalars and list offsets of its rows, and the buckets the batch copies beside the value
636        // the results still hold.
637        .saturating_add(fields.saturating_mul(std::mem::size_of::<HistogramBatchBuilder>()))
638        .saturating_add(histograms.saturating_mul(2 * HISTOGRAM_ROW_BYTES))
639        .saturating_add(2 * histogram_heap)
640}
641
642/// The bytes one match key holds: its label pairs and, for `on(...)`, a copy of each value.
643///
644/// `group_key` copies an `on(...)` value with `Arc::from` and shares the `Arc` of an
645/// `ignoring(...)` label, so only `on(...)` adds string bytes. The pairs are charged twice because
646/// the key is collected into a `Vec` that grows by doubling.
647fn match_key_bytes(metric: &SeriesLabels, labels: &MatchingLabels) -> usize {
648    match labels {
649        MatchingLabels::On(names) => {
650            names
651                .iter()
652                .fold(0usize, |bytes, name| match metric.get(name) {
653                    Some(value) if !value.is_empty() => bytes
654                        .saturating_add(KEY_LABEL_BYTES)
655                        .saturating_add(value.len()),
656                    _ => bytes,
657                })
658        }
659        MatchingLabels::Ignoring(names) => metric
660            .tags()
661            .iter()
662            .filter(|tag| !tag.value.is_empty() && !names.contains(&tag.name))
663            .count()
664            .saturating_mul(KEY_LABEL_BYTES),
665    }
666}
667
668/// The bytes `render` writes for a label set built from `metric`: each label as `name="value"`,
669/// the braces and separators between them, and the metric's name.
670fn label_text_bytes(metric: &SeriesLabels) -> usize {
671    let named = metric
672        .name()
673        .map_or(0, |name| name.len().saturating_add(10));
674    metric.tags().iter().fold(named, |bytes, tag| {
675        bytes
676            .saturating_add(tag.name.len())
677            .saturating_add(tag.value.len())
678            .saturating_add(6)
679    })
680}
681
682/// The bytes one owned copy of a histogram view holds: its scalars inline, and on the heap the
683/// buckets of both sides, the span layout of the view and its custom bounds.
684pub(crate) fn owned_histogram_bytes(view: &HistogramView<'_>) -> usize {
685    let sides = [view.positive, view.negative];
686    let buckets = sides
687        .iter()
688        .map(|side| {
689            side.buckets
690                .len()
691                .saturating_mul(std::mem::size_of::<(i32, f64)>())
692        })
693        .fold(0usize, usize::saturating_add);
694    let spans = sides
695        .iter()
696        .map(|side| {
697            side.span_offsets
698                .len()
699                .saturating_mul(std::mem::size_of::<(i32, i32)>())
700        })
701        .fold(0usize, usize::saturating_add);
702    std::mem::size_of::<FloatHistogram>()
703        .saturating_add(buckets)
704        .saturating_add(spans)
705        .saturating_add(
706            view.custom_values
707                .len()
708                .saturating_mul(std::mem::size_of::<f64>()),
709        )
710}
711
712/// The bytes one boxed histogram value holds: its scalars inline and the heap its buckets, bounds
713/// and span layout own.
714fn result_histogram_bytes(histogram: &FloatHistogram) -> usize {
715    std::mem::size_of::<FloatHistogram>().saturating_add(histogram.heap_bytes())
716}
717
718/// The bytes one row of a histogram operator holds at its peak, read once from the widest histogram
719/// of each side of a field: an owned copy of each operand, the union `+` and `-` grow into -- both
720/// sides' buckets, charged twice because the union reallocates while the old buffer is alive -- the
721/// custom bounds the wider side copies, and the value the operator boxes. A phase figure, not one per
722/// row: a row that pairs two histograms is bounded by the widest of each side.
723fn histogram_phase_bytes(many: &Operand<'_>, one: &Operand<'_>) -> usize {
724    // What one owned copy of a view takes, the buckets the union grows by and its custom bounds.
725    let operand = |operand: &Operand<'_>| match operand.widest_histogram() {
726        Some(view) => (
727            owned_histogram_bytes(&view),
728            view.positive
729                .buckets
730                .len()
731                .saturating_add(view.negative.buckets.len()),
732            view.custom_values.len(),
733        ),
734        None => (0, 0, 0),
735    };
736    let (lhs_owned, lhs_buckets, lhs_bounds) = operand(many);
737    let (rhs_owned, rhs_buckets, rhs_bounds) = operand(one);
738    if lhs_owned == 0 && rhs_owned == 0 {
739        return 0;
740    }
741    lhs_owned
742        .saturating_add(rhs_owned)
743        .saturating_add(
744            lhs_buckets
745                .saturating_add(rhs_buckets)
746                .saturating_mul(2 * std::mem::size_of::<(i32, f64)>()),
747        )
748        .saturating_add(
749            lhs_bounds
750                .max(rhs_bounds)
751                .saturating_mul(2 * std::mem::size_of::<f64>()),
752        )
753        .saturating_add(2 * std::mem::size_of::<FloatHistogram>())
754}
755
756/// Matches one field of each side, collecting the first failure of each kind as
757/// `(point, rank, message)`.
758///
759/// The field's tables and the match set it builds are its own workspace: they replace what the field
760/// before held and are gone when it returns, which is why the caller admits that release after the
761/// call. The messages it appended and the rows it filed are what stays live.
762#[allow(clippy::too_many_arguments)]
763fn binary_field(
764    matching: &BinaryMatching,
765    grid: &EvalGrid,
766    lhs: &Operand<'_>,
767    rhs: &Operand<'_>,
768    errors: &mut Vec<(usize, u8, String)>,
769    evidence: Option<FieldEvidence<'_>>,
770    annotations: Option<&PromqlAnnotationCollector>,
771    mut budget: Option<&mut Budget<'_>>,
772) -> Result<Results> {
773    let (many, one, include, one_is_left) = match &matching.cardinality {
774        Cardinality::OneToOne => (lhs, rhs, &[][..], false),
775        Cardinality::ManyToOne(include) => (lhs, rhs, &include[..], false),
776        Cardinality::OneToMany(include) => (rhs, lhs, &include[..], true),
777    };
778    let points = grid.spec().len as usize;
779    let timestamp_at = |point: usize| {
780        (grid.spec().start_ms as i128 + point as i128 * grid.spec().step_ms as i128) as i64
781    };
782    let errors_before = errors.len();
783    // The pairing phase is entered once, before the field allocates anything: its presence flags,
784    // its match groups, the widest label set a pairing builds and the histogram payload one row of
785    // the walk reads. Nothing of the field before it is still live.
786    let metadata = match budget.as_deref_mut() {
787        Some(budget) => {
788            let metadata = field_metadata_bytes(matching, include, points, many, one);
789            budget.phase(metadata.tables.saturating_add(metadata.pairing))?;
790            metadata
791        }
792        None => FieldMetadata::default(),
793    };
794    // The walk below fills `rhs` for a missing one-side sample and `lhs` for a missing many-side
795    // one, so under `group_right`, whose one side is the left, the two trade places.
796    let fill = if one_is_left {
797        FillValues {
798            lhs: matching.fill.rhs,
799            rhs: matching.fill.lhs,
800        }
801    } else {
802        matching.fill
803    };
804    // Prometheus short-circuits a point where either side is empty, before any check; with a fill
805    // value only a point where both are empty.
806    let filling = fill.lhs.is_some() || fill.rhs.is_some();
807    let lhs_present = lhs.presence(points);
808    let rhs_present = rhs.presence(points);
809    if let Some(evidence) = &evidence {
810        evidence.evidence.publish(
811            evidence.node,
812            evidence.field,
813            &lhs_present,
814            &rhs_present,
815            filling,
816        )?;
817    }
818    let evaluated: Vec<bool> = lhs_present
819        .iter()
820        .copied()
821        .zip(rhs_present.iter().copied())
822        .map(|(lhs, rhs)| if filling { lhs || rhs } else { lhs && rhs })
823        .collect();
824
825    let one_groups = group(one, &matching.labels);
826    let mut one_duplicate: Option<(usize, &GroupKey)> = None;
827    for (key, members) in &one_groups {
828        // Scanning one group is its own phase: the list of its present points is the only thing it
829        // allocates, it is charged by the block it takes as it grows, and it is dropped with the
830        // scan, so the next group's list replaces it.
831        let mut duplicate_at: Option<usize> = None;
832        let mut group_key: Option<Arc<GroupKey>> = None;
833        overlap(
834            one,
835            members,
836            |point| {
837                if evaluated[point] {
838                    // This partition's own presence already decides the point: the duplicate below
839                    // aborts the execution from here, so recording it for the other partitions
840                    // would only take their lock to store a verdict nobody will ask for.
841                    if duplicate_at.is_none_or(|first| point < first) {
842                        duplicate_at = Some(point);
843                    }
844                } else if let Some(evidence) = &evidence {
845                    // The gate is false here only because this partition holds one side of the
846                    // match. Whether the point is eligible is a property of the whole execution,
847                    // so the finding is recorded and judged once every partition has reported.
848                    let side = if one_is_left { "left" } else { "right" };
849                    evidence.evidence.record_candidate(
850                        evidence.node,
851                        evidence.field,
852                        point,
853                        Arc::clone(group_key.get_or_insert_with(|| Arc::new(key.clone()))),
854                        side,
855                        timestamp_at(point),
856                    )?;
857                }
858                Ok(())
859            },
860            metadata.tables.saturating_add(metadata.pairing),
861            budget.as_deref_mut(),
862        )?;
863        if let Some(point) = duplicate_at
864            && one_duplicate.is_none_or(|(first, _)| point < first)
865        {
866            one_duplicate = Some((point, key));
867        }
868    }
869
870    let drop_name = !matching.op.is_comparison() || matching.return_bool;
871    let mut results = Results::default();
872    let mut pairs = Pairs {
873        matching,
874        one_is_left,
875        annotations,
876        group_keys: Vec::new(),
877        group_ids: HashMap::new(),
878        // One-to-one: a match group may be matched once per point; Prometheus counts a filtered
879        // comparison as a match too, but not an operation that failed. Filling the many side
880        // consults the same set.
881        matched: (matching.cardinality == Cardinality::OneToOne || fill.lhs.is_some())
882            .then(HashSet::new),
883        implicit_many_to_one: None,
884    };
885    for (many_index, many_series) in many.series.iter().enumerate() {
886        let key = group_key(&many_series.metric, &matching.labels);
887        let candidates = one_groups.get(&key).map_or(&[][..], Vec::as_slice);
888        if candidates.is_empty() && fill.rhs.is_none() {
889            continue;
890        }
891        let group = pairs.group_id(&key);
892        for &one_index in candidates {
893            // One candidate of the one side is paired with this series, whether or not the pairing
894            // turns out to hold a row: the visit is what the test-only counter reports, before the
895            // pairing's label set and axis intersection are built.
896            #[cfg(test)]
897            VISITED_PAIRS.with(|visited| visited.set(visited.get() + 1));
898            // One pairing's label set is built before the axes are intersected, and the next
899            // pairing replaces it: its bytes are part of the phase entered above, not a figure
900            // reserved per pair.
901            let metric = result_metric(
902                &many_series.metric,
903                &one.series[one_index].metric,
904                matching,
905                include,
906                drop_name,
907            )?;
908            let label_set = if budget.is_some() {
909                result_set_bytes(&metric, &one.series[one_index].metric, include)
910            } else {
911                0
912            };
913            // Only the positions both operands carry are evaluated, and each keeps its own row:
914            // the intersection is a merge of the two axes, never an envelope with offsets.
915            // One cursor per side serves this whole pairing: `intersect_runs` walks both axes'
916            // run lists forward, and each `GridRunPair` carries the row of each side, so the rows
917            // asked for only increase from one shared run to the next -- the order a `RowCursor`
918            // requires. A cursor per run would restart at row 0 and re-walk every row before it.
919            let (mut many_cursor, mut one_cursor) =
920                (many.cursor(many_index), one.cursor(one_index));
921            // The pairing's row is opened by the first point it files and reused by every later
922            // one, so a pairing whose axes do not intersect never builds its key.
923            let mut slot = RowSlot::Unfiled(&mut results.series);
924            for pair in many.shared_runs(many_index, one, one_index) {
925                for offset in 0..pair.len {
926                    let point = pair.position + offset;
927                    let (many_value, one_value) = (
928                        many_cursor
929                            .at(pair.row + offset)
930                            .expect("a row never goes back"),
931                        one_cursor
932                            .at(pair.other_row + offset)
933                            .expect("a row never goes back"),
934                    );
935                    slot = pairs.apply(
936                        slot,
937                        &mut results.totals,
938                        &metric,
939                        label_set,
940                        group,
941                        point,
942                        many_value,
943                        one_value,
944                        true,
945                        budget.as_deref_mut(),
946                    )?;
947                }
948            }
949        }
950        // A many-side sample no one-side series matched is answered with the fill value, at the
951        // label set the match group of the many-side series gives it.
952        if let Some(value) = fill.rhs {
953            let metric = result_metric(
954                &many_series.metric,
955                &metric_of(&key)?,
956                matching,
957                include,
958                drop_name,
959            )?;
960            let label_set = if budget.is_some() {
961                result_set_bytes(&metric, &many_series.metric, include)
962            } else {
963                0
964            };
965            let mut cursor = many.cursor(many_index);
966            let mut candidate_cursors: Vec<RowCursor<'_>> =
967                candidates.iter().map(|&index| one.cursor(index)).collect();
968            // One fill label set for this many-side series, opened by the first point it files.
969            let mut slot = RowSlot::Unfiled(&mut results.series);
970            for (point, row) in many.positions(many_index) {
971                let sample = cursor.at(row).expect("a row never goes back");
972                let matched = candidates
973                    .iter()
974                    .zip(&mut candidate_cursors)
975                    .any(|(&index, cursor)| one.present(index, point, cursor));
976                if !matched {
977                    // A fill row pairs no two series, so it builds no pairing label set.
978                    slot = pairs.apply(
979                        slot,
980                        &mut results.totals,
981                        &metric,
982                        label_set,
983                        group,
984                        point,
985                        sample,
986                        SampleRef::Float(value),
987                        false,
988                        budget.as_deref_mut(),
989                    )?;
990                }
991            }
992        }
993    }
994    // Prometheus fills the many side after every match of the step, for the samples of the one
995    // side that no operation matched.
996    if let Some(value) = fill.lhs {
997        for (one_index, one_series) in one.series.iter().enumerate() {
998            let key = group_key(&one_series.metric, &matching.labels);
999            let group = pairs.group_id(&key);
1000            let metric = result_metric(
1001                &metric_of(&key)?,
1002                &one_series.metric,
1003                matching,
1004                include,
1005                drop_name,
1006            )?;
1007            let label_set = if budget.is_some() {
1008                result_set_bytes(&metric, &one_series.metric, include)
1009            } else {
1010                0
1011            };
1012            let mut cursor = one.cursor(one_index);
1013            let mut slot = RowSlot::Unfiled(&mut results.series);
1014            for (point, row) in one.positions(one_index) {
1015                if !pairs
1016                    .matched
1017                    .as_ref()
1018                    .is_some_and(|matched| matched.contains(&(group, point)))
1019                {
1020                    let sample = cursor.at(row).expect("a row never goes back");
1021                    // A fill row pairs no two series, so it builds no pairing label set: what it
1022                    // keeps is the label set it is filed under.
1023                    slot = pairs.apply(
1024                        slot,
1025                        &mut results.totals,
1026                        &metric,
1027                        label_set,
1028                        group,
1029                        point,
1030                        SampleRef::Float(value),
1031                        sample,
1032                        false,
1033                        budget.as_deref_mut(),
1034                    )?;
1035                }
1036            }
1037        }
1038    }
1039    // The match set, the groups and the pairing state are gone with the walk: taking them apart
1040    // here drops them, so the sort and the messages are what is live from here on.
1041    let Pairs {
1042        group_keys,
1043        implicit_many_to_one,
1044        ..
1045    } = pairs;
1046    // The sort phase: one figure for the tables still live beside it, the messages it may append
1047    // and one slot per row it sorts -- entered once, before it allocates any of them.
1048    if let Some(budget) = budget.as_deref_mut() {
1049        budget.phase(
1050            metadata
1051                .tables
1052                .saturating_add(metadata.errors)
1053                .saturating_add(metadata.largest_key)
1054                .saturating_add(results.totals.rows.saturating_mul(SORT_ROW_BYTES)),
1055        )?;
1056    }
1057    // Prometheus fails at the first failing step. Within a step it checks the one side, then
1058    // matches, and only after the operator checks that result label sets are unique.
1059    if let Some((point, key)) = one_duplicate {
1060        let side = if one_is_left { "left" } else { "right" };
1061        errors.push((point, 0, duplicate_message(key, side, timestamp_at(point))));
1062    }
1063    if let Some((point, group)) = implicit_many_to_one {
1064        let key = &group_keys[group];
1065        errors.push((
1066            point,
1067            1,
1068            format!(
1069                "multiple matches for labels {} at {} ms: many-to-one matching must be explicit \
1070                 (group_left/group_right)",
1071                render(key),
1072                timestamp_at(point)
1073            ),
1074        ));
1075    }
1076    if let Some(duplicate) = results.sort_rows() {
1077        let grouping = duplicate.within_group && matching.cardinality != Cardinality::OneToOne;
1078        errors.push(if grouping {
1079            (
1080                duplicate.point,
1081                1,
1082                format!(
1083                    "multiple matches for labels {} at {} ms: grouping labels must ensure \
1084                     unique matches",
1085                    render(&duplicate.key),
1086                    timestamp_at(duplicate.point)
1087                ),
1088            )
1089        } else {
1090            (
1091                duplicate.point,
1092                2,
1093                same_labelset(&duplicate.key, timestamp_at(duplicate.point)),
1094            )
1095        });
1096    }
1097    // Only the messages this field actually appended stay live until the earliest one is reported.
1098    // They join what the results retain, once the field's tables and sort are gone.
1099    if let Some(budget) = budget {
1100        let appended = errors[errors_before..]
1101            .iter()
1102            .fold(0usize, |bytes, (_, _, text)| {
1103                bytes
1104                    .saturating_add(std::mem::size_of::<String>())
1105                    .saturating_add(text.capacity())
1106            });
1107        budget.hold(appended)?;
1108    }
1109    Ok(results)
1110}
1111
1112/// The matched pairs of one field and the state Prometheus checks them against.
1113///
1114/// The results are filed beside it, not in it: a pairing's open row borrows the table it files into
1115/// while the match state stays free to move with the point.
1116struct Pairs<'a> {
1117    matching: &'a BinaryMatching,
1118    one_is_left: bool,
1119    annotations: Option<&'a PromqlAnnotationCollector>,
1120    group_keys: Vec<GroupKey>,
1121    group_ids: HashMap<GroupKey, usize>,
1122    /// The match groups an operation matched at a point, kept where Prometheus consults them:
1123    /// one-to-one matching, and filling the many side. A filtered comparison counts as a match,
1124    /// an operation that failed does not.
1125    matched: Option<HashSet<(usize, usize)>>,
1126    implicit_many_to_one: Option<(usize, usize)>,
1127}
1128
1129impl Pairs<'_> {
1130    /// The id of the match group `key`, which stands for it in `matched` and in the results.
1131    fn group_id(&mut self, key: &GroupKey) -> usize {
1132        if let Some(&id) = self.group_ids.get(key) {
1133            return id;
1134        }
1135        let id = self.group_keys.len();
1136        self.group_keys.push(key.clone());
1137        self.group_ids.insert(key.clone(), id);
1138        id
1139    }
1140
1141    /// Applies the operator to a sample of each side at `point`; a missing sample is no pair.
1142    ///
1143    /// Nothing here is charged per point: the operator's histograms are part of the phase, and the
1144    /// only figures a row can charge are the two allocation boundaries it crosses -- a block the match
1145    /// set grows into, and `label_set`, the bytes a result label set keeps when this row is the first
1146    /// filed under it, or the value the results retain. The row a pairing files under its label set
1147    /// is opened by [`RowSlot`] on the first point the pairing files, and the slot is handed back to
1148    /// file the pairing's next point with.
1149    #[allow(clippy::too_many_arguments)]
1150    fn apply<'s>(
1151        &mut self,
1152        slot: RowSlot<'s>,
1153        totals: &mut ResultTotals,
1154        metric: &SeriesLabels,
1155        label_set: usize,
1156        group: usize,
1157        point: usize,
1158        many_value: SampleRef<'_>,
1159        one_value: SampleRef<'_>,
1160        actual_pair: bool,
1161        mut budget: Option<&mut Budget<'_>>,
1162    ) -> Result<RowSlot<'s>> {
1163        if matches!(many_value, SampleRef::Missing) || matches!(one_value, SampleRef::Missing) {
1164            return Ok(slot);
1165        }
1166        let (lhs_value, rhs_value) = if self.one_is_left {
1167            (one_value, many_value)
1168        } else {
1169            (many_value, one_value)
1170        };
1171        // Prometheus runs the operation on the float a fill value puts in place of a missing sample,
1172        // so a filled pair reports the legacy dropped-sample Info too. What stays out is not the
1173        // fill but the pair: one missing a side never reaches here, and a supported operation that
1174        // declines for another reason -- incompatible bucket layouts -- is already outside what
1175        // [`unsupported_histogram_arithmetic`] reports.
1176        let dropped_op = if self.annotations.is_some() {
1177            unsupported_histogram_arithmetic(self.matching.op, &lhs_value, &rhs_value)
1178        } else {
1179            None
1180        };
1181        // A fill value is a float, so a filled pair never holds the two histograms `elem_binop`
1182        // states its reconciliation and reset diagnostics for: those stay off for it.
1183        let pair_annotations = if actual_pair { self.annotations } else { None };
1184        let Some((result, keep)) =
1185            elem_binop(self.matching.op, lhs_value, rhs_value, pair_annotations)?
1186        else {
1187            if let (Some(collector), Some(op)) = (self.annotations, dropped_op) {
1188                collector.record_info(format!(
1189                    "{op}: dropped native histogram samples because this binary operation is not supported for native histograms"
1190                ));
1191            }
1192            // The operator skipped the pair and nothing of it was filed.
1193            return Ok(slot);
1194        };
1195        // One-to-one: a match group may be matched once per point; Prometheus counts a filtered
1196        // comparison as a match too, but not an operation that failed.
1197        if let Some(matched) = &mut self.matched {
1198            // The match set is the one container this walk grows point by point, so it is charged by
1199            // the block it takes when it outgrows what it holds -- before the insert allocates it, and
1200            // never per point of a set that has room.
1201            if matched.len() + 1 > matched.capacity()
1202                && let Some(budget) = budget.as_deref_mut()
1203            {
1204                let grown = (2 * matched.capacity()).max(VEC_MIN_CAPACITY);
1205                budget.grow(
1206                    grown
1207                        .saturating_sub(matched.capacity())
1208                        .saturating_mul(MATCH_SLOT_BYTES),
1209                )?;
1210            }
1211            if !matched.insert((group, point))
1212                && self.matching.cardinality == Cardinality::OneToOne
1213                && self
1214                    .implicit_many_to_one
1215                    .is_none_or(|(first, _)| point < first)
1216            {
1217                self.implicit_many_to_one = Some((point, group));
1218            }
1219        }
1220        // The value the row keeps. A `bool` comparison keeps a float and a filtered comparison
1221        // keeps nothing; a kept value is moved into the row.
1222        let value = if self.matching.return_bool {
1223            drop(result);
1224            Some(GridSample::Float(if keep { 1.0 } else { 0.0 }))
1225        } else if keep {
1226            Some(result)
1227        } else {
1228            drop(result);
1229            None
1230        };
1231        slot.file(totals, metric, label_set, group, point, value, budget)
1232    }
1233}
1234
1235/// The labels Prometheus gives a fill sample: the match group of the sample it pairs with.
1236fn metric_of(key: &GroupKey) -> Result<SeriesLabels> {
1237    let mut name = None;
1238    let mut labels = Vec::with_capacity(key.len());
1239    for (label, value) in key {
1240        if &**label == "__name__" {
1241            name = Some(value.clone());
1242        } else {
1243            labels.push(Label {
1244                name: label.clone(),
1245                value: value.clone(),
1246            });
1247        }
1248    }
1249    SeriesLabels::try_new(name, labels).map_err(external)
1250}
1251
1252fn earliest_error(errors: Vec<(usize, u8, String)>) -> Result<()> {
1253    match errors
1254        .into_iter()
1255        .min_by_key(|(point, rank, _)| (*point, *rank))
1256    {
1257        Some((_, _, error)) => Err(DataFusionError::Execution(error)),
1258        None => Ok(()),
1259    }
1260}
1261
1262/// Applies a set operator at every grid point. Series keep their labels and values; fields are
1263/// paired by position.
1264pub fn set_vectors(
1265    op: SetOp,
1266    labels: &MatchingLabels,
1267    lhs_schema: &SeriesSchema,
1268    lhs: &[Series],
1269    rhs_schema: &SeriesSchema,
1270    rhs: &[Series],
1271) -> Result<Vec<Series>> {
1272    set_vectors_inner(op, labels, lhs_schema, lhs, rhs_schema, rhs, None)
1273}
1274
1275/// [`set_vectors`], handing the live workspace it holds to `reserve` as it allocates.
1276///
1277/// The figures follow [`binary_vectors_with_reservation`]: what the results keep is held as their
1278/// containers grow, each field's walk and sort is a phase that replaces the one before it, and the
1279/// merge is the last phase. A total `reserve` refuses ends the operation with that error.
1280pub(crate) fn set_vectors_with_reservation(
1281    op: SetOp,
1282    labels: &MatchingLabels,
1283    lhs_schema: &SeriesSchema,
1284    lhs: &[Series],
1285    rhs_schema: &SeriesSchema,
1286    rhs: &[Series],
1287    reserve: &mut dyn FnMut(usize) -> Result<()>,
1288) -> Result<Vec<Series>> {
1289    let mut budget = Budget::new(reserve);
1290    set_vectors_inner(
1291        op,
1292        labels,
1293        lhs_schema,
1294        lhs,
1295        rhs_schema,
1296        rhs,
1297        Some(&mut budget),
1298    )
1299}
1300
1301/// The one set kernel, whether or not a caller accounts for its workspace.
1302fn set_vectors_inner(
1303    op: SetOp,
1304    labels: &MatchingLabels,
1305    lhs_schema: &SeriesSchema,
1306    lhs: &[Series],
1307    rhs_schema: &SeriesSchema,
1308    rhs: &[Series],
1309    mut budget: Option<&mut Budget<'_>>,
1310) -> Result<Vec<Series>> {
1311    let grid = same_grid(lhs_schema, rhs_schema)?;
1312    if lhs_schema.fields.len() != rhs_schema.fields.len() {
1313        return Err(DataFusionError::NotImplemented(
1314            "set operators between vectors with different field counts".into(),
1315        ));
1316    }
1317    let width = lhs_schema.fields.len();
1318    if let Some(budget) = budget.as_deref_mut() {
1319        budget.hold(output_bytes(width))?;
1320    }
1321    let output = Arc::new(SeriesSchema {
1322        fields: lhs_schema.fields.clone(),
1323        eval_grid: Some(grid.clone()),
1324    });
1325    let mut errors = Vec::new();
1326    let mut fields = Vec::with_capacity(width);
1327    for field in 0..width {
1328        let lhs = Operand::try_new(lhs_schema, lhs, field)?;
1329        let rhs = Operand::try_new(rhs_schema, rhs, field)?;
1330        let results = set_field(
1331            op,
1332            labels,
1333            &grid,
1334            &lhs,
1335            &rhs,
1336            &mut errors,
1337            budget.as_deref_mut(),
1338        )?;
1339        // The field's group table and sort are gone with its frame; what it filed stays live.
1340        if let Some(budget) = budget.as_deref_mut() {
1341            budget.phase(0)?;
1342        }
1343        fields.push(results);
1344    }
1345    earliest_error(errors)?;
1346    merge_fields(fields, output, budget)
1347}
1348
1349/// The figures one set field's phases are charged from, read once from its operands.
1350struct SetFieldMetadata {
1351    /// The filter side's match-group table, without the presence bitmaps it holds.
1352    tables: usize,
1353    /// The widest key one row builds: the match key a kept series is looked up by, or the key a row
1354    /// is filed under.
1355    scratch: usize,
1356    /// The one message the field can report, a fixed frame around one rendering.
1357    error: usize,
1358}
1359
1360fn set_field_metadata(
1361    labels: &MatchingLabels,
1362    kept: &Operand<'_>,
1363    filter: &Operand<'_>,
1364) -> SetFieldMetadata {
1365    let mut tables = 0usize;
1366    for series in filter.series {
1367        tables = tables
1368            .saturating_add(match_key_bytes(&series.metric, labels))
1369            .saturating_add(GROUP_SLOT_BYTES);
1370    }
1371    // `or` files the filter side's rows too, so both sides' label sets bound a row's keys and the
1372    // text of the message.
1373    let (mut scratch, mut text) = (0usize, 0usize);
1374    for series in kept.series.iter().chain(filter.series) {
1375        scratch = scratch
1376            .max(match_key_bytes(&series.metric, labels))
1377            .max(result_key_bytes(&series.metric));
1378        text = text.max(label_text_bytes(&series.metric));
1379    }
1380    SetFieldMetadata {
1381        tables,
1382        scratch,
1383        error: ERROR_TEXT_BYTES.saturating_add(text),
1384    }
1385}
1386
1387/// Filters one field of the kept side by the presence of its match group on the filter side, and
1388/// appends the first point where two kept rows share a label set as `(point, rank, message)`.
1389fn set_field(
1390    op: SetOp,
1391    labels: &MatchingLabels,
1392    grid: &EvalGrid,
1393    lhs: &Operand<'_>,
1394    rhs: &Operand<'_>,
1395    errors: &mut Vec<(usize, u8, String)>,
1396    mut budget: Option<&mut Budget<'_>>,
1397) -> Result<Results> {
1398    let (kept, filter, keep_matched) = match op {
1399        SetOp::And => (lhs, rhs, true),
1400        SetOp::Unless => (lhs, rhs, false),
1401        SetOp::Or => (rhs, lhs, false),
1402    };
1403    // The walk is one phase, entered before the group table exists; each group's bitmap joins it
1404    // as the group is first met.
1405    let metadata = match budget.as_deref_mut() {
1406        Some(budget) => {
1407            let metadata = set_field_metadata(labels, kept, filter);
1408            budget.phase(metadata.tables.saturating_add(metadata.scratch))?;
1409            Some(metadata)
1410        }
1411        None => None,
1412    };
1413    let presence = group_presence(
1414        filter,
1415        labels,
1416        grid.spec().len as usize,
1417        budget.as_deref_mut(),
1418    )?;
1419    // A set operator hands on its operands' label sets unchanged, so a row is filed under the label
1420    // set of the series it came from.
1421    let charged = budget.is_some();
1422    let label_set = |metric: &SeriesLabels| {
1423        if charged {
1424            result_set_bytes(metric, metric, &[])
1425        } else {
1426            0
1427        }
1428    };
1429    let mut results = Results::default();
1430    if op == SetOp::Or {
1431        for index in 0..lhs.series.len() {
1432            let metric = &lhs.series[index].metric;
1433            let label_set = label_set(metric);
1434            let mut cursor = lhs.cursor(index);
1435            // The series' row is opened by the first point it files, and every later point of the
1436            // series is pushed to it.
1437            let mut slot = RowSlot::Unfiled(&mut results.series);
1438            for (point, row) in lhs.positions(index) {
1439                if let Some(value) = owned(cursor.at(row).expect("a row never goes back"))? {
1440                    slot = slot.file(
1441                        &mut results.totals,
1442                        metric,
1443                        label_set,
1444                        0,
1445                        point,
1446                        Some(value),
1447                        budget.as_deref_mut(),
1448                    )?;
1449                }
1450            }
1451        }
1452    }
1453    for (index, series) in kept.series.iter().enumerate() {
1454        let label_set = label_set(&series.metric);
1455        let bits = presence.get(&group_key(&series.metric, labels));
1456        let mut cursor = kept.cursor(index);
1457        let mut slot = RowSlot::Unfiled(&mut results.series);
1458        for (point, row) in kept.positions(index) {
1459            let sample = cursor.at(row).expect("a row never goes back");
1460            if matches!(sample, SampleRef::Missing) {
1461                continue;
1462            }
1463            let matched = bits.is_some_and(|bits| bits[point / 64] & (1 << (point % 64)) != 0);
1464            if matched == keep_matched {
1465                let value = owned(sample)?;
1466                slot = slot.file(
1467                    &mut results.totals,
1468                    &series.metric,
1469                    label_set,
1470                    0,
1471                    point,
1472                    value,
1473                    budget.as_deref_mut(),
1474                )?;
1475            }
1476        }
1477    }
1478    // The group table is gone before the sort phase, which is charged without it: the message the
1479    // sort may append and one slot per row it sorts, entered before it allocates either.
1480    drop(presence);
1481    if let (Some(budget), Some(metadata)) = (budget.as_deref_mut(), &metadata) {
1482        budget.phase(
1483            metadata
1484                .error
1485                .saturating_add(metadata.scratch)
1486                .saturating_add(results.totals.rows.saturating_mul(SORT_ROW_BYTES)),
1487        )?;
1488    }
1489    if let Some(duplicate) = results.sort_rows() {
1490        let timestamp = (grid.spec().start_ms as i128
1491            + duplicate.point as i128 * grid.spec().step_ms as i128) as i64;
1492        let message = same_labelset(&duplicate.key, timestamp);
1493        // The message stays live until the earliest one is reported.
1494        if let Some(budget) = budget {
1495            budget.hold(std::mem::size_of::<String>().saturating_add(message.capacity()))?;
1496        }
1497        errors.push((duplicate.point, 0, message));
1498    }
1499    Ok(results)
1500}
1501
1502/// The points at which each match group of `operand` holds a sample, one bit per grid point.
1503///
1504/// Prometheus decides a set operator at a step from the signatures present on the filter side, so
1505/// a kept sample needs only whether its group is present at its point: built once from the filter
1506/// side's rows, that is one lookup per kept sample however many series share the group. A group's
1507/// bitmap is charged as the group is first met, before it is allocated.
1508fn group_presence(
1509    operand: &Operand<'_>,
1510    labels: &MatchingLabels,
1511    points: usize,
1512    mut budget: Option<&mut Budget<'_>>,
1513) -> Result<HashMap<GroupKey, Vec<u64>>> {
1514    let words = points.div_ceil(64);
1515    let mut presence: HashMap<GroupKey, Vec<u64>> = HashMap::new();
1516    for (index, series) in operand.series.iter().enumerate() {
1517        let bits = match presence.entry(group_key(&series.metric, labels)) {
1518            Entry::Occupied(entry) => entry.into_mut(),
1519            Entry::Vacant(entry) => {
1520                if let Some(budget) = budget.as_deref_mut() {
1521                    budget.grow(words.saturating_mul(std::mem::size_of::<u64>()))?;
1522                }
1523                entry.insert(vec![0; words])
1524            }
1525        };
1526        let mut cursor = operand.cursor(index);
1527        for (point, row) in operand.positions(index) {
1528            if !matches!(
1529                cursor.at(row).expect("a row never goes back"),
1530                SampleRef::Missing
1531            ) {
1532                bits[point / 64] |= 1 << (point % 64);
1533            }
1534        }
1535    }
1536    Ok(presence)
1537}
1538
1539/// Joins the per-field results into series with all fields, by label set.
1540///
1541/// The merge is one phase, entered from the results the fields filed: the triples it groups, the
1542/// table it groups them in and the builder's own buffers. Its columns are reserved once per result
1543/// series, before the series pushes its first row, rather than once per row.
1544///
1545/// The phase figure is entered here, before either merge runs, so both are charged the same bytes
1546/// and neither can allocate before it is admitted.
1547fn merge_fields(
1548    fields: Vec<Results>,
1549    schema: Arc<SeriesSchema>,
1550    mut budget: Option<&mut Budget<'_>>,
1551) -> Result<Vec<Series>> {
1552    let width = schema.fields.len();
1553    // What the merge holds before it allocates any of it, read from the results themselves: the
1554    // kept triples, the label sets they are filed under and the histogram payload they carry.
1555    if let Some(budget) = budget.as_deref_mut() {
1556        let mut sets = 0usize;
1557        let mut merge = (0usize, 0usize, 0usize);
1558        for results in &fields {
1559            sets = sets.saturating_add(results.series.len());
1560            merge = (
1561                merge.0.saturating_add(results.totals.kept),
1562                merge.1.saturating_add(results.totals.histograms),
1563                merge.2.saturating_add(results.totals.histogram_heap),
1564            );
1565        }
1566        budget.phase(merge_bytes(merge.0, sets, width, merge.1, merge.2))?;
1567    }
1568    // One field of one result table is the whole merge, so its rows are written out as they are
1569    // read; every other shape keeps the merge that groups, sorts and fills rows.
1570    if width == 1 && fields.len() == 1 {
1571        return merge_single_field(fields, schema, budget);
1572    }
1573    merge_multi_field(fields, schema, budget)
1574}
1575
1576/// The merge of every field's results into one series per label set: the `(point, field, value)`
1577/// triples of a label set, sorted and filled into a row the builder writes one value per point.
1578///
1579/// The phase the two merges share is entered by [`merge_fields`], before this runs.
1580fn merge_multi_field(
1581    fields: Vec<Results>,
1582    schema: Arc<SeriesSchema>,
1583    mut budget: Option<&mut Budget<'_>>,
1584) -> Result<Vec<Series>> {
1585    let width = schema.fields.len();
1586    // Per label set: the metric and its `(point, field, value)` samples.
1587    type Merged = (SeriesLabels, Vec<(usize, usize, GridSample)>);
1588    let mut merged: HashMap<GroupKey, Merged> = HashMap::new();
1589    for (field, results) in fields.into_iter().enumerate() {
1590        for (key, rows) in results.series {
1591            let (_, samples) = merged
1592                .entry(key)
1593                .or_insert_with(|| (rows.metric.clone(), Vec::new()));
1594            for (&point, value) in rows.points.iter().zip(rows.values) {
1595                if let Some(value) = value {
1596                    samples.push((point, field, value));
1597                }
1598            }
1599        }
1600    }
1601    let mut builder = GridSeriesBuilder::try_new(schema)?;
1602    let mut row: Vec<Option<GridSample>> = Vec::with_capacity(width);
1603    let mut output = Vec::with_capacity(merged.len());
1604    for (metric, mut samples) in merged.into_values() {
1605        // One builder serves every label set, so each result series starts explicitly.
1606        builder.begin_series();
1607        samples.sort_unstable_by_key(|(point, field, _)| (*point, *field));
1608        // This series' columns, in one reservation before it writes the first row of them. They stay
1609        // live inside the series it is finished as, so the phase keeps them.
1610        if let Some(budget) = budget.as_deref_mut() {
1611            budget.grow(merge_series_columns(&samples, width))?;
1612        }
1613        let mut samples = samples.into_iter().peekable();
1614        while let Some((point, field, value)) = samples.next() {
1615            row.clear();
1616            row.resize_with(width, || None);
1617            row[field] = Some(value);
1618            while let Some((_, field, value)) = samples.next_if(|next| next.0 == point) {
1619                row[field] = Some(value);
1620            }
1621            builder.push_samples(point, &row)?;
1622        }
1623        output.extend(builder.finish(metric)?);
1624    }
1625    Ok(output)
1626}
1627
1628/// The one-field shape's merge: the label set's rows written out as they are read.
1629///
1630/// A merge of one field has nothing to merge. The field filed each label set's rows already sorted
1631/// by point and already proven to hold one row per point -- the field's own sort reports two rows at
1632/// one point as an error, which is reported before the merge runs -- so the series is its rows: no
1633/// triples table, no sort and no row buffer, one single-value row per kept sample. A sample the
1634/// operator filtered (`None`) writes no row, exactly as in [`merge_multi_field`], and a label set
1635/// whose samples were all filtered finishes as no series at all.
1636///
1637/// The rows it keeps are charged the figure [`merge_multi_field`] charges for the same samples, so
1638/// the two merges bill a one-field result the same. The order the series are handed out in is not
1639/// guaranteed -- label sets are read from a hash map, as in [`merge_multi_field`] -- so no result is
1640/// defined by it.
1641fn merge_single_field(
1642    fields: Vec<Results>,
1643    schema: Arc<SeriesSchema>,
1644    mut budget: Option<&mut Budget<'_>>,
1645) -> Result<Vec<Series>> {
1646    let mut builder = GridSeriesBuilder::try_new(schema)?;
1647    let series = fields.iter().map(|results| results.series.len()).sum();
1648    let mut output = Vec::with_capacity(series);
1649    for results in fields {
1650        for (_, rows) in results.series {
1651            // One builder serves every label set, so each result series starts explicitly.
1652            builder.begin_series();
1653            // This series' columns, in one reservation before it writes the first row of them: the
1654            // points of the samples it keeps, which are the rows the builder writes, counted in the
1655            // one walk it already takes over them.
1656            if let Some(budget) = budget.as_deref_mut() {
1657                budget.grow(merge_series_columns_of(
1658                    rows.points
1659                        .iter()
1660                        .zip(&rows.values)
1661                        .filter(|(_, value)| value.is_some())
1662                        .map(|(point, _)| *point),
1663                    1,
1664                ))?;
1665            }
1666            for (&point, value) in rows.points.iter().zip(&rows.values) {
1667                if value.is_some() {
1668                    // A one-field row is the sample itself, borrowed rather than built.
1669                    builder.push_samples(point, std::slice::from_ref(value))?;
1670                }
1671            }
1672            output.extend(builder.finish(rows.metric)?);
1673        }
1674    }
1675    Ok(output)
1676}
1677
1678/// The bytes one result series' columns take, read from the triples the multi-field merge sorts:
1679/// the points they sit at, one row per point.
1680fn merge_series_columns(samples: &[(usize, usize, GridSample)], fields: usize) -> usize {
1681    merge_series_columns_of(samples.iter().map(|(point, ..)| *point), fields)
1682}
1683
1684/// The bytes one result series' columns take: the rows it writes -- one per distinct point of its
1685/// samples, which is what the builder writes a row for -- times a row's columns. The points arrive
1686/// sorted, so a distinct point is a point that differs from the one before it.
1687///
1688/// A row is the value and validity column of every field, charged twice for the capacity each column
1689/// grows to, and the histogram index column of every field. The index columns are counted for every
1690/// field rather than only the ones that happen to carry a histogram, so the figure over-reserves
1691/// rather than missing a column, and nothing here follows how a column grows.
1692fn merge_series_columns_of(points: impl Iterator<Item = usize>, fields: usize) -> usize {
1693    let row = 2 * fields.saturating_mul(std::mem::size_of::<f64>() + 1)
1694        + fields.saturating_mul(std::mem::size_of::<Option<u32>>());
1695    let mut rows = 0usize;
1696    let mut consumed: Option<usize> = None;
1697    for point in points {
1698        if consumed != Some(point) {
1699            rows = rows.saturating_add(1);
1700            consumed = Some(point);
1701        }
1702    }
1703    rows.saturating_mul(row)
1704}
1705
1706fn same_grid(lhs: &SeriesSchema, rhs: &SeriesSchema) -> Result<Arc<EvalGrid>> {
1707    match (&lhs.eval_grid, &rhs.eval_grid) {
1708        (Some(lhs), Some(rhs)) if lhs.spec() == rhs.spec() => Ok(lhs.clone()),
1709        _ => Err(DataFusionError::Execution(
1710            "vector operands must be evaluated on the same grid".into(),
1711        )),
1712    }
1713}
1714
1715fn duplicate_message(key: &GroupKey, side: &str, timestamp: i64) -> String {
1716    format!(
1717        "found duplicate series for the match group {} on the {side} hand-side of the \
1718         operation at {timestamp} ms; many-to-many matching not allowed: matching labels must be \
1719         unique on one side",
1720        render(key),
1721    )
1722}
1723
1724/// Label pairs identifying a match group or a result; empty values are absent, as in
1725/// Prometheus.
1726pub type GroupKey = Vec<(Arc<str>, Arc<str>)>;
1727
1728/// A per-node, per-field reduction of duplicate evidence across output partitions.
1729pub struct DuplicateEvidence {
1730    slots: std::sync::Mutex<HashMap<(usize, usize), DuplicateSlot>>,
1731    reservation: std::sync::Mutex<MemoryReservation>,
1732    remaining: std::sync::atomic::AtomicUsize,
1733    aborted: std::sync::atomic::AtomicBool,
1734    final_verdict: std::sync::Mutex<Option<DuplicateCandidate>>,
1735}
1736
1737#[derive(Default)]
1738struct DuplicateSlot {
1739    grid_len: Option<usize>,
1740    lhs_present: Vec<bool>,
1741    rhs_present: Vec<bool>,
1742    candidates: HashMap<usize, DuplicateCandidate>,
1743    filling: Option<bool>,
1744}
1745
1746/// The best duplicate candidate retained for one grid point.
1747#[derive(Clone, Debug, PartialEq, Eq)]
1748pub struct DuplicateCandidate {
1749    pub point: usize,
1750    pub group: Arc<GroupKey>,
1751    /// `"left"` or `"right"`: the side that carried the duplicate.
1752    pub side: &'static str,
1753    pub timestamp: i64,
1754}
1755
1756impl DuplicateCandidate {
1757    /// The error text, built only when the verdict is reported.
1758    pub fn message(&self) -> String {
1759        duplicate_message(&self.group, self.side, self.timestamp)
1760    }
1761}
1762
1763fn candidate_owned_bytes(group: &GroupKey) -> usize {
1764    // Charge label bytes for every retained candidate, conservatively over-counting shared groups.
1765    group
1766        .iter()
1767        .map(|(name, value)| name.len().saturating_add(value.len()))
1768        .sum::<usize>()
1769        .saturating_add(
1770            group
1771                .capacity()
1772                .saturating_mul(std::mem::size_of::<(Arc<str>, Arc<str>)>()),
1773        )
1774        .saturating_add(std::mem::size_of::<DuplicateCandidate>())
1775}
1776
1777impl DuplicateEvidence {
1778    /// Creates evidence storage for each output partition; slots grow to their binary's grid.
1779    pub fn new(pool: &Arc<dyn MemoryPool>, partitions: usize) -> Self {
1780        Self {
1781            slots: std::sync::Mutex::new(HashMap::new()),
1782            reservation: std::sync::Mutex::new(
1783                MemoryConsumer::new("DuplicateEvidence").register(pool),
1784            ),
1785            remaining: std::sync::atomic::AtomicUsize::new(partitions),
1786            aborted: std::sync::atomic::AtomicBool::new(false),
1787            final_verdict: std::sync::Mutex::new(None),
1788        }
1789    }
1790
1791    /// ORs one partition's operand presence into the node/field slot.
1792    pub fn complete(&self) -> bool {
1793        self.exit_claim(false)
1794    }
1795
1796    /// Whether every output partition has completed or aborted this evidence generation.
1797    pub fn finished(&self) -> bool {
1798        self.remaining.load(std::sync::atomic::Ordering::Acquire) == 0
1799    }
1800
1801    /// Whether any claim in this generation was aborted.
1802    pub fn aborted(&self) -> bool {
1803        self.aborted.load(std::sync::atomic::Ordering::Acquire)
1804    }
1805
1806    #[cfg(test)]
1807    pub(crate) fn slot_count(&self) -> usize {
1808        self.slots.lock().unwrap().len()
1809    }
1810
1811    pub fn abort(&self) {
1812        self.exit_claim(true);
1813    }
1814
1815    fn clear_slots(&self) {
1816        let mut final_verdict = self.final_verdict.lock().unwrap();
1817        let mut slots = self.slots.lock().unwrap();
1818        final_verdict.take();
1819        slots.clear();
1820        let reservation = self.reservation.lock().unwrap();
1821        let size = reservation.size();
1822        reservation.shrink(size);
1823    }
1824
1825    fn exit_claim(&self, aborted: bool) -> bool {
1826        if aborted {
1827            self.aborted
1828                .store(true, std::sync::atomic::Ordering::Release);
1829            self.clear_slots();
1830        }
1831        let last = loop {
1832            let current = self.remaining.load(std::sync::atomic::Ordering::Acquire);
1833            if current == 0 {
1834                return false;
1835            }
1836            if self
1837                .remaining
1838                .compare_exchange(
1839                    current,
1840                    current - 1,
1841                    std::sync::atomic::Ordering::AcqRel,
1842                    std::sync::atomic::Ordering::Acquire,
1843                )
1844                .is_ok()
1845            {
1846                break current == 1;
1847            }
1848        };
1849        if last {
1850            let mut final_verdict = self.final_verdict.lock().unwrap();
1851            if !self.aborted.load(std::sync::atomic::Ordering::Acquire) {
1852                *final_verdict = self.current_verdict();
1853            }
1854            let retained_bytes = final_verdict
1855                .as_ref()
1856                .map(|candidate| candidate_owned_bytes(&candidate.group))
1857                .unwrap_or(0);
1858            self.slots.lock().unwrap().clear();
1859            let reservation = self.reservation.lock().unwrap();
1860            let release = reservation.size().saturating_sub(retained_bytes);
1861            reservation.shrink(release);
1862        }
1863        last && !self.aborted.load(std::sync::atomic::Ordering::Acquire)
1864    }
1865
1866    pub fn verdict(&self) -> Option<DuplicateCandidate> {
1867        if self.remaining.load(std::sync::atomic::Ordering::Acquire) == 0 {
1868            return self.final_verdict.lock().unwrap().clone();
1869        }
1870        self.current_verdict()
1871    }
1872
1873    /// Takes the completed verdict and releases the memory retained for its candidate.
1874    pub fn take_verdict(&self) -> Option<DuplicateCandidate> {
1875        if self.remaining.load(std::sync::atomic::Ordering::Acquire) != 0 {
1876            return None;
1877        }
1878        let mut final_verdict = self.final_verdict.lock().unwrap();
1879        let candidate = final_verdict.take()?;
1880        let reservation = self.reservation.lock().unwrap();
1881        let size = reservation.size();
1882        reservation.shrink(size);
1883        Some(candidate)
1884    }
1885
1886    fn current_verdict(&self) -> Option<DuplicateCandidate> {
1887        if self.aborted.load(std::sync::atomic::Ordering::Acquire) {
1888            return None;
1889        }
1890        let slots = self.slots.lock().unwrap();
1891        slots
1892            .iter()
1893            .filter_map(|(&(node, field), slot)| {
1894                let filling = slot.filling?;
1895                slot.candidates
1896                    .iter()
1897                    .filter_map(|(&point, candidate)| {
1898                        let lhs = slot.lhs_present.get(point).copied().unwrap_or(false);
1899                        let rhs = slot.rhs_present.get(point).copied().unwrap_or(false);
1900                        (if filling { lhs || rhs } else { lhs && rhs }).then(|| candidate.clone())
1901                    })
1902                    .min_by_key(|candidate| candidate.point)
1903                    .map(|candidate| ((candidate.point, node, field), candidate))
1904            })
1905            .min_by_key(|(key, _)| *key)
1906            .map(|(_, candidate)| candidate)
1907    }
1908
1909    pub fn publish(
1910        &self,
1911        node_index: usize,
1912        field: usize,
1913        lhs_present: &[bool],
1914        rhs_present: &[bool],
1915        filling: bool,
1916    ) -> Result<()> {
1917        let mut slots = self.slots.lock().unwrap();
1918        if self.aborted.load(std::sync::atomic::Ordering::Acquire) {
1919            return Ok(());
1920        }
1921        let slot = slots.entry((node_index, field)).or_default();
1922        if let Some(existing_len) = slot.grid_len {
1923            if existing_len != lhs_present.len() || existing_len != rhs_present.len() {
1924                return Err(DataFusionError::Internal(
1925                    "binary match grid length differs across partitions".into(),
1926                ));
1927            }
1928        } else {
1929            if lhs_present.len() != rhs_present.len() {
1930                return Err(DataFusionError::Internal(
1931                    "binary match operand grid lengths differ".into(),
1932                ));
1933            }
1934            if slot
1935                .candidates
1936                .keys()
1937                .any(|point| *point >= lhs_present.len())
1938            {
1939                return Err(DataFusionError::Internal(
1940                    "duplicate candidate is outside its binary grid".into(),
1941                ));
1942            }
1943            slot.grid_len = Some(lhs_present.len());
1944        }
1945        if let Some(existing) = slot.filling {
1946            if existing != filling {
1947                return Err(DataFusionError::Internal(
1948                    "binary match filling differs across partitions".into(),
1949                ));
1950            }
1951        } else {
1952            slot.filling = Some(filling);
1953        }
1954        let len = lhs_present.len();
1955        if len > slot.lhs_present.len() {
1956            let additional = (len - slot.lhs_present.len())
1957                .saturating_mul(2)
1958                .saturating_mul(std::mem::size_of::<bool>());
1959            self.reservation.lock().unwrap().try_grow(additional)?;
1960            slot.lhs_present.resize(len, false);
1961            slot.rhs_present.resize(len, false);
1962        }
1963        for (dst, src) in slot.lhs_present.iter_mut().zip(lhs_present) {
1964            *dst |= *src;
1965        }
1966        for (dst, src) in slot.rhs_present.iter_mut().zip(rhs_present) {
1967            *dst |= *src;
1968        }
1969        Ok(())
1970    }
1971
1972    /// Retains the first candidate for this point; presence decides whether it is reportable.
1973    pub fn record_candidate(
1974        &self,
1975        node_index: usize,
1976        field: usize,
1977        point: usize,
1978        group: Arc<GroupKey>,
1979        side: &'static str,
1980        timestamp: i64,
1981    ) -> Result<()> {
1982        let mut slots = self.slots.lock().unwrap();
1983        if self.aborted.load(std::sync::atomic::Ordering::Acquire) {
1984            return Ok(());
1985        }
1986        let slot = slots.entry((node_index, field)).or_default();
1987        if slot.grid_len.is_some_and(|len| point >= len) {
1988            return Err(DataFusionError::Internal(
1989                "duplicate candidate is outside its binary grid".into(),
1990            ));
1991        }
1992        if slot.candidates.contains_key(&point) {
1993            return Ok(());
1994        }
1995        let entry_bytes = candidate_owned_bytes(&group)
1996            .saturating_add(std::mem::size_of::<(usize, DuplicateCandidate)>());
1997        self.reservation.lock().unwrap().try_grow(entry_bytes)?;
1998        if let Err(error) = slot.candidates.try_reserve(1) {
1999            self.reservation.lock().unwrap().shrink(entry_bytes);
2000            return Err(DataFusionError::Execution(error.to_string()));
2001        }
2002        slot.candidates.insert(
2003            point,
2004            DuplicateCandidate {
2005                point,
2006                group,
2007                side,
2008                timestamp,
2009            },
2010        );
2011        Ok(())
2012    }
2013}
2014
2015pub(crate) fn group_key(metric: &SeriesLabels, labels: &MatchingLabels) -> GroupKey {
2016    let mut key: GroupKey = match labels {
2017        MatchingLabels::On(names) => names
2018            .iter()
2019            .filter_map(|name| {
2020                let value = metric.get(name)?;
2021                (!value.is_empty()).then(|| (name.clone(), Arc::from(value)))
2022            })
2023            .collect(),
2024        MatchingLabels::Ignoring(names) => metric
2025            .tags()
2026            .iter()
2027            .filter(|tag| !tag.value.is_empty() && !names.contains(&tag.name))
2028            .map(|tag| (tag.name.clone(), tag.value.clone()))
2029            .collect(),
2030    };
2031    key.sort();
2032    key.dedup();
2033    key
2034}
2035
2036fn key_of(metric: &SeriesLabels) -> GroupKey {
2037    let mut key = group_key(metric, &MatchingLabels::Ignoring(Vec::new()));
2038    if let Some(name) = metric.name() {
2039        key.insert(0, (Arc::from("__name__"), Arc::from(name)));
2040    }
2041    key
2042}
2043
2044fn render(key: &GroupKey) -> String {
2045    let labels: Vec<_> = key
2046        .iter()
2047        .map(|(name, value)| format!("{name}=\"{value}\""))
2048        .collect();
2049    format!("{{{}}}", labels.join(", "))
2050}
2051
2052/// Groups the series of `operand` by their match group.
2053fn group(operand: &Operand<'_>, labels: &MatchingLabels) -> HashMap<GroupKey, Vec<usize>> {
2054    let mut groups: HashMap<GroupKey, Vec<usize>> = HashMap::new();
2055    for (index, series) in operand.series.iter().enumerate() {
2056        groups
2057            .entry(group_key(&series.metric, labels))
2058            .or_default()
2059            .push(index);
2060    }
2061    groups
2062}
2063
2064/// Reports every point where two or more `members` are present.
2065///
2066/// The group's list of present points is the only thing this scan allocates, and scanning one group
2067/// is its own phase: the block the list takes is charged when it outgrows what it holds, and the next
2068/// group's scan enters `base` again rather than adding a second list to it. A group of one member and
2069/// a group whose members carry no sample both cost nothing, however long their axes are.
2070fn overlap(
2071    operand: &Operand<'_>,
2072    members: &[usize],
2073    mut on_duplicate: impl FnMut(usize) -> Result<()>,
2074    base: usize,
2075    mut budget: Option<&mut Budget<'_>>,
2076) -> Result<()> {
2077    if members.len() < 2 {
2078        return Ok(());
2079    }
2080    // Sorting the present points keeps the cost proportional to them, not to the span.
2081    let mut points = Vec::new();
2082    for &member in members {
2083        let mut cursor = operand.cursor(member);
2084        for (point, row) in operand.positions(member) {
2085            if !matches!(
2086                cursor.at(row).expect("a row never goes back"),
2087                SampleRef::Missing
2088            ) {
2089                // A new block of the list, reserved before the push that allocates it.
2090                if let Some(budget) = budget.as_deref_mut()
2091                    && points.len() == points.capacity()
2092                {
2093                    let capacity = points.capacity().saturating_mul(2).max(VEC_MIN_CAPACITY);
2094                    let list = capacity.saturating_mul(std::mem::size_of::<usize>());
2095                    budget.phase(base.saturating_add(list))?;
2096                }
2097                points.push(point);
2098            }
2099        }
2100    }
2101    points.sort_unstable();
2102    for (index, pair) in points.windows(2).enumerate() {
2103        if pair[0] == pair[1] && (index == 0 || points[index - 1] != pair[0]) {
2104            on_duplicate(pair[0])?;
2105        }
2106    }
2107    // The list is dropped with this scan, so the field's own phase figure is live from here on.
2108    if let Some(budget) = budget {
2109        budget.phase(base)?;
2110    }
2111    Ok(())
2112}
2113
2114fn result_metric(
2115    many: &SeriesLabels,
2116    one: &SeriesLabels,
2117    matching: &BinaryMatching,
2118    include: &[Arc<str>],
2119    drop_name: bool,
2120) -> Result<SeriesLabels> {
2121    let mut metric = many.clone();
2122    if drop_name {
2123        metric.remove_all(&METADATA_LABELS);
2124    }
2125    if matching.cardinality == Cardinality::OneToOne {
2126        match &matching.labels {
2127            MatchingLabels::On(names) => {
2128                metric.keep_only(&names.iter().map(|name| &**name).collect::<Vec<_>>())
2129            }
2130            MatchingLabels::Ignoring(names) => {
2131                metric.remove_all(&names.iter().map(|name| &**name).collect::<Vec<_>>())
2132            }
2133        }
2134    }
2135    for name in include {
2136        match one.get(name) {
2137            Some(value) if !value.is_empty() => metric
2138                .set(name, Arc::from(value))
2139                .map_err(|error| DataFusionError::External(Box::new(error)))?,
2140            _ => metric.remove(name),
2141        }
2142    }
2143    Ok(metric)
2144}
2145
2146/// Validates one operand of [`binary_vectors`]: every series must sit on the schema's grid, carry
2147/// the schema's fields, and hold one sample for every row its own axis places.
2148///
2149/// [`Series`] keeps its fields public, so a series built by struct literal can disagree with the
2150/// schema it is handed in with, and then the row the axis names has nothing to read. The kernel
2151/// cannot read such an operand, so the check lives here and runs before a field builds its matching
2152/// tables: the output schema is reserved before it, but nothing of the walk is.
2153pub(crate) fn validate_binary_operand(schema: &SeriesSchema, series: &[Series]) -> Result<()> {
2154    let grid = schema.eval_grid.as_ref().map(|grid| grid.spec());
2155    for item in series {
2156        // Both grid axes address the grid; the explicit ones cannot be indexed by position.
2157        let Some(item_grid) = item.time.grid() else {
2158            return Err(DataFusionError::Execution(
2159                "vector operand series must be on the evaluation grid".into(),
2160            ));
2161        };
2162        if Some(item_grid.spec()) != grid
2163            || item.fields.len() != schema.fields.len()
2164            || item
2165                .fields
2166                .iter()
2167                .any(|field| field.len() != item.time.len())
2168        {
2169            return Err(DataFusionError::Execution(
2170                "vector operand series does not match its schema".into(),
2171            ));
2172        }
2173    }
2174    Ok(())
2175}
2176
2177/// One field of one side's series, with verified grid axes.
2178///
2179/// An operand's series are addressed on the evaluation grid, and each may skip positions. Every
2180/// accessor therefore reads the axis: a point lookup asks the axis for the row of a position
2181/// (`row_of`, a binary search), and a traversal walks the rows the axis carries
2182/// (`positions`). Nothing here assumes a series covers one contiguous range, so a sparse operand
2183/// never reads a hole as a row.
2184struct Operand<'a> {
2185    series: &'a [Series],
2186    field: usize,
2187}
2188
2189impl<'a> Operand<'a> {
2190    fn try_new(schema: &SeriesSchema, series: &'a [Series], field: usize) -> Result<Self> {
2191        validate_binary_operand(schema, series)?;
2192        Ok(Self { series, field })
2193    }
2194
2195    fn axis(&self, index: usize) -> &'a TimeAxis {
2196        &self.series[index].time
2197    }
2198
2199    /// The widest histogram this operand's field holds.
2200    ///
2201    /// Read once before the rows are matched, so the workspace of a histogram row is reserved for
2202    /// the field rather than per row. A field of floats is answered without reading a sample: its
2203    /// segments say what it holds, so the numeric path pays nothing for this figure.
2204    fn widest_histogram(&self) -> Option<HistogramView<'a>> {
2205        let mut widest: Option<(HistogramView<'a>, usize)> = None;
2206        for series in self.series {
2207            let field = &series.fields.as_slice()[self.field];
2208            let holds_histograms = field.segments().iter().any(|segment| {
2209                matches!(
2210                    segment.dense(),
2211                    Some(DenseSamplesRef::Histogram(_) | DenseSamplesRef::Mixed(_))
2212                )
2213            });
2214            if !holds_histograms {
2215                continue;
2216            }
2217            for sample in field.iter() {
2218                let SampleRef::Histogram(view) = sample else {
2219                    continue;
2220                };
2221                if widest.is_none_or(|(_, widest)| owned_histogram_bytes(&view) > widest) {
2222                    widest = Some((view, owned_histogram_bytes(&view)));
2223                }
2224            }
2225        }
2226        widest.map(|(view, _)| view)
2227    }
2228
2229    /// Every absolute position this series carries, with its compact row, in order.
2230    fn positions(&self, index: usize) -> datatypes::series::time::Positions<'a> {
2231        self.series[index].time.positions()
2232    }
2233
2234    /// A forward reader of `series[index]`'s field, for a walk in axis order.
2235    ///
2236    /// The rows of one walk only increase, so a cursor reads the field once; reading each row
2237    /// with [`Samples::sample`](datatypes::series::samples::Samples::sample) would rescan the
2238    /// chunk descriptors per row.
2239    fn cursor(&self, index: usize) -> RowCursor<'a> {
2240        self.series[index].fields.as_slice()[self.field].cursor()
2241    }
2242
2243    /// Whether `series[index]` holds a value at absolute grid `point`, read through `cursor`.
2244    ///
2245    /// The points one walk asks about only increase, so its cursor never goes back: a candidate
2246    /// read per point through [`Samples::sample`](datatypes::series::samples::Samples::sample)
2247    /// would rescan the chunk descriptors from the start every time.
2248    fn present(&self, index: usize, point: usize, cursor: &mut RowCursor<'a>) -> bool {
2249        self.axis(index).row_of(point).is_some_and(|row| {
2250            !matches!(
2251                cursor.at(row).expect("a row never goes back"),
2252                SampleRef::Missing
2253            )
2254        })
2255    }
2256
2257    /// The positions both series carry, as shared runs with a compact row on each side.
2258    ///
2259    /// A merge over the two axes' runs, so the cost is the runs and not the positions between
2260    /// them, and neither side's row is derived by subtracting a start.
2261    fn shared_runs(
2262        &self,
2263        own: usize,
2264        other: &Operand<'a>,
2265        theirs: usize,
2266    ) -> impl Iterator<Item = GridRunPair> + 'a {
2267        self.axis(own).intersect_runs(other.axis(theirs))
2268    }
2269
2270    /// Whether any series is present at each grid point.
2271    fn presence(&self, points: usize) -> Vec<bool> {
2272        let mut presence = vec![false; points];
2273        for index in 0..self.series.len() {
2274            let mut cursor = self.cursor(index);
2275            for (point, row) in self.positions(index) {
2276                if !presence[point]
2277                    && !matches!(
2278                        cursor.at(row).expect("a row never goes back"),
2279                        SampleRef::Missing
2280                    )
2281                {
2282                    presence[point] = true;
2283                }
2284            }
2285        }
2286        presence
2287    }
2288}
2289
2290/// The legacy Info applies only to unsupported histogram arithmetic, not to other reasons a
2291/// supported histogram operation can decline a pair (such as incompatible bucket layouts).
2292fn unsupported_histogram_arithmetic(
2293    op: BinaryOp,
2294    lhs: &SampleRef<'_>,
2295    rhs: &SampleRef<'_>,
2296) -> Option<&'static str> {
2297    let symbol = match op {
2298        BinaryOp::Add => "+",
2299        BinaryOp::Sub => "-",
2300        BinaryOp::Mul => "*",
2301        BinaryOp::Div => "/",
2302        BinaryOp::Mod => "%",
2303        BinaryOp::Pow => "^",
2304        BinaryOp::Atan2 => "atan2",
2305        _ => return None,
2306    };
2307    let unsupported = match (lhs, rhs) {
2308        (SampleRef::Histogram(_), SampleRef::Histogram(_)) => {
2309            !matches!(op, BinaryOp::Add | BinaryOp::Sub)
2310        }
2311        (SampleRef::Histogram(_), SampleRef::Float(_)) => {
2312            !matches!(op, BinaryOp::Mul | BinaryOp::Div)
2313        }
2314        (SampleRef::Float(_), SampleRef::Histogram(_)) => op != BinaryOp::Mul,
2315        _ => false,
2316    };
2317    unsupported.then_some(symbol)
2318}
2319
2320/// Prometheus `vectorElemBinop` over present samples: the value and whether to keep it, or
2321/// `None` when Prometheus reports the pair as an annotation and skips it without counting the
2322/// match: an operator the sample types do not support, or an addition or subtraction of
2323/// histograms that mix exponential and custom buckets or whose counter reset hints contradict.
2324fn elem_binop(
2325    op: BinaryOp,
2326    lhs: SampleRef<'_>,
2327    rhs: SampleRef<'_>,
2328    annotations: Option<&PromqlAnnotationCollector>,
2329) -> Result<Option<(GridSample, bool)>> {
2330    let histogram = |view: &HistogramView<'_>| FloatHistogram::try_from_view(view);
2331    let mut result = match (lhs, rhs) {
2332        (SampleRef::Float(lhs), SampleRef::Float(rhs)) => {
2333            let (value, keep) = op.apply(lhs, rhs);
2334            return Ok(Some((GridSample::Float(value), keep)));
2335        }
2336        (SampleRef::Float(factor), SampleRef::Histogram(h))
2337        | (SampleRef::Histogram(h), SampleRef::Float(factor))
2338            if op == BinaryOp::Mul =>
2339        {
2340            let mut h = histogram(&h)?;
2341            h.mul(factor);
2342            h
2343        }
2344        (SampleRef::Histogram(h), SampleRef::Float(divisor)) if op == BinaryOp::Div => {
2345            let mut h = histogram(&h)?;
2346            h.div(divisor);
2347            h
2348        }
2349        (SampleRef::Histogram(lhs), SampleRef::Histogram(rhs)) => {
2350            let (mut lhs, rhs) = (histogram(&lhs)?, histogram(&rhs)?);
2351            match op {
2352                BinaryOp::Eq | BinaryOp::Ne => {
2353                    let keep = lhs.equals(&rhs) == (op == BinaryOp::Eq);
2354                    return Ok(Some((GridSample::Histogram(Box::new(lhs)), keep)));
2355                }
2356                BinaryOp::Add | BinaryOp::Sub => {
2357                    let name = if op == BinaryOp::Add {
2358                        NativeHistogramAdd::name()
2359                    } else {
2360                        NativeHistogramSub::name()
2361                    };
2362                    // The layouts decide whether there is a pair at all: Prometheus reports a pair
2363                    // whose bucket layouts cannot be combined as that one error, before it looks at
2364                    // the reset hints, so a pair that fails both carries only the schema warning.
2365                    // Synthetic fill samples have no collector here.
2366                    if lhs.uses_custom_buckets() != rhs.uses_custom_buckets() {
2367                        if let Some(collector) = annotations {
2368                            collector.record_warning(format!(
2369                                "{name}: dropped native histogram sample with incompatible schemas"
2370                            ));
2371                        }
2372                        return Ok(None);
2373                    }
2374                    // Prometheus hands the collision back as the operation's error, and a pair that
2375                    // reports one is skipped before its match is counted. A reconciliation the same
2376                    // pair needed goes unreported with it.
2377                    if matches!(
2378                        (lhs.reset_hint, rhs.reset_hint),
2379                        (
2380                            CounterResetHint::CounterReset,
2381                            CounterResetHint::NotCounterReset
2382                        ) | (
2383                            CounterResetHint::NotCounterReset,
2384                            CounterResetHint::CounterReset
2385                        )
2386                    ) {
2387                        if let Some(collector) = annotations {
2388                            collector.record_warning(format!(
2389                                "{name}: native histogram counter reset hints contradict"
2390                            ));
2391                        }
2392                        return Ok(None);
2393                    }
2394                    let outcome = if op == BinaryOp::Add {
2395                        lhs.add(&rhs)?
2396                    } else {
2397                        lhs.sub(&rhs)?
2398                    };
2399                    if outcome.custom_bounds_reconciled
2400                        && let Some(collector) = annotations
2401                    {
2402                        collector.record_info(format!(
2403                            "{name}: reconciled native histograms with different custom buckets"
2404                        ));
2405                    }
2406                    if op == BinaryOp::Sub {
2407                        lhs.reset_hint = CounterResetHint::Gauge;
2408                    }
2409                    lhs
2410                }
2411                _ => return Ok(None),
2412            }
2413        }
2414        _ => return Ok(None),
2415    };
2416    result.compact();
2417    Ok(Some((GridSample::Histogram(Box::new(result)), true)))
2418}
2419
2420/// The result rows of one field by result label set.
2421///
2422/// A pairing opens one [`RowSlot`] and looks its label set up on the first row it files, so the key
2423/// is built, hashed and compared once per pairing that files -- not once per point.
2424#[derive(Default)]
2425struct Results {
2426    series: HashMap<GroupKey, ResultRows>,
2427    /// The figures a filed row advances; see [`ResultTotals`].
2428    totals: ResultTotals,
2429}
2430
2431/// The rows filed, the rows holding a value, the rows holding a histogram and the heap those
2432/// histograms hold: counted as each row is filed, so neither later phase walks them again.
2433///
2434/// Held beside the table rather than in it, so a pairing's open row borrows the table it files into
2435/// while these figures stay free to move with the point.
2436#[derive(Default)]
2437struct ResultTotals {
2438    rows: usize,
2439    kept: usize,
2440    histograms: usize,
2441    histogram_heap: usize,
2442}
2443
2444/// Rows in arrival order: their points, the match group each came from, and their values;
2445/// `None` is a match the operator filtered.
2446struct ResultRows {
2447    metric: SeriesLabels,
2448    points: Vec<usize>,
2449    groups: Vec<usize>,
2450    values: Vec<Option<GridSample>>,
2451}
2452
2453/// Two rows of one result label set at one point.
2454struct Duplicate {
2455    point: usize,
2456    key: GroupKey,
2457    /// Whether two of the rows came from the same match group.
2458    within_group: bool,
2459}
2460
2461fn same_labelset(key: &GroupKey, timestamp: i64) -> String {
2462    format!(
2463        "vector cannot contain metrics with the same labelset {} at {timestamp} ms",
2464        render(key)
2465    )
2466}
2467
2468/// One pairing's result row, opened by the first point the pairing files.
2469///
2470/// A pairing builds its label set once, but the row it files under is looked up, created and
2471/// charged only when that pairing files the first of its points: a pairing whose samples never
2472/// pair, or whose axes do not intersect, costs what it cost before -- nothing. Once open, the row
2473/// is pushed to directly, so the points of one pairing build no key, hash nothing and clone no
2474/// metric.
2475enum RowSlot<'a> {
2476    /// No point filed yet, and the table the first one is filed in.
2477    Unfiled(&'a mut HashMap<GroupKey, ResultRows>),
2478    /// The row every point of this pairing files under.
2479    Row(&'a mut ResultRows),
2480}
2481
2482impl<'a> RowSlot<'a> {
2483    /// Files one row of one field, opening the pairing's row on its first filed point, and returns
2484    /// the slot to file the pairing's next point with.
2485    ///
2486    /// A row whose value the operator filtered is still a row: it keeps its slots and its label
2487    /// set, which the merge carries as a set without a value. A kept histogram is boxed beside its
2488    /// row, so its payload is charged here, where the value is retained, and never per grid point
2489    /// of a float.
2490    #[allow(clippy::too_many_arguments)]
2491    fn file(
2492        self,
2493        totals: &mut ResultTotals,
2494        metric: &SeriesLabels,
2495        label_set: usize,
2496        group: usize,
2497        point: usize,
2498        value: Option<GridSample>,
2499        mut budget: Option<&mut Budget<'_>>,
2500    ) -> Result<Self> {
2501        let rows = match self {
2502            Self::Row(rows) => rows,
2503            Self::Unfiled(series) => match series.entry(key_of(metric)) {
2504                Entry::Occupied(entry) => entry.into_mut(),
2505                Entry::Vacant(entry) => {
2506                    // The label set the row is filed under is only built when the table does not
2507                    // hold it yet, so these bytes are charged on the vacant entry alone.
2508                    if let Some(budget) = budget.as_deref_mut() {
2509                        budget.hold(label_set)?;
2510                    }
2511                    entry.insert(ResultRows {
2512                        metric: metric.clone(),
2513                        points: Vec::new(),
2514                        groups: Vec::new(),
2515                        values: Vec::new(),
2516                    })
2517                }
2518            },
2519        };
2520        // The row vectors grow together, so one block of them is charged once when the point,
2521        // group and value vectors outgrow the capacity they hold.
2522        if rows.points.len() == rows.points.capacity()
2523            && let Some(budget) = budget.as_deref_mut()
2524        {
2525            let grown = (2 * rows.points.capacity()).max(VEC_MIN_CAPACITY);
2526            budget.hold(
2527                grown
2528                    .saturating_sub(rows.points.capacity())
2529                    .saturating_mul(RESULT_ROW_BYTES),
2530            )?;
2531        }
2532        totals.rows = totals.rows.saturating_add(1);
2533        if let Some(value) = &value {
2534            totals.kept = totals.kept.saturating_add(1);
2535            if let GridSample::Histogram(histogram) = value {
2536                totals.histograms = totals.histograms.saturating_add(1);
2537                totals.histogram_heap =
2538                    totals.histogram_heap.saturating_add(histogram.heap_bytes());
2539                if let Some(budget) = budget {
2540                    budget.hold(result_histogram_bytes(histogram))?;
2541                }
2542            }
2543        }
2544        rows.points.push(point);
2545        rows.groups.push(group);
2546        rows.values.push(value);
2547        Ok(Self::Row(rows))
2548    }
2549}
2550
2551impl Results {
2552    /// Sorts the rows of each label set by point and returns the earliest point where a label
2553    /// set has two rows, preferring one within a match group at that point. Prometheus
2554    /// evaluates step by step and fails at the first such step.
2555    fn sort_rows(&mut self) -> Option<Duplicate> {
2556        let mut first: Option<(usize, bool, &GroupKey)> = None;
2557        for (key, rows) in &mut self.series {
2558            if !rows.points.is_sorted() {
2559                let mut order: Vec<usize> = (0..rows.points.len()).collect();
2560                order.sort_by_key(|&row| rows.points[row]);
2561                rows.points = order.iter().map(|&row| rows.points[row]).collect();
2562                rows.groups = order.iter().map(|&row| rows.groups[row]).collect();
2563                let mut values = std::mem::take(&mut rows.values);
2564                rows.values = order.iter().map(|&row| values[row].take()).collect();
2565            }
2566            let mut start = 0;
2567            while start < rows.points.len() {
2568                let point = rows.points[start];
2569                let end = start + rows.points[start..].partition_point(|&p| p == point);
2570                if end - start > 1 {
2571                    let mut groups = rows.groups[start..end].to_vec();
2572                    groups.sort_unstable();
2573                    let within_group = groups.windows(2).any(|pair| pair[0] == pair[1]);
2574                    if first.is_none_or(|(first_point, first_within, _)| {
2575                        (point, !within_group) < (first_point, !first_within)
2576                    }) {
2577                        first = Some((point, within_group, key));
2578                    }
2579                    break;
2580                }
2581                start = end;
2582            }
2583        }
2584        first.map(|(point, within_group, key)| Duplicate {
2585            point,
2586            key: key.clone(),
2587            within_group,
2588        })
2589    }
2590}
2591
2592// The one-field shape's merge against the merge every other shape keeps, on the same results.
2593//
2594// Inline rather than in `tests.rs` so the two merges and their comparison live in one file: the fast
2595// path is shown to write what the grouped, sorted merge writes, on the results both are given.
2596#[cfg(test)]
2597mod merge_shape_tests {
2598    type LabelPairs = Vec<(String, String)>;
2599    type RowValues = Vec<(usize, u64)>;
2600    type HistogramValues = Vec<(usize, [u64; 3])>;
2601    type SeriesRows = (LabelPairs, RowValues);
2602    type SeriesHistograms = (LabelPairs, HistogramValues);
2603    type MergeFn =
2604        fn(Vec<Results>, Arc<SeriesSchema>, Option<&mut Budget<'_>>) -> Result<Vec<Series>>;
2605
2606    use datatypes::series::time::GridSpec;
2607
2608    use super::*;
2609    use crate::grid_series::reference::OwnedHistogram;
2610
2611    /// A grid of twelve points, wide enough for every point the results file.
2612    fn grid() -> Arc<EvalGrid> {
2613        Arc::new(
2614            EvalGrid::try_new(GridSpec::try_new(0, 1_000, 12).expect("valid grid"))
2615                .expect("valid grid"),
2616        )
2617    }
2618
2619    /// The output schema of the one-field shape.
2620    fn schema() -> Arc<SeriesSchema> {
2621        Arc::new(SeriesSchema {
2622            fields: vec![FieldSpec {
2623                name: Arc::from("value"),
2624            }]
2625            .into(),
2626            eval_grid: Some(grid()),
2627        })
2628    }
2629
2630    fn metric(name: &str, host: &str) -> SeriesLabels {
2631        SeriesLabels::try_new(
2632            Some(Arc::from(name)),
2633            vec![Label {
2634                name: Arc::from("host"),
2635                value: Arc::from(host),
2636            }],
2637        )
2638        .expect("valid labels")
2639    }
2640
2641    /// One label set's rows as the field files them: `None` is a sample the operator filtered.
2642    fn result_rows(metric: SeriesLabels, rows: &[(usize, Option<f64>)]) -> ResultRows {
2643        ResultRows {
2644            metric,
2645            points: rows.iter().map(|(point, _)| *point).collect(),
2646            // The merge reads a row's point and value; the match group it came from is the field's
2647            // duplicate evidence, which the field's own sort has already reported.
2648            groups: vec![0; rows.len()],
2649            values: rows
2650                .iter()
2651                .map(|(_, value)| value.map(GridSample::Float))
2652                .collect(),
2653        }
2654    }
2655
2656    /// One label set's histogram rows: `Some` is a histogram in [`OwnedHistogram::parse`]'s format,
2657    /// `None` a sample the operator filtered.
2658    fn histogram_rows(metric: SeriesLabels, rows: &[(usize, Option<&str>)]) -> ResultRows {
2659        ResultRows {
2660            metric,
2661            points: rows.iter().map(|(point, _)| *point).collect(),
2662            groups: vec![0; rows.len()],
2663            values: rows
2664                .iter()
2665                .map(|(_, text)| {
2666                    text.map(|text| {
2667                        GridSample::Histogram(Box::new(
2668                            FloatHistogram::try_from_view(&OwnedHistogram::parse(text).view())
2669                                .expect("the histogram is readable"),
2670                        ))
2671                    })
2672                })
2673                .collect(),
2674        }
2675    }
2676
2677    /// The result table of one field, with the totals its filing advances.
2678    fn field_of(filed: Vec<ResultRows>) -> Results {
2679        let mut results = Results::default();
2680        for rows in filed {
2681            results.totals.rows = results.totals.rows.saturating_add(rows.points.len());
2682            results.totals.kept = results
2683                .totals
2684                .kept
2685                .saturating_add(rows.values.iter().filter(|value| value.is_some()).count());
2686            for value in rows.values.iter().flatten() {
2687                if let GridSample::Histogram(histogram) = value {
2688                    results.totals.histograms = results.totals.histograms.saturating_add(1);
2689                    results.totals.histogram_heap = results
2690                        .totals
2691                        .histogram_heap
2692                        .saturating_add(histogram.heap_bytes());
2693                }
2694            }
2695            results.series.insert(key_of(&rows.metric), rows);
2696        }
2697        results
2698    }
2699
2700    /// The one field's result table: one label set with holes in its points, one starting late, and
2701    /// one whose every sample was filtered.
2702    fn field_results() -> Results {
2703        field_of(vec![
2704            result_rows(
2705                metric("m1", "a"),
2706                &[
2707                    (0, Some(1.5)),
2708                    (1, None),
2709                    (3, Some(3.5)),
2710                    (4, Some(4.5)),
2711                    (7, Some(7.5)),
2712                ],
2713            ),
2714            result_rows(
2715                metric("m2", "b"),
2716                &[(2, Some(2.5)), (5, Some(5.5)), (6, None)],
2717            ),
2718            result_rows(metric("m3", "c"), &[(0, None), (2, None)]),
2719        ])
2720    }
2721
2722    /// Five observations summing to twelve, one of them in the zero bucket.
2723    const FIRST_HISTOGRAM: &str = "0/0/3ff0000000000000/4014000000000000/4028000000000000/0/////";
2724    /// Seven observations summing to twenty, with an empty zero bucket.
2725    const SECOND_HISTOGRAM: &str = "0/0/0/401c000000000000/4034000000000000/0/////";
2726
2727    /// The one field's histogram table: one label set at two points with a hole between them, and
2728    /// one whose every sample was filtered.
2729    fn histogram_results() -> Results {
2730        field_of(vec![
2731            histogram_rows(
2732                metric("h1", "a"),
2733                &[
2734                    (1, Some(FIRST_HISTOGRAM)),
2735                    (2, None),
2736                    (4, Some(SECOND_HISTOGRAM)),
2737                ],
2738            ),
2739            histogram_rows(metric("h2", "b"), &[(0, None), (3, None)]),
2740        ])
2741    }
2742
2743    /// A label set as sorted `(name, value)` pairs.
2744    fn labels(name: &str, host: &str) -> Vec<(String, String)> {
2745        vec![
2746            ("__name__".to_string(), name.to_string()),
2747            ("host".to_string(), host.to_string()),
2748        ]
2749    }
2750
2751    /// The label set of one series, as [`labels`] builds one.
2752    fn series_labels(series: &Series) -> Vec<(String, String)> {
2753        let mut labels: Vec<(String, String)> = series
2754            .metric
2755            .tags()
2756            .iter()
2757            .map(|tag| (tag.name.to_string(), tag.value.to_string()))
2758            .collect();
2759        if let Some(name) = series.metric.name() {
2760            labels.push(("__name__".to_string(), name.to_string()));
2761        }
2762        labels.sort();
2763        labels
2764    }
2765
2766    /// One series as its label set and its rows: the absolute grid position of each row and the bits
2767    /// of the float it holds. A row holding no value is a row neither merge writes.
2768    fn rows_of_series(series: &Series) -> SeriesRows {
2769        let mut cursor = series.fields.as_slice()[0].cursor();
2770        let rows = series
2771            .time
2772            .positions()
2773            .map(|(position, row)| {
2774                match cursor.at(row).expect("the axis and the fields are aligned") {
2775                    SampleRef::Float(value) => (position, value.to_bits()),
2776                    _ => panic!("expected a float sample"),
2777                }
2778            })
2779            .collect();
2780        (series_labels(series), rows)
2781    }
2782
2783    /// The same for a series holding native histograms: the bits of the `(zero_count, count, sum)`
2784    /// each row carries, which is what these fixtures differ in.
2785    fn histograms_of_series(series: &Series) -> SeriesHistograms {
2786        let mut cursor = series.fields.as_slice()[0].cursor();
2787        let rows = series
2788            .time
2789            .positions()
2790            .map(|(position, row)| {
2791                match cursor.at(row).expect("the axis and the fields are aligned") {
2792                    SampleRef::Histogram(view) => {
2793                        let histogram = FloatHistogram::try_from_view(&view)
2794                            .expect("the histogram is readable");
2795                        (
2796                            position,
2797                            [
2798                                histogram.zero_count.to_bits(),
2799                                histogram.count.to_bits(),
2800                                histogram.sum.to_bits(),
2801                            ],
2802                        )
2803                    }
2804                    _ => panic!("expected a histogram sample"),
2805                }
2806            })
2807            .collect();
2808        (series_labels(series), rows)
2809    }
2810
2811    /// Every series, sorted: neither merge promises an order, as both read a label set map.
2812    fn rows_of(series: &[Series]) -> Vec<SeriesRows> {
2813        let mut rows: Vec<_> = series.iter().map(rows_of_series).collect();
2814        rows.sort();
2815        rows
2816    }
2817
2818    /// Every histogram series, sorted the same way.
2819    fn histograms_of(series: &[Series]) -> Vec<SeriesHistograms> {
2820        let mut rows: Vec<_> = series.iter().map(histograms_of_series).collect();
2821        rows.sort();
2822        rows
2823    }
2824
2825    /// The bytes a merge reserved through a budget: the last figure it handed it.
2826    fn reserved_bytes(merge: MergeFn) -> usize {
2827        let reserved = std::cell::Cell::new(0usize);
2828        let mut reserve = |bytes: usize| {
2829            reserved.set(bytes);
2830            Ok(())
2831        };
2832        let mut budget = Budget::new(&mut reserve);
2833        merge(vec![field_results()], schema(), Some(&mut budget)).expect("the merge of one field");
2834        reserved.get()
2835    }
2836
2837    #[test]
2838    fn the_one_field_merge_writes_the_rows_the_multi_field_merge_writes() {
2839        let multi = merge_multi_field(vec![field_results()], schema(), None)
2840            .expect("the multi-field merge of one field");
2841        let single =
2842            merge_single_field(vec![field_results()], schema(), None).expect("the one-field merge");
2843        // A filtered sample writes no row and a label set with no value writes no series, so every
2844        // row here is a sample the field kept, at the point it kept it:
2845        let expected = vec![
2846            (
2847                labels("m1", "a"),
2848                vec![
2849                    (0, 1.5f64.to_bits()),
2850                    (3, 3.5f64.to_bits()),
2851                    (4, 4.5f64.to_bits()),
2852                    (7, 7.5f64.to_bits()),
2853                ],
2854            ),
2855            (
2856                labels("m2", "b"),
2857                vec![(2, 2.5f64.to_bits()), (5, 5.5f64.to_bits())],
2858            ),
2859        ];
2860        assert_eq!(rows_of(&multi), expected);
2861        assert_eq!(rows_of(&single), expected);
2862    }
2863
2864    /// A histogram field is one field: the entry hands it to the fast path, and its histograms come
2865    /// out row by row as the field filed them, boxed payload and hole included.
2866    #[test]
2867    fn a_histogram_field_keeps_its_rows_and_histograms_through_the_one_field_merge() {
2868        let expected = vec![(
2869            labels("h1", "a"),
2870            vec![
2871                (1, [1.0f64.to_bits(), 5.0f64.to_bits(), 12.0f64.to_bits()]),
2872                (4, [0.0f64.to_bits(), 7.0f64.to_bits(), 20.0f64.to_bits()]),
2873            ],
2874        )];
2875        let fast =
2876            merge_fields(vec![histogram_results()], schema(), None).expect("the one field's merge");
2877        let multi = merge_multi_field(vec![histogram_results()], schema(), None)
2878            .expect("the grouped, sorted merge of the same field");
2879        assert_eq!(histograms_of(&multi), expected);
2880        assert_eq!(histograms_of(&fast), expected);
2881    }
2882
2883    /// A label set whose every sample was filtered holds no row, so the merge writes no series for
2884    /// it -- read through the entry, which is what hands a one-field table to the fast path.
2885    #[test]
2886    fn a_fully_filtered_label_set_writes_no_series() {
2887        let filtered = field_of(vec![result_rows(
2888            metric("m9", "z"),
2889            &[(0, None), (1, None)],
2890        )]);
2891        assert_eq!(1, filtered.series.len(), "the field filed the label set");
2892        let merged = merge_fields(vec![filtered], schema(), None).expect("the merge of one field");
2893        assert!(merged.is_empty(), "{merged:?}");
2894    }
2895
2896    /// The two merges bill a one-field result the same: the rows of the samples it keeps. A filtered
2897    /// sample holds no column bytes in either.
2898    #[test]
2899    fn the_one_field_merge_bills_the_rows_the_multi_field_merge_bills() {
2900        let multi = reserved_bytes(merge_multi_field);
2901        let single = reserved_bytes(merge_single_field);
2902        assert!(single > 0, "the one-field merge reserved nothing");
2903        assert_eq!(
2904            multi, single,
2905            "the one-field merge reserved {single} bytes, the multi-field merge {multi}"
2906        );
2907    }
2908
2909    /// The entry admits the merge's phase figure; a column reservation past that limit is refused
2910    /// and the refusal reaches the caller, so no series are handed over.
2911    #[test]
2912    fn a_column_reservation_over_the_limit_reaches_the_caller() {
2913        // The first figure the merge asks for is its phase, entered before it allocates.
2914        let entry = std::cell::Cell::new(None);
2915        let mut record = |total: usize| {
2916            if entry.get().is_none() {
2917                entry.set(Some(total));
2918            }
2919            Ok(())
2920        };
2921        let merged = merge_fields(
2922            vec![field_results()],
2923            schema(),
2924            Some(&mut Budget::new(&mut record)),
2925        )
2926        .expect("the merge of one field under an unbounded budget");
2927        assert!(!merged.is_empty(), "the fixture writes series");
2928        let limit = entry.get().expect("the merge enters its phase figure");
2929        assert!(limit > 0, "the phase figure is what the fixture holds");
2930
2931        // A limit at the phase figure admits the entry and refuses the columns reserved after it.
2932        let mut refused = Vec::new();
2933        let mut reserve = |total: usize| {
2934            if total > limit {
2935                refused.push(total);
2936                return Err(DataFusionError::ResourcesExhausted(format!(
2937                    "the one-field merge needs {total} bytes, more than the {limit} admitted"
2938                )));
2939            }
2940            Ok(())
2941        };
2942        let error = merge_fields(
2943            vec![field_results()],
2944            schema(),
2945            Some(&mut Budget::new(&mut reserve)),
2946        )
2947        .expect_err("a column reservation over the limit is refused");
2948        assert!(
2949            matches!(error, DataFusionError::ResourcesExhausted(_)),
2950            "{error}"
2951        );
2952        assert!(
2953            !refused.is_empty(),
2954            "the refusal is a reservation past the phase figure"
2955        );
2956    }
2957}