Skip to main content

mito_codec/row_converter/sparse/
checked.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 bytes::Buf;
16use snafu::{OptionExt, ensure};
17use store_api::storage::ColumnId;
18
19use crate::error::{InvalidSparsePrimaryKeySnafu, Result};
20use crate::row_converter::encoded_string_len;
21use crate::row_converter::sparse::{
22    COLUMN_ID_ENCODE_SIZE, RESERVED_COLUMN_ID_TABLE_ID, RESERVED_COLUMN_ID_TSID,
23    SparseOffsetsCache, TABLE_ID_VALUE_OFFSET, TAGS_START_OFFSET, TSID_VALUE_OFFSET,
24    validate_prefix,
25};
26
27/// A borrowing view of one sparse primary key, with checked, lazy field lookup.
28///
29/// The scratch cache is reset on construction and retains its capacity between keys.
30/// Ordinary labels can be skipped without schema lookup: their encoding is always String.
31pub struct SparsePrimaryKeyView<'a, 'b> {
32    pk: &'a [u8],
33    cache: &'b mut SparseOffsetsCache,
34}
35
36impl<'a, 'b> SparsePrimaryKeyView<'a, 'b> {
37    /// Validates the fixed prefix and binds fresh offset discovery to this key.
38    pub fn new(pk: &'a [u8], cache: &'b mut SparseOffsetsCache) -> Result<Self> {
39        validate_prefix(pk)?;
40        cache.clear();
41        Ok(Self { pk, cache })
42    }
43
44    /// Returns the encoded value, including its null marker, or None for an absent label.
45    /// The result borrows the key, not the scratch cache.
46    pub fn encoded_value(&mut self, column_id: ColumnId) -> Result<Option<&'a [u8]>> {
47        match column_id {
48            RESERVED_COLUMN_ID_TABLE_ID => {
49                return Ok(Some(
50                    &self.pk[TABLE_ID_VALUE_OFFSET..TSID_VALUE_OFFSET - COLUMN_ID_ENCODE_SIZE],
51                ));
52            }
53            RESERVED_COLUMN_ID_TSID => {
54                return Ok(Some(&self.pk[TSID_VALUE_OFFSET..TAGS_START_OFFSET]));
55            }
56            _ => {}
57        }
58        if let Some(offset) = self.cache.get(column_id) {
59            return encoded_label(&self.pk[offset..]).map(Some);
60        }
61        while let Some((id, value)) = self.next_label()? {
62            if id == column_id {
63                return Ok(Some(value));
64            }
65        }
66        Ok(None)
67    }
68
69    /// Visits every ordinary label id in encoded order, validating the complete tail.
70    /// Resets offset discovery for this key before traversing it.
71    pub fn visit_label_ids(&mut self, mut visit: impl FnMut(ColumnId) -> Result<()>) -> Result<()> {
72        self.cache.clear();
73        while let Some((id, _)) = self.next_label()? {
74            visit(id)?;
75        }
76        Ok(())
77    }
78
79    /// Parses and caches the next ordinary label, advancing the per-key cursor.
80    fn next_label(&mut self) -> Result<Option<(ColumnId, &'a [u8])>> {
81        if self.cache.finished || self.cache.cursor == self.pk.len() {
82            self.cache.finished = true;
83            return Ok(None);
84        }
85        let bytes = &self.pk[self.cache.cursor..];
86        let id =
87            bytes
88                .first_chunk::<COLUMN_ID_ENCODE_SIZE>()
89                .context(InvalidSparsePrimaryKeySnafu {
90                    reason: "truncated label column id",
91                })?;
92        let id = u32::from_be_bytes(*id);
93        let offset = self.cache.cursor + COLUMN_ID_ENCODE_SIZE;
94        ensure!(
95            id != RESERVED_COLUMN_ID_TABLE_ID
96                && id != RESERVED_COLUMN_ID_TSID
97                && self.cache.get(id).is_none(),
98            InvalidSparsePrimaryKeySnafu {
99                reason: "duplicate or reserved label column id"
100            }
101        );
102        let value = encoded_label(&self.pk[offset..])?;
103        self.cache.insert(id, offset);
104        self.cache.cursor = offset + value.len();
105        Ok(Some((id, value)))
106    }
107
108    /// Extracts a UTF-8 label into a reusable buffer, validating it once.
109    /// Missing and null labels return `None` without modifying the buffer;
110    /// an empty label returns `Some("")`. Reserved numeric columns are rejected.
111    /// The returned string borrows `buffer`, whose contents are replaced for each label.
112    pub fn label<'buf>(
113        &mut self,
114        column_id: ColumnId,
115        buffer: &'buf mut Vec<u8>,
116    ) -> Result<Option<&'buf str>> {
117        ensure!(
118            !matches!(
119                column_id,
120                RESERVED_COLUMN_ID_TABLE_ID | RESERVED_COLUMN_ID_TSID
121            ),
122            InvalidSparsePrimaryKeySnafu {
123                reason: "reserved column is not a string label"
124            }
125        );
126        let Some(encoded) = self.encoded_value(column_id)? else {
127            return Ok(None);
128        };
129        if encoded[0] == 0 {
130            return Ok(None);
131        }
132
133        buffer.clear();
134        // encoded_value checked the markers and every chunk length. Reserve once
135        // before unchunking so the buffer does not grow for each 8-byte chunk.
136        buffer.reserve(encoded.len() - 2);
137        for chunk in encoded[2..].as_chunks::<9>().0 {
138            let len = usize::from(chunk[8]).min(8);
139            buffer.extend_from_slice(&chunk[..len]);
140        }
141        std::str::from_utf8(buffer).map(Some).map_err(|_| {
142            InvalidSparsePrimaryKeySnafu {
143                reason: "label is not valid UTF-8",
144            }
145            .build()
146        })
147    }
148
149    /// Returns the table id from the non-null prefix validated by [`Self::new`].
150    pub fn table_id(&self) -> u32 {
151        (&self.pk[TABLE_ID_VALUE_OFFSET + 1..]).get_u32()
152    }
153
154    /// Returns the series id from the non-null prefix validated by [`Self::new`].
155    pub fn tsid(&self) -> u64 {
156        (&self.pk[TSID_VALUE_OFFSET + 1..]).get_u64()
157    }
158}
159
160/// Finds the end of an Option<String> without allocating or reading its payload.
161/// Unlike memcomparable's skip_bytes, all advances are checked for truncated input.
162fn encoded_label(bytes: &[u8]) -> Result<&[u8]> {
163    let len = encoded_string_len(bytes).map_err(|error| {
164        InvalidSparsePrimaryKeySnafu {
165            reason: error.to_string(),
166        }
167        .build()
168    })?;
169    Ok(&bytes[..len])
170}
171
172#[cfg(test)]
173mod tests {
174    use datatypes::data_type::ConcreteDataType;
175    use datatypes::value::ValueRef;
176
177    use super::*;
178    use crate::index::IndexValueCodec;
179    use crate::row_converter::{PrimaryKeyCodec, SortField, SparsePrimaryKeyCodec};
180
181    #[test]
182    fn index_bytes_match_full_decode_across_chunks_and_lookup_orders() {
183        let codec = SparsePrimaryKeyCodec::schemaless();
184        let mut cache = SparseOffsetsCache::new();
185        let mut buffer = Vec::new();
186        // Reusing the cache across different keys must not reuse their field offsets.
187        for len in [0, 1, 7, 8, 9, 16, 24, 65] {
188            let label = "x".repeat(len);
189            let values = [
190                (RESERVED_COLUMN_ID_TABLE_ID, ValueRef::UInt32(42)),
191                (RESERVED_COLUMN_ID_TSID, ValueRef::UInt64(u64::MAX)),
192                (90, ValueRef::String(&label)),
193                (7, ValueRef::String("")),
194                (1, ValueRef::Null),
195                (3, ValueRef::String("last中文")),
196            ];
197            let mut pk = Vec::new();
198            codec.encode_value_refs(&values, &mut pk).unwrap();
199            // Exercise the offset cache's overflow storage as well as its inline entries.
200            codec
201                .encode_raw_tag_value((100..140).map(|id| (id, label.as_bytes())), &mut pk)
202                .unwrap();
203            // Writers normally omit null labels; existing encoded nulls must remain null too.
204            pk.extend_from_slice(&2_u32.to_be_bytes());
205            pk.push(0);
206            let decoded = codec.decode(&pk).unwrap().into_sparse();
207            for order in [
208                [
209                    RESERVED_COLUMN_ID_TABLE_ID,
210                    RESERVED_COLUMN_ID_TSID,
211                    90,
212                    7,
213                    1,
214                    3,
215                ],
216                [
217                    3,
218                    1,
219                    7,
220                    90,
221                    RESERVED_COLUMN_ID_TSID,
222                    RESERVED_COLUMN_ID_TABLE_ID,
223                ],
224            ] {
225                let mut view = SparsePrimaryKeyView::new(&pk, &mut cache).unwrap();
226                for id in order.into_iter().chain([139, 100, 132, 2]) {
227                    let expected = decoded.get(&id).filter(|v| !v.is_null()).map(|value| {
228                        let field = SortField::new(match id {
229                            RESERVED_COLUMN_ID_TABLE_ID => ConcreteDataType::uint32_datatype(),
230                            RESERVED_COLUMN_ID_TSID => ConcreteDataType::uint64_datatype(),
231                            _ => ConcreteDataType::string_datatype(),
232                        });
233                        let mut bytes = Vec::new();
234                        IndexValueCodec::encode_nonnull_value(
235                            value.as_value_ref(),
236                            &field,
237                            &mut bytes,
238                        )
239                        .unwrap();
240                        bytes
241                    });
242                    let actual =
243                        IndexValueCodec::encode_sparse_value(&mut view, id, &mut buffer).unwrap();
244                    assert_eq!(actual, expected.as_deref(), "len={len}, column={id}");
245                }
246                assert!(view.encoded_value(999).unwrap().is_none());
247            }
248        }
249    }
250
251    #[test]
252    fn visits_all_label_ids_in_order_and_resets_cache_for_each_key() {
253        let codec = SparsePrimaryKeyCodec::schemaless();
254        let mut cache = SparseOffsetsCache::new();
255        let mut first = Vec::new();
256        codec.encode_internal(1, 2, &mut first).unwrap();
257        codec
258            .encode_raw_tag_value(
259                [(8, b"a".as_slice()), (3, b"b"), (12, b"c")].into_iter(),
260                &mut first,
261            )
262            .unwrap();
263        let mut second = Vec::new();
264        codec.encode_internal(1, 2, &mut second).unwrap();
265        codec
266            .encode_raw_tag_value([(99, b"z".as_slice())].into_iter(), &mut second)
267            .unwrap();
268
269        let mut view = SparsePrimaryKeyView::new(&first, &mut cache).unwrap();
270        assert!(view.encoded_value(8).unwrap().is_some());
271        let mut visited = Vec::new();
272        view.visit_label_ids(|id| {
273            visited.push(id);
274            Ok(())
275        })
276        .unwrap();
277        assert_eq!(visited, [8, 3, 12]);
278        let mut view = SparsePrimaryKeyView::new(&second, &mut cache).unwrap();
279        visited.clear();
280        view.visit_label_ids(|id| {
281            visited.push(id);
282            Ok(())
283        })
284        .unwrap();
285        assert_eq!(visited, [99]);
286    }
287
288    #[test]
289    fn visits_unknown_ids_before_and_after_known_lookup() {
290        let codec = SparsePrimaryKeyCodec::schemaless();
291        let mut pk = Vec::new();
292        codec.encode_internal(1, 2, &mut pk).unwrap();
293        codec
294            .encode_raw_tag_value(
295                [(1, b"one".as_slice()), (5, b"five"), (9, b"nine")].into_iter(),
296                &mut pk,
297            )
298            .unwrap();
299        let mut cache = SparseOffsetsCache::new();
300        let mut view = SparsePrimaryKeyView::new(&pk, &mut cache).unwrap();
301        assert!(view.encoded_value(5).unwrap().is_some());
302        let mut visited = Vec::new();
303        view.visit_label_ids(|id| {
304            visited.push(id);
305            Ok(())
306        })
307        .unwrap();
308        assert_eq!(visited, [1, 5, 9]);
309        assert!(view.encoded_value(100).unwrap().is_none());
310    }
311
312    #[test]
313    fn full_visit_catches_malformed_tail_after_early_lookup() {
314        let codec = SparsePrimaryKeyCodec::schemaless();
315        let mut pk = Vec::new();
316        codec.encode_internal(1, 2, &mut pk).unwrap();
317        codec
318            .encode_raw_tag_value([(1, b"ok".as_slice())].into_iter(), &mut pk)
319            .unwrap();
320        pk.extend_from_slice(&2_u32.to_be_bytes());
321        pk.extend_from_slice(&[1, 1, 1]);
322        let mut cache = SparseOffsetsCache::new();
323        let mut view = SparsePrimaryKeyView::new(&pk, &mut cache).unwrap();
324        assert!(view.encoded_value(1).unwrap().is_some());
325        assert!(view.visit_label_ids(|_| Ok(())).is_err());
326    }
327
328    #[test]
329    fn visit_rejects_duplicate_reserved_truncated_and_bad_framing_tail() {
330        let codec = SparsePrimaryKeyCodec::schemaless();
331        let mut cache = SparseOffsetsCache::new();
332        let mut duplicate_tail = Vec::new();
333        codec
334            .encode_raw_tag_value(
335                [(1, b"duplicate".as_slice())].into_iter(),
336                &mut duplicate_tail,
337            )
338            .unwrap();
339        let cases = [
340            (duplicate_tail, "duplicate or reserved label column id"),
341            (
342                [
343                    RESERVED_COLUMN_ID_TABLE_ID.to_be_bytes().as_slice(),
344                    &[1, 1, b'x', 0],
345                ]
346                .concat(),
347                "duplicate or reserved label column id",
348            ),
349            (
350                [
351                    RESERVED_COLUMN_ID_TSID.to_be_bytes().as_slice(),
352                    &[1, 1, b'x', 0],
353                ]
354                .concat(),
355                "duplicate or reserved label column id",
356            ),
357            (
358                [2_u32.to_be_bytes().as_slice(), &[1, 1, b'x']].concat(),
359                "unexpected end of input",
360            ),
361            (
362                [2_u32.to_be_bytes().as_slice(), &[2]].concat(),
363                "invalid tag encoding: 2",
364            ),
365        ];
366        for (tail, expected_reason) in cases {
367            let mut pk = Vec::new();
368            codec.encode_internal(1, 2, &mut pk).unwrap();
369            codec
370                .encode_raw_tag_value([(1, b"ok".as_slice())].into_iter(), &mut pk)
371                .unwrap();
372            pk.extend_from_slice(&tail);
373            let mut view = SparsePrimaryKeyView::new(&pk, &mut cache).unwrap();
374            let error = view.visit_label_ids(|_| Ok(())).unwrap_err();
375            assert!(
376                error.to_string().contains(expected_reason),
377                "expected {expected_reason:?}, got {error}"
378            );
379        }
380
381        let mut truncated_id = Vec::new();
382        codec.encode_internal(1, 2, &mut truncated_id).unwrap();
383        truncated_id.push(1);
384        let mut view = SparsePrimaryKeyView::new(&truncated_id, &mut cache).unwrap();
385        let error = view.visit_label_ids(|_| Ok(())).unwrap_err();
386        assert!(error.to_string().contains("truncated label column id"));
387    }
388
389    #[test]
390    fn reserved_ids_preserve_unsigned_values() {
391        let codec = SparsePrimaryKeyCodec::schemaless();
392        let mut cache = SparseOffsetsCache::new();
393        for (table_id, tsid) in [(0, 0), (42, u64::MAX), (u32::MAX, 42)] {
394            let mut pk = Vec::new();
395            codec.encode_internal(table_id, tsid, &mut pk).unwrap();
396            let view = SparsePrimaryKeyView::new(&pk, &mut cache).unwrap();
397            assert_eq!(view.table_id(), table_id);
398            assert_eq!(view.tsid(), tsid);
399        }
400    }
401
402    #[test]
403    fn malformed_sparse_values_return_errors() {
404        let codec = SparsePrimaryKeyCodec::schemaless();
405        let mut pk = Vec::new();
406        codec.encode_internal(1, 2, &mut pk).unwrap();
407        codec
408            .encode_raw_tag_value([(1, b"0123456789".as_slice())].into_iter(), &mut pk)
409            .unwrap();
410        let mut cache = SparseOffsetsCache::new();
411        for end in 0..pk.len() {
412            // A complete reserved prefix is a valid key with no labels.
413            if end == TAGS_START_OFFSET {
414                continue;
415            }
416            let result = SparsePrimaryKeyView::new(&pk[..end], &mut cache)
417                .and_then(|mut view| view.encoded_value(1));
418            assert!(result.is_err(), "truncation at {end}");
419        }
420        for (offset, value) in [(0, 0), (4, 0), (13, 2), (26, 2), (27, 2), (36, 0), (45, 10)] {
421            let mut invalid = pk.clone();
422            invalid[offset] = value;
423            assert!(
424                SparsePrimaryKeyView::new(&invalid, &mut cache)
425                    .and_then(|mut view| view.encoded_value(1))
426                    .is_err()
427            );
428        }
429        let mut invalid_utf8 = pk;
430        invalid_utf8[28] = 0xff;
431        let mut view = SparsePrimaryKeyView::new(&invalid_utf8, &mut cache).unwrap();
432        assert!(IndexValueCodec::encode_sparse_value(&mut view, 1, &mut Vec::new()).is_err());
433    }
434
435    #[test]
436    fn label_reuses_buffer_across_null_empty_invalid_and_valid_values() {
437        let codec = SparsePrimaryKeyCodec::schemaless();
438        let mut cache = SparseOffsetsCache::new();
439        let mut buffer = Vec::with_capacity(256);
440        let ptr = buffer.as_ptr();
441        for label in [
442            b"1234567\xe4\xb8\xad\0\xe6\x96\x87".as_slice(),
443            b"",
444            b"\xff",
445            b"after-error",
446        ] {
447            let mut pk = Vec::new();
448            codec.encode_internal(42, 7, &mut pk).unwrap();
449            codec
450                .encode_raw_tag_value([(1, label)].into_iter(), &mut pk)
451                .unwrap();
452            pk.extend_from_slice(&2_u32.to_be_bytes());
453            pk.push(0);
454            let mut view = SparsePrimaryKeyView::new(&pk, &mut cache).unwrap();
455            let actual = view.label(1, &mut buffer);
456            match std::str::from_utf8(label) {
457                Ok(expected) => assert_eq!(actual.unwrap(), Some(expected)),
458                Err(_) => assert!(actual.is_err()),
459            }
460            assert_eq!(view.label(2, &mut buffer).unwrap(), None);
461            assert_eq!(view.label(3, &mut buffer).unwrap(), None);
462            // Null/missing values do not overwrite the scratch buffer, matching index extraction.
463            assert_eq!(buffer, label);
464            assert_eq!(buffer.as_ptr(), ptr);
465            assert!(
466                view.label(RESERVED_COLUMN_ID_TABLE_ID, &mut buffer)
467                    .is_err()
468            );
469            assert!(view.label(RESERVED_COLUMN_ID_TSID, &mut buffer).is_err());
470        }
471    }
472}