Skip to main content

datatypes/series/
samples.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::sync::Arc;
16
17use arrow::array::{Array, Float64Array, UInt32Array};
18use snafu::OptionExt;
19
20use crate::error::{InvalidSeriesSnafu, Result};
21use crate::series::SeriesLabels;
22use crate::series::histogram::{HistogramBatch, HistogramView};
23use crate::series::time::{EvalGrid, TimeAxis};
24
25#[cfg(test)]
26mod tests;
27
28fn invalid<T>(reason: impl Into<String>) -> Result<T> {
29    Err(InvalidSeriesSnafu {
30        reason: reason.into(),
31    }
32    .build())
33}
34
35/// Histogram references for each time position, backed by one immutable table.
36#[derive(Clone, Debug)]
37pub struct HistogramSamples {
38    indices: UInt32Array,
39    batch: Arc<HistogramBatch>,
40}
41impl HistogramSamples {
42    /// Validate and bind reference indices to their immutable histogram table.
43    pub fn try_new(indices: UInt32Array, batch: Arc<HistogramBatch>) -> Result<Self> {
44        if indices.iter().flatten().any(|i| i as usize >= batch.len()) {
45            return invalid("histogram sample index is out of bounds");
46        }
47        Ok(Self { indices, batch })
48    }
49    /// Read-only reference indices.
50    pub fn indices(&self) -> &UInt32Array {
51        &self.indices
52    }
53    /// Shared histogram table.
54    pub fn batch(&self) -> &Arc<HistogramBatch> {
55        &self.batch
56    }
57    /// Number of time positions.
58    pub fn len(&self) -> usize {
59        self.indices.len()
60    }
61    /// Whether this contains no positions.
62    pub fn is_empty(&self) -> bool {
63        self.indices.is_empty()
64    }
65    /// Returns a referenced histogram, or `None` for missing/out-of-range positions.
66    pub fn view_at(&self, index: usize) -> Option<HistogramView<'_>> {
67        if index >= self.indices.len() {
68            return None;
69        }
70        if self.indices.is_valid(index) {
71            self.batch.view(self.indices.value(index) as usize)
72        } else {
73            None
74        }
75    }
76    fn slice(&self, offset: usize, len: usize) -> Self {
77        Self {
78            indices: self.indices.slice(offset, len),
79            batch: self.batch.clone(),
80        }
81    }
82}
83
84/// Float and histogram values with mutually exclusive validity at each position.
85#[derive(Clone, Debug)]
86pub struct MixedSamples {
87    floats: Float64Array,
88    histograms: HistogramSamples,
89}
90impl MixedSamples {
91    /// Read-only float values, including validity bitmap.
92    pub fn floats(&self) -> &Float64Array {
93        &self.floats
94    }
95    /// Read-only histogram references and their shared table.
96    pub fn histograms(&self) -> &HistogramSamples {
97        &self.histograms
98    }
99    /// Number of positions.
100    pub fn len(&self) -> usize {
101        self.floats.len()
102    }
103    /// Whether this contains no positions.
104    pub fn is_empty(&self) -> bool {
105        self.floats.is_empty()
106    }
107}
108
109#[derive(Clone, Debug)]
110enum SampleStorage {
111    Float(Float64Array),
112    Histogram(HistogramSamples),
113    Mixed(MixedSamples),
114    Chunks(Arc<[Samples]>, usize),
115}
116
117/// Typed Arrow-backed values for a time series.
118#[derive(Clone, Debug)]
119pub struct Samples {
120    storage: SampleStorage,
121}
122
123/// A borrowed dense representation.
124pub enum DenseSamplesRef<'a> {
125    Float(&'a Float64Array),
126    Histogram(&'a HistogramSamples),
127    Mixed(&'a MixedSamples),
128}
129
130/// A sample value; ordinary NaN is a valid float, distinct from Missing.
131pub enum SampleRef<'a> {
132    Missing,
133    Float(f64),
134    Histogram(HistogramView<'a>),
135}
136
137impl Samples {
138    /// Wrap float samples without copying; nulls are missing and NaNs remain values.
139    pub fn from_float(values: Float64Array) -> Self {
140        Self {
141            storage: SampleStorage::Float(values),
142        }
143    }
144    /// Validate histogram indices and retain their referenced table.
145    pub fn try_from_histogram(indices: UInt32Array, batch: Arc<HistogramBatch>) -> Result<Self> {
146        Ok(Self {
147            storage: SampleStorage::Histogram(HistogramSamples::try_new(indices, batch)?),
148        })
149    }
150    /// Validate lengths and ensure no position is simultaneously float and histogram.
151    pub fn try_from_mixed(floats: Float64Array, histograms: HistogramSamples) -> Result<Self> {
152        if floats.len() != histograms.len() {
153            return invalid("mixed sample arrays have unequal lengths");
154        }
155        if (0..floats.len()).any(|i| floats.is_valid(i) && histograms.indices.is_valid(i)) {
156            return invalid("mixed sample position has both float and histogram values");
157        }
158        Ok(Self {
159            storage: SampleStorage::Mixed(MixedSamples { floats, histograms }),
160        })
161    }
162    /// Retain immutable chunks, flattening nested descriptors and checking total length.
163    pub fn try_from_chunks(chunks: Vec<Samples>) -> Result<Self> {
164        let mut flat = Vec::new();
165        for chunk in chunks {
166            match chunk.storage {
167                SampleStorage::Chunks(parts, _) => flat.extend(parts.iter().cloned()),
168                _ => flat.push(chunk),
169            }
170        }
171        let total = flat
172            .iter()
173            .try_fold(0usize, |n, s| n.checked_add(s.len()))
174            .context(InvalidSeriesSnafu {
175                reason: "sample chunk length overflow",
176            })?;
177        flat.retain(|s| !s.is_empty());
178        if flat.is_empty() {
179            return Ok(Self::from_float(Float64Array::new_null(0)));
180        }
181        if flat.len() == 1 {
182            return flat.pop().ok_or_else(|| {
183                InvalidSeriesSnafu {
184                    reason: "single sample chunk disappeared".to_string(),
185                }
186                .build()
187            });
188        }
189        Ok(Self {
190            storage: SampleStorage::Chunks(flat.into(), total),
191        })
192    }
193    /// Returns the dense segments in logical order without allocating, copying payloads, or
194    /// densifying the samples.
195    ///
196    /// Chunked samples expose their retained segment boundaries; different fields may therefore
197    /// have different boundaries. The logical start of each segment is the sum of the lengths of
198    /// all preceding segments, and the total length is [`Self::len`]. For non-chunked samples,
199    /// including empty samples, this returns a singleton slice containing `self`. Chunk
200    /// construction flattens nested chunks and drops empty segments; an all-empty input becomes
201    /// one empty float segment. Each segment is dense: [`Self::dense`] returns `Some` with its
202    /// typed Arrow view. Clone the samples cheaply if they need to outlive this borrow.
203    ///
204    /// ```
205    /// use arrow::array::Float64Array;
206    /// use datatypes::series::samples::{DenseSamplesRef, Samples};
207    ///
208    /// let samples = Samples::try_from_chunks(vec![
209    ///     Samples::from_float(Float64Array::from(vec![1.0, 2.0])),
210    ///     Samples::from_float(Float64Array::from(vec![3.0])),
211    /// ])
212    /// .unwrap();
213    ///
214    /// let mut logical_start = 0;
215    /// let mut starts = Vec::new();
216    /// for segment in samples.segments() {
217    ///     starts.push(logical_start);
218    ///     match segment.dense().unwrap() {
219    ///         DenseSamplesRef::Float(values) => assert_eq!(values.len(), segment.len()),
220    ///         _ => unreachable!("these segments contain floats"),
221    ///     }
222    ///     logical_start += segment.len();
223    /// }
224    /// assert_eq!(starts, vec![0, 2]);
225    /// assert_eq!(logical_start, samples.len());
226    /// ```
227    pub fn segments(&self) -> &[Samples] {
228        match &self.storage {
229            SampleStorage::Chunks(chunks, _) => chunks,
230            _ => std::slice::from_ref(self),
231        }
232    }
233    /// Number of sample positions.
234    pub fn len(&self) -> usize {
235        match &self.storage {
236            SampleStorage::Float(a) => a.len(),
237            SampleStorage::Histogram(a) => a.len(),
238            SampleStorage::Mixed(a) => a.len(),
239            SampleStorage::Chunks(_, len) => *len,
240        }
241    }
242    /// Whether this has no positions.
243    pub fn is_empty(&self) -> bool {
244        self.len() == 0
245    }
246    /// Returns a dense typed representation, or `None` for chunks.
247    pub fn dense(&self) -> Option<DenseSamplesRef<'_>> {
248        match &self.storage {
249            SampleStorage::Float(a) => Some(DenseSamplesRef::Float(a)),
250            SampleStorage::Histogram(a) => Some(DenseSamplesRef::Histogram(a)),
251            SampleStorage::Mixed(a) => Some(DenseSamplesRef::Mixed(a)),
252            SampleStorage::Chunks(_, _) => None,
253        }
254    }
255    /// Returns the sample, treating an out-of-range index as missing.
256    ///
257    /// A chunked field walks its descriptors from the start, so reading row after row with this
258    /// costs a scan per row: a sequential reader should use [`Self::cursor`] instead.
259    pub fn sample(&self, index: usize) -> SampleRef<'_> {
260        if index >= self.len() {
261            return SampleRef::Missing;
262        }
263        match &self.storage {
264            SampleStorage::Float(a) => {
265                if a.is_valid(index) {
266                    SampleRef::Float(a.value(index))
267                } else {
268                    SampleRef::Missing
269                }
270            }
271            SampleStorage::Histogram(a) => a
272                .view_at(index)
273                .map_or(SampleRef::Missing, SampleRef::Histogram),
274            SampleStorage::Mixed(a) => {
275                if a.floats.is_valid(index) {
276                    SampleRef::Float(a.floats.value(index))
277                } else {
278                    a.histograms
279                        .view_at(index)
280                        .map_or(SampleRef::Missing, SampleRef::Histogram)
281                }
282            }
283            SampleStorage::Chunks(chunks, _) => {
284                let mut i = index;
285                for part in chunks.iter() {
286                    if i < part.len() {
287                        return part.sample(i);
288                    }
289                    i -= part.len();
290                }
291                SampleRef::Missing
292            }
293        }
294    }
295    /// Iterate all positions sequentially without materializing per-sample objects.
296    pub fn iter(&self) -> impl ExactSizeIterator<Item = SampleRef<'_>> + '_ {
297        let (chunks, remaining) = match &self.storage {
298            SampleStorage::Chunks(chunks, len) => (Some(chunks.as_ref()), *len),
299            _ => (None, self.len()),
300        };
301        SamplesIter {
302            samples: self,
303            chunks,
304            chunk_index: 0,
305            local_index: 0,
306            remaining,
307        }
308    }
309    /// A forward reader of this field addressed by compact row; see [`RowCursor`].
310    pub fn cursor(&self) -> RowCursor<'_> {
311        let (chunks, remaining) = match &self.storage {
312            SampleStorage::Chunks(chunks, len) => (Some(chunks.as_ref()), *len),
313            _ => (None, self.len()),
314        };
315        RowCursor {
316            iter: SamplesIter {
317                samples: self,
318                chunks,
319                chunk_index: 0,
320                local_index: 0,
321                remaining,
322            },
323            row: 0,
324        }
325    }
326    /// Return a checked zero-copy slice (across chunks only intersected descriptors are retained).
327    pub fn slice(&self, offset: usize, len: usize) -> Result<Self> {
328        let end = offset.checked_add(len).context(InvalidSeriesSnafu {
329            reason: "sample slice bounds overflow",
330        })?;
331        if end > self.len() {
332            return invalid("sample slice is out of bounds");
333        }
334        match &self.storage {
335            SampleStorage::Float(a) => Ok(Self::from_float(a.slice(offset, len))),
336            SampleStorage::Histogram(a) => Ok(Self {
337                storage: SampleStorage::Histogram(a.slice(offset, len)),
338            }),
339            SampleStorage::Mixed(a) => Ok(Self {
340                storage: SampleStorage::Mixed(MixedSamples {
341                    floats: a.floats.slice(offset, len),
342                    histograms: a.histograms.slice(offset, len),
343                }),
344            }),
345            SampleStorage::Chunks(chunks, _) => {
346                let mut skip = offset;
347                let mut remain = len;
348                let mut out = Vec::new();
349                for chunk in chunks.iter() {
350                    if skip >= chunk.len() {
351                        skip -= chunk.len();
352                        continue;
353                    }
354                    let take = remain.min(chunk.len() - skip);
355                    if take != 0 {
356                        out.push(chunk.slice(skip, take)?);
357                        remain -= take;
358                    }
359                    skip = 0;
360                    if remain == 0 {
361                        break;
362                    }
363                }
364                Self::try_from_chunks(out)
365            }
366        }
367    }
368}
369
370/// Sequential exact-size iterator over a dense series or its chunk descriptors.
371struct SamplesIter<'a> {
372    samples: &'a Samples,
373    chunks: Option<&'a [Samples]>,
374    chunk_index: usize,
375    local_index: usize,
376    remaining: usize,
377}
378impl<'a> Iterator for SamplesIter<'a> {
379    type Item = SampleRef<'a>;
380
381    fn next(&mut self) -> Option<Self::Item> {
382        if self.remaining == 0 {
383            return None;
384        }
385        self.remaining -= 1;
386        if let Some(chunks) = self.chunks {
387            while self.chunk_index < chunks.len()
388                && self.local_index == chunks[self.chunk_index].len()
389            {
390                self.chunk_index += 1;
391                self.local_index = 0;
392            }
393            let chunk = &chunks[self.chunk_index];
394            let value = chunk.sample(self.local_index);
395            self.local_index += 1;
396            Some(value)
397        } else {
398            let index = self.samples.len() - self.remaining - 1;
399            Some(self.samples.sample(index))
400        }
401    }
402
403    fn size_hint(&self) -> (usize, Option<usize>) {
404        (self.remaining, Some(self.remaining))
405    }
406}
407impl ExactSizeIterator for SamplesIter<'_> {
408    fn len(&self) -> usize {
409        self.remaining
410    }
411}
412
413/// A forward reader of one field's samples, addressed by compact row.
414///
415/// [`Samples::sample`] rescans the chunk descriptors from the start on every call, so reading a
416/// chunked field with it row by row costs a scan per row. A cursor resumes where it stopped: the
417/// rows asked for must not go backwards, and reading `n` rows in order costs one pass over the
418/// field. That is what every operator walking a [`TimeAxis`](crate::series::time::TimeAxis) needs,
419/// since the axis says which rows exist and the cursor turns them into values.
420///
421/// ```
422/// use arrow::array::Float64Array;
423/// use datatypes::series::samples::{SampleRef, Samples};
424///
425/// let samples = Samples::try_from_chunks(vec![
426///     Samples::from_float(Float64Array::from(vec![1.0, 2.0])),
427///     Samples::from_float(Float64Array::from(vec![3.0])),
428/// ])
429/// .unwrap();
430/// let mut cursor = samples.cursor();
431/// assert!(matches!(cursor.at(2), Some(SampleRef::Float(3.0))));
432/// assert!(cursor.at(0).is_none(), "a cursor never goes back");
433/// ```
434pub struct RowCursor<'a> {
435    iter: SamplesIter<'a>,
436    /// Row the next [`RowCursor::at`] call must start from.
437    row: usize,
438}
439impl<'a> RowCursor<'a> {
440    /// Reads the sample at compact `row`, which must not be behind the previous read.
441    ///
442    /// Returns `None` when the row is behind the cursor's position or at or past the field's end.
443    /// Such a call leaves the cursor where it was, so one out-of-range row does not consume the
444    /// rows after it.
445    pub fn at(&mut self, row: usize) -> Option<SampleRef<'a>> {
446        if row < self.row {
447            return None;
448        }
449        // Bound-check before advancing: the iterator is exact-size, so draining it would make it
450        // answer `None` for every later row as well.
451        if row - self.row >= self.iter.len() {
452            return None;
453        }
454        let sample = self.iter.nth(row - self.row)?;
455        self.row = row + 1;
456        Some(sample)
457    }
458}
459
460#[derive(Clone, Debug)]
461enum Fields {
462    One(Samples),
463    Many(Box<[Samples]>),
464}
465/// Field values using inline storage for a single field.
466#[derive(Clone, Debug)]
467pub struct SeriesFields {
468    storage: Fields,
469}
470impl SeriesFields {
471    /// Create a one-field collection without allocating a field list.
472    pub fn one(field: Samples) -> Self {
473        Self {
474            storage: Fields::One(field),
475        }
476    }
477    /// Validate nonempty, equally sized fields.
478    pub fn try_from_vec(fields: Vec<Samples>) -> Result<Self> {
479        if fields.is_empty() {
480            return invalid("series fields must not be empty");
481        }
482        if fields.iter().any(|f| f.len() != fields[0].len()) {
483            return invalid("series fields have unequal lengths");
484        }
485        Ok(if fields.len() == 1 {
486            let mut fields = fields.into_iter();
487            let field = fields.next().ok_or_else(|| {
488                InvalidSeriesSnafu {
489                    reason: "single series field disappeared".to_string(),
490                }
491                .build()
492            })?;
493            Self::one(field)
494        } else {
495            Self {
496                storage: Fields::Many(fields.into_boxed_slice()),
497            }
498        })
499    }
500    /// Borrow all fields.
501    pub fn as_slice(&self) -> &[Samples] {
502        match &self.storage {
503            Fields::One(f) => std::slice::from_ref(f),
504            Fields::Many(f) => f,
505        }
506    }
507    /// Number of fields.
508    pub fn len(&self) -> usize {
509        self.as_slice().len()
510    }
511    /// Whether this has no fields.
512    pub fn is_empty(&self) -> bool {
513        false
514    }
515    /// Get a field by index.
516    pub fn get(&self, index: usize) -> Option<&Samples> {
517        self.as_slice().get(index)
518    }
519    /// Iterate fields.
520    pub fn iter(&self) -> std::slice::Iter<'_, Samples> {
521        self.as_slice().iter()
522    }
523}
524
525/// Shared name and position of each output field.
526#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Hash, Eq)]
527pub struct FieldSpec {
528    pub name: Arc<str>,
529}
530/// Shared schema describing series fields.
531#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Hash, Eq)]
532pub struct SeriesSchema {
533    pub fields: Arc<[FieldSpec]>,
534    /// Shared grid for regular series; its `GridSpec` must match each series grid axis. Explicit axes require `None`.
535    pub eval_grid: Option<Arc<EvalGrid>>,
536}
537/// A validated metric, time axis, and aligned fields.
538#[derive(Clone, Debug)]
539pub struct Series {
540    pub metric: SeriesLabels,
541    pub time: TimeAxis,
542    pub fields: SeriesFields,
543}
544impl Series {
545    /// Construct after validating schema, field lengths, and strictly increasing timestamps.
546    pub fn try_new(
547        schema: &SeriesSchema,
548        metric: SeriesLabels,
549        time: TimeAxis,
550        fields: SeriesFields,
551    ) -> Result<Self> {
552        if fields.len() != schema.fields.len() {
553            return invalid("series field count does not match schema");
554        }
555        let time_len = time.try_len()?;
556        if fields.iter().any(|f| f.len() != time_len) {
557            return invalid("series field length does not match time axis");
558        }
559        match (&schema.eval_grid, time.grid()) {
560            (Some(expected), Some(grid)) if expected.spec() == grid.spec() => {}
561            (Some(_), Some(_)) => {
562                return invalid("series grid does not match schema evaluation grid");
563            }
564            (Some(_), None) => {
565                return invalid("explicit series time axis cannot use an evaluation grid");
566            }
567            (None, Some(_)) => {
568                return invalid("grid series requires a schema evaluation grid");
569            }
570            (None, None) => {}
571        }
572        Ok(Self {
573            metric,
574            time,
575            fields,
576        })
577    }
578}