Skip to main content

datatypes/series/
time.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
15use std::borrow::Cow;
16use std::sync::Arc;
17
18use arrow::buffer::ScalarBuffer;
19use once_cell::sync::OnceCell;
20use serde::{Deserialize, Serialize};
21use snafu::OptionExt;
22
23use crate::error::{InvalidSeriesSnafu, Result};
24
25#[cfg(test)]
26mod tests;
27
28/// Value description of a non-empty, fixed-step evaluation grid.
29///
30/// The serde form is the wire form a series frame writes under `greptime.series.grid`: field names
31/// in declaration order, no optional members. Two nodes compare that text byte for byte, so the
32/// only place that spells it is a series frame's own grid metadata entry.
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(deny_unknown_fields)]
35pub struct GridSpec {
36    /// First evaluation timestamp in milliseconds.
37    pub start_ms: i64,
38    /// Positive time step in milliseconds.
39    pub step_ms: i64,
40    /// Number of evaluation points.
41    pub len: u64,
42}
43
44impl GridSpec {
45    /// Creates a validated grid specification.
46    pub fn try_new(start_ms: i64, step_ms: i64, len: u64) -> Result<Self> {
47        if step_ms <= 0 || len == 0 {
48            return invalid("grid step must be positive and grid length nonzero");
49        }
50        let Some(last) = ((len - 1) as i128)
51            .checked_mul(step_ms as i128)
52            .and_then(|offset| (start_ms as i128).checked_add(offset))
53        else {
54            return invalid("grid timestamp overflows i128");
55        };
56        let Ok(platform_len) = usize::try_from(len) else {
57            return invalid("grid timestamp or length overflows supported range");
58        };
59        if i64::try_from(last).is_err()
60            || platform_len
61                .checked_mul(std::mem::size_of::<i64>())
62                .is_none()
63        {
64            return invalid("grid timestamp or length overflows supported range");
65        }
66        Ok(Self {
67            start_ms,
68            step_ms,
69            len,
70        })
71    }
72
73    /// Creates a grid for an inclusive query range, retaining the last point not after end.
74    pub fn try_from_range(start_ms: i64, end_ms: i64, step_ms: i64) -> Result<Self> {
75        if step_ms <= 0 || end_ms < start_ms {
76            return invalid("invalid inclusive grid range or step");
77        }
78        let len = ((end_ms as i128 - start_ms as i128) / step_ms as i128) + 1;
79        Self::try_new(
80            start_ms,
81            step_ms,
82            u64::try_from(len).map_err(|_| invalid_series("grid length overflow"))?,
83        )
84    }
85}
86
87/// A lazily materialized, shareable timestamp grid.
88#[derive(Debug)]
89pub struct EvalGrid {
90    spec: GridSpec,
91    timestamps: OnceCell<ScalarBuffer<i64>>,
92}
93impl serde::Serialize for EvalGrid {
94    fn serialize<S: serde::Serializer>(
95        &self,
96        serializer: S,
97    ) -> std::result::Result<S::Ok, S::Error> {
98        self.spec.serialize(serializer)
99    }
100}
101impl<'de> serde::Deserialize<'de> for EvalGrid {
102    fn deserialize<D: serde::Deserializer<'de>>(
103        deserializer: D,
104    ) -> std::result::Result<Self, D::Error> {
105        let spec = GridSpec::deserialize(deserializer)?;
106        Self::try_deferred(spec).map_err(serde::de::Error::custom)
107    }
108}
109
110impl PartialEq for EvalGrid {
111    fn eq(&self, other: &Self) -> bool {
112        self.spec == other.spec
113    }
114}
115impl Eq for EvalGrid {}
116impl std::hash::Hash for EvalGrid {
117    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
118        self.spec.start_ms.hash(state);
119        self.spec.step_ms.hash(state);
120        self.spec.len.hash(state)
121    }
122}
123
124impl EvalGrid {
125    /// Allocates the grid timestamps once for sharing across result series.
126    pub fn try_new(spec: GridSpec) -> Result<Self> {
127        let grid = Self::try_deferred(spec)?;
128        grid.timestamps()?;
129        Ok(grid)
130    }
131
132    /// Creates a validated grid without allocating its timestamp array.
133    pub fn try_deferred(spec: GridSpec) -> Result<Self> {
134        let spec = GridSpec::try_new(spec.start_ms, spec.step_ms, spec.len)?;
135        Ok(Self {
136            spec,
137            timestamps: OnceCell::new(),
138        })
139    }
140
141    /// Returns the value specification.
142    pub fn spec(&self) -> GridSpec {
143        self.spec
144    }
145
146    /// Returns the shared timestamp buffer, materializing it on first access.
147    pub fn timestamps(&self) -> Result<&ScalarBuffer<i64>> {
148        self.timestamps.get_or_try_init(|| {
149            let len = usize::try_from(self.spec.len)
150                .map_err(|_| invalid_series("grid length overflows usize"))?;
151            Ok(self.gather_timestamps(0, len)?.into())
152        })
153    }
154
155    /// Whether the whole timestamp array exists already.
156    ///
157    /// A consumer that pays for the array -- an execution reserving what it is about to allocate --
158    /// asks this before it materializes a grid: a grid that is already materialized was charged to
159    /// whoever materialized it, and a second consumer must not charge it again.
160    pub fn is_materialized(&self) -> bool {
161        self.timestamps.get().is_some()
162    }
163
164    /// Returns the timestamps of the positions `start..start + len` as an array of their own,
165    /// leaving the grid unmaterialized.
166    ///
167    /// Every value is [`Self::timestamp_at`]'s, in position order, so gathering a window of the
168    /// grid costs its own length and not the length of the grid it is cut from.
169    fn gather_timestamps(&self, start: usize, len: usize) -> Result<Vec<i64>> {
170        let mut values = Vec::new();
171        values
172            .try_reserve_exact(len)
173            .map_err(|_| invalid_series("grid timestamp allocation failed"))?;
174        let end = start.checked_add(len).context(InvalidSeriesSnafu {
175            reason: "grid range overflow".to_string(),
176        })?;
177        for position in start..end {
178            let Some(timestamp) = self.timestamp_at(position) else {
179                return invalid("grid range exceeds its grid");
180            };
181            values.push(timestamp);
182        }
183        Ok(values)
184    }
185
186    fn timestamp_at(&self, position: usize) -> Option<i64> {
187        if position as u64 >= self.spec.len {
188            return None;
189        }
190        let timestamp =
191            (self.spec.start_ms as i128) + (position as i128) * (self.spec.step_ms as i128);
192        // GridSpec validation bounds every position, and i128 holds usize * i64.
193        Some(timestamp as i64)
194    }
195}
196
197/// A contiguous range referencing a shared evaluation grid.
198#[derive(Clone, Debug)]
199pub struct GridRange {
200    grid: Arc<EvalGrid>,
201    start: usize,
202    len: usize,
203}
204
205impl GridRange {
206    /// Creates a checked subrange; an empty range may begin at the grid end.
207    pub fn try_new(grid: Arc<EvalGrid>, start: usize, len: usize) -> Result<Self> {
208        let end = start.checked_add(len).context(InvalidSeriesSnafu {
209            reason: "grid range overflow".to_string(),
210        })?;
211        if end
212            > usize::try_from(grid.spec.len)
213                .map_err(|_| invalid_series("grid length overflows usize"))?
214        {
215            return invalid("grid range exceeds its grid");
216        }
217        Ok(Self { grid, start, len })
218    }
219
220    /// Returns the shared grid.
221    pub fn grid(&self) -> &Arc<EvalGrid> {
222        &self.grid
223    }
224    /// Returns the start index in the grid.
225    pub fn start(&self) -> usize {
226        self.start
227    }
228    /// Returns the range length.
229    pub fn len(&self) -> usize {
230        self.len
231    }
232    /// Returns whether this range is empty.
233    pub fn is_empty(&self) -> bool {
234        self.len == 0
235    }
236    /// Returns the timestamps of the positions this range names.
237    ///
238    /// A range covering the whole grid shares the grid's array, which that grid has to materialize
239    /// for any reader of all of it. A range cut out of a larger grid computes the `len` timestamps
240    /// it names instead, each one [`EvalGrid::timestamp_at`]'s for its position: reading a window
241    /// out of a large grid costs the window's rows, and leaves a deferred grid deferred.
242    pub fn timestamps(&self) -> Result<ScalarBuffer<i64>> {
243        if self.covers_grid() {
244            return Ok(self.grid.timestamps()?.clone());
245        }
246        Ok(self.grid.gather_timestamps(self.start, self.len)?.into())
247    }
248
249    /// Whether this range names every position of its grid.
250    fn covers_grid(&self) -> bool {
251        self.start == 0 && u64::try_from(self.len).is_ok_and(|len| len == self.grid.spec.len)
252    }
253}
254
255impl PartialEq for GridRange {
256    fn eq(&self, other: &Self) -> bool {
257        self.grid.spec == other.grid.spec && self.start == other.start && self.len == other.len
258    }
259}
260impl Eq for GridRange {}
261
262/// One contiguous run of positions on a shared evaluation grid.
263///
264/// The span is half-open: it names the absolute grid indices `start..start + len`. A span is
265/// never empty, so `start + len - 1` is always its last position.
266#[derive(Clone, Copy, Debug, PartialEq, Eq)]
267pub struct GridSpan {
268    start: usize,
269    len: usize,
270}
271
272// A span is never empty (the checked constructors reject a zero length), so there is no
273// `is_empty` to pair with `len`.
274#[allow(clippy::len_without_is_empty)]
275impl GridSpan {
276    /// Creates a span of `len` positions starting at absolute grid index `start`.
277    ///
278    /// [`TimeAxis::from_grid_spans`] validates it against its grid; this constructor only records
279    /// it.
280    pub fn new(start: usize, len: usize) -> Self {
281        Self { start, len }
282    }
283
284    /// Absolute grid index of the first position.
285    pub fn start(&self) -> usize {
286        self.start
287    }
288    /// Number of positions in the span.
289    pub fn len(&self) -> usize {
290        self.len
291    }
292}
293
294/// Several ordered, non-overlapping runs of one shared evaluation grid.
295///
296/// The runs are the rows an axis carries: everything outside them holds no value, so an axis over
297/// a few scattered positions costs a few spans instead of a row per empty position. The spans are
298/// strictly increasing and never overlap (`prev.start + prev.len <= next.start`); they may sit
299/// next to each other, and nothing is stored between them.
300///
301/// An axis with no rows is an empty span list that still carries its grid, so a consumer can tell
302/// "nothing here" from "not on a grid".
303#[derive(Clone, Debug)]
304pub struct GridRanges {
305    grid: Arc<EvalGrid>,
306    /// The runs, in absolute grid order; no span is empty.
307    spans: Arc<[GridSpan]>,
308    /// Compact row of each span's first row, parallel to `spans`: prefix sums of the lengths,
309    /// kept so that compact-row lookups need a binary search and not a scan.
310    rows: Arc<[usize]>,
311    /// Number of carried rows, cached so that [`Self::len`] never walks the spans.
312    len: usize,
313}
314
315// `len` is the number of carried rows; "carries no row" is answered by `TimeAxis::is_empty`.
316#[allow(clippy::len_without_is_empty)]
317impl GridRanges {
318    /// Creates a validated list of runs over `grid`.
319    ///
320    /// Rejects an empty span, a span past the end of the grid, spans that are out of order or
321    /// overlap, and any length or index that overflows `usize`.
322    ///
323    /// Not public: a list of one span is not normalized into the single run a [`TimeAxis`] fast
324    /// path expects, so callers outside this crate build axes through
325    /// [`TimeAxis::from_grid_spans`], which keeps [`TimeAxis::Grid`] for a single span.
326    pub(crate) fn try_new(grid: Arc<EvalGrid>, spans: Vec<GridSpan>) -> Result<Self> {
327        let grid_len = usize::try_from(grid.spec.len)
328            .map_err(|_| invalid_series("grid length overflows usize"))?;
329        let mut rows = Vec::new();
330        rows.try_reserve_exact(spans.len())
331            .map_err(|_| invalid_series("grid span allocation failed"))?;
332        let mut len = 0usize;
333        let mut previous_end: Option<usize> = None;
334        for span in &spans {
335            if span.len == 0 {
336                return invalid("grid spans must not be empty");
337            }
338            let end = span
339                .start
340                .checked_add(span.len)
341                .context(InvalidSeriesSnafu {
342                    reason: "grid span overflow".to_string(),
343                })?;
344            if end > grid_len {
345                return invalid("grid span exceeds its grid");
346            }
347            if previous_end.is_some_and(|previous_end| span.start < previous_end) {
348                return invalid("grid spans must be ordered and must not overlap");
349            }
350            rows.push(len);
351            len = len.checked_add(span.len).context(InvalidSeriesSnafu {
352                reason: "grid span length overflow".to_string(),
353            })?;
354            previous_end = Some(end);
355        }
356        Ok(Self {
357            grid,
358            spans: spans.into(),
359            rows: rows.into(),
360            len,
361        })
362    }
363
364    /// Creates an axis over `grid` that carries no row.
365    pub fn empty(grid: Arc<EvalGrid>) -> Self {
366        Self {
367            grid,
368            spans: Arc::from([]),
369            rows: Arc::from([]),
370            len: 0,
371        }
372    }
373
374    /// Returns the shared grid the spans refer to.
375    pub fn grid(&self) -> &Arc<EvalGrid> {
376        &self.grid
377    }
378
379    /// Returns the number of carried rows, not the distance from the first to the last position.
380    pub fn len(&self) -> usize {
381        self.len
382    }
383
384    /// Maps an absolute grid position to its compact row, or `None` when it holds no row.
385    ///
386    /// Binary search over the span starts: a point lookup never scans.
387    pub fn row_of(&self, position: usize) -> Option<usize> {
388        let index = self
389            .spans
390            .partition_point(|span| span.start <= position)
391            .checked_sub(1)?;
392        let span = self.spans[index];
393        let offset = position - span.start;
394        (offset < span.len).then(|| self.rows[index] + offset)
395    }
396
397    /// Returns the span holding compact row `index`, with the offset of the row inside it.
398    fn span_of(&self, index: usize) -> Option<(GridSpan, usize)> {
399        let span_index = self
400            .rows
401            .partition_point(|&row| row <= index)
402            .checked_sub(1)?;
403        let span = self.spans[span_index];
404        let offset = index - self.rows[span_index];
405        (offset < span.len).then_some((span, offset))
406    }
407
408    /// Returns the span that starts at or after compact row `index`, as an index into `spans`.
409    fn span_index_at(&self, index: usize) -> usize {
410        self.rows
411            .partition_point(|&row| row <= index)
412            .saturating_sub(1)
413    }
414
415    /// The spans covering compact rows `offset..offset + len`, renumbered from zero.
416    fn spans_between(&self, offset: usize, len: usize) -> Vec<GridSpan> {
417        let end = offset + len;
418        let mut sliced = Vec::new();
419        for index in self.span_index_at(offset)..self.spans.len() {
420            let row = self.rows[index];
421            if row >= end {
422                break;
423            }
424            let span = self.spans[index];
425            let from = offset.max(row) - row;
426            let to = (end - row).min(span.len);
427            if from < to {
428                sliced.push(GridSpan::new(span.start + from, to - from));
429            }
430        }
431        sliced
432    }
433
434    /// The absolute position of compact row `offset`, or the position after the last row when
435    /// `offset` is one past the end; `None` when the axis carries no row at all.
436    fn position_at(&self, offset: usize) -> Option<usize> {
437        let last = self.spans.last()?;
438        if offset >= self.len {
439            return Some(last.start + last.len);
440        }
441        let (span, inside) = self.span_of(offset)?;
442        Some(span.start + inside)
443    }
444
445    /// Cuts compact rows `offset..offset + len`, keeping the grid.
446    ///
447    /// The result is a [`TimeAxis::Grid`] when it stays within one span, including every empty
448    /// result over a non-empty axis, and [`TimeAxis::GridRanges`] otherwise.
449    fn slice(&self, offset: usize, len: usize) -> Result<TimeAxis> {
450        if len == 0 {
451            return Ok(match self.position_at(offset) {
452                Some(position) => {
453                    TimeAxis::Grid(GridRange::try_new(self.grid.clone(), position, 0)?)
454                }
455                None => TimeAxis::GridRanges(self.clone()),
456            });
457        }
458        let spans = self.spans_between(offset, len);
459        match spans.as_slice() {
460            [span] => Ok(TimeAxis::Grid(GridRange::try_new(
461                self.grid.clone(),
462                span.start,
463                span.len,
464            )?)),
465            _ => Ok(TimeAxis::GridRanges(Self::try_new(
466                self.grid.clone(),
467                spans,
468            )?)),
469        }
470    }
471}
472
473impl PartialEq for GridRanges {
474    fn eq(&self, other: &Self) -> bool {
475        self.grid.spec == other.grid.spec && self.spans == other.spans && self.len == other.len
476    }
477}
478impl Eq for GridRanges {}
479
480/// A timestamp axis represented as a grid or explicit shared Arrow buffers.
481///
482/// Checked constructors validate timestamp ordering. Public payloads are validated again by the
483/// downstream series boundary.
484///
485/// Two coordinate conventions meet here, and every method says which one it speaks:
486///
487/// * a **compact row** is an index into the axis and into the fields aligned with it, and it
488///   counts only the rows the axis carries: [`TimeAxis::len`], [`TimeAxis::timestamp`],
489///   [`TimeAxis::slice`] and the row half of [`TimeAxis::positions`] speak compact rows;
490/// * an **absolute grid position** is an index into the shared [`EvalGrid`], holes included;
491///   [`TimeAxis::positions`], [`TimeAxis::row_of`], [`TimeAxis::first_position`] and
492///   [`TimeAxis::last_position`] speak absolute grid positions.
493#[derive(Clone, Debug)]
494pub enum TimeAxis {
495    /// A slice of a shared regular evaluation grid.
496    Grid(GridRange),
497    /// Several ordered runs of one shared evaluation grid.
498    GridRanges(GridRanges),
499    /// An explicit timestamp sequence.
500    Explicit(ScalarBuffer<i64>),
501    /// Explicit timestamps held in ordered chunks without flattening.
502    ExplicitChunks(Arc<[ScalarBuffer<i64>]>),
503}
504
505/// Sequential traversal of an axis, as returned by [`TimeAxis::positions`].
506///
507/// Yields `(absolute grid position, compact row)` pairs in increasing position order, and walks
508/// the runs of a [`TimeAxis::GridRanges`] with one cursor, so a row never costs a scan over the
509/// spans before it.
510pub struct Positions<'a> {
511    source: PositionSource<'a>,
512}
513
514enum PositionSource<'a> {
515    /// A dense grid range: position and row advance together.
516    Grid {
517        start: usize,
518        row: usize,
519        len: usize,
520    },
521    /// Several runs: the cursor is the span index plus the offset inside it.
522    GridRanges {
523        spans: &'a [GridSpan],
524        span: usize,
525        offset: usize,
526        row: usize,
527        len: usize,
528    },
529    /// No grid: a row sits at its own position.
530    Rows { row: usize, len: usize },
531}
532
533impl Iterator for Positions<'_> {
534    type Item = (usize, usize);
535
536    fn next(&mut self) -> Option<(usize, usize)> {
537        match &mut self.source {
538            PositionSource::Grid { start, row, len } => {
539                if *row >= *len {
540                    return None;
541                }
542                let item = (*start + *row, *row);
543                *row += 1;
544                Some(item)
545            }
546            PositionSource::GridRanges {
547                spans,
548                span,
549                offset,
550                row,
551                len,
552            } => {
553                if *row >= *len {
554                    return None;
555                }
556                loop {
557                    let current = spans.get(*span)?;
558                    if *offset < current.len {
559                        let item = (current.start + *offset, *row);
560                        *offset += 1;
561                        *row += 1;
562                        return Some(item);
563                    }
564                    *span += 1;
565                    *offset = 0;
566                }
567            }
568            PositionSource::Rows { row, len } => {
569                if *row >= *len {
570                    return None;
571                }
572                let item = (*row, *row);
573                *row += 1;
574                Some(item)
575            }
576        }
577    }
578
579    fn size_hint(&self) -> (usize, Option<usize>) {
580        let (row, len) = match &self.source {
581            PositionSource::Grid { row, len, .. } => (*row, *len),
582            PositionSource::GridRanges { row, len, .. } => (*row, *len),
583            PositionSource::Rows { row, len } => (*row, *len),
584        };
585        let remaining = len - row;
586        (remaining, Some(remaining))
587    }
588}
589
590impl ExactSizeIterator for Positions<'_> {}
591
592impl TimeAxis {
593    /// Validates an explicit, strictly increasing timestamp sequence.
594    pub fn try_new(timestamps: ScalarBuffer<i64>) -> Result<Self> {
595        let axis = Self::Explicit(timestamps);
596        axis.try_len()?;
597        Ok(axis)
598    }
599
600    /// Validates and stores timestamp chunks without concatenating their buffers.
601    pub fn try_from_chunks(chunks: Vec<ScalarBuffer<i64>>) -> Result<Self> {
602        let axis = Self::ExplicitChunks(
603            chunks
604                .into_iter()
605                .filter(|chunk| !chunk.is_empty())
606                .collect(),
607        );
608        axis.try_len()?;
609        Ok(axis)
610    }
611
612    /// Builds an axis over `grid` from the runs `spans`, keeping the single-run fast path.
613    ///
614    /// This is what a producer holding only the rows it decided should use: one span becomes
615    /// [`Self::Grid`], several become [`Self::GridRanges`], and no span becomes an empty
616    /// [`Self::GridRanges`] that still carries the grid. In particular it never fills the
617    /// positions between two spans, which is what keeps a sparse result from costing a row per
618    /// empty position.
619    pub fn from_grid_spans(grid: Arc<EvalGrid>, spans: Vec<GridSpan>) -> Result<Self> {
620        match spans.as_slice() {
621            [] => Ok(Self::GridRanges(GridRanges::empty(grid))),
622            [span] => Ok(Self::Grid(GridRange::try_new(grid, span.start, span.len)?)),
623            _ => Ok(Self::GridRanges(GridRanges::try_new(grid, spans)?)),
624        }
625    }
626
627    /// Returns the validated timestamp count.
628    pub(crate) fn try_len(&self) -> Result<usize> {
629        match self {
630            Self::Grid(range) => Ok(range.len()),
631            // `GridRanges` is only reachable through its checked constructor.
632            Self::GridRanges(ranges) => Ok(ranges.len()),
633            Self::Explicit(values) => {
634                if values.windows(2).any(|pair| pair[0] >= pair[1]) {
635                    return invalid("timestamps must be strictly increasing");
636                }
637                Ok(values.len())
638            }
639            Self::ExplicitChunks(chunks) => {
640                let mut total = 0usize;
641                let mut previous = None;
642                for chunk in chunks.iter() {
643                    total = total
644                        .checked_add(chunk.len())
645                        .ok_or_else(|| invalid_series("timestamp length overflow"))?;
646                    if chunk.windows(2).any(|pair| pair[0] >= pair[1])
647                        || chunk
648                            .first()
649                            .is_some_and(|first| previous.is_some_and(|last| last >= *first))
650                    {
651                        return invalid("timestamps must be strictly increasing across chunks");
652                    }
653                    if let Some(last) = chunk.last() {
654                        previous = Some(*last);
655                    }
656                }
657                Ok(total)
658            }
659        }
660    }
661
662    /// Returns the compact row count, not the distance from the first to the last position.
663    ///
664    /// A [`Self::GridRanges`] answers from its cached total and does not walk its spans.
665    pub fn len(&self) -> usize {
666        match self {
667            Self::Grid(range) => range.len,
668            Self::GridRanges(ranges) => ranges.len(),
669            Self::Explicit(values) => values.len(),
670            Self::ExplicitChunks(chunks) => chunks.iter().map(|chunk| chunk.len()).sum(),
671        }
672    }
673    /// Returns whether there are no timestamps.
674    pub fn is_empty(&self) -> bool {
675        self.len() == 0
676    }
677
678    /// Returns a timestamp by compact row index.
679    pub fn timestamp(&self, index: usize) -> Option<i64> {
680        match self {
681            Self::Grid(range) => (index < range.len)
682                .then(|| range.grid.timestamp_at(range.start.checked_add(index)?))
683                .flatten(),
684            Self::GridRanges(ranges) => {
685                let (span, offset) = ranges.span_of(index)?;
686                ranges.grid.timestamp_at(span.start.checked_add(offset)?)
687            }
688            Self::Explicit(values) => values.get(index).copied(),
689            Self::ExplicitChunks(chunks) => {
690                let mut offset = index;
691                for chunk in chunks.iter() {
692                    if offset < chunk.len() {
693                        return chunk.get(offset).copied();
694                    }
695                    offset -= chunk.len();
696                }
697                None
698            }
699        }
700    }
701
702    /// Returns a zero-copy slice, retaining Arrow owners; chunked axes remain chunked.
703    ///
704    /// `offset` and `len` count compact rows, so the result stays aligned with the fields of the
705    /// series the axis belongs to. A slice that stays within one run of a [`Self::GridRanges`]
706    /// comes back as [`Self::Grid`]; every empty slice keeps the grid it was cut from.
707    pub fn slice(&self, offset: usize, len: usize) -> Result<Self> {
708        let end = offset.checked_add(len).context(InvalidSeriesSnafu {
709            reason: "timestamp slice overflow".to_string(),
710        })?;
711        if end > self.len() {
712            return invalid("timestamp slice exceeds axis");
713        }
714        match self {
715            Self::Grid(range) => Ok(Self::Grid(GridRange::try_new(
716                range.grid.clone(),
717                range.start + offset,
718                len,
719            )?)),
720            Self::GridRanges(ranges) => ranges.slice(offset, len),
721            Self::Explicit(values) => Ok(Self::Explicit(values.slice(offset, len))),
722            Self::ExplicitChunks(chunks) => {
723                let mut remain = len;
724                let mut skip = offset;
725                let mut sliced = Vec::new();
726                for chunk in chunks.iter() {
727                    if skip >= chunk.len() {
728                        skip -= chunk.len();
729                        continue;
730                    }
731                    let take = remain.min(chunk.len() - skip);
732                    if take > 0 {
733                        sliced.push(chunk.slice(skip, take));
734                        remain -= take;
735                    }
736                    skip = 0;
737                    if remain == 0 {
738                        break;
739                    }
740                }
741                Ok(Self::ExplicitChunks(sliced.into()))
742            }
743        }
744    }
745
746    /// Returns the single contiguous range this axis covers, if it covers exactly one.
747    ///
748    /// [`Self::Grid`] always answers `Some`, including for an empty range that still names the
749    /// position it sits at. A [`Self::GridRanges`] holding several runs, and every explicit axis,
750    /// answer `None`: their rows are not one range, and a caller that assumed one would read the
751    /// holes between them as rows.
752    pub fn as_grid_range(&self) -> Option<&GridRange> {
753        match self {
754            Self::Grid(range) => Some(range),
755            Self::GridRanges(_) | Self::Explicit(_) | Self::ExplicitChunks(_) => None,
756        }
757    }
758
759    /// Returns the evaluation grid the axis is addressed on, if it has one.
760    ///
761    /// Both [`Self::Grid`] and [`Self::GridRanges`] answer `Some`; the explicit axes answer `None`.
762    pub fn grid(&self) -> Option<&Arc<EvalGrid>> {
763        match self {
764            Self::Grid(range) => Some(range.grid()),
765            Self::GridRanges(ranges) => Some(ranges.grid()),
766            Self::Explicit(_) | Self::ExplicitChunks(_) => None,
767        }
768    }
769
770    /// Maps an absolute grid position to its compact row, or `None` when the axis carries no row
771    /// there.
772    ///
773    /// A point lookup: a [`Self::GridRanges`] binary-searches its spans, it does not scan them.
774    /// On an explicit axis a row sits at its own position, so only the length bounds it.
775    pub fn row_of(&self, position: usize) -> Option<usize> {
776        match self {
777            Self::Grid(range) => (position >= range.start
778                && position
779                    .checked_sub(range.start)
780                    .is_some_and(|row| row < range.len))
781            .then(|| position - range.start),
782            Self::GridRanges(ranges) => ranges.row_of(position),
783            Self::Explicit(_) | Self::ExplicitChunks(_) => {
784                (position < self.len()).then_some(position)
785            }
786        }
787    }
788
789    /// Walks the axis once, yielding `(absolute grid position, compact row)` in position order.
790    ///
791    /// This is the traversal every consumer of a grid axis should use: a helper walks the runs of
792    /// a [`Self::GridRanges`] with a single cursor, so a row never rescans the spans before it.
793    /// On an explicit axis there is no grid, so a row sits at its own position.
794    pub fn positions(&self) -> Positions<'_> {
795        let len = self.len();
796        let source = match self {
797            Self::Grid(range) => PositionSource::Grid {
798                start: range.start,
799                row: 0,
800                len,
801            },
802            Self::GridRanges(ranges) => PositionSource::GridRanges {
803                spans: &ranges.spans,
804                span: 0,
805                offset: 0,
806                row: 0,
807                len,
808            },
809            Self::Explicit(_) | Self::ExplicitChunks(_) => PositionSource::Rows { row: 0, len },
810        };
811        Positions { source }
812    }
813
814    /// Returns the absolute grid position of the first carried row.
815    pub fn first_position(&self) -> Option<usize> {
816        match self {
817            Self::Grid(range) => (!range.is_empty()).then_some(range.start),
818            Self::GridRanges(ranges) => ranges.spans.first().map(GridSpan::start),
819            Self::Explicit(_) | Self::ExplicitChunks(_) => (!self.is_empty()).then_some(0),
820        }
821    }
822
823    /// Returns the absolute grid position of the last carried row.
824    pub fn last_position(&self) -> Option<usize> {
825        match self {
826            Self::Grid(range) => (!range.is_empty()).then(|| range.start + range.len - 1),
827            Self::GridRanges(ranges) => ranges.spans.last().map(|span| span.start + span.len - 1),
828            Self::Explicit(_) | Self::ExplicitChunks(_) => self.len().checked_sub(1),
829        }
830    }
831
832    /// Returns whether the carried rows form one run, which is what a fast path can rely on.
833    ///
834    /// A [`Self::GridRanges`] answers `true` only for a single span, so an empty span list reports
835    /// `false`: it names no run, and therefore no position a fast path could start at.
836    pub fn is_contiguous(&self) -> bool {
837        match self {
838            Self::Grid(_) => true,
839            Self::GridRanges(ranges) => ranges.spans.len() == 1,
840            Self::Explicit(_) => true,
841            Self::ExplicitChunks(chunks) => chunks.len() <= 1,
842        }
843    }
844
845    /// Returns the timestamps of the carried rows, in compact-row order.
846    ///
847    /// An axis covering the whole grid lends the grid's array; a grid axis holding fewer positions
848    /// than its grid computes the rows it carries and lends nothing, so gathering a window out of
849    /// a large grid costs the window and leaves a deferred grid deferred. An axis of several runs,
850    /// and a chunked explicit axis, allocate one array of the carried rows.
851    pub fn timestamps(&self) -> Result<Cow<'_, [i64]>> {
852        match self {
853            Self::Grid(range) => {
854                if !range.covers_grid() {
855                    return Ok(Cow::Owned(
856                        range.grid.gather_timestamps(range.start(), range.len())?,
857                    ));
858                }
859                Ok(Cow::Borrowed(&range.grid.timestamps()?[..]))
860            }
861            Self::GridRanges(ranges) => {
862                let mut timestamps = Vec::with_capacity(ranges.len());
863                for (position, _) in self.positions() {
864                    timestamps.push(
865                        ranges
866                            .grid
867                            .timestamp_at(position)
868                            .ok_or_else(|| invalid_series("grid span timestamp is out of range"))?,
869                    );
870                }
871                Ok(Cow::Owned(timestamps))
872            }
873            Self::Explicit(values) => Ok(Cow::Borrowed(values)),
874            Self::ExplicitChunks(_) => Ok(Cow::Owned(
875                (0..self.len())
876                    .filter_map(|row| self.timestamp(row))
877                    .collect(),
878            )),
879        }
880    }
881
882    /// Returns one run per stored span of carried rows, as [`GridRun`]s.
883    ///
884    /// One run for a contiguous axis, one per stored span for [`Self::GridRanges`], and none when
885    /// no row is carried. Adjacent stored spans stay two runs, so a run is a maximal run only when
886    /// the axis was built from maximal spans (as the series builder does). A run is where bulk
887    /// work pays off: the rows inside it are consecutive in both coordinates, so its samples can
888    /// be sliced and zipped instead of read one by one.
889    pub fn runs(&self) -> GridRuns<'_> {
890        let (one, spans) = match self {
891            Self::Grid(range) => (
892                Some(GridRun {
893                    position: range.start,
894                    row: 0,
895                    len: range.len,
896                }),
897                &[][..],
898            ),
899            Self::GridRanges(ranges) => (None, &ranges.spans[..]),
900            Self::Explicit(_) | Self::ExplicitChunks(_) => (
901                Some(GridRun {
902                    position: 0,
903                    row: 0,
904                    len: self.len(),
905                }),
906                &[][..],
907            ),
908        };
909        GridRuns {
910            one: one.filter(|run| run.len > 0),
911            spans,
912            span: 0,
913            row: 0,
914        }
915    }
916
917    /// Intersects the carried rows of two axes, yielding one shared run per pair of overlapping
918    /// stored runs as `(first absolute position, row in `self`, row in `other`, length)`.
919    ///
920    /// A single merge pass over the two run lists, so the cost is the number of runs and not their
921    /// product. This is how a pairwise operator aligns two axes: it never builds the dense
922    /// envelope `first_position()..last_position()`, which would visit -- and densify -- the holes,
923    /// and it never re-derives the row of a position by subtracting starts, which is wrong as soon
924    /// as either side skips a row.
925    ///
926    /// Both axes must be addressed on the same [`GridSpec`]: the positions it yields are indices
927    /// into one shared [`EvalGrid`], so two different grids line up only by coincidence. An
928    /// explicit axis carries no grid and must not be passed at all -- its rows are not absolute
929    /// positions on any shared grid, so the pairs would be silent nonsense. Debug builds assert
930    /// the precondition and therefore panic on a violation; release builds trust the caller.
931    pub fn intersect_runs<'a>(&'a self, other: &'a Self) -> impl Iterator<Item = GridRunPair> + 'a {
932        debug_assert!(
933            matches!(
934                (self.grid(), other.grid()),
935                (Some(lhs), Some(rhs)) if lhs.spec() == rhs.spec()
936            ),
937            "intersect_runs requires two axes on one grid, \
938             but an explicit axis carries none and two grids only meet by coincidence",
939        );
940        let mut lhs = self.runs().peekable();
941        let mut rhs = other.runs().peekable();
942        std::iter::from_fn(move || {
943            loop {
944                let left = *lhs.peek()?;
945                let right = *rhs.peek()?;
946                let start = left.position.max(right.position);
947                let end = (left.position + left.len).min(right.position + right.len);
948                if start >= end {
949                    // No shared position in this pair of runs: drop the one that ends first.
950                    if left.position + left.len <= right.position + right.len {
951                        lhs.next();
952                    } else {
953                        rhs.next();
954                    }
955                    continue;
956                }
957                let len = end - start;
958                let pair = GridRunPair {
959                    position: start,
960                    row: left.row + (start - left.position),
961                    other_row: right.row + (start - right.position),
962                    len,
963                };
964                // Consume the shared piece from both sides, keeping the remainder for the next
965                // round.
966                if left.position + left.len <= end {
967                    lhs.next();
968                }
969                if right.position + right.len <= end {
970                    rhs.next();
971                }
972                return Some(pair);
973            }
974        })
975    }
976}
977
978/// A run of carried rows: `len` rows starting at absolute position `position` and compact
979/// `row`, both of which advance by one per row.
980#[derive(Clone, Copy, Debug, PartialEq, Eq)]
981pub struct GridRun {
982    /// Absolute grid position of the run's first row.
983    pub position: usize,
984    /// Compact row of the run's first row.
985    pub row: usize,
986    /// Number of rows in the run; never zero.
987    pub len: usize,
988}
989
990/// A run shared by two axes, with the compact row of each.
991#[derive(Clone, Copy, Debug, PartialEq, Eq)]
992pub struct GridRunPair {
993    /// Absolute grid position of the shared run's first row.
994    pub position: usize,
995    /// Compact row of the first shared position in the axis `intersect_runs` was called on.
996    pub row: usize,
997    /// Compact row of the first shared position in the other axis.
998    pub other_row: usize,
999    /// Number of rows in the shared run; never zero.
1000    pub len: usize,
1001}
1002
1003/// Lazily produced runs of one axis; see [`TimeAxis::runs`].
1004///
1005/// A contiguous axis holds its one run inline; a sparse axis walks its spans with a cursor.
1006pub struct GridRuns<'a> {
1007    one: Option<GridRun>,
1008    spans: &'a [GridSpan],
1009    span: usize,
1010    row: usize,
1011}
1012
1013impl Iterator for GridRuns<'_> {
1014    type Item = GridRun;
1015
1016    fn next(&mut self) -> Option<GridRun> {
1017        if let Some(run) = self.one.take() {
1018            return Some(run);
1019        }
1020        let span = *self.spans.get(self.span)?;
1021        self.span += 1;
1022        let run = GridRun {
1023            position: span.start,
1024            row: self.row,
1025            len: span.len,
1026        };
1027        self.row += span.len;
1028        Some(run)
1029    }
1030}
1031
1032/// Walks every position at least one of `axes` carries, once, in increasing order.
1033///
1034/// A merge over one cursor per axis: each step costs one comparison per axis, and no position is
1035/// visited twice. This is how an operator covering several axes (a histogram's bucket series, an
1036/// aggregate over an input set) visits the positions that hold something, instead of scanning the
1037/// envelope from the earliest to the latest position and densifying every hole in between.
1038///
1039/// Every axis must be addressed on the same [`GridSpec`]: a position names a point of one shared
1040/// [`EvalGrid`], so merging axes of two different grids would interleave unrelated positions. An
1041/// explicit axis carries no grid and must not be passed at all -- its rows are not absolute
1042/// positions on any shared grid. Debug builds assert the precondition and therefore panic on a
1043/// violation; release builds trust the caller.
1044pub fn union_positions<'a>(axes: impl IntoIterator<Item = &'a TimeAxis>) -> UnionPositions<'a> {
1045    // Materialized once so that the debug assert above can see every axis' grid before the first
1046    // cursor is built; the cursors below borrow these references, not the list.
1047    let axes: Vec<&'a TimeAxis> = axes.into_iter().collect();
1048    debug_assert!(
1049        {
1050            let mut specs = axes.iter().map(|axis| axis.grid().map(|grid| grid.spec()));
1051            match specs.next() {
1052                // No axis at all: the merge yields nothing and reads no grid.
1053                None => true,
1054                Some(None) => false,
1055                Some(Some(first)) => specs.all(|spec| spec == Some(first)),
1056            }
1057        },
1058        "union_positions requires every axis on one grid, \
1059         but an explicit axis carries none and two grids only meet by coincidence",
1060    );
1061    let cursors: Vec<Positions<'a>> = axes.into_iter().map(TimeAxis::positions).collect();
1062    let pending = vec![None; cursors.len()];
1063    UnionPositions { cursors, pending }
1064}
1065
1066/// The positions of several axes, merged; see [`union_positions`].
1067pub struct UnionPositions<'a> {
1068    cursors: Vec<Positions<'a>>,
1069    /// The next `(position, row)` of each cursor, buffered so that it can be peeked without a
1070    /// second cursor type.
1071    pending: Vec<Option<(usize, usize)>>,
1072}
1073
1074impl Iterator for UnionPositions<'_> {
1075    type Item = usize;
1076
1077    fn next(&mut self) -> Option<usize> {
1078        let mut lowest: Option<usize> = None;
1079        for (cursor, pending) in self.cursors.iter_mut().zip(&mut self.pending) {
1080            if pending.is_none() {
1081                *pending = cursor.next();
1082            }
1083            if let Some((position, _)) = *pending {
1084                lowest = Some(lowest.map_or(position, |lowest| lowest.min(position)));
1085            }
1086        }
1087        let lowest = lowest?;
1088        // Every axis standing at this position advances; the others keep their buffered position.
1089        for pending in &mut self.pending {
1090            if matches!(*pending, Some((position, _)) if position == lowest) {
1091                *pending = None;
1092            }
1093        }
1094        Some(lowest)
1095    }
1096}
1097
1098fn invalid_series(reason: &str) -> crate::error::Error {
1099    InvalidSeriesSnafu {
1100        reason: reason.to_string(),
1101    }
1102    .build()
1103}
1104
1105fn invalid<T>(reason: &str) -> Result<T> {
1106    InvalidSeriesSnafu {
1107        reason: reason.to_string(),
1108    }
1109    .fail()
1110}