Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Solutions · 13. Data streams: reservoir sampling, Bloom filters and count–min sketches

School of Engineering, Nazarbayev University

Worked solutions to the three exercises of Lecture 13. Each solution is computed here and checked with assert statements against an exact identity or an independent calculation. The first code cell sets up the notebook and runs Demonstration 1 of the lecture without showing its output, because some of the solutions use its variables.

Exercise 1

Problem. Verify the Distributed Merge (Semilattice Join) Property of Bloom Filters: given two overlapping edge-sensor packet sets AA (500 IDs) and BB (500 IDs, sharing 200 common IDs so ∣A∪B∣=800|A \cup B| = 800 and ∣A∩B∣=200|A \cap B| = 200), construct bit vectors bA\mathbf{b}_A, bB\mathbf{b}_B, and centralized bA∪B\mathbf{b}_{A \cup B} using identical SHA-256 double hashing (m_bits = 8192, k_hashes = 7). Prove np.array_equal(b_A | b_B, b_AuB) bit-for-bit, and verify that bA∧bB\mathbf{b}_A \land \mathbf{b}_B achieves 0 false negatives on A∩BA \cap B while bounding its false-positive rate relative to bA∩B\mathbf{b}_{A \cap B}.


Exercise 1: Bit-for-bit Bloom filter union homomorphism BF(A u B) == BF(A) | BF(B)
==================================================================================
Bitwise equality BF(A) | BF(B) == BF(A u B) across all 8192 bits: True
Merged Union FPR = 0.400% | Bitwise-AND Intersection FN on A n B = 0
Intersection FPR : Bitwise AND (b_A & b_B) = 0.000% vs. fresh BF(A n B) = 0.0000%
<Figure size 836x429 with 1 Axes>

Figure S13.1. Percentage of bits set in Bloom filters for two nodes, for their OR-merge, for a filter built centrally on the union, and for intersections. The OR-merge and the central filter are identical.

Explanation. Setting bits in a Bloom filter is an idempotent, commutative, associative join ({0,1}m,∨)(\{0, 1\}^m, \lor): inserting xx maps x↦e(x)x \mapsto \mathbf{e}(x) and updates b←b∨e(x)\mathbf{b} \leftarrow \mathbf{b} \lor \mathbf{e}(x). Therefore ⋁x∈A∪Be(x)=(⋁x∈Ae(x))∨(⋁y∈Be(y))\bigvee_{x \in A \cup B} \mathbf{e}(x) = \left(\bigvee_{x \in A} \mathbf{e}(x)\right) \lor \left(\bigvee_{y \in B} \mathbf{e}(y)\right) holds identically without approximation. Intersections are different: bA∧bB\mathbf{b}_A \land \mathbf{b}_B contains BF(A∩B)\mathrm{BF}(A \cap B), so it has no false negatives, but bits set by elements outside the intersection can raise its false-positive rate above that of a freshly built BF(A∩B)\mathrm{BF}(A \cap B). In this example both rates are zero.


Exercise 2

Problem. Diagnose two destructive streaming anti-patterns: (a) Compare Vitter’s vitter_reservoir_sample (N=40N = 40, k=5k = 5) against a naive unscaled replacement loop (reservoir[rng.integers(0, k)] = stream[t] for every t≥kt \ge k) across 4,0004{,}000 runs and verify the exact exponential forgetting formula pibuggy=1k(1−1k)N−1−ip_i^{\mathrm{buggy}} = \frac{1}{k}\left(1 - \frac{1}{k}\right)^{N - 1 - i} for i≥ki \ge k; (b) Sweep Bloom filter bit size mm downward from 8,0008{,}000 to 256 bits (plus excessive k=18k = 18 hashes) for n=800n = 800 items to expose catastrophic 100% bit-array saturation.


Exercise 2: Exponential memory decay in naive reservoir sampling and Bloom filter saturation
============================================================================================
[Part A] Early item i=0 inclusion : Vitter = 0.1275 (exact 0.1250) vs. Naive Bug = 0.00050 (theory 0.00041)
         Final item i=39 inclusion: Vitter = 0.1250 (exact 0.1250) vs. Naive Bug = 1.0000 (exact 1.0000)
[Part B] At m=512 bits, n=800 items, k=18 hashes: bit fill = 100.00%, empirical FPR = 100.00%
<Figure size 1254x451 with 2 Axes>

Figure S13.2. Two failure modes. (a) Inclusion probability of each stream position for Vitter’s algorithm and for a naive overwrite, which forgets early items exponentially. (b) False-positive rate against the filter size for the optimal and a fixed number of hashes; with 18 hashes the filter saturates.

Explanation. (a) Without decaying the acceptance probability as k/(t+1)k/(t+1), a reservoir becomes an exponentially weighted moving window where the very last arrival xN−1x_{N-1} enters with probability 100%100\% while x0x_0 survives with (4/5)35=0.04%(4/5)^{35} = 0.04\%. (b) Hardcoding k=18k = 18 hashes when m=512<n=800m = 512 < n = 800 attempts 14,40014{,}400 bit writes into 512 slots (1−e−14400/512=1−6×10−131 - e^{-14400/512} = 1 - 6\times 10^{-13}), flipping every single bit to 1 so every unseen query falsely reports 'PRESENT'.


Exercise 3

Problem. Implement misra_gries_heavy_hitters(stream, k_counters) in pure Python/NumPy maintaining at most k_counters (item -> count) entries: if item is tracked, increment its counter; else if fewer than k_counters items are tracked, insert item: 1; else decrement all k_counters counters by 1 and purge zeros. Prove and verify on both a 10,000-element Zipfian telemetry stream and a worst-case adversarial stream that every decrement step cancels k+1k + 1 distinct items, guaranteeing fx−Nk+1≤c^x≤fxf_x - \frac{N}{k + 1} \le \hat{c}_x \le f_x and 100% recall of all heavy hitters with fx>Nk+1f_x > \frac{N}{k + 1}.


Exercise 3: Implement it yourself — deterministic O(k) Misra-Gries heavy-hitters summary
========================================================================================
Conservation check: sum(c) + (k+1)*decrements = 10000 == N = 10000
k = 9 active counters retained all 2 heavy hitters (> 1000 occurrences) with max underestimate = 762 <= 1000
<Figure size 825x451 with 1 Axes>

Figure S13.3. Largest underestimate of the Misra–Gries summary against the number of counters kk, below the worst-case bound N/(k+1)N/(k+1) (dashed).

Summary. Notice the contrast between Count-Min Sketch (f^x≥fx\hat{f}_x \ge f_x, randomized upper bound via hashing) and Misra-Gries (c^x≤fx\hat{c}_x \le f_x, deterministic lower bound via (k+1)(k+1)-way cancellation): every decrement step destroys exactly one copy of k+1k + 1 distinct items (sum(counters) + (k+1)*decrements == N), so an item appearing >N/(k+1)> N/(k+1) times cannot be cancelled to zero no matter how adversarially the remaining stream is ordered.