Skip to main content

mito2/series_index/
identity.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//! The exact series identity that SSTs already store.
16//!
17//! `tsid` is a hash, so two distinct series can share one [`MetricSeriesId`]. The
18//! sparse primary key stored by the SST is exact, so every place that decides
19//! whether two rows belong to the same series decides it on [`ExactSeriesKey`].
20
21use std::cmp::Ordering;
22use std::fmt;
23use std::hash::{Hash, Hasher};
24
25use mito_codec::row_converter::SparseOffsetsCache;
26use mito_codec::row_converter::sparse::SparsePrimaryKeyView;
27use snafu::ResultExt;
28use store_api::storage::ColumnId;
29
30use crate::error::{DecodeSnafu, Result};
31use crate::series_index::MetricSeriesId;
32
33/// The identity semantics *and storage layout* an artifact was written with.
34///
35/// This is the one mandatory discriminator every artifact manifest carries. Artifacts
36/// written under hash-only identity are structurally valid and perfectly ordered, so
37/// nothing else in them distinguishes them from exact ones: an already collapsed series
38/// index looks fine and its lost labels cannot be recovered. A manifest that does not
39/// name this encoding is therefore not reusable, whatever its coverage says.
40///
41/// The serialized value names the layout as well as the identity, because two artifacts can
42/// store the same exact key in incompatible places: the samples format kept one copy per block
43/// inside its pages, then moved to one copy per series in a dedicated key area.
44/// An artifact of the older layout is structurally valid and ordered too, so without
45/// the layout in this value maintenance would mark it reusable and only a part read would fail.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
47pub(crate) enum IdentityEncoding {
48    /// Identity is [`ExactSeriesKey`], stored inside the artifact's own pages: the
49    /// series-index layout, and the retired samples layout that repeated the key in every
50    /// block descriptor.
51    #[serde(rename = "exact-sparse-key")]
52    ExactSparseKey,
53    /// Identity is [`ExactSeriesKey`], stored once per series in each sample group's key area
54    /// after its column payloads.
55    #[serde(rename = "exact-sparse-key-area")]
56    ExactSparseKeyArea,
57}
58
59impl IdentityEncoding {
60    /// The encoding new samples artifacts are written with; their readers require exactly this.
61    ///
62    /// Distinct from the series-index encoding on purpose: it names the key-area layout, so an
63    /// artifact written before the key area cannot be taken for a current one.
64    pub(crate) const CURRENT_SAMPLES: Self = Self::ExactSparseKeyArea;
65
66    /// The encoding new series-index artifacts are written with; their readers require this.
67    pub(crate) const CURRENT_SERIES_INDEX: Self = Self::ExactSparseKey;
68}
69
70/// The exact identity of one series: its canonical sparse primary-key bytes.
71///
72/// The key is the SST's own encoding of
73/// `(table_id, tsid, label column-id/value pairs sorted by name, non-null only)`,
74/// as produced by [`mito_codec::row_converter::sparse::SparsePrimaryKeyCodec`]. No
75/// second label encoding exists: callers hand in the bytes they read from the SST.
76///
77/// # Ordering
78///
79/// Identity and order are both defined on the encoded bytes only:
80///
81/// * `PartialEq`/`Hash` use the bytes, so two keys are the same series iff their
82///   encodings are equal.
83/// * `Ord` is byte-lexicographic. The reserved `table_id`/`tsid` prefix is fixed
84///   width and order preserving, so this order groups every key that shares one
85///   [`MetricSeriesId`] together and sorts those groups by `MetricSeriesId`.
86///   Inside one group it orders by the encoded `(column_id, value)` label sequence.
87///
88/// This is also the order SSTs store rows in, so artifact writers receive input in
89/// key order and can reject regressions instead of guessing.
90///
91/// `id` is always derived from `key` and never participates in comparison: every
92/// comparison below reads `key` only.
93///
94/// # Assumptions
95///
96/// This is *storage* identity, not Prometheus label-set identity. It relies on the
97/// existing sparse format's invariants, none of which it redefines:
98///
99/// * `tsid` is a stable hash for a label set within one logical table; a rebuild of
100///   the same rows writes the same `tsid`.
101/// * Column IDs are stable for a region, so the encoded `(column_id, value)` pairs
102///   identify the same labels over time. Re-creating a region with different IDs
103///   changes the key bytes.
104/// * Labels are encoded in the codec's canonical order (sorted by column name), and
105///   null labels are omitted while empty strings are encoded. This type never
106///   normalizes either case.
107///
108/// Equal keys therefore mean "the same series as far as this database stores it".
109/// They are not claimed to be equal to any Prometheus series identity.
110#[derive(Clone)]
111pub(crate) struct ExactSeriesKey {
112    /// Order-preserving `(table_id, tsid)` prefix decoded from `key`.
113    id: MetricSeriesId,
114    /// Canonical sparse primary-key encoding of the whole series.
115    key: Box<[u8]>,
116}
117
118impl ExactSeriesKey {
119    /// Wraps one encoded sparse primary key after validating its framing.
120    ///
121    /// # Length
122    ///
123    /// This entry point deliberately has no length cap, and neither does any other:
124    /// key length is bounded by the containers that store a key (one key per block,
125    /// plus the descriptor, page, and column limits), and a cap enforced on only one
126    /// entry point would let a writer publish a key another one refuses. Long labels
127    /// are real data — a single 8 KiB label already encodes to a larger sparse key —
128    /// so framing validation is the only requirement here.
129    pub(crate) fn from_sparse_key(key: &[u8], offsets: &mut SparseOffsetsCache) -> Result<Self> {
130        let mut view = SparsePrimaryKeyView::new(key, offsets).context(DecodeSnafu)?;
131        // `new` validates the reserved prefix only; walk the labels so a truncated or
132        // trailing-garbage key cannot become an identity that happens to share a prefix.
133        view.visit_label_ids(|_| Ok(())).context(DecodeSnafu)?;
134        Ok(Self::from_view(&view, key))
135    }
136
137    /// Constructs an identity from bytes already encoded or validated at the source.
138    pub(super) fn from_prevalidated_sparse_key(key: &[u8]) -> Option<Self> {
139        let (table_id, tsid) =
140            mito_codec::row_converter::sparse::read_prevalidated_series_ids(key)?;
141        Some(Self {
142            id: MetricSeriesId { table_id, tsid },
143            key: key.into(),
144        })
145    }
146
147    /// The reserved `(table_id, tsid)` prefix. It is a coarse bucket, not identity.
148    pub(crate) fn id(&self) -> MetricSeriesId {
149        self.id
150    }
151
152    /// The canonical bytes; the only thing that decides identity.
153    pub(crate) fn bytes(&self) -> &[u8] {
154        &self.key
155    }
156
157    /// Builds the key from a view already validated against `key`.
158    fn from_view(view: &SparsePrimaryKeyView<'_, '_>, key: &[u8]) -> Self {
159        Self {
160            id: MetricSeriesId {
161                table_id: view.table_id(),
162                tsid: view.tsid(),
163            },
164            key: key.into(),
165        }
166    }
167}
168
169// Only `key` participates in identity. `id` is a prefix function of `key`, so a
170// future field cannot accidentally join (or reorder) the identity.
171
172impl PartialEq for ExactSeriesKey {
173    fn eq(&self, other: &Self) -> bool {
174        self.key == other.key
175    }
176}
177
178impl Eq for ExactSeriesKey {}
179
180impl PartialOrd for ExactSeriesKey {
181    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
182        Some(self.cmp(other))
183    }
184}
185
186impl Ord for ExactSeriesKey {
187    fn cmp(&self, other: &Self) -> Ordering {
188        self.key.cmp(&other.key)
189    }
190}
191
192impl fmt::Debug for ExactSeriesKey {
193    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194        f.debug_struct("ExactSeriesKey")
195            .field("id", &self.id)
196            .field("key", &Hex(&self.key))
197            .finish()
198    }
199}
200
201/// Lets a map keyed by the exact key be probed with the raw canonical bytes it was
202/// built from, so hot loops do not allocate a key per row. `Ord`/`Eq` are byte
203/// comparisons, which is exactly `[u8]`'s order, so the borrow is consistent.
204impl std::borrow::Borrow<[u8]> for ExactSeriesKey {
205    fn borrow(&self) -> &[u8] {
206        &self.key
207    }
208}
209
210impl Hash for ExactSeriesKey {
211    fn hash<H: Hasher>(&self, state: &mut H) {
212        self.key.hash(state);
213    }
214}
215
216/// Prints at most [`HEX_LIMIT`] bytes of a key, so logs stay bounded.
217struct Hex<'a>(&'a [u8]);
218
219const HEX_LIMIT: usize = 64;
220
221impl fmt::Debug for Hex<'_> {
222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223        for byte in self.0.iter().take(HEX_LIMIT) {
224            write!(f, "{byte:02x}")?;
225        }
226        if self.0.len() > HEX_LIMIT {
227            write!(f, "...({} bytes)", self.0.len())?;
228        }
229        Ok(())
230    }
231}
232
233/// Decodes one sparse primary key into its exact identity and `tag_columns` labels.
234///
235/// This is the only decoder artifact writers use, so the identity they aggregate and
236/// the labels they persist always come from the same key.
237pub(crate) fn decode_series_identity(
238    primary_key: &[u8],
239    tag_columns: &[(ColumnId, String)],
240    offsets: &mut SparseOffsetsCache,
241    buf: &mut Vec<u8>,
242) -> Result<(ExactSeriesKey, Vec<Option<String>>)> {
243    let mut view = SparsePrimaryKeyView::new(primary_key, offsets).context(DecodeSnafu)?;
244    // Validate every label once and cache its offset; the tag lookups below reuse it,
245    // and a truncated key never reaches a persisted row.
246    view.visit_label_ids(|_| Ok(())).context(DecodeSnafu)?;
247    let key = ExactSeriesKey::from_view(&view, primary_key);
248    let mut tags = Vec::with_capacity(tag_columns.len());
249    for (column_id, _) in tag_columns {
250        tags.push(
251            view.label(*column_id, buf)
252                .context(DecodeSnafu)?
253                .map(str::to_owned),
254        );
255    }
256    Ok((key, tags))
257}
258
259#[cfg(test)]
260mod tests {
261    use store_api::codec::PrimaryKeyEncoding;
262
263    use super::*;
264    use crate::test_util::sst_util::{new_sparse_primary_key, sst_region_metadata_with_encoding};
265
266    fn metadata() -> std::sync::Arc<store_api::metadata::RegionMetadata> {
267        std::sync::Arc::new(sst_region_metadata_with_encoding(
268            PrimaryKeyEncoding::Sparse,
269        ))
270    }
271
272    fn key(tags: &[&str], table_id: u32, tsid: u64) -> Vec<u8> {
273        new_sparse_primary_key(tags, &metadata(), table_id, tsid)
274    }
275
276    #[test]
277    fn identity_is_the_exact_key_not_the_tsid() {
278        let mut offsets = SparseOffsetsCache::new();
279        let first =
280            ExactSeriesKey::from_sparse_key(&key(&["host-020078", "z"], 1, 7), &mut offsets)
281                .unwrap();
282        let partner =
283            ExactSeriesKey::from_sparse_key(&key(&["host-029838", "z"], 1, 7), &mut offsets)
284                .unwrap();
285        assert_eq!(first.id(), partner.id());
286        assert_ne!(first, partner);
287        assert_ne!(first.bytes(), partner.bytes());
288        let same = ExactSeriesKey::from_sparse_key(&key(&["host-020078", "z"], 1, 7), &mut offsets)
289            .unwrap();
290        assert_eq!(first, same);
291    }
292
293    #[test]
294    fn order_groups_equal_identifiers_and_sorts_groups_by_identifier() {
295        let mut offsets = SparseOffsetsCache::new();
296        let mut keys = Vec::new();
297        for (table_id, tsid, label) in [
298            (1, 2, "b"),
299            (1, 2, "a"),
300            (1, 3, "a"),
301            (2, 1, "a"),
302            (1, 2, "c"),
303        ] {
304            keys.push(
305                ExactSeriesKey::from_sparse_key(&key(&[label, "z"], table_id, tsid), &mut offsets)
306                    .unwrap(),
307            );
308        }
309        let mut sorted = keys.clone();
310        sorted.sort();
311        // Byte order sorts by (table_id, tsid) first, then by the encoded labels, and
312        // every key sharing an identifier stays adjacent.
313        let ids: Vec<_> = sorted.iter().map(|key| key.id()).collect();
314        assert_eq!(
315            ids,
316            vec![
317                MetricSeriesId {
318                    table_id: 1,
319                    tsid: 2
320                },
321                MetricSeriesId {
322                    table_id: 1,
323                    tsid: 2
324                },
325                MetricSeriesId {
326                    table_id: 1,
327                    tsid: 2
328                },
329                MetricSeriesId {
330                    table_id: 1,
331                    tsid: 3
332                },
333                MetricSeriesId {
334                    table_id: 2,
335                    tsid: 1
336                },
337            ]
338        );
339        // Ordering is decided on the encoded bytes alone.
340        for pair in keys.windows(2) {
341            assert_eq!(pair[0].cmp(&pair[1]), pair[0].bytes().cmp(pair[1].bytes()));
342        }
343        assert!(sorted.is_sorted());
344    }
345
346    #[test]
347    fn long_keys_are_identity_not_an_error() {
348        let mut offsets = SparseOffsetsCache::new();
349        // One 8 KiB label already encodes to a sparse key past 8 KiB. Both entry points
350        // must accept it: the containers that store a key bound its length, and a cap on
351        // one entry point alone would publish keys another refuses.
352        let label = "x".repeat(8 * 1024);
353        let encoded = key(&[&label, "z"], 1, 7);
354        assert!(encoded.len() > 8 * 1024, "{}", encoded.len());
355        let exact = ExactSeriesKey::from_sparse_key(&encoded, &mut offsets).unwrap();
356        assert_eq!(encoded, exact.bytes());
357        let tag_columns = [(0, "tag_0".to_string()), (1, "tag_1".to_string())];
358        let (decoded, tags) =
359            decode_series_identity(&encoded, &tag_columns, &mut offsets, &mut Vec::new()).unwrap();
360        assert_eq!(exact, decoded);
361        assert_eq!(Some(label), tags[0]);
362    }
363
364    #[test]
365    fn malformed_keys_are_rejected() {
366        let mut offsets = SparseOffsetsCache::new();
367        assert!(ExactSeriesKey::from_sparse_key(&[], &mut offsets).is_err());
368        assert!(ExactSeriesKey::from_sparse_key(&[0; 13], &mut offsets).is_err());
369        let good = key(&["a", "b"], 1, 1);
370        assert!(ExactSeriesKey::from_sparse_key(&good[..good.len() - 1], &mut offsets).is_err());
371        assert_eq!(
372            ExactSeriesKey::from_prevalidated_sparse_key(&good)
373                .unwrap()
374                .id(),
375            MetricSeriesId {
376                table_id: 1,
377                tsid: 1
378            }
379        );
380    }
381}