Skip to main content

mito2/series_index/columnar/
codec.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//! Bounded, explicit wire codecs. Encoding and compression have independent IDs.
16
17use std::collections::HashMap;
18use std::io::Read;
19
20use crate::error::Result;
21use crate::series_index::columnar::{invalid, require, unsupported};
22
23pub(crate) const COLUMN_LIMIT: usize = 64 * 1024 * 1024;
24pub(crate) const COLUMN_STORED_LIMIT: usize = COLUMN_LIMIT + 1024 * 1024;
25pub(crate) const INTEGER: u16 = 1;
26pub(crate) const DICTIONARY: u16 = 2;
27
28#[derive(Debug, Clone, Copy)]
29#[repr(u16)]
30pub(crate) enum Compression {
31    #[allow(
32        dead_code,
33        reason = "Uncompressed encoding is supported for format tests."
34    )]
35    None = 0,
36    Zstd = 1,
37}
38
39pub(crate) fn checksum(bytes: &[u8]) -> u64 {
40    twox_hash::XxHash64::oneshot(0, bytes)
41}
42
43pub(crate) fn compress(bytes: &[u8], compression: Compression, level: i32) -> Result<Vec<u8>> {
44    match compression {
45        Compression::None => Ok(bytes.to_vec()),
46        Compression::Zstd => zstd::stream::encode_all(bytes, level)
47            .map_err(|e| invalid(format!("series compression: {e}"))),
48    }
49}
50
51pub(crate) fn decompress(bytes: &[u8], compression: u16, decoded: usize) -> Result<Vec<u8>> {
52    let output = match compression {
53        0 => bytes.to_vec(),
54        1 => {
55            let decoder = zstd::stream::read::Decoder::with_buffer(bytes)
56                .map_err(|e| invalid(format!("series zstd header: {e}")))?;
57            let mut output = Vec::new();
58            // Never let a frame's claimed size control allocation or output growth.
59            decoder
60                .take(decoded as u64 + 1)
61                .read_to_end(&mut output)
62                .map_err(|e| invalid(format!("series decompression: {e}")))?;
63            output
64        }
65        id => return Err(unsupported(format!("series compression {id}"))),
66    };
67    require(output.len() == decoded, "series decoded length mismatch")?;
68    Ok(output)
69}
70
71/// Output scratch a released decoder keeps: the next block of the same stream reuses the
72/// allocation instead of growing a new one.
73pub(crate) const RELEASED_OUTPUT_BYTES: usize = 64 * 1024;
74
75/// The magic number every modern zstd frame starts with, little-endian.
76///
77/// This build of zstd also decodes legacy frames, and their decompressor buffers by the window the
78/// frame declares before any window cap applies (a 13-byte legacy frame can ask for megabytes). The
79/// writer emits modern frames only, so anything else is malformed input rather than a compatibility
80/// requirement, and it is refused before it reaches the decoder.
81const MODERN_FRAME_MAGIC: &[u8] = &[0x28, 0xB5, 0x2F, 0xFD];
82
83#[cfg(test)]
84std::thread_local! {
85    /// Decompression contexts this thread has built. A stream must build one and reuse it for
86    /// every block it decodes, which nothing observable outside that stream shows, so tests
87    /// count the allocations directly. The counter is thread-local because a current-thread
88    /// runtime polls a stream on one thread and a decoder never moves between streams.
89    static CONTEXTS_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
90}
91
92/// Test-only: decompression contexts this thread has built so far.
93#[cfg(test)]
94pub(crate) fn contexts_built() -> usize {
95    CONTEXTS_BUILT.with(std::cell::Cell::get)
96}
97
98/// Scratch state for synchronous decoding of one sample block's columns.
99/// The caller reserves decoded column memory before allocating this output buffer.
100/// A stream owns one decoder and reuses it for every block it reads; no buffer or context is
101/// shared with another stream or retained in a cache.
102#[derive(Default)]
103pub(crate) struct PayloadDecoder {
104    context: Option<zstd::zstd_safe::DCtx<'static>>,
105    output: Vec<u8>,
106}
107
108impl PayloadDecoder {
109    /// Releases the decompression context and any scratch above [`RELEASED_OUTPUT_BYTES`].
110    ///
111    /// A stream calls this before it waits for I/O that does not need the decoder: the context is
112    /// its only sizeable state, and the next compressed block builds it again. A modest output
113    /// buffer survives, so consecutive blocks of one stream still share it.
114    pub(crate) fn release(&mut self) {
115        self.context = None;
116        self.output.clear();
117        self.output.shrink_to(RELEASED_OUTPUT_BYTES);
118    }
119
120    pub(crate) fn decompress<'a>(
121        &'a mut self,
122        bytes: &'a [u8],
123        compression: u16,
124        decoded: usize,
125    ) -> Result<&'a [u8]> {
126        require(
127            decoded <= COLUMN_LIMIT,
128            "series decoded payload exceeds limit",
129        )?;
130        match compression {
131            0 => {
132                require(bytes.len() == decoded, "series decoded length mismatch")?;
133                Ok(bytes)
134            }
135            1 => {
136                // One modern frame per payload is what the writer emits. Anything else is refused
137                // here rather than decoded: a legacy frame's decompressor buffers by the window the
138                // frame declares before any window limit applies, so a corrupt artifact could ask
139                // for unbounded memory, and a payload carrying more than one frame has no place in
140                // this format at all.
141                require(
142                    bytes.starts_with(MODERN_FRAME_MAGIC),
143                    "series payload is not a modern zstd frame",
144                )?;
145                require(
146                    zstd::zstd_safe::find_frame_compressed_size(bytes).ok() == Some(bytes.len()),
147                    "series payload is not one zstd frame",
148                )?;
149                let context = match self.context {
150                    Some(ref mut context) => context,
151                    None => {
152                        let created = zstd::zstd_safe::DCtx::try_create()
153                            .ok_or_else(|| invalid("cannot allocate series decoder context"))?;
154                        #[cfg(test)]
155                        CONTEXTS_BUILT.with(|built| built.set(built.get() + 1));
156                        self.context.insert(created)
157                    }
158                };
159                // Reset even after a previous corrupt, truncated, or oversized frame.
160                context
161                    .reset(zstd::zstd_safe::ResetDirective::SessionOnly)
162                    .map_err(|e| invalid(format!("series decoder reset: {e}")))?;
163                self.output.clear();
164                // The bounded, validated metadata length controls the allocation,
165                // never the frame's claimed size. One extra byte detects overflow.
166                self.output
167                    .try_reserve_exact(decoded + 1)
168                    .map_err(|e| invalid(format!("series decode allocation: {e}")))?;
169                zstd::stream::read::Decoder::with_context(bytes, context)
170                    .take(decoded as u64 + 1)
171                    .read_to_end(&mut self.output)
172                    .map_err(|e| invalid(format!("series decompression: {e}")))?;
173                require(
174                    self.output.len() == decoded,
175                    "series decoded length mismatch",
176                )?;
177                Ok(&self.output)
178            }
179            id => Err(unsupported(format!("series compression {id}"))),
180        }
181    }
182}
183
184/// Test-only views of the decoder's scratch, so a test can assert what a release gives back.
185#[cfg(test)]
186impl PayloadDecoder {
187    pub(crate) fn holds_context(&self) -> bool {
188        self.context.is_some()
189    }
190
191    pub(crate) fn retained_output_bytes(&self) -> usize {
192        self.output.capacity()
193    }
194}
195
196pub(crate) fn put_u32(out: &mut Vec<u8>, value: u32) {
197    out.extend(value.to_le_bytes());
198}
199pub(crate) fn put_u64(out: &mut Vec<u8>, value: u64) {
200    out.extend(value.to_le_bytes());
201}
202pub(crate) fn put_string(out: &mut Vec<u8>, value: &str) {
203    put_u64(out, value.len() as u64);
204    out.extend(value.as_bytes());
205}
206pub(crate) fn put_varint(out: &mut Vec<u8>, mut value: u64) {
207    while value >= 128 {
208        out.push(value as u8 | 128);
209        value >>= 7;
210    }
211    out.push(value as u8);
212}
213
214pub(crate) struct Cursor<'a> {
215    bytes: &'a [u8],
216    offset: usize,
217}
218impl<'a> Cursor<'a> {
219    pub(crate) fn new(bytes: &'a [u8]) -> Self {
220        Self { bytes, offset: 0 }
221    }
222    pub(crate) fn remaining(&self) -> usize {
223        self.bytes.len() - self.offset
224    }
225    pub(crate) fn take(&mut self, count: usize) -> Result<&'a [u8]> {
226        let end = self
227            .offset
228            .checked_add(count)
229            .ok_or_else(|| invalid("series length overflow"))?;
230        let result = self
231            .bytes
232            .get(self.offset..end)
233            .ok_or_else(|| invalid("truncated series payload"))?;
234        self.offset = end;
235        Ok(result)
236    }
237    pub(crate) fn u8(&mut self) -> Result<u8> {
238        Ok(self.take(1)?[0])
239    }
240    pub(crate) fn u16(&mut self) -> Result<u16> {
241        let b = self.take(2)?;
242        Ok(u16::from_le_bytes([b[0], b[1]]))
243    }
244    pub(crate) fn u32(&mut self) -> Result<u32> {
245        let b = self.take(4)?;
246        Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
247    }
248    pub(crate) fn u64(&mut self) -> Result<u64> {
249        let b = self.take(8)?;
250        Ok(u64::from_le_bytes([
251            b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
252        ]))
253    }
254    pub(crate) fn length(&mut self) -> Result<usize> {
255        usize::try_from(self.u64()?).map_err(|_| invalid("series length exceeds address space"))
256    }
257    pub(crate) fn string(&mut self) -> Result<String> {
258        let len = self.length()?;
259        std::str::from_utf8(self.take(len)?)
260            .map(str::to_owned)
261            .map_err(|_| invalid("invalid series UTF-8"))
262    }
263    pub(crate) fn varint(&mut self) -> Result<u64> {
264        let mut value = 0;
265        for shift in (0..70).step_by(7) {
266            let byte = self.u8()?;
267            require(shift != 63 || byte <= 1, "series varint overflow")?;
268            value |= u64::from(byte & 127) << shift;
269            if byte & 128 == 0 {
270                return Ok(value);
271            }
272        }
273        Err(invalid("series varint overflow"))
274    }
275    pub(crate) fn end(self) -> Result<()> {
276        require(self.remaining() == 0, "trailing series payload bytes")
277    }
278}
279
280pub(crate) fn encode_integers(values: &[u64]) -> Vec<u8> {
281    let mut out = Vec::new();
282    let mut previous = 0u64;
283    for &value in values {
284        let delta = value.wrapping_sub(previous) as i64;
285        put_varint(&mut out, ((delta as u64) << 1) ^ ((delta >> 63) as u64));
286        previous = value;
287    }
288    out
289}
290
291pub(crate) fn decode_integers(bytes: &[u8], count: usize) -> Result<Vec<u64>> {
292    require(count <= bytes.len(), "integer count exceeds payload")?;
293    let mut cursor = Cursor::new(bytes);
294    let mut out = Vec::with_capacity(count);
295    let mut previous = 0u64;
296    for _ in 0..count {
297        let value = cursor.varint()?;
298        let delta = (value >> 1) ^ (0u64.wrapping_sub(value & 1));
299        previous = previous.wrapping_add(delta);
300        out.push(previous);
301    }
302    cursor.end()?;
303    Ok(out)
304}
305
306#[derive(Debug)]
307pub(crate) struct Dictionary {
308    pub(crate) values: Vec<Option<String>>,
309    pub(crate) codes: Vec<u32>,
310}
311
312pub(crate) fn encode_dictionary(values: &[Option<&str>]) -> Result<Vec<u8>> {
313    let mut lookup: HashMap<&str, u32> = HashMap::new();
314    let mut dictionary = Vec::new();
315    put_u64(&mut dictionary, 0); // patched with the entry count below
316    dictionary.push(0); // slot zero is always null
317    let mut codes = Vec::new();
318    for value in values {
319        let code = match value {
320            None => 0,
321            Some(value) => {
322                if let Some(code) = lookup.get(value) {
323                    *code
324                } else {
325                    let code = u32::try_from(lookup.len() + 1)
326                        .map_err(|_| invalid("too many dictionary entries"))?;
327                    lookup.insert(value, code);
328                    dictionary.push(1);
329                    put_string(&mut dictionary, value);
330                    code
331                }
332            }
333        };
334        put_varint(&mut codes, u64::from(code));
335        require(
336            dictionary.len() + codes.len() <= COLUMN_LIMIT,
337            "series dictionary exceeds chunk limit",
338        )?;
339    }
340    dictionary[..8].copy_from_slice(&((lookup.len() + 1) as u64).to_le_bytes());
341    let mut out = Vec::new();
342    put_varint(&mut out, dictionary.len() as u64);
343    out.extend(dictionary);
344    out.extend(codes);
345    Ok(out)
346}
347
348pub(crate) fn decode_dictionary(bytes: &[u8], count: usize) -> Result<Dictionary> {
349    let mut cursor = Cursor::new(bytes);
350    let length =
351        usize::try_from(cursor.varint()?).map_err(|_| invalid("dictionary length overflow"))?;
352    let mut dictionary = Cursor::new(cursor.take(length)?);
353    let entries = dictionary.length()?;
354    require(
355        entries > 0 && entries <= dictionary.remaining(),
356        "invalid dictionary count",
357    )?;
358    require(
359        count <= cursor.remaining(),
360        "dictionary code count exceeds payload",
361    )?;
362    let mut values = Vec::new();
363    let mut unique = std::collections::HashSet::new();
364    for index in 0..entries {
365        let present = dictionary.u8()?;
366        if index == 0 {
367            require(present == 0, "dictionary slot zero must be null")?;
368            values.push(None);
369        } else {
370            require(present == 1, "nonzero dictionary slot must be present")?;
371            let value = dictionary.string()?;
372            require(unique.insert(value.clone()), "duplicate dictionary value")?;
373            values.push(Some(value));
374        }
375    }
376    dictionary.end()?;
377    let mut codes = Vec::with_capacity(count);
378    for _ in 0..count {
379        let code = cursor.varint()?;
380        require(
381            code < entries as u64 && code <= u32::MAX as u64,
382            "invalid dictionary code",
383        )?;
384        codes.push(code as u32);
385    }
386    cursor.end()?;
387    Ok(Dictionary { values, codes })
388}