tsdb_reader/chunkenc/mod.rs
1//! Chunk encoding dispatch and shared sample types.
2
3pub mod bstream;
4pub mod decode_limits;
5pub mod histogram;
6pub mod varbit;
7pub mod xor;
8pub mod xor2;
9
10use crate::error::{Error, Result};
11
12pub use decode_limits::DecodeLimits;
13
14/// `math.Float64frombits(value.StaleNaN)` used by Prometheus.
15pub const STALE_NAN_BITS: u64 = 0x7ff0_0000_0000_0002;
16
17/// One run of consecutive populated buckets in a native histogram.
18///
19/// Prometheus stores spans as deltas to keep histograms with a few populated
20/// buckets compact; this is the decoded form.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub struct Span {
23 /// Offset of the first bucket in the run, relative to the schema's zero
24 /// bucket.
25 pub offset: i32,
26 /// Number of buckets in the run.
27 pub length: u32,
28}
29
30/// Which on-disk representation produced a histogram sample.
31///
32/// Integer histograms keep their observation counts as `uint64`/`int64` and
33/// are exposed through [`IntHistogramSample`]; float histograms use `f64`
34/// throughout and are exposed through [`FloatHistogramSample`]. The two are
35/// never mixed, because converting an integer histogram to `f64` would lose
36/// precision above 2^53 observations.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum HistogramKind {
39 /// Encoded as `histogram` / `histogramST` (encodings 2 and 5).
40 Int,
41 /// Encoded as `floathistogram` / `floathistogramST` (encodings 3 and 6).
42 Float,
43}
44
45/// Counter-reset hint for one histogram sample.
46///
47/// Discriminants match Prometheus' `histogram.CounterResetHint`, which is *not*
48/// the same bit order as the 2-bit chunk header: the header uses
49/// `01`/`10` for not-reset/reset while the hint uses `1`/`2`. The two are kept
50/// apart so a round trip cannot silently swap them; [`Self::from_header_bits`]
51/// does the translation.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53#[repr(u8)]
54pub enum CounterResetHint {
55 /// Unknown, the reader has to detect a reset itself.
56 Unknown = 0,
57 /// This sample starts after a counter reset.
58 CounterReset = 1,
59 /// This sample definitely does not start a counter reset.
60 NotCounterReset = 2,
61 /// Gauge histogram: counters do not reset at all.
62 GaugeType = 3,
63}
64
65impl CounterResetHint {
66 /// Maps the raw 2-bit chunk header onto the hint.
67 pub fn from_header_bits(bits: u8) -> Self {
68 match bits & 0b11 {
69 1 => Self::NotCounterReset,
70 2 => Self::CounterReset,
71 3 => Self::GaugeType,
72 _ => Self::Unknown,
73 }
74 }
75
76 /// The header bits this hint was decoded from.
77 pub fn as_u8(self) -> u8 {
78 self as u8
79 }
80
81 /// Per-sample hint, derived exactly like Prometheus' `counterResetHint`:
82 /// gauge chunks stay gauge, every sample after the first cannot be a
83 /// reset, and everything else is conservatively "unknown".
84 pub fn for_sample(chunk_hint: Self, sample_index: u64) -> Self {
85 match chunk_hint {
86 Self::GaugeType => Self::GaugeType,
87 _ if sample_index > 1 => Self::NotCounterReset,
88 _ => Self::Unknown,
89 }
90 }
91}
92
93/// One decoded integer native histogram sample.
94///
95/// Counts stay exact: `count`/`zero_count` are the `uint64` values stored in
96/// the chunk and the bucket slices are `int64`, matching Prometheus'
97/// `histogram.Histogram`. Bucket slices borrow from the decoder, so the sample
98/// is only valid for the duration of [`SampleSink::push_int_histogram`].
99#[derive(Debug, Clone, Copy)]
100pub struct IntHistogramSample<'a> {
101 /// Sample timestamp, in milliseconds since the Unix epoch.
102 pub ts: i64,
103 /// Start timestamp (ST encoding only), `0` otherwise.
104 pub st: i64,
105 /// Total number of observations, exactly as stored.
106 pub count: u64,
107 /// Observations in the zero bucket, exactly as stored.
108 pub zero_count: u64,
109 /// Sum of all observed values (always a float, even for integer counts).
110 pub sum: f64,
111 /// Bucket schema; the resolution of the exponential buckets.
112 pub schema: i32,
113 /// Width of the zero bucket (`[-zero_threshold, +zero_threshold]`).
114 pub zero_threshold: f64,
115 /// Runs of populated positive buckets.
116 pub pos_spans: &'a [Span],
117 /// Runs of populated negative buckets.
118 pub neg_spans: &'a [Span],
119 /// Absolute positive bucket counts (deltas already accumulated in int64).
120 pub pos_counts: &'a [i64],
121 /// Absolute negative bucket counts (deltas already accumulated in int64).
122 pub neg_counts: &'a [i64],
123 /// First-order positive bucket deltas, i.e. Prometheus `PositiveBuckets`.
124 pub pos_deltas: &'a [i64],
125 /// First-order negative bucket deltas, i.e. Prometheus `NegativeBuckets`.
126 pub neg_deltas: &'a [i64],
127 /// Custom bucket bounds when the histogram uses them instead of a schema.
128 pub custom_values: &'a [f64],
129 /// 2-bit counter-reset header of the chunk.
130 pub chunk_reset_hint: CounterResetHint,
131 /// Per-sample counter-reset hint, derived from the chunk header.
132 pub counter_reset_hint: CounterResetHint,
133}
134
135/// One decoded float native histogram sample.
136///
137/// All bucket slices borrow from the decoder's scratch buffers, so the sample
138/// is only valid for the duration of [`SampleSink::push_float_histogram`].
139/// Copy the values out if you need to keep them.
140#[derive(Debug, Clone, Copy)]
141pub struct FloatHistogramSample<'a> {
142 /// Sample timestamp, in milliseconds since the Unix epoch.
143 pub ts: i64,
144 /// Start timestamp (ST encoding only), `0` otherwise.
145 pub st: i64,
146 /// Total number of observations.
147 pub count: f64,
148 /// Observations in the zero bucket.
149 pub zero_count: f64,
150 /// Sum of all observed values.
151 pub sum: f64,
152 /// Bucket schema; the resolution of the exponential buckets.
153 pub schema: i32,
154 /// Width of the zero bucket (`[-zero_threshold, +zero_threshold]`).
155 pub zero_threshold: f64,
156 /// Runs of populated positive buckets.
157 pub pos_spans: &'a [Span],
158 /// Runs of populated negative buckets.
159 pub neg_spans: &'a [Span],
160 /// Absolute bucket counts (deltas already accumulated).
161 pub pos_buckets: &'a [f64],
162 /// Absolute negative bucket counts (deltas already accumulated).
163 pub neg_buckets: &'a [f64],
164 /// Custom bucket bounds when the histogram uses them instead of a schema.
165 pub custom_values: &'a [f64],
166 /// 2-bit counter-reset header of the chunk.
167 pub chunk_reset_hint: CounterResetHint,
168 /// Per-sample counter-reset hint, derived from the chunk header.
169 pub counter_reset_hint: CounterResetHint,
170}
171
172/// Receives decoded samples in time order.
173///
174/// `chunkenc::decode` calls these once per sample, without allocating; the
175/// sink is where an export writes rows or forwards them to another system.
176/// Integer and float histograms have separate methods so a sink never has to
177/// guess whether the counts it receives are exact.
178pub trait SampleSink {
179 /// A float sample. NaNs, including Prometheus stale markers, are passed
180 /// through unchanged.
181 fn push_float(&mut self, ts: i64, value: f64);
182 /// An integer native histogram sample. Counts are exact `u64`/`i64`.
183 fn push_int_histogram(&mut self, h: &IntHistogramSample<'_>);
184 /// A float native histogram sample. The borrow ends when the call returns.
185 fn push_float_histogram(&mut self, h: &FloatHistogramSample<'_>);
186}
187
188/// How many samples a chunk produced, split by kind.
189#[derive(Debug, Clone, Copy, Default)]
190pub struct DecodeOutcome {
191 /// Float samples decoded.
192 pub floats: u64,
193 /// Integer histogram samples decoded.
194 pub int_histograms: u64,
195 /// Float histogram samples decoded.
196 pub float_histograms: u64,
197}
198
199impl DecodeOutcome {
200 /// Total histogram samples, integer plus float.
201 pub fn histograms(&self) -> u64 {
202 self.int_histograms + self.float_histograms
203 }
204
205 /// Total samples, float plus histogram.
206 pub fn samples(&self) -> u64 {
207 self.floats + self.histograms()
208 }
209}
210
211/// Not a real chunk: an empty placeholder.
212pub const ENC_NONE: u8 = 0;
213/// Gorilla-style XOR encoding for float samples (index v1 era).
214pub const ENC_XOR: u8 = 1;
215/// Integer native histogram, without a start timestamp.
216pub const ENC_HISTOGRAM: u8 = 2;
217/// Float native histogram, without a start timestamp.
218pub const ENC_FLOAT_HISTOGRAM: u8 = 3;
219/// XOR encoding with improved timestamp compression (index v2+).
220pub const ENC_XOR2: u8 = 4;
221/// Integer native histogram carrying a start timestamp.
222pub const ENC_HISTOGRAM_ST: u8 = 5;
223/// Float native histogram carrying a start timestamp.
224pub const ENC_FLOAT_HISTOGRAM_ST: u8 = 6;
225
226/// Human-readable name of an encoding byte, for logs and error messages.
227pub fn encoding_name(enc: u8) -> &'static str {
228 match enc {
229 ENC_NONE => "none",
230 ENC_XOR => "XOR",
231 ENC_HISTOGRAM => "histogram",
232 ENC_FLOAT_HISTOGRAM => "floathistogram",
233 ENC_XOR2 => "XOR2",
234 ENC_HISTOGRAM_ST => "histogramST",
235 ENC_FLOAT_HISTOGRAM_ST => "floathistogramST",
236 _ => "unknown",
237 }
238}
239
240/// True when this crate can decode the encoding byte.
241///
242/// Encodings 0-6 are defined by the format; anything else means the segment
243/// was written by a newer or non-Prometheus implementation.
244pub fn is_known_encoding(enc: u8) -> bool {
245 matches!(
246 enc,
247 ENC_NONE
248 | ENC_XOR
249 | ENC_HISTOGRAM
250 | ENC_FLOAT_HISTOGRAM
251 | ENC_XOR2
252 | ENC_HISTOGRAM_ST
253 | ENC_FLOAT_HISTOGRAM_ST
254 )
255}
256
257/// Which histogram kind an encoding byte carries, if it is a histogram.
258pub fn encoding_histogram_kind(enc: u8) -> Option<HistogramKind> {
259 match enc {
260 ENC_HISTOGRAM | ENC_HISTOGRAM_ST => Some(HistogramKind::Int),
261 ENC_FLOAT_HISTOGRAM | ENC_FLOAT_HISTOGRAM_ST => Some(HistogramKind::Float),
262 _ => None,
263 }
264}
265
266/// Decodes a chunk body (encoding byte already stripped).
267///
268/// Uses [`DecodeLimits::default()`]; call [`decode_with_limits`] to widen or
269/// tighten the caps, e.g. for hostile input or for a block known to contain
270/// very wide histograms.
271pub fn decode<S: SampleSink>(encoding: u8, data: &[u8], sink: &mut S) -> Result<DecodeOutcome> {
272 decode_with_limits(encoding, data, &DecodeLimits::default(), sink)
273}
274
275/// Decodes a chunk body with explicit limits.
276///
277/// Every count that comes from the payload (samples, spans, buckets, custom
278/// bounds) is checked before it is used to allocate, so a corrupt chunk fails
279/// fast instead of reserving memory for a size it claims to have.
280pub fn decode_with_limits<S: SampleSink>(
281 encoding: u8,
282 data: &[u8],
283 limits: &DecodeLimits,
284 sink: &mut S,
285) -> Result<DecodeOutcome> {
286 match encoding {
287 ENC_NONE => Ok(DecodeOutcome::default()),
288 ENC_XOR => Ok(DecodeOutcome {
289 floats: xor::decode(data, limits, sink)?,
290 ..Default::default()
291 }),
292 ENC_XOR2 => Ok(DecodeOutcome {
293 floats: xor2::decode(data, limits, sink)?,
294 ..Default::default()
295 }),
296 ENC_HISTOGRAM => Ok(DecodeOutcome {
297 int_histograms: histogram::decode_int(data, false, limits, sink)?,
298 ..Default::default()
299 }),
300 ENC_HISTOGRAM_ST => Ok(DecodeOutcome {
301 int_histograms: histogram::decode_int(data, true, limits, sink)?,
302 ..Default::default()
303 }),
304 ENC_FLOAT_HISTOGRAM => Ok(DecodeOutcome {
305 float_histograms: histogram::decode_float(data, false, limits, sink)?,
306 ..Default::default()
307 }),
308 ENC_FLOAT_HISTOGRAM_ST => Ok(DecodeOutcome {
309 float_histograms: histogram::decode_float(data, true, limits, sink)?,
310 ..Default::default()
311 }),
312 other => Err(Error::Unsupported(format!(
313 "chunk encoding {other} ({})",
314 encoding_name(other)
315 ))),
316 }
317}
318
319#[cfg(test)]
320mod tests {
321 use super::*;
322
323 #[test]
324 fn reset_hint_mapping() {
325 assert_eq!(
326 CounterResetHint::from_header_bits(0),
327 CounterResetHint::Unknown
328 );
329 assert_eq!(
330 CounterResetHint::from_header_bits(1),
331 CounterResetHint::NotCounterReset
332 );
333 assert_eq!(
334 CounterResetHint::from_header_bits(2),
335 CounterResetHint::CounterReset
336 );
337 assert_eq!(
338 CounterResetHint::from_header_bits(3),
339 CounterResetHint::GaugeType
340 );
341 assert_eq!(
342 CounterResetHint::from_header_bits(0xff),
343 CounterResetHint::GaugeType
344 );
345 // The hint discriminants follow the model enum, not the header bits.
346 assert_eq!(CounterResetHint::CounterReset.as_u8(), 1);
347 assert_eq!(CounterResetHint::NotCounterReset.as_u8(), 2);
348 }
349
350 #[test]
351 fn per_sample_hint_follows_prometheus() {
352 use CounterResetHint::*;
353 assert_eq!(CounterResetHint::for_sample(GaugeType, 1), GaugeType);
354 assert_eq!(CounterResetHint::for_sample(CounterReset, 1), Unknown);
355 assert_eq!(
356 CounterResetHint::for_sample(CounterReset, 2),
357 NotCounterReset
358 );
359 assert_eq!(CounterResetHint::for_sample(Unknown, 7), NotCounterReset);
360 }
361
362 #[test]
363 fn histogram_kind_per_encoding() {
364 assert_eq!(
365 encoding_histogram_kind(ENC_HISTOGRAM),
366 Some(HistogramKind::Int)
367 );
368 assert_eq!(
369 encoding_histogram_kind(ENC_FLOAT_HISTOGRAM_ST),
370 Some(HistogramKind::Float)
371 );
372 assert_eq!(encoding_histogram_kind(ENC_XOR2), None);
373 assert!(is_known_encoding(ENC_NONE));
374 assert!(is_known_encoding(ENC_FLOAT_HISTOGRAM_ST));
375 assert!(!is_known_encoding(7));
376 }
377
378 #[test]
379 fn outcome_counts_add_up() {
380 let o = DecodeOutcome {
381 floats: 3,
382 int_histograms: 2,
383 float_histograms: 1,
384 };
385 assert_eq!(o.histograms(), 3);
386 assert_eq!(o.samples(), 6);
387 }
388}