Sub topic 9
Common Bugs: Off-by-One Ranges, Modulo Bias, and Seeding
This chapter assumes you know Algorithm R from earlier in the tutorial and the frequency test from the previous chapter. You should also be comfortable with Python's random module. Algorithm R is only a few lines long, but small mistakes in those lines produce samples that look random and are still biased. A reservoir that is off by a few percent will not crash and will not raise an exception. It quietly skews every estimate computed from it. The three most common sources of this bias are the range of the random index, the way a raw random number is reduced to that range, and how the generator is seeded.
Where the bugs enter
Each item past the first k goes through the same decision. A bug at any step changes the probability that the item is kept.
Off-by-one ranges
The inclusive-versus-exclusive trap
The correct rule is that the item at 0-based index i is kept with probability k/(i+1). That requires j to be uniform over the i+1 values 0, 1, ..., i. Python has two functions that are easy to mix up:
| Call | Values produced | Count of values |
|---|---|---|
| `rng.randint(0, i)` | 0 to i, inclusive | i + 1 |
| `rng.randrange(i + 1)` | 0 to i | i + 1 |
| `rng.randrange(i)` | 0 to i − 1 | i |
| `rng.randint(0, i - 1)` | 0 to i − 1 | i |
Other libraries use different conventions. NumPy's Generator.integers(low, high) excludes high by default. Java's nextInt(bound) excludes bound. When you port Algorithm R between languages, check the bounds again. Do not copy the arithmetic as written.
Measuring the damage
The buggy version below draws j from 0 to i − 1. It keeps item i with probability k/i instead of k/(i+1).
import random
from collections import Counter
def reservoir_buggy(stream, k, rng):
reservoir = []
for i, item in enumerate(stream):
if i < k:
reservoir.append(item)
else:
j = rng.randint(0, i - 1) # BUG: never produces i
if j < k:
reservoir[j] = item
return reservoir
def reservoir_fixed(stream, k, rng):
reservoir = []
for i, item in enumerate(stream):
if i < k:
reservoir.append(item)
else:
j = rng.randint(0, i) # correct: 0..i inclusive
if j < k:
reservoir[j] = item
return reservoir
def frequencies(sampler, n=10, k=3, trials=100_000, seed=1):
rng = random.Random(seed)
counts = Counter()
for _ in range(trials):
counts.update(sampler(range(n), k, rng))
return [round(counts[x] / trials, 3) for x in range(n)]
print("buggy:", frequencies(reservoir_buggy))
print("fixed:", frequencies(reservoir_fixed))The fixed sampler prints values near 0.3 for every item. The buggy one prints about 0.222 for items 0 to 2 and about 0.333 for items 3 to 9. You can derive these numbers. At i = k the buggy rule keeps the item with probability k/k = 1, so item k always evicts one of the first k items. From then on, any item kept at step i survives each later step m with probability 1 − 1/m, and the product telescopes:
- Items k through n−1: (k/i) · (i/(n−1)) = k/(n−1) = 3/9 ≈ 0.333.
- Items 0 through k−1: they survive steps k to n−1, giving (k−1)/(n−1) = 2/9 ≈ 0.222.
The expected sample size is still exactly k (3 · 2/9 + 7 · 3/9 = 3), so a check on reservoir size alone cannot catch this bug. Only a per-item frequency test will.
Related off-by-one mistakes
- Fill condition
i <= k. This appends k + 1 items, so the reservoir is too large. A length assertion catches it. - Mixed indexing. If you write
enumerate(stream, start=1), i becomes the count of items seen so far. The keep probability is then k/i, which needsrandint(1, i)with the testj <= k, orrandrange(i)withj < k. If you shift only one of the bounds, you get the k/i or k/(i+2) family of errors. - Equivalent alternatives that are correct. Writing
if rng.random() < k / (i + 1): reservoir[rng.randrange(k)] = itemgives the right distribution. The decision to keep and the choice of slot are independent, and each is uniform. It costs two random calls per kept item instead of one.
Modulo bias
How it happens
Suppose a generator produces integers uniformly in [0, M). The obvious way to get a value in [0, n) is r % n. If n does not divide M, some residues occur once more often than others. With M = 8 and n = 3, the raw values 0 to 7 map to 0, 1, 2, 0, 1, 2, 0, 1. Residues 0 and 1 each get 3 of the 8 raw values, and residue 2 gets only 2.
In reservoir sampling this bias always points the same way. The residues that get the extra weight are the smallest ones, and the accept region j < k is made of the smallest residues. So modulo bias always raises the keep probability.
import random
rng = random.Random(7)
n = 200
trials = 1_000_000
# 8-bit raw values: 256 outcomes, so residues 0..55 occur twice, 56..199 once
low = sum(1 for _ in range(trials) if rng.getrandbits(8) % n < 56)
print(low / trials) # about 0.4375 (112/256), not 56/200 = 0.28When the raw range is too small
The worst case is when n is larger than M. C's rand() can have RAND_MAX equal to 32767 on some platforms. Then rand() % (i + 1) can never be 32768 or more. Once the stream passes 32,768 items, j < k holds with a fixed probability k/32768 instead of k/(i+1). At i = 1,000,000 that keeps items about 30 times more often than it should. The final reservoir then fills almost entirely with items from the end of the stream.
The fix: rejection sampling
Draw just enough bits to cover n, and throw away results that fall outside the range. CPython's randrange and randint already work this way, so they are unbiased.
import random
def randbelow(n, rng):
"""Uniform integer in [0, n) without modulo bias."""
bits = n.bit_length()
while True:
r = rng.getrandbits(bits)
if r < n:
return r
rng = random.Random(3)
print([randbelow(7, rng) for _ in range(10)])Because 2^bits < 2n, each attempt succeeds with probability greater than 1/2, so the loop runs fewer than 2 times on average.
Seeding
Same seed, same choices
A seeded generator is deterministic. In Algorithm R the random calls depend only on the position i, not on the item values. So two partitions of equal length that use the same seed choose the same positions.
import random
def reservoir_sample(stream, k, rng):
reservoir = []
for i, item in enumerate(stream):
if i < k:
reservoir.append(item)
else:
j = rng.randint(0, i)
if j < k:
reservoir[j] = item
return reservoir
partitions = [range(0, 1000), range(1000, 2000)]
# BUG: every worker builds its generator from the same seed
bad = [sorted(reservoir_sample(p, 3, random.Random(42))) for p in partitions]
print(bad) # second list is the first plus 1000
# FIX: derive an independent seed per worker from one root generator
root = random.Random(2026)
good = [sorted(reservoir_sample(p, 3, random.Random(root.getrandbits(64))))
for p in partitions]
print(good)This bug also happens without an explicit constant. A seed taken from time.time() rounded to seconds is shared by every worker that starts in the same second. Forked processes inherit the parent's generator state unless they reseed. When the partition samples are merged, as in the merging chapter later, the correlation means the combined sample is no longer uniform.
With NumPy, np.random.SeedSequence(entropy).spawn(n_workers) produces child seeds that are designed to give independent streams. Use it rather than seed + worker_id.
Reseeding inside the loop
Calling random.seed(s) inside the loop, or once per batch with the same s, resets the stream. Every batch then makes the same decisions. Seed once, when you create the generator.
Global state
The module-level functions such as random.randint share one hidden generator. Any other library that calls random advances it, so a run you seeded yourself can still fail to reproduce. Pass an explicit rng object, as every sampler in this tutorial does.
Predictable generators
The Mersenne Twister behind random is not cryptographically secure. Its state can be recovered after observing 624 outputs of 32 bits each. If someone could gain by predicting which records get sampled, for example in audit sampling or fraud review, use random.SystemRandom(). It has the same interface, so you can pass it in as rng without changing the sampler.
Checklist
| Check | Catches |
|---|---|
| `assert len(reservoir) == min(k, n)` | Fill condition `i <= k` |
| Per-item frequency test at small n | Off-by-one ranges, mixed indexing |
| Run with n larger than the raw generator range | Modulo bias, small `RAND_MAX` |
| Compare samples across partitions | Shared seeds |
| Same seed run twice gives identical output | Hidden global state |
Exercise
A colleague writes j = rng.randrange(i) for a 0-based index i and accepts when j < k. With k = 2 and n = 5, what is the inclusion probability of item 0, and of item 4?
Show answer
The keep probability becomes k/i, the same bug as randint(0, i - 1). Items k to n−1 end with probability k/(n−1) = 2/4 = 0.5. Items 0 to k−1 end with probability (k−1)/(n−1) = 1/4 = 0.25. So item 0 has probability 0.25 and item 4 has 0.5, instead of 2/5 = 0.4 for both.
Exercise
A raw 16-bit generator (M = 65536) is reduced with r % (i + 1). At i = 39999, what probability does the sampler use to keep the item when k = 10, and what is the correct probability?
Show answer
65536 = 1 × 40000 + 25536, so residues 0 to 25535 occur twice and the rest once. The accept region 0 to 9 is all doubled, which gives 20/65536 ≈ 0.000305. The correct value is 10/40000 = 0.00025, so the sampler keeps the item about 22% too often.
Exercise
Why does a shared seed across equal-length partitions produce matching positions in Algorithm R, and would A-Res with a shared seed have the same flaw?
Show answer
Algorithm R's random calls depend only on the index i, so the same seed gives the same accept and slot decisions at the same offsets. A-Res draws one uniform u per item in order, so the item at each offset gets the same u. Equal weights at the same offsets then give the same choices, and the keys are correlated across partitions in any case. Both samplers need independent seeds per partition.