use tsdb_reader::chunkenc::{
self, CounterResetHint, FloatHistogramSample, HistogramKind, IntHistogramSample, SampleSink,
Span,
};
#[derive(serde::Deserialize, Debug, Clone)]
struct SpanGt {
offset: i32,
length: u32,
}
#[derive(serde::Deserialize, Debug, Clone)]
struct IntSampleGt {
t: i64,
st: i64,
count: u64,
zero_count: u64,
sum_bits: u64,
schema: i32,
zero_threshold: f64,
pos_spans: Vec<SpanGt>,
neg_spans: Vec<SpanGt>,
pos_deltas: Vec<i64>,
neg_deltas: Vec<i64>,
pos_counts: Vec<i64>,
neg_counts: Vec<i64>,
chunk_reset_hint: u8,
counter_reset_hint: u8,
}
#[derive(serde::Deserialize, Debug, Clone)]
struct FloatSampleGt {
t: i64,
st: i64,
count: f64,
zero_count: f64,
sum_bits: u64,
schema: i32,
zero_threshold: f64,
pos_spans: Vec<SpanGt>,
neg_spans: Vec<SpanGt>,
pos_buckets: Vec<f64>,
neg_buckets: Vec<f64>,
chunk_reset_hint: u8,
counter_reset_hint: u8,
}
#[derive(serde::Deserialize, Debug)]
struct Case {
name: String,
encoding: String,
bytes_hex: String,
#[serde(default)]
int_samples: Vec<IntSampleGt>,
#[serde(default)]
float_samples: Vec<FloatSampleGt>,
}
#[derive(serde::Deserialize, Debug)]
struct Fixtures {
cases: Vec<Case>,
}
#[derive(Debug, Clone)]
struct OwnedInt {
s: IntHistogramSample<'static>,
}
#[derive(Default)]
struct Collector {
ints: Vec<OwnedInt>,
floats: Vec<FloatHistogramSample<'static>>,
}
fn own_int(h: &IntHistogramSample<'_>) -> OwnedInt {
OwnedInt {
s: IntHistogramSample {
ts: h.ts,
st: h.st,
count: h.count,
zero_count: h.zero_count,
sum: h.sum,
schema: h.schema,
zero_threshold: h.zero_threshold,
pos_spans: Box::leak(h.pos_spans.to_vec().into_boxed_slice()),
neg_spans: Box::leak(h.neg_spans.to_vec().into_boxed_slice()),
pos_counts: Box::leak(h.pos_counts.to_vec().into_boxed_slice()),
neg_counts: Box::leak(h.neg_counts.to_vec().into_boxed_slice()),
pos_deltas: Box::leak(h.pos_deltas.to_vec().into_boxed_slice()),
neg_deltas: Box::leak(h.neg_deltas.to_vec().into_boxed_slice()),
custom_values: Box::leak(h.custom_values.to_vec().into_boxed_slice()),
chunk_reset_hint: h.chunk_reset_hint,
counter_reset_hint: h.counter_reset_hint,
},
}
}
fn own_float(h: &FloatHistogramSample<'_>) -> FloatHistogramSample<'static> {
FloatHistogramSample {
ts: h.ts,
st: h.st,
count: h.count,
zero_count: h.zero_count,
sum: h.sum,
schema: h.schema,
zero_threshold: h.zero_threshold,
pos_spans: Box::leak(h.pos_spans.to_vec().into_boxed_slice()),
neg_spans: Box::leak(h.neg_spans.to_vec().into_boxed_slice()),
pos_buckets: Box::leak(h.pos_buckets.to_vec().into_boxed_slice()),
neg_buckets: Box::leak(h.neg_buckets.to_vec().into_boxed_slice()),
custom_values: Box::leak(h.custom_values.to_vec().into_boxed_slice()),
chunk_reset_hint: h.chunk_reset_hint,
counter_reset_hint: h.counter_reset_hint,
}
}
impl SampleSink for Collector {
fn push_float(&mut self, _ts: i64, _value: f64) {}
fn push_int_histogram(&mut self, h: &IntHistogramSample<'_>) {
self.ints.push(own_int(h));
}
fn push_float_histogram(&mut self, h: &FloatHistogramSample<'_>) {
self.floats.push(own_float(h));
}
}
fn fixtures() -> Fixtures {
let path =
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data/hist_exactness.json");
let raw = std::fs::read_to_string(&path).expect("hist_exactness.json is vendored");
serde_json::from_str(&raw).expect("fixture JSON parses")
}
fn hex_decode(s: &str) -> Vec<u8> {
(0..s.len() / 2)
.map(|i| u8::from_str_radix(&s[i * 2..i * 2 + 2], 16).unwrap())
.collect()
}
fn spans(v: &[SpanGt]) -> Vec<Span> {
v.iter()
.map(|s| Span {
offset: s.offset,
length: s.length,
})
.collect()
}
const fn hint(v: u8) -> CounterResetHint {
match v {
1 => CounterResetHint::CounterReset,
2 => CounterResetHint::NotCounterReset,
3 => CounterResetHint::GaugeType,
_ => CounterResetHint::Unknown,
}
}
#[test]
fn integer_and_float_histograms_match_the_reference_implementation() {
let fixtures = fixtures();
assert_eq!(fixtures.cases.len(), 4, "expected four fixture cases");
for case in &fixtures.cases {
let bytes = hex_decode(&case.bytes_hex);
let enc = match case.encoding.as_str() {
"histogram" => chunkenc::ENC_HISTOGRAM,
"floathistogram" => chunkenc::ENC_FLOAT_HISTOGRAM,
other => panic!("{}: unexpected encoding {other}", case.name),
};
assert_eq!(
chunkenc::encoding_histogram_kind(enc),
Some(if enc == chunkenc::ENC_HISTOGRAM {
HistogramKind::Int
} else {
HistogramKind::Float
})
);
let mut sink = Collector::default();
let outcome = chunkenc::decode(enc, &bytes, &mut sink)
.unwrap_or_else(|e| panic!("decode {}: {e}", case.name));
assert_eq!(
outcome.int_histograms as usize,
case.int_samples.len(),
"{}: integer sample count",
case.name
);
assert_eq!(
outcome.float_histograms as usize,
case.float_samples.len(),
"{}: float sample count",
case.name
);
for (got, want) in sink.ints.iter().zip(&case.int_samples) {
let got = &got.s;
assert_eq!(got.ts, want.t, "{}: ts", case.name);
assert_eq!(got.st, want.st, "{}: st", case.name);
assert_eq!(got.count, want.count, "{}: exact count", case.name);
assert_eq!(got.zero_count, want.zero_count, "{}: zero count", case.name);
assert_eq!(
got.sum.to_bits(),
want.sum_bits,
"{}: sum bits at t={}",
case.name,
want.t
);
assert_eq!(got.schema, want.schema, "{}: schema", case.name);
assert_eq!(
got.zero_threshold.to_bits(),
want.zero_threshold.to_bits(),
"{}: zero threshold",
case.name
);
assert_eq!(
got.pos_spans,
spans(&want.pos_spans),
"{}: pos spans",
case.name
);
assert_eq!(
got.neg_spans,
spans(&want.neg_spans),
"{}: neg spans",
case.name
);
assert_eq!(
got.pos_deltas, want.pos_deltas,
"{}: positive deltas (Prometheus PositiveBuckets)",
case.name
);
assert_eq!(
got.neg_deltas, want.neg_deltas,
"{}: negative deltas (Prometheus NegativeBuckets)",
case.name
);
assert_eq!(
got.pos_counts, want.pos_counts,
"{}: absolute positive counts",
case.name
);
assert_eq!(
got.neg_counts, want.neg_counts,
"{}: absolute negative counts",
case.name
);
assert_eq!(
got.chunk_reset_hint,
hint(want.chunk_reset_hint),
"{}: chunk reset header",
case.name
);
assert_eq!(
got.counter_reset_hint,
hint(want.counter_reset_hint),
"{}: per-sample counter reset hint",
case.name
);
}
for (got, want) in sink.floats.iter().zip(&case.float_samples) {
assert_eq!(got.ts, want.t, "{}: float ts", case.name);
assert_eq!(got.st, want.st, "{}: float st", case.name);
assert_eq!(got.count, want.count, "{}: float count", case.name);
assert_eq!(got.zero_count, want.zero_count, "{}: float zero", case.name);
assert_eq!(got.sum.to_bits(), want.sum_bits, "{}: float sum", case.name);
assert_eq!(got.schema, want.schema, "{}: float schema", case.name);
assert_eq!(
got.zero_threshold.to_bits(),
want.zero_threshold.to_bits(),
"{}: float zero threshold",
case.name
);
assert_eq!(
got.pos_spans,
spans(&want.pos_spans),
"{}: float pos spans",
case.name
);
assert_eq!(
got.neg_spans,
spans(&want.neg_spans),
"{}: float neg spans",
case.name
);
assert_eq!(
got.pos_buckets, want.pos_buckets,
"{}: float pos buckets",
case.name
);
assert_eq!(
got.neg_buckets, want.neg_buckets,
"{}: float neg buckets",
case.name
);
assert_eq!(
got.chunk_reset_hint,
hint(want.chunk_reset_hint),
"{}: float chunk reset header",
case.name
);
assert_eq!(
got.counter_reset_hint,
hint(want.counter_reset_hint),
"{}: float reset hint",
case.name
);
}
}
}
#[test]
fn large_integer_counts_are_not_rounded_through_f64() {
let fixtures = fixtures();
let case = fixtures
.cases
.iter()
.find(|c| c.name == "histogram_large_counts")
.expect("large-count fixture");
let mut sink = Collector::default();
chunkenc::decode(
chunkenc::ENC_HISTOGRAM,
&hex_decode(&case.bytes_hex),
&mut sink,
)
.unwrap();
let first = &sink.ints[0].s;
assert_eq!(first.count, (1u64 << 60) + 3);
assert_eq!(first.count as f64 as u64, 1u64 << 60);
assert_ne!(first.count as f64 as u64, first.count);
}