tsdb-reader 0.2.0

Read-only, zero-copy Prometheus TSDB block reader: index v1-v3, all chunk encodings, integer histograms, postings lookups, tombstones
Documentation
//! Symbol table (format v1 inline references, v2/v3 32-symbol offset groups).

use std::cell::RefCell;
use std::sync::Arc;

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

use super::toc::be32;

/// How many symbols share one offset entry on v2/v3.
pub(crate) const SYMBOL_FACTOR: usize = 32;
/// `log2` of the direct-mapped cache size.
const SYMBOL_CACHE_BITS: usize = 14;

/// Direct-mapped cache slot: symbol reference plus its resolved string.
type SymbolCache = Vec<Option<(u32, Arc<str>)>>;

/// The symbol table of one index file.
///
/// v2/v3 store only every 32nd symbol offset; the others are reached by
/// walking varint-prefixed strings, exactly like Prometheus does. Resolved
/// strings are memoised in a small direct-mapped cache so a repeated label
/// value does not allocate twice.
pub(crate) struct Symbols {
    /// Absolute file offset of the first symbol entry.
    base: usize,
    /// Absolute file offset of the end of the symbol section (CRC excluded).
    end: usize,
    count: usize,
    /// Absolute offsets of every 32nd symbol (same scheme as Prometheus).
    offsets: Vec<usize>,
    version: u8,
    cache: RefCell<SymbolCache>,
}

impl Symbols {
    /// Empty table for indexes that do not carry symbols (defensive path).
    pub(crate) fn empty() -> Self {
        Self {
            base: 0,
            end: 0,
            count: 0,
            offsets: Vec::new(),
            version: 1,
            cache: RefCell::new(vec![None; 1 << SYMBOL_CACHE_BITS]),
        }
    }

    /// Parses the symbol table at `off`, validating its length and count.
    pub(crate) fn new(buf: &[u8], off: usize, version: u8, verify: bool) -> Result<Self> {
        if off == 0 || off + 8 > buf.len() {
            return Err(Error::format("invalid symbol table offset"));
        }
        let len = be32(buf, off)? as usize;
        let count = be32(buf, off + 4)? as usize;
        let payload_start = off + 4;
        let payload_end = payload_start
            .checked_add(len)
            .ok_or_else(|| Error::format("symbol table length overflow"))?;
        if payload_end + 4 > buf.len() {
            return Err(Error::format("symbol table exceeds file size"));
        }
        if verify {
            let want = be32(buf, payload_end)?;
            crate::checksum::verify(
                true,
                want,
                &buf[payload_start..payload_end],
                "index symbols",
            )?;
        }

        let mut offsets = Vec::with_capacity(1 + count / SYMBOL_FACTOR);
        let mut pos = off + 8; // skip len + count
        let mut seen = 0usize;
        while pos < payload_end {
            if seen % SYMBOL_FACTOR == 0 {
                offsets.push(pos);
            }
            let slen = varint::uvarint(buf, &mut pos)? as usize;
            pos = pos
                .checked_add(slen)
                .ok_or_else(|| Error::format("symbol length overflow"))?;
            if pos > payload_end {
                return Err(Error::format("symbol exceeds symbol table"));
            }
            seen += 1;
        }
        if seen != count {
            return Err(Error::format(format!(
                "symbol count mismatch: header {count}, scanned {seen}"
            )));
        }

        Ok(Self {
            base: off + 8,
            end: payload_end,
            count,
            offsets,
            version,
            cache: RefCell::new(vec![None; 1 << SYMBOL_CACHE_BITS]),
        })
    }

    /// Number of symbols declared by the table header.
    pub(crate) fn count(&self) -> usize {
        self.count
    }

    /// Resolves a symbol reference to its string.
    pub(crate) fn lookup(&self, buf: &[u8], r: u32) -> Result<Arc<str>> {
        let slot = ((r as usize).wrapping_mul(0x9E37_79B1) >> (32 - SYMBOL_CACHE_BITS))
            & ((1 << SYMBOL_CACHE_BITS) - 1);
        if let Some((cached_ref, s)) = &self.cache.borrow()[slot] {
            if *cached_ref == r {
                return Ok(s.clone());
            }
        }

        let mut pos = if self.version == 1 {
            r as usize
        } else {
            let idx = r as usize;
            if idx >= self.count {
                return Err(Error::format(format!(
                    "symbol reference {idx} out of range (count {})",
                    self.count
                )));
            }
            let mut p = *self
                .offsets
                .get(idx / SYMBOL_FACTOR)
                .ok_or_else(|| Error::format("symbol offset group missing"))?;
            for _ in 0..(idx % SYMBOL_FACTOR) {
                let slen = varint::uvarint(buf, &mut p)? as usize;
                p += slen;
            }
            p
        };

        if pos < self.base || pos >= self.end {
            return Err(Error::format(format!("symbol offset {pos} out of range")));
        }
        let len = varint::uvarint(buf, &mut pos)? as usize;
        let end = pos
            .checked_add(len)
            .ok_or_else(|| Error::format("symbol length overflow"))?;
        if end > self.end {
            return Err(Error::format("symbol exceeds symbol table"));
        }
        let s: Arc<str> = std::str::from_utf8(&buf[pos..end])
            .map_err(|e| Error::format(format!("invalid utf-8 symbol: {e}")))?
            .into();
        self.cache.borrow_mut()[slot] = Some((r, s.clone()));
        Ok(s)
    }
}

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

    /// Builds a v2 symbol table: `count` symbols, offset groups every 32.
    ///
    /// A 5-byte fake header stands in front so the table does not start at the
    /// file offset the reader reserves for the index magic.
    fn table(symbols: &[&str]) -> Vec<u8> {
        let mut payload = Vec::new();
        for s in symbols {
            payload.push(s.len() as u8);
            payload.extend_from_slice(s.as_bytes());
        }
        let mut out = vec![0xBAA_AD700u32.to_be_bytes()[0], 2, 0, 0, 0];
        // The length field counts the symbol bytes plus the 32-bit count.
        out.extend_from_slice(&((payload.len() + 4) as u32).to_be_bytes());
        out.extend_from_slice(&(symbols.len() as u32).to_be_bytes());
        out.extend_from_slice(&payload);
        // The CRC covers the count field and the payload, not the length.
        let crc = crc32c::crc32c(&out[9..]);
        out.extend_from_slice(&crc.to_be_bytes());
        out
    }

    #[test]
    fn resolves_v2_references() {
        let names: Vec<String> = (0..40).map(|i| format!("sym{i:03}")).collect();
        let refs: Vec<&str> = names.iter().map(String::as_str).collect();
        let buf = table(&refs);
        let syms = Symbols::new(&buf, 5, 2, true).unwrap();
        assert_eq!(syms.count(), 40);
        for (i, want) in refs.iter().enumerate() {
            assert_eq!(&*syms.lookup(&buf, i as u32).unwrap(), *want);
        }
        // Out-of-range references are reported, not panicked.
        assert!(syms.lookup(&buf, 40).is_err());
    }
}