Skip to main content

feldera_modular_bloom/
density.rs

1use crate::layout::ModuleLayout;
2
3/// How many bits are set in each module of a filter.
4///
5/// Recorded when the filter is built so that a later reader can work out what
6/// accuracy a given number of modules buys without holding any of them. That is
7/// what lets a caller decide how much of a stored filter to read before reading
8/// any of it.
9#[derive(Clone, Debug, PartialEq, Eq)]
10pub struct ModuleDensity {
11    set_bits: Vec<u64>,
12}
13
14impl ModuleDensity {
15    /// Records `set_bits[i]` bits set in module `i`.
16    pub fn new(set_bits: Vec<u64>) -> Self {
17        Self { set_bits }
18    }
19
20    /// Counts the bits set in each module of `words`, which must hold whole
21    /// modules of `layout` laid out in order.
22    pub fn measure(layout: &ModuleLayout, words: &[u64]) -> Self {
23        Self::new(
24            words
25                .chunks(layout.words_per_module() as usize)
26                .map(|module| module.iter().map(|w| u64::from(w.count_ones())).sum())
27                .collect(),
28        )
29    }
30
31    /// Bits set in each module, in order.
32    pub fn set_bits(&self) -> &[u64] {
33        &self.set_bits
34    }
35
36    /// Modules this covers, which may be fewer than the layout describes.
37    pub fn modules(&self) -> u32 {
38        self.set_bits.len() as u32
39    }
40
41    /// Appends the count for one more module.
42    pub fn push(&mut self, set_bits: u64) {
43        self.set_bits.push(set_bits);
44    }
45
46    /// Fraction of bits set across the first `modules` modules.
47    ///
48    /// Returns 0.0 when nothing is covered.
49    pub fn fill_ratio(&self, layout: &ModuleLayout, modules: u32) -> f64 {
50        let covered = modules.min(self.modules()) as usize;
51        if covered == 0 {
52            return 0.0;
53        }
54        let set: u64 = self.set_bits[..covered].iter().sum();
55        set as f64 / (covered as u64 * layout.bits_per_module()) as f64
56    }
57
58    /// False positive rate of a filter holding the first `modules` modules.
59    ///
60    /// `modules` above `layout.total_modules()` is clamped. Modules this does
61    /// not cover are charged the mean fill of the ones it does, which is what a
62    /// filter measured from a prefix falls back on; zero coverage gives 1.0,
63    /// since nothing is known to reject anything.
64    pub fn false_positive_rate(&self, layout: &ModuleLayout, modules: u32) -> f64 {
65        let modules = modules.min(layout.total_modules()) as usize;
66        if modules == 0 || self.set_bits.is_empty() {
67            return 1.0;
68        }
69
70        // Multiply per-module rates rather than raising a mean fill to a power:
71        // the mean form is biased by Jensen's inequality.
72        let bits = layout.bits_per_module() as f64;
73        let hashes = i32::try_from(layout.hashes_per_module()).unwrap_or(i32::MAX);
74        let mean = self.fill_ratio(layout, self.modules());
75        (0..modules)
76            .map(|module| match self.set_bits.get(module) {
77                Some(&set) => (set as f64 / bits).powi(hashes),
78                None => mean.powi(hashes),
79            })
80            .product()
81    }
82
83    /// Smallest number of modules whose rate is at or below `target`.
84    ///
85    /// Returns `layout.total_modules()` when even the whole filter misses `target`,
86    /// and 0 when `target` is 1.0 or above.
87    pub fn modules_for(&self, layout: &ModuleLayout, target: f64) -> u32 {
88        (0..=layout.total_modules())
89            .find(|&modules| self.false_positive_rate(layout, modules) <= target)
90            .unwrap_or_else(|| layout.total_modules())
91    }
92}
93
94#[cfg(test)]
95mod tests {
96    use super::ModuleDensity;
97    use crate::layout::ModuleLayout;
98
99    fn layout() -> ModuleLayout {
100        ModuleLayout::new(4, 1_000, 3).unwrap()
101    }
102
103    /// Half the bits set in every module gives 0.5^hashes per module.
104    #[test]
105    fn rate_is_the_product_of_the_per_module_rates() {
106        let g = layout();
107        let half = g.bits_per_module() / 2;
108        let density = ModuleDensity::new(vec![half; 4]);
109
110        assert_eq!(density.false_positive_rate(&g, 0), 1.0);
111        for modules in 1..=4u32 {
112            let expected = 0.5f64.powi(3 * modules as i32);
113            let got = density.false_positive_rate(&g, modules);
114            assert!(
115                (got - expected).abs() < 1e-12,
116                "{modules}: {got} vs {expected}"
117            );
118        }
119        // A module count above the layout's is clamped to it.
120        assert_eq!(
121            density.false_positive_rate(&g, 99),
122            density.false_positive_rate(&g, 4)
123        );
124    }
125
126    /// A density that records fewer modules than it is asked about uses the
127    /// mean of the modules it does record for the rest.
128    #[test]
129    fn partial_coverage_falls_back_to_the_mean() {
130        let g = layout();
131        let half = g.bits_per_module() / 2;
132        let full = ModuleDensity::new(vec![half; 4]);
133        let prefix = ModuleDensity::new(vec![half]);
134        assert_eq!(
135            prefix.false_positive_rate(&g, 4),
136            full.false_positive_rate(&g, 4)
137        );
138    }
139
140    /// With nothing recorded there is nothing to reject with.
141    #[test]
142    fn empty_density_admits_everything() {
143        let g = layout();
144        let empty = ModuleDensity::new(Vec::new());
145        for modules in 0..=4u32 {
146            assert_eq!(empty.false_positive_rate(&g, modules), 1.0);
147        }
148        assert_eq!(empty.modules_for(&g, 1e-4), 4);
149    }
150
151    #[test]
152    fn modules_for_picks_the_smallest_sufficient_count() {
153        let g = layout();
154        let half = g.bits_per_module() / 2;
155        let density = ModuleDensity::new(vec![half; 4]);
156
157        // Each module contributes 0.5^3 = 1/8.
158        assert_eq!(density.modules_for(&g, 1.0), 0);
159        assert_eq!(density.modules_for(&g, 0.125), 1);
160        assert_eq!(density.modules_for(&g, 0.02), 2);
161        assert_eq!(density.modules_for(&g, 0.002), 3);
162        assert_eq!(density.modules_for(&g, 0.0003), 4);
163        // Unreachable targets give the whole filter rather than failing.
164        assert_eq!(density.modules_for(&g, 1e-12), 4);
165    }
166
167    #[test]
168    fn measure_counts_each_module() {
169        let g = ModuleLayout::new(3, 2, 1).unwrap();
170        // Module 0 has 3 bits set, module 1 has 1, module 2 has none.
171        let words = vec![0b111u64, 0, 0b1, 0, 0, 0];
172        let density = ModuleDensity::measure(&g, &words);
173        assert_eq!(density.set_bits(), &[3, 1, 0]);
174        assert_eq!(density.modules(), 3);
175    }
176}