Skip to content

The corpus pipeline in Data Engineering must drop exact duplicate paragraphs from millions of documents. A Python set of paragraph hashes costs 8 bytes of hash plus about 60 bytes of overhead per entry. A Bloom filter answers “have I seen this?” in about 10 bits per paragraph, with no false negatives and a false-positive rate you choose. The dedup stage in Exact dedup: paragraph hashes, a Bloom screen, and a sort-merge confirm then confirms every “seen” answer exactly with a sort-merge on the full hashes, so a false positive costs time, never data.

Concepts from other sections (4)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

  • Block hash: a hash over token ids chained with the parent hash, independent of the payload format. Read more: 12.5 The KV format v2 migration in Systems Engineering
  • Bijection: a function that is both injective and surjective, and so has an inverse. Read more: 11.3.4 Relations, functions, and validation in Mathematics
  • Standard deviation: Var⁡(X)\sqrt{\operatorname{Var}(X)}, the typical distance of a random variable from its mean, in the same units as the variable itself. Read more: Chapter 13: Probability and Statistics in Mathematics
  • Counting Bloom filter: a Bloom filter whose bits are replaced by small counters, so an element can be deleted by decrementing its counters; it supports deletion at the cost of several times the space. Read more: Chapter 14: Probabilistic data structures

This section derives the sizing formulas and the double-hashing scheme from first principles, works a 20-bit filter by hand down to its 35 serialized bytes, and then builds the filter in Rust. The serialized format matters as much as the filter. Languages in this system meet only over processes and files, and the one Bloom filter on the serving path, the dedup screen, is written in Python. No other code calls this Rust filter; what the two share is the byte layout fixed by formats/bloom.md. This section is optional and stands on its own.

The math comes from Mathematics: the false-positive rate and the optimal kk, and FNV-1a and the SplitMix finalizer. The solution is bloom.rs, and the independent Python screen is _Bloom in python/corpus/dedup.py.

Learning objectives

  • Explain why a Bloom filter has no false negatives and derive its false-positive rate (1−e−kn/m)k(1 - e^{-kn/m})^k.
  • Size a filter for nn items at rate pp with m=⌈−nln⁡p/(ln⁡2)2⌉m = \lceil -n \ln p / (\ln 2)^2 \rceil and k=round(mnln⁡2)k = \mathrm{round}(\frac{m}{n} \ln 2).
  • Generate kk probes from two hashes by double hashing, and explain why h2h_2 is forced odd.
  • Merge filters by OR and serialize them to a fixed, portable byte layout.
  • Validate untrusted bytes before using them.

The notation for this section:

SymbolMeaningType
nnitems inserted (or expected)u64
mmbits in the filteru64, 1≤m≤2401 \le m \le 2^{40}
kkhash functions (bits per item)u32, k≥1k \ge 1
pptarget false-positive ratereal in (0,1)(0, 1)
xxan item: a byte string&[u8]
g0,…,gk−1g_0, \dots, g_{k-1}the bit positions of xxu64 in [0,m)[0, m)
ffthe fraction of bits setreal in [0,1][0, 1]

Insert sets bits g0(x),…,gk−1(x)g_0(x), \dots, g_{k-1}(x); contains answers yes when all kk are set. An inserted item’s bits stay set forever, because nothing clears bits, so there are no false negatives. A non-member is reported present only if all kk of its bits were set by other items.

How often does that happen? Model each of the knkn bit choices as uniform and independent. One bit stays 0 after all of them with probability (1−1/m)kn≈e−kn/m(1 - 1/m)^{kn} \approx e^{-kn/m}, so the fraction of set bits is about f=1−e−kn/mf = 1 - e^{-kn/m}, and a fresh item’s kk probes all hit set bits with probability

q(k)=fk≈(1−e−kn/m)k.q(k) = f^k \approx \left(1 - e^{-kn/m}\right)^k.

More hash functions mean more checks per query but more bits set. Minimizing ln⁡q=kln⁡(1−e−kn/m)\ln q = k \ln(1 - e^{-kn/m}) over kk gives k∗=mnln⁡2k^\ast = \frac{m}{n}\ln 2, where exactly half the bits are set, and q=2−k∗q = 2^{-k^\ast}. Solving p=2−mnln⁡2p = 2^{-\frac{m}{n}\ln 2} for mm:

m=⌈−nln⁡p(ln⁡2)2⌉,k=max⁡(1,round(mnln⁡2)),m = \left\lceil \frac{-n \ln p}{(\ln 2)^2} \right\rceil, \qquad k = \max\left(1, \mathrm{round}\left(\tfrac{m}{n} \ln 2\right)\right),

rounding half away from zero. That is about 1.44log⁡2(1/p)1.44 \log_2(1/p) bits per item: 9.6 bits at 1%, 14.4 at 0.1%. For example, 4 items at 10% need 20 bits and 3 hashes.

Computing kk independent hashes per item is slow. Kirsch and Mitzenmacher showed that gi=h1+i⋅h2g_i = h_1 + i \cdot h_2 (mod mm) loses nothing asymptotically. The format fixes:

h1=fnv1a64(x),h2=mix64(h1)∨1,gi=((h1+i h2) mod 264) mod m.h_1 = \text{fnv1a64}(x), \qquad h_2 = \text{mix64}(h_1) \lor 1, \qquad g_i = \big((h_1 + i\,h_2) \bmod 2^{64}\big) \bmod m.

FNV-1a 64 is the same hash as the KV block hash of formats/kv-block.md. Start from the offset basis 0xcbf29ce484222325; for each byte, XOR it in, then multiply by the prime 0x100000001b3 (mod 2642^{64}). Multiplying first and XORing after is FNV-1, a different hash. mix64 is the SplitMix64 finalizer, a bijection that spreads every input bit over every output bit. Forcing h2h_2 odd keeps the kk probes distinct when mm is a power of two. Bit gg lives in byte ⌊g/8⌋\lfloor g/8 \rfloor at bit position g mod 8g \bmod 8, least significant bit first.

The approximation above assumes independent bits. Given an actual filter, the exact probability that a random fresh item is a false positive is fkf^k with ff the measured fraction of set bits, because each probe lands on a uniform bit. Over NN fresh items the count of false positives is then Binomial(N,fk)(N, f^k), with mean NfkN f^k and standard deviation Nfk(1−fk)\sqrt{N f^k (1 - f^k)}. A statistical test can ask the count to lie within 3 standard deviations, which a correct filter fails about 0.3% of the time.

Two filters with the same mm and kk (and so the same hash positions) merge by bitwise OR: the result has exactly the bits that inserting both sets would set. n_inserted counts insert calls, and a union adds the counts.

to_bytes writes the 32-byte little-endian header (magic TLBF, version 1, mm, kk, a reserved zero, n_inserted) and then the ⌈m/8⌉\lceil m/8 \rceil bytes of bits; from_bytes rejects anything else. Every implementation of the format produces the same 35 bytes for the worked example below.

The Python pipeline’s _Bloom in python/corpus/dedup.py is a separate implementation with the same sizing and probes; it keeps the bits in memory and does not serialize. For the same items, both set the same bits.

Call with_rate(4, 0.1). Then −4ln⁡0.1/(ln⁡2)2=9.2103/0.48045=19.17-4 \ln 0.1 / (\ln 2)^2 = 9.2103 / 0.48045 = 19.17, so m=20m = 20; 204ln⁡2=3.466\frac{20}{4} \ln 2 = 3.466, so k=3k = 3. The bit array is ⌈20/8⌉=3\lceil 20/8 \rceil = 3 bytes.

Insert cat: h1=fnv1a64(cat)=f5e307190ce4a327h_1 = \text{fnv1a64}(\texttt{cat}) = \texttt{f5e307190ce4a327} and h2=mix64(h1)∨1=abc55d317f9d6793h_2 = \text{mix64}(h_1) \lor 1 = \texttt{abc55d317f9d6793}, which give g=11,14,17g = 11, 14, 17 (the format page lists every item’s positions). dog gives 13,0,313, 0, 3. After inserting both, the set bits are 0 and 3 (byte 0: 20+23=092^0 + 2^3 = \texttt{09}), 11, 13, 14 (byte 1: bits 3, 5, 6 of that byte, 8+32+64=688 + 32 + 64 = \texttt{68}), and 17 (byte 2: bit 1, 02\texttt{02}): 09 68 02.

Query bird: it probes 14,7,1614, 7, 16. Bit 7 is clear, so contains(b"bird") is false. Six of 20 bits are set, f=0.3f = 0.3, and a fresh item’s chance of a false positive is 0.33=2.7%0.3^3 = 2.7\%.

to_bytes is the 35 bytes

54 4c 42 46 01 00 00 00 14 00 00 00 00 00 00 00 "TLBF", version 1, m = 20
03 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 k = 3, reserved 0, n_inserted = 2
09 68 02 the bits
// rust/crates/tl-ds/src/bloom.rs (formats/bloom.md)
pub const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325; pub const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
pub const MAGIC: [u8; 4] = *b"TLBF"; pub const VERSION: u32 = 1; pub const HEADER_LEN: usize = 32;
pub const MAX_BITS: u64 = 1 << 40;
pub enum BloomError { BadParams(String), Mismatch(String), Format(String) } // Display + Error
pub fn fnv1a64(bytes: &[u8]) -> u64;
pub fn mix64(z: u64) -> u64;
pub fn optimal_m(n: u64, p: f64) -> u64;
pub fn optimal_k(m: u64, n: u64) -> u32;
pub fn predicted_fp_rate(m: u64, k: u32, n: u64) -> f64;
#[derive(Clone, Debug, PartialEq, Eq)] pub struct Bloom { /* m, k, n_inserted, bits */ }
impl Bloom {
pub fn with_rate(n: u64, p: f64) -> Result<Bloom, BloomError>; // BadParams unless n >= 1, 0 < p < 1
pub fn new(m: u64, k: u32) -> Result<Bloom, BloomError>; // 1 <= m <= 2^40, k >= 1
pub fn m(&self) -> u64; pub fn k(&self) -> u32; pub fn n_inserted(&self) -> u64;
pub fn bit_positions(&self, item: &[u8]) -> Vec<u64>;
pub fn insert(&mut self, item: &[u8]); pub fn contains(&self, item: &[u8]) -> bool;
pub fn union(&mut self, other: &Bloom) -> Result<(), BloomError>; // Mismatch when m or k differ
pub fn count_ones(&self) -> u64;
pub fn to_bytes(&self) -> Vec<u8>; pub fn from_bytes(b: &[u8]) -> Result<Bloom, BloomError>;
}

Read the solution in this order: hashing and sizing first, then the bit array, then bytes. Seven observations shape it.

  1. “Have I seen this?” with no false negatives means a set bit can never be cleared: the structure only ever ORs bits in. A miss is certain; a hit is probabilistic.
  2. The false-positive rate is fkf^k, the chance that kk independent probes all land on set bits. Minimizing it for a given m/nm/n gives k=mnln⁡2k = \frac{m}{n}\ln 2 (half the bits set), and inverting gives m=⌈−nln⁡p/(ln⁡2)2⌉m = \lceil -n \ln p / (\ln 2)^2 \rceil. The ceiling matters: flooring makes the filter short of its target. For the worked example, 19.17 becomes 20 bits and 3.466 becomes 3 hashes.
  3. kk hashes per item are expensive; two are enough. gi=h1+i h2g_i = h_1 + i\,h_2 gives kk probes from two hashes. h2h_2 must be odd so that, when mm is a power of two, the kk probes are distinct (an odd step generates every residue).
  4. h2h_2 must not be a simple function of h1h_1‘s low bits, or the two probes correlate. Running h1h_1 through the SplitMix64 finalizer, a bijection that mixes every bit, makes h2h_2 look independent at the cost of a few multiplies.
  5. Filters built in different processes and languages must be interchangeable, so everything that decides a bit is fixed by the format: FNV-1a (xor, then multiply), mix64, the wrap-around arithmetic mod 2642^{64} before mod mm, and LSB-first bit numbering. The header records mm, kk, and the count so a filter can be validated and merged.
  6. Two filters with the same mm and kk probe the same positions for every item, so OR is exactly the filter of the union of the sets; different mm or kk have no meaningful union and must be refused.
  7. Bytes from a file are untrusted. from_bytes checks every header field and that the length is exactly 32+⌈m/8⌉32 + \lceil m/8 \rceil; otherwise a later contains could index past the bit array.

Each line is one formula from the derivation; the casts and wrapping_mul make the arithmetic mod 2642^{64} explicit, which is what other implementations must reproduce.

/// FNV-1a 64 over `bytes`: for each byte, xor it in, then multiply.
pub fn fnv1a64(bytes: &[u8]) -> u64 {
let mut h = FNV_OFFSET;
for &b in bytes {
h ^= b as u64; // xor FIRST: this is what makes it FNV-1a, not FNV-1
h = h.wrapping_mul(FNV_PRIME);
}
h
}
/// The SplitMix64 finalizer: a bijection on u64 that mixes every bit.
pub fn mix64(z: u64) -> u64 {
let z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
let z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
/// ceil(-n ln p / (ln 2)^2): round UP, or the filter misses its target rate.
pub fn optimal_m(n: u64, p: f64) -> u64 {
let ln2 = std::f64::consts::LN_2;
(-(n as f64) * p.ln() / (ln2 * ln2)).ceil() as u64
}
/// max(1, round(m / n * ln 2)); f64::round rounds half away from zero.
pub fn optimal_k(m: u64, n: u64) -> u32 {
let k = (m as f64 / n as f64 * std::f64::consts::LN_2).round(); // round, not truncate: 6.64 -> 7
if k < 1.0 { 1 } else { k as u32 }
}

Construction validates before allocating. !(p > 0.0 && p < 1.0) is written that way so that NaN, for which every comparison is false, is rejected too.

pub fn with_rate(n: u64, p: f64) -> Result<Bloom, BloomError> {
if n < 1 {
return Err(BloomError::BadParams(format!("n must be >= 1, got {n}")));
}
if !(p > 0.0 && p < 1.0) { // also catches NaN
return Err(BloomError::BadParams(format!("p must be in (0, 1), got {p}")));
}
let m = optimal_m(n, p);
Bloom::new(m, optimal_k(m, n)) // new() enforces 1 <= m <= 2^40, k >= 1
}
pub fn new(m: u64, k: u32) -> Result<Bloom, BloomError> {
if m == 0 || k == 0 { /* ... */ }
if m > MAX_BITS { /* ... */ } // refuse a 128 GiB+ allocation from a bad config
Ok(Bloom { m, k, n_inserted: 0, bits: vec![0; m.div_ceil(8) as usize] })
}

bit_positions is the single definition of where an item’s bits are; insert and contains both use it, so they cannot disagree.

/// g_i = (h1 + i * h2) mod 2^64 mod m, h1 = fnv1a64(item), h2 = mix64(h1) | 1.
pub fn bit_positions(&self, item: &[u8]) -> Vec<u64> {
let h1 = fnv1a64(item);
let h2 = mix64(h1) | 1; // odd: distinct probes when m is a power of two
(0..self.k as u64).map(|i| h1.wrapping_add(i.wrapping_mul(h2)) % self.m).collect()
}
pub fn insert(&mut self, item: &[u8]) {
for g in self.bit_positions(item) {
self.bits[(g / 8) as usize] |= 1 << (g % 8); // byte g/8, bit g%8 from the LSB
}
self.n_inserted += 1;
}
pub fn contains(&self, item: &[u8]) -> bool {
self.bit_positions(item)
.into_iter()
.all(|g| self.bits[(g / 8) as usize] & (1 << (g % 8)) != 0) // every probe must be set
}
pub fn union(&mut self, other: &Bloom) -> Result<(), BloomError> {
if self.m != other.m || self.k != other.k {
return Err(BloomError::Mismatch(/* ... */)); // different probes: no meaningful union
}
for (a, b) in self.bits.iter_mut().zip(&other.bits) {
*a |= *b; // OR: a member of either set stays present
}
self.n_inserted += other.n_inserted;
Ok(())
}

The header is written field by field in little-endian, so the layout does not depend on struct padding or host byte order. from_bytes checks in the order that makes each read safe: length before any field, then magic, then the rest.

pub fn to_bytes(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(HEADER_LEN + self.bits.len());
out.extend_from_slice(&MAGIC); // "TLBF"
out.extend_from_slice(&VERSION.to_le_bytes()); // u32
out.extend_from_slice(&self.m.to_le_bytes()); // u64
out.extend_from_slice(&self.k.to_le_bytes()); // u32
out.extend_from_slice(&0u32.to_le_bytes()); // reserved
out.extend_from_slice(&self.n_inserted.to_le_bytes()); // u64: 32 bytes so far
out.extend_from_slice(&self.bits);
out
}
pub fn from_bytes(b: &[u8]) -> Result<Bloom, BloomError> {
let fail = |why: String| Err(BloomError::Format(why));
if b.len() < HEADER_LEN { return fail(/* ... */); } // before reading any field
if b[0..4] != MAGIC { return fail(/* ... */); }
// ... read version, m, k, reserved, n (little-endian) ...
if version != VERSION { return fail(/* ... */); }
if m == 0 || k == 0 { return fail(/* ... */); }
if m > MAX_BITS { return fail(/* ... */); }
if reserved != 0 { return fail(/* ... */); }
let want = HEADER_LEN as u64 + m.div_ceil(8);
if b.len() as u64 != want { return fail(/* ... */); } // exact: never trust m alone
Ok(Bloom { m, k, n_inserted: n, bits: b[HEADER_LEN..].to_vec() })
}

The full solution is bloom.rs.

insert and contains are O(k+∣x∣)O(k + |x|): one pass of FNV over the item, one mix64, and kk bit operations. Space is mm bits, about 1.44log⁡2(1/p)1.44 \log_2(1/p) per item; union is O(m/8)O(m/8).

Against the alternatives: a hash set of paragraph hashes is exact and simple, but costs about 68 bytes per entry in Python against about 1.2 bytes per entry for a 1% filter. Because dedup confirms every positive exactly anyway, a filter’s false positives cost a little time and never correctness. kk independent hash functions give the same false-positive rate asymptotically, at kk times the hashing work, and with kk algorithms every other implementation must reproduce bit for bit. Counting Bloom filters and cuckoo filters support deletion, which dedup never needs; a counting filter costs 4 or more times the space. As for storage, Vec<bool> is 8 times larger, and a u64 word array is equally compact in memory but makes the on-disk layout depend on word order; bytes with LSB-first bits are the layout the format fixes.

Two tradeoffs are accepted. bit_positions allocates a small Vec per call, which is simple and testable; a hot loop could iterate instead. And the filter has fixed capacity: inserting far more than nn items raises the rate as (1−e−kn/m)k(1 - e^{-kn/m})^k, and the header’s n_inserted lets a reader see that it happened.

A correct filter handles these cases:

CaseKind of checkChecksWhy it matters downstream
The hand example’s sizing and bitsunitm=20m = 20, k=3k = 3, the positions of cat, dog, bird, the 35 bytesthe code, the format page, and the worked example agree
Hash function values by handgoldenFNV-1a of "", “a”, “cat”; mix64 of 0 and 1every implementation sets the same bits
Sizing formulasunitmm and kk for five (n,p)(n, p), including the rounding of kk; byte lengththe screen is as small as the target allows
Bad parameters are errorsboundaryn=0n = 0, p∉(0,1)p \notin (0, 1), NaN, k=0k = 0, m>240m > 2^{40} are BadParamsa bad config fails at start, not with a 128 GiB allocation
No false negativesproperty5,000 random items found in their filter, after a byte round trip, and in the uniondedup never keeps a duplicate it has seen
The false-positive rate is within three sigmastatistical100,000 fresh items: false positives within 3 sd of NfkN f^k, and below 2% at a 1% designthe filter is as good as its sizing promises
Union is the filter of both setsunitOR of two filters equals the filter of both; counts add; mismatched mm or kk refusedthe dedup stage merges per-shard screens
Golden bytes match the formatgolden10 reference cases (empty items, odd mm, p=10−6p = 10^{-6}): bytes and probe answersevery implementation of the format writes the same bytes
from_bytes rejects malformed inputboundarybad magic, version, m=0m = 0, k=0k = 0, reserved, short, long, inconsistent lengtha corrupt file is refused, not misread

A model property-test suite (proptest with a fixed seed and no failure files: the worked example bytes, the sizing table, “every inserted item is present”, “bytes round-trip”, “union equals one filter of both sets”, a mismatched union, and malformed bytes) is in ds08_bloom.rs.

The pitfalls, many of which make the bytes disagree with every other implementation:

PitfallSymptomHow the solution avoids it
Flooring mm instead of taking the ceilingthe filter is a bit short: the rate misses its target and bytes differ from every other implementationoptimal_m uses .ceil()
Using mix64(h1) without forcing it oddprobes coincide when mm is a power of two; bits differ from the formatbit_positions uses mix64(h1) | 1
Numbering bits from the most significant endbytes read back wrong in every other implementationbit g is 1 << (g % 8) in byte g / 8
Truncating kk instead of rounding6.64 becomes 6 hashes; more false positivesoptimal_k uses .round()
Forgetting to add the counts in unionthe header’s n_inserted is wrong after a mergeunion adds other.n_inserted
Setting fewer than kk bits on insertfalse negatives: duplicates slip through dedupinsert sets every position bit_positions returns
Dropping the i⋅h2i \cdot h_2 termall kk probes hit one bit: the rate is ff, not fkf^keach probe is h1 + i * h2
AND instead of OR in unionthe union forgets members of both setsunion ORs the bit arrays
Trusting the length in from_bytesa truncated file loads and later panics on an out-of-range bitfrom_bytes requires the exact length
FNV-1 (multiply, then XOR) instead of FNV-1aevery position differs from the format and from kv-block.md hashesfnv1a64 xors before it multiplies

Nothing calls this filter: the dedup stage in Exact dedup never calls Rust. Its Python exact_dedup sizes its own screen at about 10 bits per paragraph with these formulas, inserts each paragraph hash, and confirms every positive exactly; for the same items both screens set the same bits. Read that section with this one in mind.

Production systems take the same idea in several directions:

  • datatrove exact dedup uses sharded hashing with sort-merge and no filter at all, trading disk for certainty (src/datatrove/pipeline/dedup/exact_substrings.py, sentence_dedup.py).
  • RedisBloom offers scalable filters that add layers as nn grows past the design (src/sb.c).
  • Cuckoo filters and xor filters support deletion and use about 20% fewer bits at low false-positive rates (Fan et al., 2014; Graf and Lemire, 2020).
  • Parquet and ORC store split-block Bloom filters per column chunk, read before a scan (the Apache Parquet BloomFilter.md spec).
  • Bloom filter: an mm-bit array with kk hash probes per item, answering membership with no false negatives.
  • False positive: a non-member whose kk probes all land on bits set by other items.
  • Double hashing: generating probes gi=h1+i h2g_i = h_1 + i\,h_2 from two hashes.
  • FNV-1a: a byte-at-a-time hash that XORs each byte in and then multiplies by a prime.
  • SplitMix64 finalizer (mix64): a bijection on 64-bit words that mixes every input bit into every output bit.
  • Union: the bitwise OR of two filters with the same mm and kk.
  • A Bloom filter is mm bits and kk hash functions: insert sets kk bits, contains checks them, so a member is never missed and a non-member is reported present with probability about (1−e−kn/m)k(1 - e^{-kn/m})^k.
  • For nn items at rate pp, m=⌈−nln⁡p/(ln⁡2)2⌉m = \lceil -n \ln p / (\ln 2)^2 \rceil bits and k=round(mnln⁡2)k = \mathrm{round}(\frac{m}{n} \ln 2) hashes: 4 items at 10% need 20 bits and 3 hashes.
  • Two hashes are enough: gi=h1+i h2 mod mg_i = h_1 + i\,h_2 \bmod m (double hashing) with h1h_1 = FNV-1a 64 and h2h_2 = the SplitMix finalizer of h1h_1, forced odd.
  • Union is bitwise OR of two filters with the same mm and kk, which is exactly the filter of both sets.
  • A fixed byte layout makes the filter portable: every implementation of the format produces the same 35 bytes for the worked example.
  1. Why is h2h_2 forced odd?
    AnswerWhen $m$ is a power of two, the probes $h_1 + i\,h_2 \bmod m$ cycle with period $m / \gcd(h_2, m)$. An even $h_2$ shares a factor of 2 with $m$, so probes can repeat within $k$ steps (in the extreme $h_2 \equiv 0$, all $k$ probes hit one bit and the rate is $f$, not $f^k$). An odd $h_2$ is coprime to $m$, so the $k$ probes are distinct.
  2. Why can a Bloom filter never give a false negative, and what single change to the code would break that?
    Answer`insert` sets exactly the bits `contains` checks (both call `bit_positions`), and nothing ever clears a bit. Any change that makes the two disagree breaks it: setting fewer than $k$ bits in `insert`, or AND instead of OR in `union` (which clears bits set by only one side).
  3. Why does optimal_m take the ceiling and optimal_k round?
    Answer$m$ is a resource: fewer bits than $-n \ln p / (\ln 2)^2$ means the rate exceeds the target, so it must round up. $k$ is an optimum of a smooth function, so the nearest integer is best; truncation (6.64 to 6) lands further from the optimum and raises the rate. Both choices are also fixed by the format so every implementation builds the same filter.
  4. Why does from_bytes require the length to equal 32+⌈m/8⌉32 + \lceil m/8 \rceil exactly, rather than at least that?
    AnswerShorter would leave `bits` too small, and a probe near $m$ would index past it and panic later, far from the cause. Longer means the file is not what its header says (wrong $m$, a concatenation, corruption); accepting it would misread data silently. Exact equality refuses both at load time.
  5. In the worked example, why is the false-positive chance of a fresh item 2.7%2.7\% rather than the designed 10%10\%?
    AnswerThe filter was sized for 4 items but holds only 2, so only 6 of 20 bits are set: $f = 0.3$ and $f^3 = 0.027$. The design rate is reached when the filter holds its full $n$.