Skip to main content

datatypes/
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
15pub mod aggregate_state;
16pub mod frame;
17pub mod histogram;
18pub mod raw;
19pub mod samples;
20pub mod time;
21
22#[cfg(test)]
23mod tests;
24
25use std::any::Any;
26use std::sync::{Arc, OnceLock};
27
28use arrow::array::{Array, StringArray};
29use arrow::record_batch::RecordBatch;
30
31use crate::error::{InvalidSeriesSnafu, Result};
32
33/// Ordering guarantee within one stream and each of its output partitions.
34///
35/// Every series has strictly increasing sample positions, including across chunks; positions
36/// are raw timestamps or, for evaluated series, current-stage evaluation times or grid positions.
37/// They need not all be explicit times on the grid. Within one series or producer fragment,
38/// no mode permits duplicate positions. `Interleaved` permits A1, B1, A2; only the latter two modes
39/// keep each series contiguous. `KeyThenTime` also orders by this stream's series identity, then time:
40/// raw streams use the complete bound-compatible identity (not just a TSID or hash), while
41/// evaluated streams use current name/label identity, not storage primary keys or object address/hash.
42/// This ordering is not a query-global ordering, partition-ownership rule, or finality guarantee.
43///
44/// A raw frame adapter accepts only a subset of `Interleaved`: it transports independently closed
45/// producer fragment chains in sequence, allowing the same key and overlapping timestamps in
46/// different fragment chains. Finality closes a fragment, not necessarily the logical series. The
47/// adapter rejects switching keys before a chain closes; it does not support arbitrary multiplexing
48/// of open chains, even though the general ordering permits it.
49#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
50pub enum SeriesOrdering {
51    /// Series chunks may interleave; positions within each series remain strictly increasing.
52    Interleaved,
53    /// Each series is contiguous; distinct series need not be ordered.
54    Contiguous,
55    /// Series are ordered by stream identity and then by strictly increasing position.
56    KeyThenTime,
57}
58
59/// A label with shared UTF-8 name and value strings.
60#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
61pub struct Label {
62    /// Label name.
63    pub name: Arc<str>,
64    /// Label value.
65    pub value: Arc<str>,
66}
67
68/// The PromQL-visible labels of one series: an optional metric name (`__name__`)
69/// plus its name-sorted ordinary labels.
70///
71/// The metric name is only the `__name__` value (see [`Self::name`]); this type is
72/// the whole label set a PromQL series shows. It is neither a canonical
73/// matching/grouping identity nor a storage identity (read key / primary key).
74#[derive(Clone, Debug)]
75pub struct SeriesLabels {
76    name: Option<Arc<str>>,
77    tags: LabelStorage,
78}
79
80impl serde::Serialize for SeriesLabels {
81    fn serialize<S: serde::Serializer>(
82        &self,
83        serializer: S,
84    ) -> std::result::Result<S::Ok, S::Error> {
85        (&self.name, self.tags()).serialize(serializer)
86    }
87}
88impl<'de> serde::Deserialize<'de> for SeriesLabels {
89    fn deserialize<D: serde::Deserializer<'de>>(
90        deserializer: D,
91    ) -> std::result::Result<Self, D::Error> {
92        let (name, tags): (Option<Arc<str>>, Vec<Label>) =
93            serde::Deserialize::deserialize(deserializer)?;
94        Self::try_new(name, tags).map_err(serde::de::Error::custom)
95    }
96}
97
98/// Shared, bounded series metadata and the owner of its memory reservation.
99/// Columns map logical label names to UTF-8 arrays; null labels are absent.
100pub struct SeriesLabelBatch {
101    batch: RecordBatch,
102    columns: Vec<(Arc<str>, usize)>,
103    _owner: Arc<dyn Any + Send + Sync>,
104}
105
106impl std::fmt::Debug for SeriesLabelBatch {
107    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108        f.debug_struct("SeriesLabelBatch")
109            .field("rows", &self.batch.num_rows())
110            .field("columns", &self.columns)
111            .finish_non_exhaustive()
112    }
113}
114
115impl SeriesLabelBatch {
116    /// Validates mappings once. The owner must account for the retained backing buffers.
117    pub fn try_new(
118        batch: RecordBatch,
119        mut columns: Vec<(Arc<str>, usize)>,
120        owner: Arc<dyn Any + Send + Sync>,
121    ) -> Result<Self> {
122        columns.sort_unstable_by(|a, b| a.0.cmp(&b.0));
123        if columns.iter().any(|(name, index)| {
124            name.as_ref() == "__name__"
125                || batch
126                    .columns()
127                    .get(*index)
128                    .is_none_or(|a| !a.as_any().is::<StringArray>())
129        }) || columns.windows(2).any(|p| p[0].0 == p[1].0)
130        {
131            return invalid_series("invalid batch label mapping");
132        }
133        Ok(Self {
134            batch,
135            columns,
136            _owner: owner,
137        })
138    }
139
140    /// Estimates retained buffers and one row view per batch row, including lazy
141    /// owned-label materialization. Shared buffers are conservatively counted per
142    /// array. Additional independent views of a row need their own reservation.
143    /// This is a reservation estimate, not an allocator-exact accounting contract.
144    pub fn estimated_size(&self) -> usize {
145        let arc_header = 2 * std::mem::size_of::<usize>();
146        let row_views = self
147            .batch
148            .num_rows()
149            .saturating_mul(std::mem::size_of::<BatchLabels>() + arc_header);
150        let mut bytes = self
151            .batch
152            .get_array_memory_size()
153            .saturating_add(std::mem::size_of::<Self>() + arc_header)
154            .saturating_add(
155                self.columns
156                    .capacity()
157                    .saturating_mul(std::mem::size_of::<(Arc<str>, usize)>()),
158            )
159            .saturating_add(row_views);
160        for (name, column) in &self.columns {
161            bytes = bytes.saturating_add(name.len() + arc_header);
162            for row in 0..self.batch.num_rows() {
163                if let Some(value) = self.value(*column, row) {
164                    // Vec-to-Arc conversion may temporarily retain both label arrays.
165                    bytes = bytes
166                        .saturating_add(2 * std::mem::size_of::<Label>())
167                        .saturating_add(value.len())
168                        .saturating_add(arc_header + std::mem::align_of::<usize>());
169                }
170            }
171        }
172        bytes.saturating_add(self.batch.num_rows().saturating_mul(arc_header))
173    }
174
175    fn value(&self, column: usize, row: usize) -> Option<&str> {
176        let strings = self
177            .batch
178            .column(column)
179            .as_any()
180            .downcast_ref::<StringArray>()?;
181        (!strings.is_null(row)).then(|| strings.value(row))
182    }
183}
184
185#[derive(Clone, Debug)]
186enum LabelStorage {
187    Owned(Arc<[Label]>),
188    Batch(Arc<BatchLabels>),
189}
190
191#[derive(Debug)]
192struct BatchLabels {
193    batch: Arc<SeriesLabelBatch>,
194    row: usize,
195    // Existing consumers requesting owned labels share one lazy materialization.
196    materialized: OnceLock<Arc<[Label]>>,
197}
198
199impl PartialEq for SeriesLabels {
200    fn eq(&self, other: &Self) -> bool {
201        if self.name != other.name {
202            return false;
203        }
204        if let (LabelStorage::Batch(a), LabelStorage::Batch(b)) = (&self.tags, &other.tags)
205            && Arc::ptr_eq(a, b)
206        {
207            return true;
208        }
209        self.tags() == other.tags()
210    }
211}
212impl Eq for SeriesLabels {}
213
214impl std::hash::Hash for SeriesLabels {
215    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
216        std::hash::Hash::hash(&self.name, state);
217        std::hash::Hash::hash(self.tags(), state);
218    }
219}
220
221impl SeriesLabels {
222    /// Creates a metric name, sorting labels and rejecting duplicates or `__name__` tags.
223    pub fn try_new(name: Option<Arc<str>>, mut tags: Vec<Label>) -> Result<Self> {
224        tags.sort_unstable_by(|a, b| a.name.cmp(&b.name));
225        if tags.iter().any(|tag| tag.name.as_ref() == "__name__") {
226            return invalid_series("__name__ must be stored as the metric name");
227        }
228        if tags.windows(2).any(|pair| pair[0].name == pair[1].name) {
229            return invalid_series("duplicate label name");
230        }
231        Ok(Self {
232            name,
233            tags: LabelStorage::Owned(tags.into()),
234        })
235    }
236
237    /// Returns the metric name, if present.
238    pub fn name(&self) -> Option<&str> {
239        self.name.as_deref()
240    }
241
242    /// Returns ordinary labels sorted by name.
243    pub fn tags(&self) -> &[Label] {
244        match &self.tags {
245            LabelStorage::Owned(tags) => tags,
246            LabelStorage::Batch(labels) => labels.materialized.get_or_init(|| {
247                labels
248                    .batch
249                    .columns
250                    .iter()
251                    .filter_map(|(name, column)| {
252                        labels.batch.value(*column, labels.row).map(|value| Label {
253                            name: name.clone(),
254                            value: Arc::from(value),
255                        })
256                    })
257                    .collect::<Vec<_>>()
258                    .into()
259            }),
260        }
261    }
262
263    /// Creates a shared row view without encoding keys or allocating owned label strings.
264    pub fn from_batch(
265        name: Option<Arc<str>>,
266        batch: Arc<SeriesLabelBatch>,
267        row: usize,
268    ) -> Result<Self> {
269        if row >= batch.batch.num_rows() {
270            return invalid_series("series label row out of bounds");
271        }
272        Ok(Self {
273            name,
274            tags: LabelStorage::Batch(Arc::new(BatchLabels {
275                batch,
276                row,
277                materialized: OnceLock::new(),
278            })),
279        })
280    }
281
282    /// Returns a label value, distinguishing absence from an empty value.
283    pub fn get(&self, label: &str) -> Option<&str> {
284        if label == "__name__" {
285            self.name()
286        } else if let LabelStorage::Batch(labels) = &self.tags {
287            let i = labels
288                .batch
289                .columns
290                .binary_search_by(|(name, _)| name.as_ref().cmp(label))
291                .ok()?;
292            labels.batch.value(labels.batch.columns[i].1, labels.row)
293        } else {
294            self.tags()
295                .binary_search_by(|tag| tag.name.as_ref().cmp(label))
296                .ok()
297                .map(|index| self.tags()[index].value.as_ref())
298        }
299    }
300
301    /// Sets the metric name or an ordinary label, preserving other shared labels.
302    pub fn set(&mut self, label: &str, value: Arc<str>) -> Result<()> {
303        if label == "__name__" {
304            self.name = Some(value);
305            return Ok(());
306        }
307        match self
308            .tags()
309            .binary_search_by(|tag| tag.name.as_ref().cmp(label))
310        {
311            Ok(index) => {
312                let mut tags = self.tags().to_vec();
313                tags[index].value = value;
314                self.tags = LabelStorage::Owned(tags.into());
315            }
316            Err(index) => {
317                let mut tags = self.tags().to_vec();
318                tags.insert(
319                    index,
320                    Label {
321                        name: Arc::from(label),
322                        value,
323                    },
324                );
325                self.tags = LabelStorage::Owned(tags.into());
326            }
327        }
328        Ok(())
329    }
330
331    /// Removes a label or clears the metric name.
332    pub fn remove(&mut self, label: &str) {
333        if label == "__name__" {
334            self.name = None;
335        } else if let Ok(index) = self
336            .tags()
337            .binary_search_by(|tag| tag.name.as_ref().cmp(label))
338        {
339            let mut tags = self.tags().to_vec();
340            tags.remove(index);
341            self.tags = LabelStorage::Owned(tags.into());
342        }
343    }
344
345    /// Keeps only the named labels and metric name.
346    pub fn keep_only(&mut self, labels: &[&str]) {
347        if !labels.contains(&"__name__") {
348            self.name = None;
349        }
350        let kept: Vec<_> = self
351            .tags()
352            .iter()
353            .filter(|tag| labels.contains(&tag.name.as_ref()))
354            .cloned()
355            .collect();
356        if kept.len() != self.tags().len() {
357            self.tags = LabelStorage::Owned(kept.into());
358        }
359    }
360
361    /// Removes the selected labels and metric name.
362    pub fn remove_all(&mut self, labels: &[&str]) {
363        if labels.contains(&"__name__") {
364            self.name = None;
365        }
366        let kept: Vec<_> = self
367            .tags()
368            .iter()
369            .filter(|tag| !labels.contains(&tag.name.as_ref()))
370            .cloned()
371            .collect();
372        if kept.len() != self.tags().len() {
373            self.tags = LabelStorage::Owned(kept.into());
374        }
375    }
376}
377
378fn invalid_series<T>(reason: &str) -> Result<T> {
379    InvalidSeriesSnafu {
380        reason: reason.to_string(),
381    }
382    .fail()
383}