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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
//! Lazy, tombstone-aware sample iteration across series and chunks.
//!
//! [`BlockReader::samples`] walks the whole block in one loop: series in
//! lexicographic order, chunks in time order, samples in time order, with
//! deleted samples filtered out. Nothing is buffered beyond one chunk, so a
//! block larger than memory streams at a constant footprint.
//!
//! ```no_run
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # #[cfg(feature = "meta")]
//! # {
//! use tsdb_reader::{BlockReader, ReaderOptions, TimeRange};
//!
//! let block = BlockReader::open("/data/01ARZ3NDEKTSV4RRFFQ69G5FAV".as_ref(), ReaderOptions::default())?;
//! let mut iter = block.samples(TimeRange::all());
//! while let Some(sample) = iter.next_sample()? {
//!     println!("{} {}", sample.timestamp, sample.series.metric_name().unwrap_or(""));
//! }
//! # }
//! # Ok(())
//! # }
//! ```
//!
//! The lower-level API ( [`BlockReader::series`] plus [`crate::chunkenc::decode`] )
//! stays available for callers that need finer control, e.g. decoding all
//! samples of a chunk into one batch.

use crate::block::BlockReader;
use crate::chunkenc::{
    self, CounterResetHint, DecodeLimits, FloatHistogramSample, IntHistogramSample, SampleSink,
    Span,
};
use crate::chunks::ChunkReader;
use crate::error::{Error, Result};
use crate::index::{IndexReader, SeriesRef};
use crate::tombstones::{self, Tombstones};

/// Half-open time range `[start, end)`, in milliseconds since the Unix epoch.
///
/// Prometheus block bounds are half-open too (`maxTime` is exclusive), while
/// chunk metadata and tombstones use closed intervals; [`Self::overlaps_chunk`]
/// does the translation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TimeRange {
    /// Inclusive lower bound.
    pub start: i64,
    /// Exclusive upper bound.
    pub end: i64,
}

impl TimeRange {
    /// Builds a range. An empty range (`end <= start`) yields no samples.
    pub const fn new(start: i64, end: i64) -> Self {
        Self { start, end }
    }

    /// Everything.
    pub const fn all() -> Self {
        Self {
            start: i64::MIN,
            end: i64::MAX,
        }
    }

    /// True when the range selects nothing.
    pub const fn is_empty(&self) -> bool {
        self.end <= self.start
    }

    /// True when `ts` is inside the range.
    pub const fn contains(&self, ts: i64) -> bool {
        ts >= self.start && ts < self.end
    }

    /// True when the closed interval `[mint, maxt]` intersects the range.
    pub const fn overlaps_chunk(&self, mint: i64, maxt: i64) -> bool {
        maxt >= self.start && mint < self.end
    }
}

impl Default for TimeRange {
    fn default() -> Self {
        Self::all()
    }
}

/// Knobs for [`SampleIterator`].
#[derive(Debug, Clone)]
pub struct SampleIterOptions {
    /// Time range to emit.
    pub range: TimeRange,
    /// Drop samples covered by tombstones. Turning this off exports deleted
    /// samples too, which is occasionally useful for audits.
    pub skip_deleted: bool,
    /// Report a corruption error when timestamps go backwards inside a series.
    ///
    /// Prometheus never writes such chunks; noticing it early beats exporting
    /// out-of-order rows.
    pub strict_order: bool,
    /// Caps applied to every chunk decode.
    pub limits: DecodeLimits,
}

impl Default for SampleIterOptions {
    fn default() -> Self {
        Self {
            range: TimeRange::all(),
            skip_deleted: true,
            strict_order: true,
            limits: DecodeLimits::default(),
        }
    }
}

/// One decoded sample, borrowed from the iterator's scratch buffer.
///
/// The value borrows from the iterator, so it is valid until the next call to
/// [`SampleIterator::next_sample`].
#[derive(Debug, Clone, Copy)]
pub struct Sample<'a> {
    /// Series the sample belongs to, including its labels and chunk list.
    pub series: &'a SeriesRef,
    /// Timestamp in milliseconds since the Unix epoch.
    pub timestamp: i64,
    /// Decoded value.
    pub value: SampleValue<'a>,
}

/// A decoded sample value.
#[derive(Debug, Clone, Copy)]
pub enum SampleValue<'a> {
    /// A float sample, including Prometheus stale markers (NaN).
    Float(f64),
    /// An integer native histogram; counts are exact.
    IntHistogram(IntHistogramSample<'a>),
    /// A float native histogram.
    FloatHistogram(FloatHistogramSample<'a>),
}

/// Streams every sample of a block, filtered by time range and tombstones.
///
/// Created by [`BlockReader::samples`] or [`SampleIterator::new`]; the latter
/// works on the parts returned by [`BlockReader::into_parts`], which is how a
/// worker thread gets its own iterator without sharing the index.
pub struct SampleIterator<'a> {
    /// Kept so callers can report the index version that produced the samples.
    index: &'a IndexReader,
    chunks: &'a ChunkReader,
    tombstones: &'a Tombstones,
    opts: SampleIterOptions,

    series_iter: crate::index::SeriesIter<'a>,
    series: Option<SeriesRef>,
    chunk_idx: usize,
    /// Tombstone intervals of the current series; empty is the common case.
    deleted: Vec<(i64, i64)>,
    series_key: String,

    pending: Pending,
    cursor: usize,
    last_ts: Option<i64>,
    done: bool,

    // Counters, mostly for tests and progress reporting.
    samples_emitted: u64,
    chunks_decoded: u64,
    samples_filtered: u64,
}

impl<'a> SampleIterator<'a> {
    /// Builds an iterator over the parts of a block.
    pub fn new(
        index: &'a IndexReader,
        chunks: &'a ChunkReader,
        tombstones: &'a Tombstones,
        opts: SampleIterOptions,
    ) -> Self {
        Self {
            index,
            chunks,
            tombstones,
            opts,
            series_iter: index.series(0),
            series: None,
            chunk_idx: 0,
            deleted: Vec::new(),
            series_key: String::new(),
            pending: Pending::default(),
            cursor: 0,
            last_ts: None,
            done: false,
            samples_emitted: 0,
            chunks_decoded: 0,
            samples_filtered: 0,
        }
    }

    /// Options this iterator was built with.
    pub fn options(&self) -> &SampleIterOptions {
        &self.opts
    }

    /// The index being read.
    pub fn index(&self) -> &'a IndexReader {
        self.index
    }

    /// Samples returned so far.
    pub fn samples_emitted(&self) -> u64 {
        self.samples_emitted
    }

    /// Chunks decoded so far, i.e. chunks that overlapped the range.
    pub fn chunks_decoded(&self) -> u64 {
        self.chunks_decoded
    }

    /// Samples skipped because they were outside the range or tombstoned.
    pub fn samples_filtered(&self) -> u64 {
        self.samples_filtered
    }

    /// Returns the next sample, or `None` at the end of the block.
    ///
    /// Chunks are decoded one at a time into a reused buffer, so memory stays
    /// bounded by the largest chunk, not by the block.
    pub fn next_sample(&mut self) -> Result<Option<Sample<'_>>> {
        loop {
            if self.cursor < self.pending.len() {
                let ts = self.pending.ts(self.cursor);
                let inside = self.opts.range.contains(ts);
                let deleted = self.opts.skip_deleted && tombstone_hit(&self.deleted, ts);
                if let Some(last) = self.last_ts {
                    if self.opts.strict_order && ts < last {
                        return Err(Error::corrupt(format!(
                            "series {}: timestamp {ts} goes backwards (previous {last})",
                            self.series_key
                        )));
                    }
                }
                let idx = self.cursor;
                self.cursor += 1;
                if !inside || deleted {
                    self.samples_filtered += 1;
                    continue;
                }
                self.last_ts = Some(ts);
                self.samples_emitted += 1;
                let series = self.series.as_ref().expect("a series is loaded");
                let value = self.pending.value(idx);
                return Ok(Some(Sample {
                    series,
                    timestamp: ts,
                    value,
                }));
            }

            if !self.load_next_chunk()? {
                self.done = true;
                return Ok(None);
            }
        }
    }

    /// Advances to the next chunk that can contribute samples.
    ///
    /// Returns `false` once every series has been visited.
    fn load_next_chunk(&mut self) -> Result<bool> {
        loop {
            if self.done {
                return Ok(false);
            }
            let Some(series) = self.series.as_ref() else {
                if !self.advance_series()? {
                    return Ok(false);
                }
                continue;
            };

            if self.chunk_idx >= series.chunks.len() {
                if !self.advance_series()? {
                    return Ok(false);
                }
                continue;
            }

            let chunk = series.chunks[self.chunk_idx];
            self.chunk_idx += 1;
            // Whole-chunk skip: the metadata range is exact, so a disjoint
            // chunk never needs decoding.
            if !self
                .opts
                .range
                .overlaps_chunk(chunk.min_time, chunk.max_time)
            {
                continue;
            }

            self.pending.reset();
            let slice = self.chunks.chunk(chunk.reference).map_err(|e| {
                contextual(
                    format!(
                        "series {} chunk {} (ref {:#x})",
                        self.series_key,
                        self.chunk_idx - 1,
                        chunk.reference
                    ),
                    e,
                )
            })?;
            let outcome = chunkenc::decode_with_limits(
                slice.encoding,
                slice.data,
                &self.opts.limits,
                &mut self.pending,
            )
            .map_err(|e| {
                contextual(
                    format!(
                        "series {} chunk {} (ref {:#x}, encoding {})",
                        self.series_key,
                        self.chunk_idx - 1,
                        chunk.reference,
                        chunkenc::encoding_name(slice.encoding)
                    ),
                    e,
                )
            })?;
            self.chunks_decoded += 1;
            if outcome.samples() == 0 {
                continue;
            }
            self.cursor = 0;
            return Ok(true);
        }
    }

    /// Moves to the next series, loading its tombstones.
    fn advance_series(&mut self) -> Result<bool> {
        loop {
            let Some(next) = self.series_iter.next() else {
                self.series = None;
                return Ok(false);
            };
            let series = next?;
            // Series entirely outside the range are skipped without touching
            // their chunks.
            let intersects = match (series.min_time(), series.max_time()) {
                (Some(mint), Some(maxt)) => self.opts.range.overlaps_chunk(mint, maxt),
                _ => false,
            };
            if !intersects {
                continue;
            }
            self.series_key = series_key(&series);
            self.deleted.clear();
            if self.opts.skip_deleted {
                self.deleted
                    .extend_from_slice(self.tombstones.intervals(series.id));
            }
            self.series = Some(series);
            self.chunk_idx = 0;
            self.last_ts = None;
            return Ok(true);
        }
    }
}

impl BlockReader {
    /// Iterates every sample in the given range, filtering tombstones.
    pub fn samples(&self, range: TimeRange) -> SampleIterator<'_> {
        self.samples_with(SampleIterOptions {
            range,
            ..SampleIterOptions::default()
        })
    }

    /// Iterates samples with explicit options.
    pub fn samples_with(&self, opts: SampleIterOptions) -> SampleIterator<'_> {
        SampleIterator::new(self.index(), self.chunk_reader(), self.tombstones(), opts)
    }
}

/// `name=value,name=value` for error messages.
fn series_key(series: &SeriesRef) -> String {
    let mut out = String::new();
    for (i, (n, v)) in series.labels.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        out.push_str(n);
        out.push('=');
        out.push_str(v);
    }
    out
}

/// Adds context to a corruption error, keeping the error class.
fn contextual(prefix: String, err: Error) -> Error {
    match err {
        Error::Format(m) => Error::Format(format!("{prefix}: {m}")),
        Error::Decode(m) => Error::Decode(format!("{prefix}: {m}")),
        Error::Corrupt(m) => Error::Corrupt(format!("{prefix}: {m}")),
        Error::Checksum(s) => Error::Corrupt(format!("{prefix}: checksum mismatch in {s}")),
        // A truncated payload is corruption, not a generic IO problem: the
        // caller wants to know which chunk was short.
        Error::Eof(off) => {
            Error::Corrupt(format!("{prefix}: unexpected end of data at byte {off}"))
        }
        other => other,
    }
}

fn tombstone_hit(intervals: &[(i64, i64)], ts: i64) -> bool {
    if intervals.is_empty() {
        return false;
    }
    tombstone_is_deleted(intervals, ts)
}

/// Thin wrapper so the local module and [`crate::tombstones`] agree on the
/// closed-interval rule.
fn tombstone_is_deleted(intervals: &[(i64, i64)], ts: i64) -> bool {
    tombstones::is_deleted(intervals, ts)
}

// ---------------------------------------------------------------------------
// Scratch buffer
// ---------------------------------------------------------------------------

/// One decoded chunk's worth of samples, reused across chunks.
#[derive(Default)]
struct Pending {
    items: Vec<Item>,
    len: usize,
}

enum Item {
    Float { ts: i64, value: f64 },
    Int(OwnedIntHistogram),
    FloatHist(OwnedFloatHistogram),
}

impl Default for Item {
    fn default() -> Self {
        Item::Float { ts: 0, value: 0.0 }
    }
}

impl Pending {
    fn reset(&mut self) {
        self.len = 0;
    }

    fn len(&self) -> usize {
        self.len
    }

    fn ts(&self, idx: usize) -> i64 {
        match &self.items[idx] {
            Item::Float { ts, .. } => *ts,
            Item::Int(h) => h.ts,
            Item::FloatHist(h) => h.ts,
        }
    }

    fn value(&self, idx: usize) -> SampleValue<'_> {
        match &self.items[idx] {
            Item::Float { value, .. } => SampleValue::Float(*value),
            Item::Int(h) => SampleValue::IntHistogram(h.view()),
            Item::FloatHist(h) => SampleValue::FloatHistogram(h.view()),
        }
    }

    fn slot(&mut self) -> usize {
        let idx = self.len;
        if idx >= self.items.len() {
            self.items.push(Item::default());
        }
        self.len += 1;
        idx
    }
}

impl SampleSink for Pending {
    fn push_float(&mut self, ts: i64, value: f64) {
        let idx = self.slot();
        self.items[idx] = Item::Float { ts, value };
    }

    fn push_int_histogram(&mut self, h: &IntHistogramSample<'_>) {
        let idx = self.slot();
        match &mut self.items[idx] {
            Item::Int(owned) => owned.set(h),
            slot => *slot = Item::Int(OwnedIntHistogram::from_sample(h)),
        }
    }

    fn push_float_histogram(&mut self, h: &FloatHistogramSample<'_>) {
        let idx = self.slot();
        match &mut self.items[idx] {
            Item::FloatHist(owned) => owned.set(h),
            slot => *slot = Item::FloatHist(OwnedFloatHistogram::from_sample(h)),
        }
    }
}

/// An integer histogram copied out of the decoder's scratch buffers.
struct OwnedIntHistogram {
    ts: i64,
    st: i64,
    count: u64,
    zero_count: u64,
    sum: f64,
    schema: i32,
    zero_threshold: f64,
    pos_spans: Vec<Span>,
    neg_spans: Vec<Span>,
    pos_counts: Vec<i64>,
    neg_counts: Vec<i64>,
    pos_deltas: Vec<i64>,
    neg_deltas: Vec<i64>,
    custom_values: Vec<f64>,
    chunk_reset_hint: CounterResetHint,
    counter_reset_hint: CounterResetHint,
}

impl OwnedIntHistogram {
    fn from_sample(h: &IntHistogramSample<'_>) -> Self {
        let mut out = Self {
            ts: 0,
            st: 0,
            count: 0,
            zero_count: 0,
            sum: 0.0,
            schema: 0,
            zero_threshold: 0.0,
            pos_spans: Vec::new(),
            neg_spans: Vec::new(),
            pos_counts: Vec::new(),
            neg_counts: Vec::new(),
            pos_deltas: Vec::new(),
            neg_deltas: Vec::new(),
            custom_values: Vec::new(),
            chunk_reset_hint: CounterResetHint::Unknown,
            counter_reset_hint: CounterResetHint::Unknown,
        };
        out.set(h);
        out
    }

    fn set(&mut self, h: &IntHistogramSample<'_>) {
        self.ts = h.ts;
        self.st = h.st;
        self.count = h.count;
        self.zero_count = h.zero_count;
        self.sum = h.sum;
        self.schema = h.schema;
        self.zero_threshold = h.zero_threshold;
        copy_spans(&mut self.pos_spans, h.pos_spans);
        copy_spans(&mut self.neg_spans, h.neg_spans);
        self.pos_counts.clear();
        self.pos_counts.extend_from_slice(h.pos_counts);
        self.neg_counts.clear();
        self.neg_counts.extend_from_slice(h.neg_counts);
        self.pos_deltas.clear();
        self.pos_deltas.extend_from_slice(h.pos_deltas);
        self.neg_deltas.clear();
        self.neg_deltas.extend_from_slice(h.neg_deltas);
        self.custom_values.clear();
        self.custom_values.extend_from_slice(h.custom_values);
        self.chunk_reset_hint = h.chunk_reset_hint;
        self.counter_reset_hint = h.counter_reset_hint;
    }

    fn view(&self) -> IntHistogramSample<'_> {
        IntHistogramSample {
            ts: self.ts,
            st: self.st,
            count: self.count,
            zero_count: self.zero_count,
            sum: self.sum,
            schema: self.schema,
            zero_threshold: self.zero_threshold,
            pos_spans: &self.pos_spans,
            neg_spans: &self.neg_spans,
            pos_counts: &self.pos_counts,
            neg_counts: &self.neg_counts,
            pos_deltas: &self.pos_deltas,
            neg_deltas: &self.neg_deltas,
            custom_values: &self.custom_values,
            chunk_reset_hint: self.chunk_reset_hint,
            counter_reset_hint: self.counter_reset_hint,
        }
    }
}

/// A float histogram copied out of the decoder's scratch buffers.
struct OwnedFloatHistogram {
    ts: i64,
    st: i64,
    count: f64,
    zero_count: f64,
    sum: f64,
    schema: i32,
    zero_threshold: f64,
    pos_spans: Vec<Span>,
    neg_spans: Vec<Span>,
    pos_buckets: Vec<f64>,
    neg_buckets: Vec<f64>,
    custom_values: Vec<f64>,
    chunk_reset_hint: CounterResetHint,
    counter_reset_hint: CounterResetHint,
}

impl OwnedFloatHistogram {
    fn from_sample(h: &FloatHistogramSample<'_>) -> Self {
        let mut out = Self {
            ts: 0,
            st: 0,
            count: 0.0,
            zero_count: 0.0,
            sum: 0.0,
            schema: 0,
            zero_threshold: 0.0,
            pos_spans: Vec::new(),
            neg_spans: Vec::new(),
            pos_buckets: Vec::new(),
            neg_buckets: Vec::new(),
            custom_values: Vec::new(),
            chunk_reset_hint: CounterResetHint::Unknown,
            counter_reset_hint: CounterResetHint::Unknown,
        };
        out.set(h);
        out
    }

    fn set(&mut self, h: &FloatHistogramSample<'_>) {
        self.ts = h.ts;
        self.st = h.st;
        self.count = h.count;
        self.zero_count = h.zero_count;
        self.sum = h.sum;
        self.schema = h.schema;
        self.zero_threshold = h.zero_threshold;
        copy_spans(&mut self.pos_spans, h.pos_spans);
        copy_spans(&mut self.neg_spans, h.neg_spans);
        self.pos_buckets.clear();
        self.pos_buckets.extend_from_slice(h.pos_buckets);
        self.neg_buckets.clear();
        self.neg_buckets.extend_from_slice(h.neg_buckets);
        self.custom_values.clear();
        self.custom_values.extend_from_slice(h.custom_values);
        self.chunk_reset_hint = h.chunk_reset_hint;
        self.counter_reset_hint = h.counter_reset_hint;
    }

    fn view(&self) -> FloatHistogramSample<'_> {
        FloatHistogramSample {
            ts: self.ts,
            st: self.st,
            count: self.count,
            zero_count: self.zero_count,
            sum: self.sum,
            schema: self.schema,
            zero_threshold: self.zero_threshold,
            pos_spans: &self.pos_spans,
            neg_spans: &self.neg_spans,
            pos_buckets: &self.pos_buckets,
            neg_buckets: &self.neg_buckets,
            custom_values: &self.custom_values,
            chunk_reset_hint: self.chunk_reset_hint,
            counter_reset_hint: self.counter_reset_hint,
        }
    }
}

fn copy_spans(dst: &mut Vec<Span>, src: &[Span]) {
    dst.clear();
    dst.extend_from_slice(src);
}

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

    #[test]
    fn range_translation_is_half_open() {
        let r = TimeRange::new(100, 200);
        assert!(r.contains(100));
        assert!(r.contains(199));
        assert!(!r.contains(200));
        // Chunk metadata is a closed interval.
        assert!(r.overlaps_chunk(199, 300));
        assert!(!r.overlaps_chunk(50, 99));
        assert!(!r.overlaps_chunk(200, 300));
        assert!(TimeRange::new(5, 5).is_empty());
        assert!(TimeRange::all().contains(i64::MIN));
    }

    #[test]
    fn pending_buffer_is_reused() {
        let mut p = Pending::default();
        p.push_float(1, 2.0);
        p.push_float(3, 4.0);
        assert_eq!(p.len(), 2);
        assert_eq!(p.ts(1), 3);
        matches!(p.value(0), SampleValue::Float(_));
        let capacity = p.items.capacity();
        p.reset();
        assert_eq!(p.len(), 0);
        // The slots survive a reset, so a second chunk does not reallocate.
        assert_eq!(p.items.capacity(), capacity);
        p.push_float(5, 6.0);
        assert_eq!(p.ts(0), 5);
    }

    #[test]
    fn integer_histogram_slots_keep_their_buffers() {
        let mut p = Pending::default();
        let sample = IntHistogramSample {
            ts: 10,
            st: 0,
            count: 1 << 60,
            zero_count: 0,
            sum: 1.0,
            schema: 1,
            zero_threshold: 0.0,
            pos_spans: &[Span {
                offset: 0,
                length: 1,
            }],
            neg_spans: &[],
            pos_counts: &[1 << 40],
            neg_counts: &[],
            pos_deltas: &[1 << 40],
            neg_deltas: &[],
            custom_values: &[],
            chunk_reset_hint: CounterResetHint::Unknown,
            counter_reset_hint: CounterResetHint::NotCounterReset,
        };
        p.push_int_histogram(&sample);
        match p.value(0) {
            SampleValue::IntHistogram(v) => {
                assert_eq!(v.count, 1 << 60);
                assert_eq!(v.pos_counts, &[1 << 40]);
                assert_eq!(v.counter_reset_hint, CounterResetHint::NotCounterReset);
            }
            other => panic!("expected an integer histogram, got {other:?}"),
        }
    }
}