Skip to main content

feldera_modular_bloom/
layout.rs

1use crate::error::LayoutError;
2
3/// The shape of a modular Bloom filter.
4///
5/// This is the metadata a caller persists alongside the module words and hands
6/// back when reloading. It describes the filter as it was built, independently
7/// of how many modules a particular reader chooses to keep resident.
8///
9/// All modules are the same size. Equal sizing is what keeps the ratio of
10/// hashes to bits constant as modules are dropped, and therefore what keeps
11/// every rung of the ladder optimally configured.
12#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
13pub struct ModuleLayout {
14    total_modules: u32,
15    words_per_module: u32,
16    hashes_per_module: u32,
17}
18
19impl ModuleLayout {
20    /// Describes a filter of `total_modules` modules, each `words_per_module`
21    /// 64-bit words wide, with `hashes_per_module` hashes set per key in each.
22    ///
23    /// The filter's effective hash count is `total_modules * hashes_per_module`.
24    pub fn new(
25        total_modules: u32,
26        words_per_module: u32,
27        hashes_per_module: u32,
28    ) -> Result<Self, LayoutError> {
29        if total_modules == 0 {
30            return Err(LayoutError::NoModules);
31        }
32        if hashes_per_module == 0 {
33            return Err(LayoutError::NoHashes);
34        }
35        if words_per_module == 0 {
36            return Err(LayoutError::NoBits);
37        }
38
39        let overflow = || LayoutError::Overflow {
40            modules: total_modules,
41            words_per_module,
42        };
43        total_modules
44            .checked_mul(hashes_per_module)
45            .ok_or_else(overflow)?;
46        let total_words = u64::from(total_modules) * u64::from(words_per_module);
47        // Bit positions are computed in `u64`, and the words are allocated as
48        // one contiguous block.
49        total_words.checked_mul(64).ok_or_else(overflow)?;
50        // On a 32-bit target the word count can exceed `usize`, which is the
51        // filter not fitting in memory rather than a conversion mishap.
52        usize::try_from(total_words)
53            .map_err(|_| overflow())?
54            .checked_mul(8)
55            .ok_or_else(overflow)?;
56
57        Ok(Self {
58            total_modules,
59            words_per_module,
60            hashes_per_module,
61        })
62    }
63
64    /// Chooses a layout that holds `estimated_keys` keys at
65    /// `target_false_positive_rate` when all `modules` modules are resident.
66    ///
67    /// The hash count is rounded to a multiple of `modules` so that dropping a
68    /// module removes a whole number of hashes. Bits are then sized to hit the
69    /// requested rate exactly at that rounded hash count, which costs a fraction
70    /// of a percent of memory against the unrounded optimum.
71    pub fn for_keys(
72        estimated_keys: u64,
73        target_false_positive_rate: f64,
74        modules: u32,
75    ) -> Result<Self, LayoutError> {
76        if !(target_false_positive_rate > 0.0 && target_false_positive_rate < 1.0) {
77            return Err(LayoutError::InvalidFalsePositiveRate {
78                rate: target_false_positive_rate,
79            });
80        }
81        if modules == 0 {
82            return Err(LayoutError::NoModules);
83        }
84
85        // Optimal hashes for the target rate is -log2(fp). Round to a whole
86        // number per module, never below one, so a dropped module always sheds
87        // hashes as well as bits.
88        let ideal_hashes = -target_false_positive_rate.log2();
89        let hashes_per_module = (ideal_hashes / f64::from(modules)).round().max(1.0);
90        let hashes_per_module = hashes_per_module.min(f64::from(u32::MAX)) as u32;
91        let sizing_overflow = || LayoutError::SizingOverflow {
92            estimated_keys,
93            target_false_positive_rate,
94            modules,
95        };
96        let total_hashes = modules
97            .checked_mul(hashes_per_module)
98            .ok_or_else(sizing_overflow)?;
99
100        // Solve for bits per key based on the rounded hash count, so the requested rate is met
101        // exactly despite the rounding.
102        //
103        // 1. fp = fill^total_hashes
104        // 2. fill = 1 - e^(-total_hashes/bits_per_key)
105        //
106        // =>
107        //
108        // fill = fp^(1/total_hashes)
109        // bits_per_key = -total_hashes / ln(1.0-fill)
110        let fill = target_false_positive_rate.powf(1.0 / f64::from(total_hashes));
111        let bits_per_key = -f64::from(total_hashes) / (1.0 - fill).ln();
112
113        let total_bits = (estimated_keys as f64 * bits_per_key).ceil();
114        if !total_bits.is_finite() {
115            return Err(sizing_overflow());
116        }
117
118        // Round the module up, never down: a module short of its computed size
119        // silently misses the target rate.
120        let total_words = (total_bits / 64.0).ceil().max(0.0);
121        let words_per_module = (total_words / f64::from(modules)).ceil().max(1.0);
122        if words_per_module > f64::from(u32::MAX) {
123            return Err(sizing_overflow());
124        }
125
126        Self::new(modules, words_per_module as u32, hashes_per_module)
127    }
128
129    /// Describes a monolithic `fastbloom` filter of `words` words using
130    /// `num_hashes` hashes as a one-module filter.
131    pub fn monolithic(num_hashes: u32, words: usize) -> Result<Self, LayoutError> {
132        let words = u32::try_from(words).map_err(|_| LayoutError::Overflow {
133            modules: 1,
134            words_per_module: u32::MAX,
135        })?;
136        Self::new(1, words, num_hashes)
137    }
138
139    /// Returns the same layout with `modules` modules.
140    ///
141    /// Useful for costing a hypothetical residency without holding the bits.
142    pub fn with_modules(&self, modules: u32) -> Result<Self, LayoutError> {
143        Self::new(modules, self.words_per_module, self.hashes_per_module)
144    }
145
146    /// Modules the filter was built with.
147    pub fn total_modules(&self) -> u32 {
148        self.total_modules
149    }
150
151    /// 64-bit words each module occupies.
152    pub fn words_per_module(&self) -> u32 {
153        self.words_per_module
154    }
155
156    /// Hashes set per key within each module.
157    pub fn hashes_per_module(&self) -> u32 {
158        self.hashes_per_module
159    }
160
161    /// Bits each module occupies.
162    pub fn bits_per_module(&self) -> u64 {
163        u64::from(self.words_per_module) * 64
164    }
165
166    /// Bytes each module occupies.
167    pub fn bytes_per_module(&self) -> usize {
168        self.words_per_module as usize * 8
169    }
170
171    /// Words the complete filter occupies.
172    pub fn total_words(&self) -> u64 {
173        u64::from(self.total_modules) * u64::from(self.words_per_module)
174    }
175
176    /// Bytes the complete filter occupies.
177    pub fn total_bytes(&self) -> usize {
178        self.total_words() as usize * 8
179    }
180
181    /// Hashes set per key across the complete filter.
182    pub fn total_hashes(&self) -> u32 {
183        self.total_modules * self.hashes_per_module
184    }
185
186    /// Bits per key the complete filter spends on `keys` keys.
187    pub fn bits_per_key(&self, keys: u64) -> f64 {
188        if keys == 0 {
189            return f64::INFINITY;
190        }
191        (self.total_words() * 64) as f64 / keys as f64
192    }
193}