1use crate::block::BlockReader;
29use crate::chunkenc::{
30 self, CounterResetHint, DecodeLimits, FloatHistogramSample, IntHistogramSample, SampleSink,
31 Span,
32};
33use crate::chunks::ChunkReader;
34use crate::error::{Error, Result};
35use crate::index::{IndexReader, SeriesRef};
36use crate::tombstones::{self, Tombstones};
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub struct TimeRange {
45 pub start: i64,
47 pub end: i64,
49}
50
51impl TimeRange {
52 pub const fn new(start: i64, end: i64) -> Self {
54 Self { start, end }
55 }
56
57 pub const fn all() -> Self {
59 Self {
60 start: i64::MIN,
61 end: i64::MAX,
62 }
63 }
64
65 pub const fn is_empty(&self) -> bool {
67 self.end <= self.start
68 }
69
70 pub const fn contains(&self, ts: i64) -> bool {
72 ts >= self.start && ts < self.end
73 }
74
75 pub const fn overlaps_chunk(&self, mint: i64, maxt: i64) -> bool {
77 maxt >= self.start && mint < self.end
78 }
79}
80
81impl Default for TimeRange {
82 fn default() -> Self {
83 Self::all()
84 }
85}
86
87#[derive(Debug, Clone)]
89pub struct SampleIterOptions {
90 pub range: TimeRange,
92 pub skip_deleted: bool,
95 pub strict_order: bool,
100 pub limits: DecodeLimits,
102}
103
104impl Default for SampleIterOptions {
105 fn default() -> Self {
106 Self {
107 range: TimeRange::all(),
108 skip_deleted: true,
109 strict_order: true,
110 limits: DecodeLimits::default(),
111 }
112 }
113}
114
115#[derive(Debug, Clone, Copy)]
120pub struct Sample<'a> {
121 pub series: &'a SeriesRef,
123 pub timestamp: i64,
125 pub value: SampleValue<'a>,
127}
128
129#[derive(Debug, Clone, Copy)]
131pub enum SampleValue<'a> {
132 Float(f64),
134 IntHistogram(IntHistogramSample<'a>),
136 FloatHistogram(FloatHistogramSample<'a>),
138}
139
140pub struct SampleIterator<'a> {
146 index: &'a IndexReader,
148 chunks: &'a ChunkReader,
149 tombstones: &'a Tombstones,
150 opts: SampleIterOptions,
151
152 series_iter: crate::index::SeriesIter<'a>,
153 series: Option<SeriesRef>,
154 chunk_idx: usize,
155 deleted: Vec<(i64, i64)>,
157 series_key: String,
158
159 pending: Pending,
160 cursor: usize,
161 last_ts: Option<i64>,
162 done: bool,
163
164 samples_emitted: u64,
166 chunks_decoded: u64,
167 samples_filtered: u64,
168}
169
170impl<'a> SampleIterator<'a> {
171 pub fn new(
173 index: &'a IndexReader,
174 chunks: &'a ChunkReader,
175 tombstones: &'a Tombstones,
176 opts: SampleIterOptions,
177 ) -> Self {
178 Self {
179 index,
180 chunks,
181 tombstones,
182 opts,
183 series_iter: index.series(0),
184 series: None,
185 chunk_idx: 0,
186 deleted: Vec::new(),
187 series_key: String::new(),
188 pending: Pending::default(),
189 cursor: 0,
190 last_ts: None,
191 done: false,
192 samples_emitted: 0,
193 chunks_decoded: 0,
194 samples_filtered: 0,
195 }
196 }
197
198 pub fn options(&self) -> &SampleIterOptions {
200 &self.opts
201 }
202
203 pub fn index(&self) -> &'a IndexReader {
205 self.index
206 }
207
208 pub fn samples_emitted(&self) -> u64 {
210 self.samples_emitted
211 }
212
213 pub fn chunks_decoded(&self) -> u64 {
215 self.chunks_decoded
216 }
217
218 pub fn samples_filtered(&self) -> u64 {
220 self.samples_filtered
221 }
222
223 pub fn next_sample(&mut self) -> Result<Option<Sample<'_>>> {
228 loop {
229 if self.cursor < self.pending.len() {
230 let ts = self.pending.ts(self.cursor);
231 let inside = self.opts.range.contains(ts);
232 let deleted = self.opts.skip_deleted && tombstone_hit(&self.deleted, ts);
233 if let Some(last) = self.last_ts {
234 if self.opts.strict_order && ts < last {
235 return Err(Error::corrupt(format!(
236 "series {}: timestamp {ts} goes backwards (previous {last})",
237 self.series_key
238 )));
239 }
240 }
241 let idx = self.cursor;
242 self.cursor += 1;
243 if !inside || deleted {
244 self.samples_filtered += 1;
245 continue;
246 }
247 self.last_ts = Some(ts);
248 self.samples_emitted += 1;
249 let series = self.series.as_ref().expect("a series is loaded");
250 let value = self.pending.value(idx);
251 return Ok(Some(Sample {
252 series,
253 timestamp: ts,
254 value,
255 }));
256 }
257
258 if !self.load_next_chunk()? {
259 self.done = true;
260 return Ok(None);
261 }
262 }
263 }
264
265 fn load_next_chunk(&mut self) -> Result<bool> {
269 loop {
270 if self.done {
271 return Ok(false);
272 }
273 let Some(series) = self.series.as_ref() else {
274 if !self.advance_series()? {
275 return Ok(false);
276 }
277 continue;
278 };
279
280 if self.chunk_idx >= series.chunks.len() {
281 if !self.advance_series()? {
282 return Ok(false);
283 }
284 continue;
285 }
286
287 let chunk = series.chunks[self.chunk_idx];
288 self.chunk_idx += 1;
289 if !self
292 .opts
293 .range
294 .overlaps_chunk(chunk.min_time, chunk.max_time)
295 {
296 continue;
297 }
298
299 self.pending.reset();
300 let slice = self.chunks.chunk(chunk.reference).map_err(|e| {
301 contextual(
302 format!(
303 "series {} chunk {} (ref {:#x})",
304 self.series_key,
305 self.chunk_idx - 1,
306 chunk.reference
307 ),
308 e,
309 )
310 })?;
311 let outcome = chunkenc::decode_with_limits(
312 slice.encoding,
313 slice.data,
314 &self.opts.limits,
315 &mut self.pending,
316 )
317 .map_err(|e| {
318 contextual(
319 format!(
320 "series {} chunk {} (ref {:#x}, encoding {})",
321 self.series_key,
322 self.chunk_idx - 1,
323 chunk.reference,
324 chunkenc::encoding_name(slice.encoding)
325 ),
326 e,
327 )
328 })?;
329 self.chunks_decoded += 1;
330 if outcome.samples() == 0 {
331 continue;
332 }
333 self.cursor = 0;
334 return Ok(true);
335 }
336 }
337
338 fn advance_series(&mut self) -> Result<bool> {
340 loop {
341 let Some(next) = self.series_iter.next() else {
342 self.series = None;
343 return Ok(false);
344 };
345 let series = next?;
346 let intersects = match (series.min_time(), series.max_time()) {
349 (Some(mint), Some(maxt)) => self.opts.range.overlaps_chunk(mint, maxt),
350 _ => false,
351 };
352 if !intersects {
353 continue;
354 }
355 self.series_key = series_key(&series);
356 self.deleted.clear();
357 if self.opts.skip_deleted {
358 self.deleted
359 .extend_from_slice(self.tombstones.intervals(series.id));
360 }
361 self.series = Some(series);
362 self.chunk_idx = 0;
363 self.last_ts = None;
364 return Ok(true);
365 }
366 }
367}
368
369impl BlockReader {
370 pub fn samples(&self, range: TimeRange) -> SampleIterator<'_> {
372 self.samples_with(SampleIterOptions {
373 range,
374 ..SampleIterOptions::default()
375 })
376 }
377
378 pub fn samples_with(&self, opts: SampleIterOptions) -> SampleIterator<'_> {
380 SampleIterator::new(self.index(), self.chunk_reader(), self.tombstones(), opts)
381 }
382}
383
384fn series_key(series: &SeriesRef) -> String {
386 let mut out = String::new();
387 for (i, (n, v)) in series.labels.iter().enumerate() {
388 if i > 0 {
389 out.push(',');
390 }
391 out.push_str(n);
392 out.push('=');
393 out.push_str(v);
394 }
395 out
396}
397
398fn contextual(prefix: String, err: Error) -> Error {
400 match err {
401 Error::Format(m) => Error::Format(format!("{prefix}: {m}")),
402 Error::Decode(m) => Error::Decode(format!("{prefix}: {m}")),
403 Error::Corrupt(m) => Error::Corrupt(format!("{prefix}: {m}")),
404 Error::Checksum(s) => Error::Corrupt(format!("{prefix}: checksum mismatch in {s}")),
405 Error::Eof(off) => {
408 Error::Corrupt(format!("{prefix}: unexpected end of data at byte {off}"))
409 }
410 other => other,
411 }
412}
413
414fn tombstone_hit(intervals: &[(i64, i64)], ts: i64) -> bool {
415 if intervals.is_empty() {
416 return false;
417 }
418 tombstone_is_deleted(intervals, ts)
419}
420
421fn tombstone_is_deleted(intervals: &[(i64, i64)], ts: i64) -> bool {
424 tombstones::is_deleted(intervals, ts)
425}
426
427#[derive(Default)]
433struct Pending {
434 items: Vec<Item>,
435 len: usize,
436}
437
438enum Item {
439 Float { ts: i64, value: f64 },
440 Int(OwnedIntHistogram),
441 FloatHist(OwnedFloatHistogram),
442}
443
444impl Default for Item {
445 fn default() -> Self {
446 Item::Float { ts: 0, value: 0.0 }
447 }
448}
449
450impl Pending {
451 fn reset(&mut self) {
452 self.len = 0;
453 }
454
455 fn len(&self) -> usize {
456 self.len
457 }
458
459 fn ts(&self, idx: usize) -> i64 {
460 match &self.items[idx] {
461 Item::Float { ts, .. } => *ts,
462 Item::Int(h) => h.ts,
463 Item::FloatHist(h) => h.ts,
464 }
465 }
466
467 fn value(&self, idx: usize) -> SampleValue<'_> {
468 match &self.items[idx] {
469 Item::Float { value, .. } => SampleValue::Float(*value),
470 Item::Int(h) => SampleValue::IntHistogram(h.view()),
471 Item::FloatHist(h) => SampleValue::FloatHistogram(h.view()),
472 }
473 }
474
475 fn slot(&mut self) -> usize {
476 let idx = self.len;
477 if idx >= self.items.len() {
478 self.items.push(Item::default());
479 }
480 self.len += 1;
481 idx
482 }
483}
484
485impl SampleSink for Pending {
486 fn push_float(&mut self, ts: i64, value: f64) {
487 let idx = self.slot();
488 self.items[idx] = Item::Float { ts, value };
489 }
490
491 fn push_int_histogram(&mut self, h: &IntHistogramSample<'_>) {
492 let idx = self.slot();
493 match &mut self.items[idx] {
494 Item::Int(owned) => owned.set(h),
495 slot => *slot = Item::Int(OwnedIntHistogram::from_sample(h)),
496 }
497 }
498
499 fn push_float_histogram(&mut self, h: &FloatHistogramSample<'_>) {
500 let idx = self.slot();
501 match &mut self.items[idx] {
502 Item::FloatHist(owned) => owned.set(h),
503 slot => *slot = Item::FloatHist(OwnedFloatHistogram::from_sample(h)),
504 }
505 }
506}
507
508struct OwnedIntHistogram {
510 ts: i64,
511 st: i64,
512 count: u64,
513 zero_count: u64,
514 sum: f64,
515 schema: i32,
516 zero_threshold: f64,
517 pos_spans: Vec<Span>,
518 neg_spans: Vec<Span>,
519 pos_counts: Vec<i64>,
520 neg_counts: Vec<i64>,
521 pos_deltas: Vec<i64>,
522 neg_deltas: Vec<i64>,
523 custom_values: Vec<f64>,
524 chunk_reset_hint: CounterResetHint,
525 counter_reset_hint: CounterResetHint,
526}
527
528impl OwnedIntHistogram {
529 fn from_sample(h: &IntHistogramSample<'_>) -> Self {
530 let mut out = Self {
531 ts: 0,
532 st: 0,
533 count: 0,
534 zero_count: 0,
535 sum: 0.0,
536 schema: 0,
537 zero_threshold: 0.0,
538 pos_spans: Vec::new(),
539 neg_spans: Vec::new(),
540 pos_counts: Vec::new(),
541 neg_counts: Vec::new(),
542 pos_deltas: Vec::new(),
543 neg_deltas: Vec::new(),
544 custom_values: Vec::new(),
545 chunk_reset_hint: CounterResetHint::Unknown,
546 counter_reset_hint: CounterResetHint::Unknown,
547 };
548 out.set(h);
549 out
550 }
551
552 fn set(&mut self, h: &IntHistogramSample<'_>) {
553 self.ts = h.ts;
554 self.st = h.st;
555 self.count = h.count;
556 self.zero_count = h.zero_count;
557 self.sum = h.sum;
558 self.schema = h.schema;
559 self.zero_threshold = h.zero_threshold;
560 copy_spans(&mut self.pos_spans, h.pos_spans);
561 copy_spans(&mut self.neg_spans, h.neg_spans);
562 self.pos_counts.clear();
563 self.pos_counts.extend_from_slice(h.pos_counts);
564 self.neg_counts.clear();
565 self.neg_counts.extend_from_slice(h.neg_counts);
566 self.pos_deltas.clear();
567 self.pos_deltas.extend_from_slice(h.pos_deltas);
568 self.neg_deltas.clear();
569 self.neg_deltas.extend_from_slice(h.neg_deltas);
570 self.custom_values.clear();
571 self.custom_values.extend_from_slice(h.custom_values);
572 self.chunk_reset_hint = h.chunk_reset_hint;
573 self.counter_reset_hint = h.counter_reset_hint;
574 }
575
576 fn view(&self) -> IntHistogramSample<'_> {
577 IntHistogramSample {
578 ts: self.ts,
579 st: self.st,
580 count: self.count,
581 zero_count: self.zero_count,
582 sum: self.sum,
583 schema: self.schema,
584 zero_threshold: self.zero_threshold,
585 pos_spans: &self.pos_spans,
586 neg_spans: &self.neg_spans,
587 pos_counts: &self.pos_counts,
588 neg_counts: &self.neg_counts,
589 pos_deltas: &self.pos_deltas,
590 neg_deltas: &self.neg_deltas,
591 custom_values: &self.custom_values,
592 chunk_reset_hint: self.chunk_reset_hint,
593 counter_reset_hint: self.counter_reset_hint,
594 }
595 }
596}
597
598struct OwnedFloatHistogram {
600 ts: i64,
601 st: i64,
602 count: f64,
603 zero_count: f64,
604 sum: f64,
605 schema: i32,
606 zero_threshold: f64,
607 pos_spans: Vec<Span>,
608 neg_spans: Vec<Span>,
609 pos_buckets: Vec<f64>,
610 neg_buckets: Vec<f64>,
611 custom_values: Vec<f64>,
612 chunk_reset_hint: CounterResetHint,
613 counter_reset_hint: CounterResetHint,
614}
615
616impl OwnedFloatHistogram {
617 fn from_sample(h: &FloatHistogramSample<'_>) -> Self {
618 let mut out = Self {
619 ts: 0,
620 st: 0,
621 count: 0.0,
622 zero_count: 0.0,
623 sum: 0.0,
624 schema: 0,
625 zero_threshold: 0.0,
626 pos_spans: Vec::new(),
627 neg_spans: Vec::new(),
628 pos_buckets: Vec::new(),
629 neg_buckets: Vec::new(),
630 custom_values: Vec::new(),
631 chunk_reset_hint: CounterResetHint::Unknown,
632 counter_reset_hint: CounterResetHint::Unknown,
633 };
634 out.set(h);
635 out
636 }
637
638 fn set(&mut self, h: &FloatHistogramSample<'_>) {
639 self.ts = h.ts;
640 self.st = h.st;
641 self.count = h.count;
642 self.zero_count = h.zero_count;
643 self.sum = h.sum;
644 self.schema = h.schema;
645 self.zero_threshold = h.zero_threshold;
646 copy_spans(&mut self.pos_spans, h.pos_spans);
647 copy_spans(&mut self.neg_spans, h.neg_spans);
648 self.pos_buckets.clear();
649 self.pos_buckets.extend_from_slice(h.pos_buckets);
650 self.neg_buckets.clear();
651 self.neg_buckets.extend_from_slice(h.neg_buckets);
652 self.custom_values.clear();
653 self.custom_values.extend_from_slice(h.custom_values);
654 self.chunk_reset_hint = h.chunk_reset_hint;
655 self.counter_reset_hint = h.counter_reset_hint;
656 }
657
658 fn view(&self) -> FloatHistogramSample<'_> {
659 FloatHistogramSample {
660 ts: self.ts,
661 st: self.st,
662 count: self.count,
663 zero_count: self.zero_count,
664 sum: self.sum,
665 schema: self.schema,
666 zero_threshold: self.zero_threshold,
667 pos_spans: &self.pos_spans,
668 neg_spans: &self.neg_spans,
669 pos_buckets: &self.pos_buckets,
670 neg_buckets: &self.neg_buckets,
671 custom_values: &self.custom_values,
672 chunk_reset_hint: self.chunk_reset_hint,
673 counter_reset_hint: self.counter_reset_hint,
674 }
675 }
676}
677
678fn copy_spans(dst: &mut Vec<Span>, src: &[Span]) {
679 dst.clear();
680 dst.extend_from_slice(src);
681}
682
683#[cfg(test)]
684mod tests {
685 use super::*;
686
687 #[test]
688 fn range_translation_is_half_open() {
689 let r = TimeRange::new(100, 200);
690 assert!(r.contains(100));
691 assert!(r.contains(199));
692 assert!(!r.contains(200));
693 assert!(r.overlaps_chunk(199, 300));
695 assert!(!r.overlaps_chunk(50, 99));
696 assert!(!r.overlaps_chunk(200, 300));
697 assert!(TimeRange::new(5, 5).is_empty());
698 assert!(TimeRange::all().contains(i64::MIN));
699 }
700
701 #[test]
702 fn pending_buffer_is_reused() {
703 let mut p = Pending::default();
704 p.push_float(1, 2.0);
705 p.push_float(3, 4.0);
706 assert_eq!(p.len(), 2);
707 assert_eq!(p.ts(1), 3);
708 matches!(p.value(0), SampleValue::Float(_));
709 let capacity = p.items.capacity();
710 p.reset();
711 assert_eq!(p.len(), 0);
712 assert_eq!(p.items.capacity(), capacity);
714 p.push_float(5, 6.0);
715 assert_eq!(p.ts(0), 5);
716 }
717
718 #[test]
719 fn integer_histogram_slots_keep_their_buffers() {
720 let mut p = Pending::default();
721 let sample = IntHistogramSample {
722 ts: 10,
723 st: 0,
724 count: 1 << 60,
725 zero_count: 0,
726 sum: 1.0,
727 schema: 1,
728 zero_threshold: 0.0,
729 pos_spans: &[Span {
730 offset: 0,
731 length: 1,
732 }],
733 neg_spans: &[],
734 pos_counts: &[1 << 40],
735 neg_counts: &[],
736 pos_deltas: &[1 << 40],
737 neg_deltas: &[],
738 custom_values: &[],
739 chunk_reset_hint: CounterResetHint::Unknown,
740 counter_reset_hint: CounterResetHint::NotCounterReset,
741 };
742 p.push_int_histogram(&sample);
743 match p.value(0) {
744 SampleValue::IntHistogram(v) => {
745 assert_eq!(v.count, 1 << 60);
746 assert_eq!(v.pos_counts, &[1 << 40]);
747 assert_eq!(v.counter_reset_hint, CounterResetHint::NotCounterReset);
748 }
749 other => panic!("expected an integer histogram, got {other:?}"),
750 }
751 }
752}