Skip to main content

dataprof_core/sampling/
sampler.rs

1//! The runtime that applies a [`SamplingStrategy`] to a stream of rows.
2//!
3//! Strategies fall into two families, and the difference is not cosmetic:
4//!
5//! * **Streaming** strategies (`Systematic`, `Stratified`, `Progressive`,
6//!   `Importance`) decide each row on the spot, so a row can be folded into the
7//!   running statistics immediately and memory stays bounded.
8//! * **Fixed-size** strategies (`Reservoir`, `Random`) cannot. Whether row 5
9//!   belongs in a uniform sample of 10 is not known until the stream ends —
10//!   row 5 may be evicted at row 900. Streaming statistics are not retractable,
11//!   so a row that was folded in and later evicted would silently corrupt the
12//!   profile. These strategies therefore buffer the candidate rows and hand the
13//!   final sample back at end of stream, costing `size` rows of memory.
14//!
15//! [`RowSampler`] hides that split behind one interface so every engine treats
16//! sampling identically. Consult [`RowSampler::is_buffered`] to know which of
17//! [`RowSampler::accept`] or [`RowSampler::offer`] to call.
18
19use crate::errors::DataProfilerError;
20
21use super::reservoir::ReservoirSampler;
22use super::strategies::{SamplingState, SamplingStrategy};
23
24/// A borrowed view of one row, addressable by column name.
25///
26/// Sampling reads at most a couple of columns per row, so this scans the header
27/// slice rather than building a map — allocating a `HashMap` per row would cost
28/// far more than the lookup it saves.
29#[derive(Clone, Copy)]
30pub struct RowView<'a> {
31    headers: &'a [String],
32    values: &'a [String],
33}
34
35impl<'a> RowView<'a> {
36    pub fn new(headers: &'a [String], values: &'a [String]) -> Self {
37        Self { headers, values }
38    }
39
40    /// The value of `column`, or `None` when the row has no such field.
41    pub fn get(&self, column: &str) -> Option<&'a str> {
42        let index = self.headers.iter().position(|h| h == column)?;
43        self.values.get(index).map(String::as_str)
44    }
45
46    pub fn headers(&self) -> &'a [String] {
47        self.headers
48    }
49
50    pub fn values(&self) -> &'a [String] {
51        self.values
52    }
53}
54
55/// Running mean and variance over one column, used by `Progressive` to measure
56/// how precise the sample has become. Welford's method: numerically stable and
57/// single-pass, so precision can be checked after every row without a rescan.
58#[derive(Debug, Default, Clone)]
59struct RunningMoments {
60    count: u64,
61    mean: f64,
62    m2: f64,
63}
64
65impl RunningMoments {
66    fn push(&mut self, value: f64) {
67        self.count += 1;
68        let delta = value - self.mean;
69        self.mean += delta / self.count as f64;
70        self.m2 += delta * (value - self.mean);
71    }
72
73    /// Relative standard error of the mean: `stderr / |mean|`.
74    ///
75    /// `None` until there are enough observations to have a variance, or when
76    /// the mean sits at zero and a *relative* error is undefined.
77    fn relative_standard_error(&self) -> Option<f64> {
78        if self.count < 2 {
79            return None;
80        }
81        let variance = self.m2 / (self.count - 1) as f64;
82        let standard_error = (variance / self.count as f64).sqrt();
83        let mean_magnitude = self.mean.abs();
84        if mean_magnitude <= f64::EPSILON {
85            return None;
86        }
87        Some(standard_error / mean_magnitude)
88    }
89}
90
91/// Precision tracker behind the `Progressive` strategy.
92#[derive(Debug, Default)]
93struct PrecisionTracker {
94    /// Moments per column position, for columns seen holding numbers.
95    columns: Vec<Option<RunningMoments>>,
96    numeric_columns: usize,
97}
98
99impl PrecisionTracker {
100    fn observe(&mut self, row: RowView<'_>) {
101        if self.columns.len() < row.values().len() {
102            self.columns.resize(row.values().len(), None);
103        }
104        for (index, raw) in row.values().iter().enumerate() {
105            let trimmed = raw.trim();
106            if trimmed.is_empty() {
107                continue;
108            }
109            // A column counts as numeric once a value parses; a later
110            // non-numeric value does not retract that, it is simply skipped.
111            let Ok(value) = trimmed.parse::<f64>() else {
112                continue;
113            };
114            if !value.is_finite() {
115                continue;
116            }
117            let slot = &mut self.columns[index];
118            if slot.is_none() {
119                *slot = Some(RunningMoments::default());
120                self.numeric_columns += 1;
121            }
122            // decode-audit: impossible — the slot was just populated above.
123            slot.as_mut()
124                .expect("numeric column slot is present")
125                .push(value);
126        }
127    }
128
129    /// Whether every numeric column has reached the target relative standard
130    /// error. `false` when nothing numeric has been seen: precision cannot be
131    /// claimed for data it could not measure.
132    fn meets_target(&self, target: f64) -> bool {
133        if self.numeric_columns == 0 {
134            return false;
135        }
136        self.columns
137            .iter()
138            .flatten()
139            .all(|moments| match moments.relative_standard_error() {
140                Some(rse) => rse <= target,
141                // Not yet measurable — not yet precise enough.
142                None => false,
143            })
144    }
145}
146
147/// A fixed-size uniform sample held in memory until the stream ends.
148#[derive(Debug)]
149struct SampleBuffer {
150    capacity: usize,
151    rows: Vec<Vec<String>>,
152    sampler: ReservoirSampler,
153    seen: usize,
154}
155
156impl SampleBuffer {
157    fn new(capacity: usize) -> Self {
158        Self {
159            capacity,
160            rows: Vec::new(),
161            sampler: ReservoirSampler::new(capacity),
162            seen: 0,
163        }
164    }
165
166    /// Offer a row to the sample, replacing an existing member if selected.
167    ///
168    /// Algorithm R: the first `capacity` rows fill the reservoir, after which
169    /// row `n` replaces a uniformly chosen member with probability
170    /// `capacity / n`. Every row of the stream ends up equally likely to be in
171    /// the final sample.
172    fn offer(&mut self, values: Vec<String>) {
173        self.seen += 1;
174        if self.capacity == 0 {
175            return;
176        }
177        if self.rows.len() < self.capacity {
178            self.rows.push(values);
179            return;
180        }
181        if let Some(position) = self.sampler.replacement_slot(self.seen) {
182            self.rows[position] = values;
183        }
184    }
185
186    fn take(&mut self) -> Vec<Vec<String>> {
187        std::mem::take(&mut self.rows)
188    }
189}
190
191/// Applies a [`SamplingStrategy`] to a stream of rows, holding all the state
192/// the strategy needs across rows.
193///
194/// A fresh state per row — which is what calling a stateless helper amounts to
195/// — silently disables every stateful strategy, so engines must create one
196/// sampler per scan and keep it for the whole scan.
197#[derive(Debug)]
198pub struct RowSampler {
199    /// Streaming filters, applied in order; a row must pass all of them.
200    filters: Vec<SamplingStrategy>,
201    /// Terminal fixed-size stage, if the strategy has one.
202    buffer: Option<SampleBuffer>,
203    state: SamplingState,
204    precision: PrecisionTracker,
205    /// Rows offered to the sampler, whether or not they were kept.
206    iterated: usize,
207    /// Rows the sampler accepted for immediate folding (streaming path only).
208    accepted: usize,
209}
210
211impl RowSampler {
212    /// Build a sampler for `strategy`, validating that it can be applied.
213    ///
214    /// Rejects here rather than mid-scan: a caller learns that a strategy is
215    /// unusable before the source is read, not after a partial profile exists.
216    pub fn new(strategy: &SamplingStrategy) -> Result<Self, DataProfilerError> {
217        let mut filters = Vec::new();
218        let mut buffer = None;
219        Self::flatten(strategy, &mut filters, &mut buffer)?;
220
221        Ok(Self {
222            filters,
223            buffer,
224            state: SamplingState::new(),
225            precision: PrecisionTracker::default(),
226            iterated: 0,
227            accepted: 0,
228        })
229    }
230
231    /// Split a (possibly multi-stage) strategy into streaming filters and at
232    /// most one terminal fixed-size stage.
233    fn flatten(
234        strategy: &SamplingStrategy,
235        filters: &mut Vec<SamplingStrategy>,
236        buffer: &mut Option<SampleBuffer>,
237    ) -> Result<(), DataProfilerError> {
238        match strategy {
239            SamplingStrategy::None => Ok(()),
240            SamplingStrategy::Reservoir { size } | SamplingStrategy::Random { size } => {
241                if buffer.is_some() {
242                    // Two fixed-size stages have no combined meaning: each wants
243                    // to define the final sample.
244                    return Err(DataProfilerError::InvalidConfiguration {
245                        message: "a multi-stage strategy may contain at most one fixed-size stage \
246                                  (random or reservoir)"
247                            .to_string(),
248                        suggestion: "Keep a single fixed-size stage and express the rest as \
249                                     filters, e.g. multi_stage([systematic(10), reservoir(1000)])."
250                            .to_string(),
251                    });
252                }
253                *buffer = Some(SampleBuffer::new(*size));
254                Ok(())
255            }
256            SamplingStrategy::MultiStage { stages } => {
257                for stage in stages {
258                    // A filter after the fixed-size stage would have nothing to
259                    // filter: the sample is only final once the source ends.
260                    if buffer.is_some() && !Self::is_fixed_size(stage) {
261                        return Err(DataProfilerError::InvalidConfiguration {
262                            message: "a fixed-size stage (random or reservoir) must be the last \
263                                      stage of a multi-stage strategy"
264                                .to_string(),
265                            suggestion: "Reorder the stages so filters such as systematic or \
266                                         stratified come first, e.g. \
267                                         multi_stage([systematic(10), reservoir(1000)])."
268                                .to_string(),
269                        });
270                    }
271                    Self::flatten(stage, filters, buffer)?;
272                }
273                Ok(())
274            }
275            other => {
276                filters.push(other.clone());
277                Ok(())
278            }
279        }
280    }
281
282    /// Whether a stage draws a fixed-size sample, and so must come last.
283    fn is_fixed_size(strategy: &SamplingStrategy) -> bool {
284        match strategy {
285            SamplingStrategy::Reservoir { .. } | SamplingStrategy::Random { .. } => true,
286            SamplingStrategy::MultiStage { stages } => stages.iter().any(Self::is_fixed_size),
287            _ => false,
288        }
289    }
290
291    /// Whether rows must be handed to [`offer`](Self::offer) instead of being
292    /// folded in as [`accept`](Self::accept) approves them.
293    pub fn is_buffered(&self) -> bool {
294        self.buffer.is_some()
295    }
296
297    /// Whether this sampler can ever exclude a row.
298    pub fn is_noop(&self) -> bool {
299        self.filters.is_empty() && self.buffer.is_none()
300    }
301
302    /// Decide whether a row passes the streaming filters.
303    ///
304    /// Always call this, including on the buffered path, so the filters of a
305    /// multi-stage strategy run before the fixed-size stage sees a row.
306    pub fn accept(&mut self, row: RowView<'_>) -> bool {
307        self.iterated += 1;
308        let index = self.iterated - 1;
309
310        for filter in &self.filters {
311            if !Self::passes(filter, index, row, &mut self.state, &mut self.precision) {
312                return false;
313            }
314        }
315
316        if self.buffer.is_none() {
317            self.accepted += 1;
318        }
319        true
320    }
321
322    /// Hand a row that passed [`accept`](Self::accept) to the fixed-size stage.
323    ///
324    /// Only meaningful when [`is_buffered`](Self::is_buffered) is true.
325    pub fn offer(&mut self, values: Vec<String>) {
326        if let Some(buffer) = self.buffer.as_mut() {
327            buffer.offer(values);
328        }
329    }
330
331    /// The final sample from the fixed-size stage, ready to fold into the
332    /// statistics. Empty for a purely streaming strategy.
333    pub fn take_sample(&mut self) -> Vec<Vec<String>> {
334        match self.buffer.as_mut() {
335            Some(buffer) => {
336                let rows = buffer.take();
337                self.accepted += rows.len();
338                rows
339            }
340            None => Vec::new(),
341        }
342    }
343
344    /// Rows the sampler has seen, sampled or not.
345    pub fn iterated_rows(&self) -> usize {
346        self.iterated
347    }
348
349    /// Rows that ended up in the sample.
350    pub fn sampled_rows(&self) -> usize {
351        self.accepted
352    }
353
354    fn passes(
355        filter: &SamplingStrategy,
356        index: usize,
357        row: RowView<'_>,
358        state: &mut SamplingState,
359        precision: &mut PrecisionTracker,
360    ) -> bool {
361        match filter {
362            #[allow(clippy::manual_is_multiple_of)]
363            SamplingStrategy::Systematic { interval } => {
364                if *interval == 0 {
365                    return true;
366                }
367                index % interval == 0
368            }
369            SamplingStrategy::Stratified {
370                key_columns,
371                samples_per_stratum,
372            } => state.take_from_stratum(row, key_columns, *samples_per_stratum),
373            SamplingStrategy::Importance {
374                weight_column,
375                weight_threshold,
376            } => match row.get(weight_column) {
377                // A row whose weight is missing or unparseable has no stated
378                // importance, so it is not important enough to keep.
379                Some(raw) => matches!(raw.trim().parse::<f64>(), Ok(w) if w >= *weight_threshold),
380                None => false,
381            },
382            SamplingStrategy::Progressive {
383                initial_size,
384                confidence_level,
385                max_size,
386            } => {
387                let taken = state.progressive_taken();
388                if taken >= *max_size {
389                    return false;
390                }
391                if taken >= *initial_size && precision.meets_target(1.0 - confidence_level) {
392                    return false;
393                }
394                precision.observe(row);
395                state.record_progressive();
396                true
397            }
398            // Fixed-size stages never reach here; `None` and `MultiStage` are
399            // flattened away by `flatten`.
400            _ => true,
401        }
402    }
403}
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408
409    fn headers() -> Vec<String> {
410        vec!["group".into(), "weight".into(), "value".into()]
411    }
412
413    fn row(group: &str, weight: &str, value: &str) -> Vec<String> {
414        vec![group.into(), weight.into(), value.into()]
415    }
416
417    fn run(strategy: SamplingStrategy, rows: usize) -> (usize, usize) {
418        let headers = headers();
419        let mut sampler = RowSampler::new(&strategy).expect("valid strategy");
420        for i in 0..rows {
421            let values = row(
422                &format!("g{}", i % 3),
423                &format!("{}", i % 10),
424                &format!("{}", 100 + (i % 7)),
425            );
426            let view = RowView::new(&headers, &values);
427            if sampler.accept(view) && sampler.is_buffered() {
428                sampler.offer(values);
429            }
430        }
431        let final_rows = sampler.take_sample().len();
432        (sampler.sampled_rows(), final_rows)
433    }
434
435    #[test]
436    fn reservoir_yields_exactly_its_size() {
437        let (sampled, buffered) = run(SamplingStrategy::Reservoir { size: 10 }, 100);
438        assert_eq!(buffered, 10);
439        assert_eq!(sampled, 10);
440    }
441
442    #[test]
443    fn reservoir_smaller_than_its_size_keeps_every_row() {
444        let (sampled, buffered) = run(SamplingStrategy::Reservoir { size: 50 }, 20);
445        assert_eq!(buffered, 20, "a short stream cannot fill the reservoir");
446        assert_eq!(sampled, 20);
447    }
448
449    #[test]
450    fn random_matches_reservoir_semantics() {
451        let (_, buffered) = run(SamplingStrategy::Random { size: 25 }, 500);
452        assert_eq!(buffered, 25);
453    }
454
455    #[test]
456    fn systematic_takes_every_nth_row() {
457        let (sampled, _) = run(SamplingStrategy::Systematic { interval: 10 }, 100);
458        assert_eq!(sampled, 10);
459    }
460
461    #[test]
462    fn stratified_caps_each_stratum() {
463        let (sampled, _) = run(
464            SamplingStrategy::Stratified {
465                key_columns: vec!["group".into()],
466                samples_per_stratum: 2,
467            },
468            100,
469        );
470        // Three distinct groups, two rows each.
471        assert_eq!(sampled, 6);
472    }
473
474    #[test]
475    fn importance_keeps_rows_at_or_above_the_weight() {
476        let (sampled, _) = run(
477            SamplingStrategy::Importance {
478                weight_column: "weight".into(),
479                weight_threshold: 8.0,
480            },
481            100,
482        );
483        // weight cycles 0..9, so 8 and 9 qualify: 20 of 100.
484        assert_eq!(sampled, 20);
485    }
486
487    #[test]
488    fn importance_on_a_missing_column_keeps_nothing() {
489        let (sampled, _) = run(
490            SamplingStrategy::Importance {
491                weight_column: "absent".into(),
492                weight_threshold: 0.0,
493            },
494            50,
495        );
496        assert_eq!(sampled, 0);
497    }
498
499    #[test]
500    fn progressive_stays_within_its_bounds() {
501        let (sampled, _) = run(
502            SamplingStrategy::Progressive {
503                initial_size: 5,
504                confidence_level: 0.95,
505                max_size: 40,
506            },
507            500,
508        );
509        assert!(
510            (5..=40).contains(&sampled),
511            "progressive took {sampled} rows, outside 5..=40"
512        );
513    }
514
515    #[test]
516    fn progressive_stops_once_precision_is_reached() {
517        // A constant column has zero variance, so its relative standard error
518        // is 0 immediately: the strategy must stop at initial_size rather than
519        // run to max_size.
520        let headers = vec!["value".to_string()];
521        let strategy = SamplingStrategy::Progressive {
522            initial_size: 10,
523            confidence_level: 0.95,
524            max_size: 1_000,
525        };
526        let mut sampler = RowSampler::new(&strategy).unwrap();
527        for _ in 0..500 {
528            let values = vec!["42".to_string()];
529            sampler.accept(RowView::new(&headers, &values));
530        }
531        assert_eq!(
532            sampler.sampled_rows(),
533            10,
534            "zero-variance data reaches any precision target at initial_size"
535        );
536    }
537
538    #[test]
539    fn progressive_without_numeric_columns_runs_to_max_size() {
540        let headers = vec!["label".to_string()];
541        let strategy = SamplingStrategy::Progressive {
542            initial_size: 5,
543            confidence_level: 0.95,
544            max_size: 30,
545        };
546        let mut sampler = RowSampler::new(&strategy).unwrap();
547        for i in 0..500 {
548            let values = vec![format!("text_{i}")];
549            sampler.accept(RowView::new(&headers, &values));
550        }
551        assert_eq!(
552            sampler.sampled_rows(),
553            30,
554            "precision is unmeasurable without numbers, so the cap decides"
555        );
556    }
557
558    #[test]
559    fn multi_stage_applies_the_filter_then_the_fixed_size_stage() {
560        let strategy = SamplingStrategy::MultiStage {
561            stages: vec![
562                SamplingStrategy::Systematic { interval: 2 },
563                SamplingStrategy::Reservoir { size: 10 },
564            ],
565        };
566        let (sampled, buffered) = run(strategy, 100);
567        assert_eq!(buffered, 10, "the reservoir bounds the final sample");
568        assert_eq!(sampled, 10);
569    }
570
571    #[test]
572    fn multi_stage_rejects_two_fixed_size_stages() {
573        let strategy = SamplingStrategy::MultiStage {
574            stages: vec![
575                SamplingStrategy::Reservoir { size: 10 },
576                SamplingStrategy::Random { size: 5 },
577            ],
578        };
579        let error = RowSampler::new(&strategy).expect_err("two fixed-size stages are ambiguous");
580        assert!(error.to_string().contains("at most one fixed-size stage"));
581    }
582
583    #[test]
584    fn multi_stage_rejects_a_filter_after_a_fixed_size_stage() {
585        let strategy = SamplingStrategy::MultiStage {
586            stages: vec![
587                SamplingStrategy::Reservoir { size: 10 },
588                SamplingStrategy::Systematic { interval: 2 },
589            ],
590        };
591        let error = RowSampler::new(&strategy).expect_err("a filter cannot follow the reservoir");
592        assert!(error.to_string().contains("must be the last stage"));
593    }
594
595    #[test]
596    fn none_is_a_noop() {
597        let sampler = RowSampler::new(&SamplingStrategy::None).unwrap();
598        assert!(sampler.is_noop());
599        assert!(!sampler.is_buffered());
600    }
601
602    #[test]
603    fn row_view_reads_by_name() {
604        let headers = headers();
605        let values = row("a", "1.5", "9");
606        let view = RowView::new(&headers, &values);
607        assert_eq!(view.get("weight"), Some("1.5"));
608        assert_eq!(view.get("missing"), None);
609    }
610}