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
//! Symbol table (format v1 inline references, v2/v3 32-symbol offset groups).

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 default per-iterator cache size (4096 slots, roughly 100 KiB).
const SYMBOL_CACHE_BITS: usize = 12;

/// Direct-mapped cache of resolved symbols, owned by one iterator.
///
/// The cache deliberately lives next to the cursor instead of inside
/// [`super::IndexReader`]: a shared cache would need a lock (or a `RefCell`,
/// which would make the reader `!Sync`), and every symbol lookup of every
/// thread would contend on it. One cache per iterator keeps lookups lock-free
/// while still avoiding a second allocation for a repeated label value.
pub(crate) struct SymbolCache {
    slots: Vec<Option<(u32, Arc<str>)>>,
}

impl SymbolCache {
    /// Cache sized for a sequential scan (default 4096 slots).
    pub(crate) fn new() -> Self {
        Self {
            slots: vec![None; 1 << SYMBOL_CACHE_BITS],
        }
    }

    /// Tiny cache for one-off lookups (resolving a single series reference).
    pub(crate) fn small() -> Self {
        Self {
            slots: vec![None; 16],
        }
    }

    fn slot(&self, reference: u32) -> usize {
        ((reference as usize).wrapping_mul(0x9E37_79B1) >> (32 - self.bits()))
            & (self.slots.len() - 1)
    }

    fn bits(&self) -> u32 {
        (self.slots.len().trailing_zeros()).min(16)
    }
}

/// 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. The table
/// itself is immutable and shared, so `IndexReader` is `Sync`; resolved strings
/// are memoised in a [`SymbolCache`] owned by the caller.
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,
}

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,
        }
    }

    /// 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,
        })
    }

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

    /// Resolves a symbol reference to its string, memoising it in `cache`.
    pub(crate) fn lookup(&self, buf: &[u8], r: u32, cache: &mut SymbolCache) -> Result<Arc<str>> {
        let slot = cache.slot(r);
        if let Some((cached_ref, s)) = &cache.slots[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();
        cache.slots[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);
        let mut cache = SymbolCache::new();
        for (i, want) in refs.iter().enumerate() {
            assert_eq!(&*syms.lookup(&buf, i as u32, &mut cache).unwrap(), *want);
        }
        // A second lookup hits the cache and returns the same string.
        assert_eq!(&*syms.lookup(&buf, 3, &mut cache).unwrap(), "sym003");
        // Out-of-range references are reported, not panicked.
        assert!(syms.lookup(&buf, 40, &mut cache).is_err());
    }
}