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