Skip to main content

promql/
grid_series.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//! Building evaluated series that cover only their result range on a shared grid.
16
17use std::collections::HashMap;
18use std::collections::hash_map::Entry;
19use std::sync::Arc;
20
21use datafusion::arrow::array::builder::NullBufferBuilder;
22use datafusion::arrow::array::{Array, Float64Array, UInt32Array};
23use datafusion::error::{DataFusionError, Result};
24use datatypes::series::SeriesLabels;
25use datatypes::series::histogram::{HistogramBatch, HistogramBatchBuilder};
26use datatypes::series::samples::{
27    DenseSamplesRef, HistogramSamples, SampleRef, Samples, Series, SeriesFields, SeriesSchema,
28};
29use datatypes::series::time::{EvalGrid, GridSpan, TimeAxis};
30
31use crate::histogram_eval::float_histogram::FloatHistogram;
32
33#[cfg(test)]
34pub(crate) mod reference;
35#[cfg(test)]
36mod tests;
37
38pub(crate) fn series_bytes(series: &Series) -> usize {
39    let runs = series.time.runs().count();
40    let segments: usize = series
41        .fields
42        .iter()
43        .map(|field| field.segments().len())
44        .sum();
45    std::mem::size_of::<Series>()
46        .saturating_add(std::mem::size_of::<TimeAxis>())
47        .saturating_add(runs.saturating_mul(std::mem::size_of::<(usize, usize)>()))
48        .saturating_add(
49            segments.saturating_mul(std::mem::size_of::<Samples>() + std::mem::size_of::<usize>()),
50        )
51        .saturating_add(fields_bytes(&series.fields))
52        .saturating_add(series.metric.name().map_or(0, str::len))
53        .saturating_add(std::mem::size_of_val(series.metric.tags()))
54        .saturating_add(
55            series
56                .metric
57                .tags()
58                .iter()
59                .map(|tag| tag.name.len() + tag.value.len())
60                .sum::<usize>(),
61        )
62}
63
64pub(crate) fn fields_bytes(fields: &SeriesFields) -> usize {
65    fields
66        .iter()
67        .map(|field| {
68            field.segments().iter().fold(0usize, |total, segment| {
69                total.saturating_add(segment_bytes(segment))
70            })
71        })
72        .fold(0usize, usize::saturating_add)
73}
74
75/// The bytes one dense segment of samples holds.
76pub(crate) fn segment_bytes(segment: &Samples) -> usize {
77    match segment.dense() {
78        Some(DenseSamplesRef::Float(values)) => values.get_array_memory_size(),
79        Some(DenseSamplesRef::Histogram(histograms)) => histograms
80            .indices()
81            .get_array_memory_size()
82            .saturating_add(table_bytes(histograms.batch())),
83        Some(DenseSamplesRef::Mixed(mixed)) => mixed
84            .floats()
85            .get_array_memory_size()
86            .saturating_add(mixed.histograms().indices().get_array_memory_size())
87            .saturating_add(table_bytes(mixed.histograms().batch())),
88        // `segments` hands out dense segments only, so a nested chunk never reaches here.
89        None => 0,
90    }
91}
92
93/// The bytes one histogram table holds: the batch struct and the arrays its columns view.
94pub(crate) fn table_bytes(table: &Arc<HistogramBatch>) -> usize {
95    std::mem::size_of::<HistogramBatch>().saturating_add(table.as_arrow().get_array_memory_size())
96}
97
98pub(crate) fn field_builder_bytes(width: usize) -> usize {
99    width.saturating_mul(std::mem::size_of::<FieldBuilder>())
100}
101
102/// Builds one grid series from rows pushed at absolute grid indices.
103///
104/// A push names one position and the value each field holds there. Rows are accumulated
105/// compactly: a row is kept only when at least one field holds a value at that position, so an
106/// empty stretch costs one skipped push and no storage at all. Fields stay row-aligned, so a field
107/// with no value at a retained row still gets a null there; the Arrow layout needs one row per
108/// retained position, and the position does hold a value.
109///
110/// [`GridSeriesBuilder::finish`] hands out all the buffered rows as **one** [`Series`], whose
111/// [`TimeAxis`] names the maximal runs of consecutive positions the rows make up. The rows are not
112/// densified: the axis says where they sit, so a series over two far-apart positions costs two rows
113/// and two spans, not a row per position between them.
114///
115/// A builder serves one series at a time. [`GridSeriesBuilder::begin_series`] starts the next one;
116/// nothing else resets the series state, so [`GridSeriesBuilder::take_buffered`] can hand out the
117/// rows gathered so far and let the same series go on.
118pub struct GridSeriesBuilder {
119    schema: Arc<SeriesSchema>,
120    grid: Arc<EvalGrid>,
121    /// Smallest index the next push may use.
122    next: usize,
123    /// Grid index of each retained row, ascending.
124    ///
125    /// This vector is the only record of where the gaps are, and it says only where rows sit:
126    /// with `V` entries, `F` fields and `k` runs (`k <= V`) the whole series costs `8*F*V` value
127    /// bytes plus validity bits, one `usize` per retained row and `O(k)` run descriptors. Nothing
128    /// is proportional to the positions holding no value.
129    indices: Vec<usize>,
130    /// One row per retained row, per field; empty when nothing is buffered.
131    fields: Vec<FieldBuilder>,
132}
133
134struct FieldBuilder {
135    values: Vec<f64>,
136    nulls: NullBufferBuilder,
137    /// Created at the first histogram value; holds an index per row from then on.
138    histograms: Option<HistogramColumn>,
139}
140
141struct HistogramColumn {
142    batch: HistogramBatchBuilder,
143    indices: Vec<Option<u32>>,
144}
145
146/// A value of [`GridSeriesBuilder::push_samples`].
147pub(crate) enum GridSample {
148    Float(f64),
149    /// Boxed so that buffered float results stay as small as `Option<f64>`.
150    Histogram(Box<FloatHistogram>),
151}
152
153const _: () = assert!(std::mem::size_of::<Option<GridSample>>() == 16);
154
155/// `sample` as an owned value; `None` when missing.
156pub(crate) fn owned(sample: SampleRef<'_>) -> Result<Option<GridSample>> {
157    Ok(match sample {
158        SampleRef::Missing => None,
159        SampleRef::Float(value) => Some(GridSample::Float(value)),
160        SampleRef::Histogram(view) => Some(GridSample::Histogram(Box::new(
161            FloatHistogram::try_from_view(&view)?,
162        ))),
163    })
164}
165
166impl GridSeriesBuilder {
167    /// Creates a builder for series of `schema`, which must have an evaluation grid.
168    pub fn try_new(schema: Arc<SeriesSchema>) -> Result<Self> {
169        let grid = schema.eval_grid.clone().ok_or_else(|| {
170            DataFusionError::Execution("grid series schema requires an evaluation grid".into())
171        })?;
172        Ok(Self {
173            schema,
174            grid,
175            next: 0,
176            indices: Vec::new(),
177            fields: Vec::new(),
178        })
179    }
180
181    /// Reserves capacity for the exact number of valued rows in the next series.
182    ///
183    /// Call after `begin_series` and before its first push. Existing public callers may continue
184    /// to rely on normal growth; callers with a budget can reserve the concrete row capacity first.
185    pub(crate) fn reserve_rows(&mut self, rows: usize) -> Result<()> {
186        self.indices
187            .try_reserve_exact(rows.saturating_sub(self.indices.len()))
188            .map_err(|error| {
189                DataFusionError::Execution(format!("cannot reserve grid row indices: {error}"))
190            })?;
191        if rows == 0 {
192            return Ok(());
193        }
194        if self.fields.is_empty() {
195            self.fields = (0..self.schema.fields.len())
196                .map(|_| FieldBuilder::new(rows))
197                .collect();
198        }
199        for field in &mut self.fields {
200            field
201                .values
202                .try_reserve_exact(rows.saturating_sub(field.values.len()))
203                .map_err(|error| {
204                    DataFusionError::Execution(format!("cannot reserve grid values: {error}"))
205                })?;
206            field.nulls = NullBufferBuilder::new(rows);
207        }
208        Ok(())
209    }
210
211    /// Pushes the field values at absolute grid `index`; `None` is a missing value.
212    ///
213    /// Indices must be strictly increasing; skipped indices are positions that hold no value.
214    pub fn push(&mut self, index: usize, values: &[Option<f64>]) -> Result<()> {
215        if !self.start_row(index, values.len(), values.iter().all(Option::is_none))? {
216            return Ok(());
217        }
218        for (field, value) in self.fields.iter_mut().zip(values) {
219            field.push_float(*value);
220        }
221        Ok(())
222    }
223
224    /// Like [`GridSeriesBuilder::push`], with native histogram values.
225    pub(crate) fn push_samples(
226        &mut self,
227        index: usize,
228        values: &[Option<GridSample>],
229    ) -> Result<()> {
230        if !self.start_row(index, values.len(), values.iter().all(Option::is_none))? {
231            return Ok(());
232        }
233        for (field, value) in self.fields.iter_mut().zip(values) {
234            match value {
235                Some(GridSample::Histogram(h)) => {
236                    let column = field.start_histogram();
237                    column.indices.push(Some(h.push_to(&mut column.batch)?));
238                }
239                Some(GridSample::Float(value)) => field.push_float(Some(*value)),
240                None => field.push_float(None),
241            }
242        }
243        Ok(())
244    }
245
246    /// Like [`GridSeriesBuilder::push_samples`], with the values taken as the fields hand them out.
247    ///
248    /// A histogram value goes into its column straight from the view it was read as: the owned
249    /// form beside this builder exists for the paths that compute a histogram, while a selection
250    /// that only hands a sample on has nothing to compute and copies nothing. The row this writes
251    /// and the row [`GridSeriesBuilder::push_samples`] writes are the same, so a value pushed
252    /// either way leaves the same payload.
253    pub(crate) fn push_refs(&mut self, index: usize, values: &[SampleRef<'_>]) -> Result<()> {
254        if !self.start_row(
255            index,
256            values.len(),
257            values
258                .iter()
259                .all(|value| matches!(value, SampleRef::Missing)),
260        )? {
261            return Ok(());
262        }
263        for (field, value) in self.fields.iter_mut().zip(values) {
264            match value {
265                SampleRef::Histogram(view) => {
266                    let column = field.start_histogram();
267                    column
268                        .indices
269                        .push(Some(column.batch.push(*view).map_err(external)?));
270                }
271                SampleRef::Float(value) => field.push_float(Some(*value)),
272                SampleRef::Missing => field.push_float(None),
273            }
274        }
275        Ok(())
276    }
277
278    /// Validates the row and retains it; returns whether it holds a value to write.
279    fn start_row(&mut self, index: usize, len: usize, empty: bool) -> Result<bool> {
280        if len != self.schema.fields.len() {
281            return Err(DataFusionError::Execution(format!(
282                "grid series row has {len} fields, schema has {}",
283                self.schema.fields.len()
284            )));
285        }
286        if index < self.next || index >= self.grid.spec().len as usize {
287            return Err(DataFusionError::Execution(format!(
288                "grid series index {index} is not increasing or exceeds grid length {}",
289                self.grid.spec().len as usize
290            )));
291        }
292        self.next = index + 1;
293        if empty {
294            // A position holding no value anywhere is not a row: an index absent from `indices`
295            // already says exactly that, so writing it down would only cost storage.
296            return Ok(false);
297        }
298        if self.fields.is_empty() {
299            self.fields = (0..len).map(|_| FieldBuilder::new(0)).collect();
300        }
301        self.indices.push(index);
302        Ok(true)
303    }
304
305    /// Whether rows have been pushed that no caller has taken yet.
306    ///
307    /// Every hand-out drains the buffer, so "rows buffered" and "rows a caller has not taken" are
308    /// the same thing: a `true` here means the next [`Self::finish`] or [`Self::take_buffered`] has
309    /// something to return.
310    pub fn has_pending(&self) -> bool {
311        !self.indices.is_empty()
312    }
313
314    /// Starts the series the following pushes belong to.
315    ///
316    /// This is the only place that resets the series state, so it is the logical-series boundary:
317    /// [`Self::finish`] hands the rows out but resets nothing, and [`Self::take_buffered`]
318    /// deliberately does not reset anything either.
319    ///
320    /// Panics in debug builds when rows are still pending, which means the previous series was
321    /// left unread.
322    pub fn begin_series(&mut self) {
323        debug_assert!(
324            !self.has_pending(),
325            "a new series starts with rows of the previous one still pending"
326        );
327        self.next = 0;
328        self.indices.clear();
329        self.fields.clear();
330    }
331
332    /// Hands out every row buffered so far as one series, without ending the series.
333    ///
334    /// This is a prefix flush: the rows pushed since the last hand-out become one [`Series`] whose
335    /// axis names the runs they make up. `None` means nothing is buffered, and the caller may push
336    /// more rows. Later pushes still belong to the same logical series, so the caller keeps the
337    /// metric and reads the next hand-out as a continuation rather than as a new series.
338    ///
339    /// Nothing is reset: not the metric, not the index cursor, not the position order. A caller
340    /// that wants a new series calls [`Self::begin_series`].
341    pub fn take_buffered(&mut self, metric: SeriesLabels) -> Result<Option<Series>> {
342        self.collect(metric)
343    }
344
345    /// Returns the series the pushed rows make up: one [`Series`] over the runs of consecutive
346    /// positions that hold a value, or `None` when no retained row holds one.
347    ///
348    /// The rows share the one buffer per field, so the result costs a span per run and not a row
349    /// per position between the runs. This ends the logical series; the next one starts with
350    /// [`Self::begin_series`], which is the only reset.
351    pub fn finish(&mut self, metric: SeriesLabels) -> Result<Option<Series>> {
352        self.collect(metric)
353    }
354
355    /// Turns the buffered rows into one series over the runs they make up.
356    fn collect(&mut self, metric: SeriesLabels) -> Result<Option<Series>> {
357        if self.indices.is_empty() {
358            return Ok(None);
359        }
360        let fields = std::mem::take(&mut self.fields);
361        let indices = std::mem::take(&mut self.indices);
362        let mut samples = Vec::new();
363        samples.try_reserve_exact(fields.len()).map_err(|error| {
364            DataFusionError::Execution(format!("cannot reserve grid field descriptions: {error}"))
365        })?;
366        for mut field in fields {
367            let floats = Float64Array::new(field.values.into(), field.nulls.finish());
368            let sample = if let Some(column) = field.histograms {
369                let batch = column.batch.finish().map_err(external)?;
370                let histograms =
371                    HistogramSamples::try_new(UInt32Array::from(column.indices), batch)
372                        .map_err(external)?;
373                Samples::try_from_mixed(floats, histograms).map_err(external)?
374            } else {
375                Samples::from_float(floats)
376            };
377            samples.push(sample);
378        }
379        let fields = SeriesFields::try_from_vec(samples).map_err(external)?;
380        // The runs are all the axis has to remember about the gaps, and the rows are already
381        // compact, so no position holding no value is visited or stored.
382        let run_count = count_runs(&indices);
383        let spans = spans_of(&indices, run_count)?;
384        let time = TimeAxis::from_grid_spans(self.grid.clone(), spans).map_err(external)?;
385        Series::try_new(&self.schema, metric, time, fields)
386            .map(Some)
387            .map_err(external)
388    }
389}
390
391/// Cuts the retained indices into maximal runs of consecutive positions.
392fn count_runs(indices: &[usize]) -> usize {
393    indices
394        .windows(2)
395        .filter(|pair| pair[1] != pair[0] + 1)
396        .count()
397        .saturating_add(usize::from(!indices.is_empty()))
398}
399
400fn spans_of(indices: &[usize], runs: usize) -> Result<Vec<GridSpan>> {
401    let mut spans: Vec<GridSpan> = Vec::new();
402    spans.try_reserve_exact(runs).map_err(|error| {
403        DataFusionError::Execution(format!("cannot reserve grid spans: {error}"))
404    })?;
405    let mut start = 0;
406    while let Some(&position) = indices.get(start) {
407        let mut len = 1;
408        while indices.get(start + len) == Some(&(position + len)) {
409            len += 1;
410        }
411        spans.push(GridSpan::new(position, len));
412        start += len;
413    }
414    Ok(spans)
415}
416
417impl FieldBuilder {
418    fn new(rows: usize) -> Self {
419        Self {
420            values: Vec::new(),
421            nulls: NullBufferBuilder::new(rows),
422            histograms: None,
423        }
424    }
425
426    fn push_float(&mut self, value: Option<f64>) {
427        self.values.push(value.unwrap_or_default());
428        self.nulls.append(value.is_some());
429        if let Some(column) = &mut self.histograms {
430            column.indices.push(None);
431        }
432    }
433
434    /// Writes the value columns of a row holding a histogram, opening the histogram column if this
435    /// is its first value, and hands back the column the new row's index still goes into.
436    fn start_histogram(&mut self) -> &mut HistogramColumn {
437        self.values.push(0.0);
438        self.nulls.append(false);
439        let rows = self.values.len() - 1;
440        self.histograms.get_or_insert_with(|| HistogramColumn {
441            batch: HistogramBatchBuilder::new(),
442            indices: vec![None; rows],
443        })
444    }
445}
446
447/// Prometheus `schema.IsMetadataLabel`: the labels removed with the metric name.
448pub(crate) const METADATA_LABELS: [&str; 3] = ["__name__", "__type__", "__unit__"];
449
450pub(crate) type LabelSet = Vec<(Arc<str>, Arc<str>)>;
451
452/// A label set as Prometheus prints one in errors: `{name="value", ...}`.
453pub(crate) fn render_label_set(labels: &LabelSet) -> String {
454    let labels: Vec<String> = labels
455        .iter()
456        .map(|(name, value)| format!("{name}=\"{value}\""))
457        .collect();
458    format!("{{{}}}", labels.join(", "))
459}
460
461/// The label set Prometheus compares, which has no empty values.
462pub(crate) fn label_set(metric: &SeriesLabels) -> LabelSet {
463    let name = metric
464        .name()
465        .filter(|name| !name.is_empty())
466        .map(|name| (Arc::from("__name__"), Arc::from(name)));
467    name.into_iter()
468        .chain(
469            metric
470                .tags()
471                .iter()
472                .filter(|tag| !tag.value.is_empty())
473                .map(|tag| (tag.name.clone(), tag.value.clone())),
474        )
475        .collect()
476}
477
478/// Merges series that share a label set into one, as Prometheus does after a function that
479/// rewrites labels or drops `__name__`; two of them holding one field at one point fail, whether
480/// the samples are floats or native histograms.
481///
482/// The merge rearranges the payloads instead of rewriting them: a merged row takes the value its
483/// member carries at that position -- a float, a NaN, or a native histogram -- and a field another
484/// field's row does not fill keeps a null there. The values keep their storage: a run of rows one
485/// member holds in one dense segment is handed out as a [`Samples::slice`] of that segment, so a
486/// histogram table is shared rather than copied. The result costs one row per position holding a
487/// value, plus the rows the other fields fill, and nothing for a position of the grid holding none.
488pub fn merge_same_labelset(schema: &Arc<SeriesSchema>, series: Vec<Series>) -> Result<Vec<Series>> {
489    let mut groups: HashMap<LabelSet, Vec<usize>> = HashMap::with_capacity(series.len());
490    let mut collided = false;
491    for (index, series) in series.iter().enumerate() {
492        match groups.entry(label_set(&series.metric)) {
493            Entry::Occupied(mut entry) => {
494                entry.get_mut().push(index);
495                collided = true;
496            }
497            Entry::Vacant(entry) => {
498                entry.insert(vec![index]);
499            }
500        }
501    }
502    if !collided {
503        return Ok(series);
504    }
505
506    // The merged axis and the fields placed on it are the schema's grid: a member of another grid
507    // would land its rows at positions naming other timestamps.
508    let grid = schema.eval_grid.clone().ok_or_else(|| {
509        DataFusionError::Execution("grid series schema requires an evaluation grid".into())
510    })?;
511    let mut series: Vec<Option<Series>> = series.into_iter().map(Some).collect();
512    let mut output = Vec::with_capacity(groups.len());
513    // The groups in the order their first member arrived: a `HashMap` would hand the merged series
514    // back in an order that changes between runs, and the root's chunk stream exposes exactly this
515    // order, so two executions of one query could report their series differently.
516    let mut groups: Vec<(LabelSet, Vec<usize>)> = groups.into_iter().collect();
517    groups.sort_unstable_by_key(|(_, members)| members[0]);
518    // `(absolute position, member slot, compact row)`, sorted by position before merging. The slot
519    // indexes the group's fragments, so a row names its member without a search.
520    let mut rows: Vec<(usize, usize, usize)> = Vec::new();
521    // The position of each merged row, ascending, with the positions several fragments share held
522    // once.
523    let mut positions: Vec<usize> = Vec::new();
524    for (labels, members) in groups {
525        if let [member] = members[..] {
526            output.extend(series[member].take());
527            continue;
528        }
529        // Validate every fragment before indexing it: the merge reads its fields and places its
530        // rows on the schema's grid.
531        let mut fragments: Vec<&Series> = Vec::with_capacity(members.len());
532        for &member in &members {
533            let fragment = series[member].as_ref().ok_or_else(|| {
534                DataFusionError::Execution("each series is in exactly one label set".into())
535            })?;
536            let Some(fragment_grid) = fragment.time.grid() else {
537                return Err(DataFusionError::Execution(
538                    "merging requires evaluated series".into(),
539                ));
540            };
541            if fragment_grid.spec() != grid.spec() {
542                return Err(DataFusionError::Execution(
543                    "merging requires one evaluation grid".into(),
544                ));
545            }
546            if fragment.fields.len() != schema.fields.len() {
547                return Err(DataFusionError::Execution(format!(
548                    "merging requires {} fields, a fragment holds {}",
549                    schema.fields.len(),
550                    fragment.fields.len()
551                )));
552            }
553            // The alignment is checked before a row is read: a field of another length would either
554            // run off the axis or leave values the axis never reaches.
555            let time_len = fragment.time.len();
556            if let Some((field, samples)) = fragment
557                .fields
558                .iter()
559                .enumerate()
560                .find(|(_, samples)| samples.len() != time_len)
561            {
562                return Err(DataFusionError::Execution(format!(
563                    "merging requires every field to hold the {time_len} rows of its axis, field \
564                     {field} holds {}",
565                    samples.len()
566                )));
567            }
568            fragments.push(fragment);
569        }
570        rows.clear();
571        for (member_slot, fragment) in fragments.iter().enumerate() {
572            // One forward reader per field: the axis names the rows that exist, and a row holding
573            // no value in any field is not a merged row.
574            let mut readers: Vec<FieldReader<'_>> =
575                fragment.fields.iter().map(FieldReader::new).collect();
576            for (position, row) in fragment.time.positions() {
577                let mut present = false;
578                for reader in &mut readers {
579                    let (segment, offset) = reader.locate(row)?;
580                    present |= !matches!(segment.sample(offset), SampleRef::Missing);
581                }
582                if present {
583                    rows.push((position, member_slot, row));
584                }
585            }
586        }
587        // By position, then by member slot: the slots follow the order the fragments were collected
588        // in, so a member's rows only go forward and its readers never go back.
589        rows.sort_unstable();
590        positions.clear();
591        positions.extend(rows.iter().map(|&(position, _, _)| position));
592        positions.dedup();
593        let mut fields = Vec::with_capacity(schema.fields.len());
594        for field in 0..schema.fields.len() {
595            let mut readers: Vec<FieldReader<'_>> = fragments
596                .iter()
597                .map(|fragment| FieldReader::new(&fragment.fields.as_slice()[field]))
598                .collect();
599            fields.push(merge_field(&mut readers, &rows, &labels)?);
600        }
601        // The runs are all the axis remembers about the holes, so a sparse merge stores one span
602        // per run and no row for the positions between them.
603        let time =
604            TimeAxis::from_grid_spans(grid.clone(), spans_of(&positions, count_runs(&positions))?)
605                .map_err(external)?;
606        let fields = SeriesFields::try_from_vec(fields).map_err(external)?;
607        // The first fragment names the output, as it always has: a label set ignores empty values,
608        // so the metric of the first member is the one the merged series keeps.
609        let metric = fragments[0].metric.clone();
610        output.push(Series::try_new(schema, metric, time, fields).map_err(external)?);
611    }
612    Ok(output)
613}
614
615/// Builds one field of the merged series, one sample per merged row.
616///
617/// The rows are walked in output order. A row holding a value of this field in one member continues
618/// the run of rows that member holds in one dense segment, and a run is handed out as one
619/// [`Samples::slice`]; the rows another field fills become one null run, so the field stays aligned
620/// with the merged axis while sharing the values it carries.
621fn merge_field(
622    readers: &mut [FieldReader<'_>],
623    rows: &[(usize, usize, usize)],
624    labels: &LabelSet,
625) -> Result<Samples> {
626    let mut chunks: Vec<Samples> = Vec::new();
627    // The run of values the last merged row continued, if any.
628    let mut run: Option<FieldRun<'_>> = None;
629    // Merged rows this field leaves empty, waiting for the null run that carries them.
630    let mut missing = 0;
631    let mut start = 0;
632    while start < rows.len() {
633        let position = rows[start].0;
634        let mut end = start;
635        // At most one member may hold this field here; the second value is the collision Prometheus
636        // rejects, since the two label sets became one.
637        let mut value: Option<(usize, &Samples, usize)> = None;
638        while end < rows.len() && rows[end].0 == position {
639            let (_, member, row) = rows[end];
640            let (segment, offset) = readers[member].locate(row)?;
641            if !matches!(segment.sample(offset), SampleRef::Missing) {
642                if value.is_some() {
643                    let labels: Vec<_> = labels
644                        .iter()
645                        .map(|(name, value)| format!("{name}=\"{value}\""))
646                        .collect();
647                    return Err(DataFusionError::Execution(format!(
648                        "vector cannot contain metrics with the same labelset {{{}}}",
649                        labels.join(", ")
650                    )));
651                }
652                value = Some((member, segment, offset));
653            }
654            end += 1;
655        }
656        match value {
657            Some((member, segment, offset)) => {
658                if let Some(run) = &mut run
659                    && run.continues(member, segment, offset)
660                {
661                    run.len += 1;
662                } else {
663                    if let Some(run) = run.take() {
664                        run.push(&mut chunks)?;
665                    }
666                    push_missing(&mut chunks, &mut missing);
667                    run = Some(FieldRun {
668                        member,
669                        segment,
670                        offset,
671                        len: 1,
672                    });
673                }
674            }
675            None => {
676                if let Some(run) = run.take() {
677                    run.push(&mut chunks)?;
678                }
679                missing += 1;
680            }
681        }
682        start = end;
683    }
684    if let Some(run) = run {
685        run.push(&mut chunks)?;
686    }
687    push_missing(&mut chunks, &mut missing);
688    Samples::try_from_chunks(chunks).map_err(external)
689}
690
691/// A run of merged rows one member field fills out of one dense segment, without copying values.
692///
693/// The run grows only while the next merged row is the same member's next row in the same segment,
694/// so handing it out is one [`Samples::slice`] of that segment: the payload stays where it is, and
695/// the rows a hole skipped are not part of the run.
696struct FieldRun<'a> {
697    /// The member slot the run reads, which indexes the [`FieldReader`]s of the field.
698    member: usize,
699    /// The dense segment holding the run's values.
700    segment: &'a Samples,
701    /// Offset of the run's first row inside `segment`.
702    offset: usize,
703    /// How many rows of `segment` the run covers.
704    len: usize,
705}
706
707impl FieldRun<'_> {
708    /// Returns whether the value at `offset` of `segment` continues the run: the same member's next
709    /// row in the same dense segment.
710    fn continues(&self, member: usize, segment: &Samples, offset: usize) -> bool {
711        self.member == member
712            && std::ptr::eq(self.segment, segment)
713            && self.offset + self.len == offset
714    }
715
716    /// Pushes the run as one slice of its dense segment.
717    fn push(self, chunks: &mut Vec<Samples>) -> Result<()> {
718        chunks.push(
719            self.segment
720                .slice(self.offset, self.len)
721                .map_err(external)?,
722        );
723        Ok(())
724    }
725}
726
727/// Reads one field's rows by locating the dense segment each row sits in.
728///
729/// [`Samples::sample`] rescans a chunked field from its first segment on every row, so reading a
730/// field row by row would cost a scan over the segments before it. The rows a merge reads only go
731/// forward, so this walks the segments once and returns the segment with the offset of the row
732/// inside it, which is what a [`FieldRun`] slices.
733struct FieldReader<'a> {
734    segments: &'a [Samples],
735    /// Index of the segment `start` belongs to.
736    segment: usize,
737    /// Logical row the current segment starts at.
738    start: usize,
739}
740
741impl<'a> FieldReader<'a> {
742    /// Creates a reader at the first row of `samples`.
743    fn new(samples: &'a Samples) -> Self {
744        Self {
745            segments: samples.segments(),
746            segment: 0,
747            start: 0,
748        }
749    }
750
751    /// Returns the dense segment holding `row` and the offset of `row` inside it.
752    ///
753    /// Rows must not go backwards. A row past the field is an error rather than a panic: a member is
754    /// only read after its fields are validated to align with its axis.
755    fn locate(&mut self, row: usize) -> Result<(&'a Samples, usize)> {
756        while let Some(segment) = self.segments.get(self.segment) {
757            if let Some(offset) = row
758                .checked_sub(self.start)
759                .filter(|offset| *offset < segment.len())
760            {
761                return Ok((segment, offset));
762            }
763            self.segment += 1;
764            self.start += segment.len();
765        }
766        Err(DataFusionError::Execution(
767            "merging requires each field to be row-aligned with its time axis".into(),
768        ))
769    }
770}
771
772/// Pushes the merged rows a field leaves empty as one null run.
773fn push_missing(chunks: &mut Vec<Samples>, missing: &mut usize) {
774    if *missing != 0 {
775        chunks.push(Samples::from_float(Float64Array::new_null(*missing)));
776        *missing = 0;
777    }
778}
779
780pub(crate) fn external(error: datatypes::error::Error) -> DataFusionError {
781    DataFusionError::External(Box::new(error))
782}