Skip to main content

feldera_modular_bloom/
filter.rs

1use crate::bits::{HashChain, index, set, test};
2use crate::density::ModuleDensity;
3use crate::error::LoadError;
4use crate::layout::ModuleLayout;
5
6/// Given a key hash and a module count, yields the bit positions that key
7/// occupies, as offsets into the modules laid out back to back.
8///
9/// Every position comes from one hash chain seeded by the hash and advanced
10/// once per position. Positions are grouped by module and yielded in module
11/// order: `hashes_per_module` of them land in module 0, the next
12/// `hashes_per_module` in module 1, and so on. Each is reduced into the
13/// `words_per_module` words of the module it belongs to, so a position never
14/// falls outside that module.
15struct BitPositions {
16    /// Source of the derived hashes, advanced once per position.
17    chain: HashChain,
18    /// Size of one module, in 64-bit words.
19    words_per_module: u64,
20    /// Size of one module, in bits.
21    bits_per_module: u64,
22    /// Positions yielded per module.
23    hashes_per_module: u32,
24    /// Bit offset of the module currently being yielded.
25    base: u64,
26    /// Modules still to yield after the current one.
27    modules_left: u32,
28    /// Positions still to yield within the current module.
29    hashes_left: u32,
30}
31
32impl BitPositions {
33    /// Yields `modules * layout.hashes_per_module()` positions, covering the
34    /// first `modules` modules of `layout`.
35    ///
36    /// What a smaller `modules` yields is a prefix of what a larger one yields.
37    /// Truncation depends on that: a filter that has dropped its trailing
38    /// modules must probe the modules it kept at the positions insertion wrote.
39    #[inline(always)]
40    fn new(layout: &ModuleLayout, modules: u32, hash: u64) -> Self {
41        Self {
42            chain: HashChain::new(hash),
43            words_per_module: u64::from(layout.words_per_module()),
44            bits_per_module: layout.bits_per_module(),
45            hashes_per_module: layout.hashes_per_module(),
46            base: 0,
47            modules_left: modules,
48            hashes_left: if modules == 0 {
49                0
50            } else {
51                layout.hashes_per_module()
52            },
53        }
54    }
55}
56
57impl Iterator for BitPositions {
58    type Item = u64;
59
60    #[inline(always)]
61    fn next(&mut self) -> Option<u64> {
62        if self.hashes_left == 0 {
63            self.modules_left = self.modules_left.checked_sub(1)?;
64            if self.modules_left == 0 {
65                return None;
66            }
67            self.base += self.bits_per_module;
68            self.hashes_left = self.hashes_per_module;
69        }
70        self.hashes_left -= 1;
71        Some(self.base + index(self.words_per_module, self.chain.next()))
72    }
73}
74
75/// Accumulates keys into every module of a filter.
76///
77/// Keys can only be added here, before [`Self::finish`]. A finished filter may
78/// drop modules, and a key added after that would be missing from the dropped
79/// ones, so reloading them later would report it absent.
80#[derive(Clone, Debug)]
81pub struct ModularBloomFilterBuilder {
82    words: Vec<u64>,
83    layout: ModuleLayout,
84}
85
86impl ModularBloomFilterBuilder {
87    /// Allocates every module of `layout`, zeroed.
88    pub fn new(layout: ModuleLayout) -> Self {
89        Self {
90            words: vec![0u64; layout.total_words() as usize],
91            layout,
92        }
93    }
94
95    /// Shape of the filter under construction.
96    pub fn layout(&self) -> &ModuleLayout {
97        &self.layout
98    }
99
100    /// Records `hash` in every module.
101    ///
102    /// Keys may arrive in any order and may repeat.
103    // Callers drive this one key at a time from another crate. Inline to avoid call overhead.
104    #[inline]
105    pub fn insert_hash(&mut self, hash: u64) {
106        let words = self.words.as_mut_slice();
107        for bit in BitPositions::new(&self.layout, self.layout.total_modules(), hash) {
108            set(words, bit);
109        }
110    }
111
112    /// Completes the filter with all modules resident.
113    pub fn finish(self) -> ModularBloomFilter {
114        let density = ModuleDensity::measure(&self.layout, &self.words);
115        ModularBloomFilter {
116            words: self.words,
117            density,
118            layout: self.layout,
119        }
120    }
121}
122
123/// A Bloom filter whose accuracy can be traded for memory by dropping modules.
124///
125/// A probe consults resident modules in order and stops at the first rejection,
126/// so an absent key usually touches far fewer modules than are resident.
127#[derive(Clone, Debug)]
128pub struct ModularBloomFilter {
129    /// Resident modules, laid out back to back starting at module 0.
130    words: Vec<u64>,
131    /// Bits set per module. Covers every module the layout describes when the
132    /// caller supplied a recorded density, otherwise only the resident ones.
133    density: ModuleDensity,
134    layout: ModuleLayout,
135}
136
137impl ModularBloomFilter {
138    /// Loads a filter from `words`, which hold whole modules laid out in order
139    /// starting at module 0.
140    ///
141    /// Pass all `layout.total_modules()` modules to load the filter at the
142    /// accuracy it was written with. Pass the first `n` of them, meaning
143    /// `n * layout.words_per_module()` words, to load it at the accuracy `n`
144    /// modules give; the result holds only those modules and occupies
145    /// `n * layout.bytes_per_module()` bytes.
146    ///
147    /// Fails if `words` is not a whole number of modules, or holds more modules
148    /// than `layout` describes.
149    pub fn from_modules(layout: ModuleLayout, words: &[u64]) -> Result<Self, LoadError> {
150        let words_per_module = layout.words_per_module() as usize;
151        if !words.len().is_multiple_of(words_per_module) {
152            return Err(LoadError::PartialModule {
153                words: words.len(),
154                words_per_module: layout.words_per_module(),
155            });
156        }
157
158        let resident = words.len() / words_per_module;
159        if resident > layout.total_modules() as usize {
160            return Err(LoadError::TooManyModules {
161                modules: resident as u32,
162                total_modules: layout.total_modules(),
163            });
164        }
165
166        Ok(Self {
167            density: ModuleDensity::measure(&layout, words),
168            words: words.to_vec(),
169            layout,
170        })
171    }
172
173    /// Loads a filter from `words` together with the density recorded when it
174    /// was built.
175    ///
176    /// `density` may cover more modules than `words` holds, which is the point:
177    /// rates and [`Self::modules_for`] then answer for residencies the filter is
178    /// not currently at, including from a filter loaded with no modules at all.
179    /// A `density` covering fewer modules than `words` holds is discarded in
180    /// favour of measuring them, which is what [`Self::from_modules`] does.
181    pub fn from_modules_with_density(
182        layout: ModuleLayout,
183        words: &[u64],
184        density: ModuleDensity,
185    ) -> Result<Self, LoadError> {
186        let mut filter = Self::from_modules(layout, words)?;
187        if density.modules() >= filter.resident_modules() {
188            filter.density = density;
189        }
190        Ok(filter)
191    }
192
193    /// Bits set per module, for a caller that wants to record them alongside
194    /// the words.
195    pub fn density(&self) -> &ModuleDensity {
196        &self.density
197    }
198
199    /// Appends one more module, raising the filter's accuracy by one rung.
200    ///
201    /// `words` must hold exactly `layout().words_per_module()` words, and
202    /// must be the module at index `resident_modules()`, since modules are
203    /// stored in order. Modules already resident are left untouched.
204    ///
205    /// Fails if `words` is the wrong length, or if every module the layout
206    /// describes is already resident.
207    pub fn push_module(&mut self, words: &[u64]) -> Result<(), LoadError> {
208        if words.len() != self.layout.words_per_module() as usize {
209            return Err(LoadError::PartialModule {
210                words: words.len(),
211                words_per_module: self.layout.words_per_module(),
212            });
213        }
214        if self.resident_modules() >= self.layout.total_modules() {
215            return Err(LoadError::TooManyModules {
216                modules: self.resident_modules() + 1,
217                total_modules: self.layout.total_modules(),
218            });
219        }
220        let appended = self.resident_modules() + 1;
221        self.words.extend_from_slice(words);
222        if self.density.modules() < appended {
223            self.density
224                .push(words.iter().map(|w| u64::from(w.count_ones())).sum());
225        }
226        Ok(())
227    }
228
229    /// Returns `false` only when `hash` was definitely never inserted.
230    #[inline]
231    pub fn contains_hash(&self, hash: u64) -> bool {
232        BitPositions::new(&self.layout, self.resident_modules(), hash)
233            .all(|bit| test(&self.words, bit))
234    }
235
236    /// Shape the filter was built with, whatever its current residency.
237    pub fn layout(&self) -> &ModuleLayout {
238        &self.layout
239    }
240
241    /// Modules currently held in memory.
242    pub fn resident_modules(&self) -> u32 {
243        (self.words.len() / self.layout.words_per_module() as usize) as u32
244    }
245
246    /// Bytes the resident modules occupy.
247    pub fn resident_bytes(&self) -> usize {
248        self.words.len() * 8
249    }
250
251    /// Drops modules beyond the first `modules`, releasing their memory.
252    ///
253    /// Truncating to zero leaves a filter that admits every key, which is the
254    /// same answer a batch with no filter gives. Truncating to at least the
255    /// current residency does nothing.
256    pub fn truncate(&mut self, modules: u32) {
257        if modules >= self.resident_modules() {
258            return;
259        }
260        self.words
261            .truncate(modules as usize * self.layout.words_per_module() as usize);
262        self.words.shrink_to_fit();
263    }
264
265    /// Drops every module the filter can spare while still meeting
266    /// `target_false_positive_rate`, and returns the new residency.
267    ///
268    /// The rate is taken from the bits actually set, not from an assumed key
269    /// count, so the result holds even for a filter whose layout was sized
270    /// from a bad estimate. Never grows the filter: a target the current
271    /// residency cannot meet leaves it unchanged.
272    pub fn retune(&mut self, target_false_positive_rate: f64) -> u32 {
273        let wanted = self
274            .modules_for(target_false_positive_rate)
275            .min(self.resident_modules());
276        self.truncate(wanted);
277        self.resident_modules()
278    }
279
280    /// Smallest residency that would still meet `target_false_positive_rate`.
281    ///
282    /// Answers the question without changing the filter, so a memory budget can
283    /// cost several filters before committing to any of them.
284    pub fn modules_for(&self, target_false_positive_rate: f64) -> u32 {
285        self.density
286            .modules_for(&self.layout, target_false_positive_rate)
287    }
288
289    /// Fraction of bits set, measured over the resident modules.
290    ///
291    /// Modules are all the same size, so the mean of their fills is exactly the
292    /// set bits over the resident bits. Dividing by the layout's full size
293    /// instead would make a truncated filter under-report its own rate.
294    pub fn fill_ratio(&self) -> f64 {
295        self.density
296            .fill_ratio(&self.layout, self.resident_modules())
297    }
298
299    /// False positive rate at the current residency, from the measured fill.
300    pub fn false_positive_rate(&self) -> f64 {
301        self.false_positive_rate_with(self.resident_modules())
302    }
303
304    /// False positive rate this filter would have with `modules` resident.
305    ///
306    /// Accepts any `modules` up to `layout().total_modules()`, including
307    /// counts above the current residency; the fill of the resident modules
308    /// stands in for the ones not held. Larger values are clamped.
309    pub fn false_positive_rate_with(&self, modules: u32) -> f64 {
310        self.density.false_positive_rate(&self.layout, modules)
311    }
312
313    /// Words of module `index`, or `None` if it is not resident.
314    ///
315    /// This is the handle a caller writes to storage. Modules are independent,
316    /// so they may be written and read individually.
317    pub fn module(&self, index: u32) -> Option<&[u64]> {
318        let per = self.layout.words_per_module() as usize;
319        let start = index as usize * per;
320        self.words.get(start..start + per)
321    }
322
323    /// Words of each resident module, in order.
324    ///
325    /// Allocates a vector of slice references; use [`Self::module`] to reach a
326    /// single module without allocating.
327    pub fn modules(&self) -> Vec<&[u64]> {
328        self.words
329            .chunks(self.layout.words_per_module() as usize)
330            .collect()
331    }
332}
333
334#[cfg(test)]
335mod tests {
336    use super::{
337        BitPositions, ModularBloomFilter, ModularBloomFilterBuilder, ModuleDensity, ModuleLayout,
338    };
339
340    fn sample(i: u64) -> u64 {
341        let mut x = i;
342        x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
343        x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
344        x ^ (x >> 31)
345    }
346
347    /// Probing a prefix of the modules must reproduce exactly the bits that
348    /// insertion wrote for them. One chain serves every module, so a mistake in
349    /// how it is advanced would silently shift a truncated filter's bits and
350    /// turn every stored key into a false negative.
351    #[test]
352    fn a_prefix_walk_reproduces_the_full_walk() {
353        for (modules, hashes) in [(1u32, 1u32), (4, 3), (8, 2), (13, 1), (5, 4)] {
354            let layout = ModuleLayout::new(modules, 64, hashes).unwrap();
355            for i in 0..2_000u64 {
356                let hash = sample(i);
357                let full: Vec<u64> = BitPositions::new(&layout, modules, hash).collect();
358                assert_eq!(full.len(), modules as usize * hashes as usize);
359                for prefix in 0..=modules {
360                    let partial: Vec<u64> = BitPositions::new(&layout, prefix, hash).collect();
361                    assert_eq!(
362                        partial,
363                        full[..prefix as usize * hashes as usize],
364                        "{modules} modules, prefix {prefix}"
365                    );
366                }
367            }
368        }
369    }
370
371    /// Every bit must land inside its own module's region, or truncation would
372    /// drop bits a retained module still depends on.
373    #[test]
374    fn every_bit_lands_in_its_own_module() {
375        let layout = ModuleLayout::new(6, 128, 3).unwrap();
376        let bits = layout.bits_per_module();
377        for i in 0..5_000u64 {
378            let mut seen = 0usize;
379            for bit in BitPositions::new(&layout, 6, sample(i)) {
380                let module = (seen / 3) as u64;
381                assert!(
382                    bit >= module * bits && bit < (module + 1) * bits,
383                    "bit {bit} escaped module {module}"
384                );
385                seen += 1;
386            }
387            assert_eq!(seen, 18);
388        }
389    }
390
391    /// Modules must carry independent load, not merely differ. Correlated
392    /// modules produce no false negatives, so every membership test still passes
393    /// while the filter's accuracy collapses to that of a single module.
394    #[test]
395    fn modules_carry_independent_load() {
396        let keys = 200_000u64;
397        let layout = ModuleLayout::for_keys(keys, 1e-4, 4).unwrap();
398        let mut builder = ModularBloomFilterBuilder::new(layout);
399        for i in 0..keys {
400            builder.insert_hash(sample(i));
401        }
402        let filter = builder.finish();
403
404        let fills: Vec<f64> = (0..4)
405            .map(|m| {
406                ModuleDensity::measure(&layout, filter.module(m).unwrap()).fill_ratio(&layout, 1)
407            })
408            .collect();
409        let mean = fills.iter().sum::<f64>() / 4.0;
410        let spread =
411            fills.iter().cloned().fold(0.0, f64::max) - fills.iter().cloned().fold(1.0, f64::min);
412        let band = 8.0 * (mean * (1.0 - mean) / layout.bits_per_module() as f64).sqrt();
413        assert!(
414            spread <= band,
415            "module fill spans {spread:.5} around {mean:.4}, band {band:.5}: {fills:?}"
416        );
417
418        for a in 0..4u32 {
419            for b in (a + 1)..4u32 {
420                assert_ne!(
421                    filter.module(a).unwrap(),
422                    filter.module(b).unwrap(),
423                    "modules {a} and {b} hold identical bits"
424                );
425            }
426        }
427    }
428
429    /// A recorded density that covers less than the filter holds is discarded,
430    /// and the resident modules are measured instead.
431    ///
432    /// Trusting it would let the filter report a rate no module of it has.
433    #[test]
434    fn a_short_density_is_replaced_by_measurement() {
435        let layout = ModuleLayout::new(4, 64, 3).unwrap();
436        let mut builder = ModularBloomFilterBuilder::new(layout);
437        for i in 0..200u64 {
438            builder.insert_hash(sample(i));
439        }
440        let words: Vec<u64> = builder.finish().modules().concat();
441        let per = layout.words_per_module() as usize;
442        let prefix = &words[..2 * per];
443
444        // One entry for two resident modules, and a false one at that: an empty
445        // module would make the filter claim it rejects everything.
446        let short = ModuleDensity::new(vec![0]);
447        let loaded = ModularBloomFilter::from_modules_with_density(layout, prefix, short).unwrap();
448        let measured = ModularBloomFilter::from_modules(layout, prefix).unwrap();
449
450        assert_eq!(loaded.density(), measured.density());
451        assert_eq!(
452            loaded.false_positive_rate_with(2),
453            measured.false_positive_rate_with(2)
454        );
455        assert!(
456            loaded.false_positive_rate_with(2) > 0.0,
457            "the discarded density claims a rate of zero"
458        );
459    }
460}