tsdb-reader 0.3.0

Read-only, zero-copy Prometheus TSDB block reader: index v1-v3, all chunk encodings, integer histograms, postings and label matchers, tombstones
Documentation
//! Chunk encoding dispatch and shared sample types.

pub mod bstream;
pub mod decode_limits;
pub mod histogram;
pub mod varbit;
pub mod xor;
pub mod xor2;

use crate::error::{Error, Result};

pub use decode_limits::DecodeLimits;

/// `math.Float64frombits(value.StaleNaN)` used by Prometheus.
pub const STALE_NAN_BITS: u64 = 0x7ff0_0000_0000_0002;

/// One run of consecutive populated buckets in a native histogram.
///
/// Prometheus stores spans as deltas to keep histograms with a few populated
/// buckets compact; this is the decoded form.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Span {
    /// Offset of the first bucket in the run, relative to the schema's zero
    /// bucket.
    pub offset: i32,
    /// Number of buckets in the run.
    pub length: u32,
}

/// Which on-disk representation produced a histogram sample.
///
/// Integer histograms keep their observation counts as `uint64`/`int64` and
/// are exposed through [`IntHistogramSample`]; float histograms use `f64`
/// throughout and are exposed through [`FloatHistogramSample`]. The two are
/// never mixed, because converting an integer histogram to `f64` would lose
/// precision above 2^53 observations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HistogramKind {
    /// Encoded as `histogram` / `histogramST` (encodings 2 and 5).
    Int,
    /// Encoded as `floathistogram` / `floathistogramST` (encodings 3 and 6).
    Float,
}

/// Counter-reset hint for one histogram sample.
///
/// Discriminants match Prometheus' `histogram.CounterResetHint`, which is *not*
/// the same bit order as the 2-bit chunk header: the header uses
/// `01`/`10` for not-reset/reset while the hint uses `1`/`2`. The two are kept
/// apart so a round trip cannot silently swap them; [`Self::from_header_bits`]
/// does the translation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum CounterResetHint {
    /// Unknown, the reader has to detect a reset itself.
    Unknown = 0,
    /// This sample starts after a counter reset.
    CounterReset = 1,
    /// This sample definitely does not start a counter reset.
    NotCounterReset = 2,
    /// Gauge histogram: counters do not reset at all.
    GaugeType = 3,
}

impl CounterResetHint {
    /// Maps the raw 2-bit chunk header onto the hint.
    pub fn from_header_bits(bits: u8) -> Self {
        match bits & 0b11 {
            1 => Self::NotCounterReset,
            2 => Self::CounterReset,
            3 => Self::GaugeType,
            _ => Self::Unknown,
        }
    }

    /// The header bits this hint was decoded from.
    pub fn as_u8(self) -> u8 {
        self as u8
    }

    /// Per-sample hint, derived exactly like Prometheus' `counterResetHint`:
    /// gauge chunks stay gauge, every sample after the first cannot be a
    /// reset, and everything else is conservatively "unknown".
    pub fn for_sample(chunk_hint: Self, sample_index: u64) -> Self {
        match chunk_hint {
            Self::GaugeType => Self::GaugeType,
            _ if sample_index > 1 => Self::NotCounterReset,
            _ => Self::Unknown,
        }
    }
}

/// One decoded integer native histogram sample.
///
/// Counts stay exact: `count`/`zero_count` are the `uint64` values stored in
/// the chunk and the bucket slices are `int64`, matching Prometheus'
/// `histogram.Histogram`. Bucket slices borrow from the decoder, so the sample
/// is only valid for the duration of [`SampleSink::push_int_histogram`].
#[derive(Debug, Clone, Copy)]
pub struct IntHistogramSample<'a> {
    /// Sample timestamp, in milliseconds since the Unix epoch.
    pub ts: i64,
    /// Start timestamp (ST encoding only), `0` otherwise.
    pub st: i64,
    /// Total number of observations, exactly as stored.
    pub count: u64,
    /// Observations in the zero bucket, exactly as stored.
    pub zero_count: u64,
    /// Sum of all observed values (always a float, even for integer counts).
    pub sum: f64,
    /// Bucket schema; the resolution of the exponential buckets.
    pub schema: i32,
    /// Width of the zero bucket (`[-zero_threshold, +zero_threshold]`).
    pub zero_threshold: f64,
    /// Runs of populated positive buckets.
    pub pos_spans: &'a [Span],
    /// Runs of populated negative buckets.
    pub neg_spans: &'a [Span],
    /// Absolute positive bucket counts (deltas already accumulated in int64).
    pub pos_counts: &'a [i64],
    /// Absolute negative bucket counts (deltas already accumulated in int64).
    pub neg_counts: &'a [i64],
    /// First-order positive bucket deltas, i.e. Prometheus `PositiveBuckets`.
    pub pos_deltas: &'a [i64],
    /// First-order negative bucket deltas, i.e. Prometheus `NegativeBuckets`.
    pub neg_deltas: &'a [i64],
    /// Custom bucket bounds when the histogram uses them instead of a schema.
    pub custom_values: &'a [f64],
    /// 2-bit counter-reset header of the chunk.
    pub chunk_reset_hint: CounterResetHint,
    /// Per-sample counter-reset hint, derived from the chunk header.
    pub counter_reset_hint: CounterResetHint,
}

/// One decoded float native histogram sample.
///
/// All bucket slices borrow from the decoder's scratch buffers, so the sample
/// is only valid for the duration of [`SampleSink::push_float_histogram`].
/// Copy the values out if you need to keep them.
#[derive(Debug, Clone, Copy)]
pub struct FloatHistogramSample<'a> {
    /// Sample timestamp, in milliseconds since the Unix epoch.
    pub ts: i64,
    /// Start timestamp (ST encoding only), `0` otherwise.
    pub st: i64,
    /// Total number of observations.
    pub count: f64,
    /// Observations in the zero bucket.
    pub zero_count: f64,
    /// Sum of all observed values.
    pub sum: f64,
    /// Bucket schema; the resolution of the exponential buckets.
    pub schema: i32,
    /// Width of the zero bucket (`[-zero_threshold, +zero_threshold]`).
    pub zero_threshold: f64,
    /// Runs of populated positive buckets.
    pub pos_spans: &'a [Span],
    /// Runs of populated negative buckets.
    pub neg_spans: &'a [Span],
    /// Absolute bucket counts (deltas already accumulated).
    pub pos_buckets: &'a [f64],
    /// Absolute negative bucket counts (deltas already accumulated).
    pub neg_buckets: &'a [f64],
    /// Custom bucket bounds when the histogram uses them instead of a schema.
    pub custom_values: &'a [f64],
    /// 2-bit counter-reset header of the chunk.
    pub chunk_reset_hint: CounterResetHint,
    /// Per-sample counter-reset hint, derived from the chunk header.
    pub counter_reset_hint: CounterResetHint,
}

/// Receives decoded samples in time order.
///
/// `chunkenc::decode` calls these once per sample, without allocating; the
/// sink is where an export writes rows or forwards them to another system.
/// Integer and float histograms have separate methods so a sink never has to
/// guess whether the counts it receives are exact.
pub trait SampleSink {
    /// A float sample. NaNs, including Prometheus stale markers, are passed
    /// through unchanged.
    fn push_float(&mut self, ts: i64, value: f64);
    /// An integer native histogram sample. Counts are exact `u64`/`i64`.
    fn push_int_histogram(&mut self, h: &IntHistogramSample<'_>);
    /// A float native histogram sample. The borrow ends when the call returns.
    fn push_float_histogram(&mut self, h: &FloatHistogramSample<'_>);
}

/// How many samples a chunk produced, split by kind.
#[derive(Debug, Clone, Copy, Default)]
pub struct DecodeOutcome {
    /// Float samples decoded.
    pub floats: u64,
    /// Integer histogram samples decoded.
    pub int_histograms: u64,
    /// Float histogram samples decoded.
    pub float_histograms: u64,
}

impl DecodeOutcome {
    /// Total histogram samples, integer plus float.
    pub fn histograms(&self) -> u64 {
        self.int_histograms + self.float_histograms
    }

    /// Total samples, float plus histogram.
    pub fn samples(&self) -> u64 {
        self.floats + self.histograms()
    }
}

/// Not a real chunk: an empty placeholder.
pub const ENC_NONE: u8 = 0;
/// Gorilla-style XOR encoding for float samples (index v1 era).
pub const ENC_XOR: u8 = 1;
/// Integer native histogram, without a start timestamp.
pub const ENC_HISTOGRAM: u8 = 2;
/// Float native histogram, without a start timestamp.
pub const ENC_FLOAT_HISTOGRAM: u8 = 3;
/// XOR encoding with improved timestamp compression (index v2+).
pub const ENC_XOR2: u8 = 4;
/// Integer native histogram carrying a start timestamp.
pub const ENC_HISTOGRAM_ST: u8 = 5;
/// Float native histogram carrying a start timestamp.
pub const ENC_FLOAT_HISTOGRAM_ST: u8 = 6;

/// Human-readable name of an encoding byte, for logs and error messages.
pub fn encoding_name(enc: u8) -> &'static str {
    match enc {
        ENC_NONE => "none",
        ENC_XOR => "XOR",
        ENC_HISTOGRAM => "histogram",
        ENC_FLOAT_HISTOGRAM => "floathistogram",
        ENC_XOR2 => "XOR2",
        ENC_HISTOGRAM_ST => "histogramST",
        ENC_FLOAT_HISTOGRAM_ST => "floathistogramST",
        _ => "unknown",
    }
}

/// True when this crate can decode the encoding byte.
///
/// Encodings 0-6 are defined by the format; anything else means the segment
/// was written by a newer or non-Prometheus implementation.
pub fn is_known_encoding(enc: u8) -> bool {
    matches!(
        enc,
        ENC_NONE
            | ENC_XOR
            | ENC_HISTOGRAM
            | ENC_FLOAT_HISTOGRAM
            | ENC_XOR2
            | ENC_HISTOGRAM_ST
            | ENC_FLOAT_HISTOGRAM_ST
    )
}

/// Which histogram kind an encoding byte carries, if it is a histogram.
pub fn encoding_histogram_kind(enc: u8) -> Option<HistogramKind> {
    match enc {
        ENC_HISTOGRAM | ENC_HISTOGRAM_ST => Some(HistogramKind::Int),
        ENC_FLOAT_HISTOGRAM | ENC_FLOAT_HISTOGRAM_ST => Some(HistogramKind::Float),
        _ => None,
    }
}

/// Decodes a chunk body (encoding byte already stripped).
///
/// Uses [`DecodeLimits::default()`]; call [`decode_with_limits`] to widen or
/// tighten the caps, e.g. for hostile input or for a block known to contain
/// very wide histograms.
pub fn decode<S: SampleSink>(encoding: u8, data: &[u8], sink: &mut S) -> Result<DecodeOutcome> {
    decode_with_limits(encoding, data, &DecodeLimits::default(), sink)
}

/// Decodes a chunk body with explicit limits.
///
/// Every count that comes from the payload (samples, spans, buckets, custom
/// bounds) is checked before it is used to allocate, so a corrupt chunk fails
/// fast instead of reserving memory for a size it claims to have.
pub fn decode_with_limits<S: SampleSink>(
    encoding: u8,
    data: &[u8],
    limits: &DecodeLimits,
    sink: &mut S,
) -> Result<DecodeOutcome> {
    match encoding {
        ENC_NONE => Ok(DecodeOutcome::default()),
        ENC_XOR => Ok(DecodeOutcome {
            floats: xor::decode(data, limits, sink)?,
            ..Default::default()
        }),
        ENC_XOR2 => Ok(DecodeOutcome {
            floats: xor2::decode(data, limits, sink)?,
            ..Default::default()
        }),
        ENC_HISTOGRAM => Ok(DecodeOutcome {
            int_histograms: histogram::decode_int(data, false, limits, sink)?,
            ..Default::default()
        }),
        ENC_HISTOGRAM_ST => Ok(DecodeOutcome {
            int_histograms: histogram::decode_int(data, true, limits, sink)?,
            ..Default::default()
        }),
        ENC_FLOAT_HISTOGRAM => Ok(DecodeOutcome {
            float_histograms: histogram::decode_float(data, false, limits, sink)?,
            ..Default::default()
        }),
        ENC_FLOAT_HISTOGRAM_ST => Ok(DecodeOutcome {
            float_histograms: histogram::decode_float(data, true, limits, sink)?,
            ..Default::default()
        }),
        other => Err(Error::Unsupported(format!(
            "chunk encoding {other} ({})",
            encoding_name(other)
        ))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reset_hint_mapping() {
        assert_eq!(
            CounterResetHint::from_header_bits(0),
            CounterResetHint::Unknown
        );
        assert_eq!(
            CounterResetHint::from_header_bits(1),
            CounterResetHint::NotCounterReset
        );
        assert_eq!(
            CounterResetHint::from_header_bits(2),
            CounterResetHint::CounterReset
        );
        assert_eq!(
            CounterResetHint::from_header_bits(3),
            CounterResetHint::GaugeType
        );
        assert_eq!(
            CounterResetHint::from_header_bits(0xff),
            CounterResetHint::GaugeType
        );
        // The hint discriminants follow the model enum, not the header bits.
        assert_eq!(CounterResetHint::CounterReset.as_u8(), 1);
        assert_eq!(CounterResetHint::NotCounterReset.as_u8(), 2);
    }

    #[test]
    fn per_sample_hint_follows_prometheus() {
        use CounterResetHint::*;
        assert_eq!(CounterResetHint::for_sample(GaugeType, 1), GaugeType);
        assert_eq!(CounterResetHint::for_sample(CounterReset, 1), Unknown);
        assert_eq!(
            CounterResetHint::for_sample(CounterReset, 2),
            NotCounterReset
        );
        assert_eq!(CounterResetHint::for_sample(Unknown, 7), NotCounterReset);
    }

    #[test]
    fn histogram_kind_per_encoding() {
        assert_eq!(
            encoding_histogram_kind(ENC_HISTOGRAM),
            Some(HistogramKind::Int)
        );
        assert_eq!(
            encoding_histogram_kind(ENC_FLOAT_HISTOGRAM_ST),
            Some(HistogramKind::Float)
        );
        assert_eq!(encoding_histogram_kind(ENC_XOR2), None);
        assert!(is_known_encoding(ENC_NONE));
        assert!(is_known_encoding(ENC_FLOAT_HISTOGRAM_ST));
        assert!(!is_known_encoding(7));
    }

    #[test]
    fn outcome_counts_add_up() {
        let o = DecodeOutcome {
            floats: 3,
            int_histograms: 2,
            float_histograms: 1,
        };
        assert_eq!(o.histograms(), 3);
        assert_eq!(o.samples(), 6);
    }
}