Sub topic 13
Merging Reservoirs Across Partitions
This chapter assumes you have read the earlier chapters on Algorithm R and on sampling by random keys. You should be comfortable with heapq, with conditional probability, and with the idea that a uniform sample of size k means every k-subset is equally likely.
Large streams are rarely processed by one machine. A log pipeline might split traffic across 64 workers, and a batch job might read 1,000 files in parallel. Each worker can keep its own reservoir in one pass and O(k) memory. At the end you need one sample of the whole stream, and that sample must be just as uniform as one built by a single sampler reading everything in order. This chapter covers two correct ways to merge, one way that looks reasonable but is wrong, and the details that decide which correct method to use.
The Merge Problem
Suppose the stream is split into partitions A and B, with nA and nB items. Worker A returns a uniform sample of min(k, nA) items from A, and worker B does the same for B. You want a uniform k-sample of the nA + n_B items in A ∪ B.
A correct merge must meet these requirements:
- It uses only the reservoirs and a small amount of metadata, never the raw partitions.
- It is associative and commutative: merging (A, B) then C gives the same distribution as A then (B, C), in any order. Distributed frameworks rely on this so they can reduce results in a tree, in whatever order workers finish.
- It handles partitions with fewer than k items, including empty ones.
The Tempting Wrong Merge
The obvious approach is to pool the two reservoirs and draw k items uniformly from the pool. This is biased whenever the partitions have different sizes, because it treats a pooled item from a small partition the same as one from a large partition. An item from a small partition has already survived an easy selection, while an item from a large partition survived a hard one.
Take k = 3, nA = 2 and nB = 8. Reservoir A holds both items of A. Reservoir B holds 3 of the 8 items of B. The pool has 5 items, and each pooled item survives the final draw with probability 3/5.
| Item origin | P(in local reservoir) | P(survives pooled draw) | Final probability | Correct value |
|---|---|---|---|---|
| Partition A | 1 | 3/5 | 0.600 | 0.3 |
| Partition B | 3/8 | 3/5 | 0.225 | 0.3 |
Items from A are oversampled by a factor of 2. The pooled merge is only correct when both partitions have the same size, and you usually can't guarantee that.
Method 1: Merge by Random Keys
The random-keys chapter showed that giving every item an independent uniform key and keeping the k smallest keys gives a uniform sample. Keys also make merging trivial. If each worker keeps (key, item) pairs, then the merged sample is just the k smallest keys among the pairs in both reservoirs.
The argument is short. Let S be the k items with the smallest keys in A ∪ B. Any item in S that comes from A has a key that is among the k smallest in A ∪ B, so it is also among the k smallest in A alone. That means it is in reservoir A. The same holds for B. So S is contained in the union of the two reservoirs, and taking the k smallest keys of that union recovers S exactly. Taking a minimum is associative and commutative, so tree-shaped reduction works with no extra effort.
The merge needs no partition counts. A partition with fewer than k items simply returns all its items with their keys.
Weighted reservoirs merge the same way
A-Res, from the previous chapter, keeps the k largest keys u^(1/w). The same containment argument applies with "largest" in place of "smallest". Merged A-Res reservoirs therefore form a valid weighted sample without replacement of the combined stream, as long as you keep the keys and not only the items. Count-based merging (Method 2 below) does not extend to weighted samples, so for weighted sampling keys are the only practical choice.
Method 2: Merge Algorithm R Reservoirs by Counts
Plain Algorithm R does not store keys. You can still merge its reservoirs if each worker also reports n, the number of items it saw. The idea is to simulate what a single uniform sample of A ∪ B would look like:
- Decide how many of the m = min(k, nA + nB) output items come from A. In a uniform m-subset of A ∪ B this count follows a hypergeometric distribution: it is the number of A items you get when drawing m items without replacement from nA items of A and nB items of B.
- Pick that many items uniformly from reservoir A, and the rest uniformly from reservoir B.
Step 2 is valid because a uniform subset of a uniform subset is itself a uniform subset of the original. Conditioned on how many items come from A, a uniform sample of A ∪ B is a uniform subset of A of that size, together with an independent uniform subset of B. The merged result has size m and total count nA + nB, so it can be merged again.
Code: Both Merges and a Check
The script below implements both correct merges and the wrong pooled merge. It then measures inclusion frequencies on the 2-versus-8 example from the table. It uses only the standard library.
import heapq
import random
from collections import Counter
def keyed_reservoir(stream, k, rng):
# Keep the k items with the smallest uniform random keys
return heapq.nsmallest(k, ((rng.random(), item) for item in stream),
key=lambda pair: pair[0])
def merge_keyed(a, b, k):
return heapq.nsmallest(k, a + b, key=lambda pair: pair[0])
def reservoir_sample(stream, k, rng):
reservoir, n = [], 0
for i, item in enumerate(stream):
n += 1
if i < k:
reservoir.append(item)
else:
j = rng.randint(0, i)
if j < k:
reservoir[j] = item
return reservoir, n
def merge_counted(a, n_a, b, n_b, k, rng):
# a: uniform sample of min(k, n_a) items from A; same for b
total = n_a + n_b
m = min(k, total)
take_a, rem_a, rem_total = 0, n_a, total
for _ in range(m): # hypergeometric draw, one position at a time
if rng.randrange(rem_total) < rem_a:
take_a += 1
rem_a -= 1
rem_total -= 1
merged = rng.sample(a, take_a) + rng.sample(b, m - take_a)
return merged, total
def merge_pooled_wrong(a, b, k, rng):
pool = a + b
return rng.sample(pool, min(k, len(pool)))
def main():
k, trials = 3, 100_000
part_a, part_b = list(range(2)), list(range(2, 10))
rng = random.Random(12345)
counts = {"keyed": Counter(), "counted": Counter(), "pooled": Counter()}
for _ in range(trials):
ka = keyed_reservoir(part_a, k, rng)
kb = keyed_reservoir(part_b, k, rng)
for _, x in merge_keyed(ka, kb, k):
counts["keyed"][x] += 1
ra, na = reservoir_sample(part_a, k, rng)
rb, nb = reservoir_sample(part_b, k, rng)
merged, _ = merge_counted(ra, na, rb, nb, k, rng)
for x in merged:
counts["counted"][x] += 1
for x in merge_pooled_wrong(ra, rb, k, rng):
counts["pooled"][x] += 1
print("item keyed counted pooled (target 0.300)")
for x in range(10):
print(f"{x:>4} {counts['keyed'][x] / trials:.3f} "
f"{counts['counted'][x] / trials:.3f} "
f"{counts['pooled'][x] / trials:.3f}")
if __name__ == "__main__":
main()When you run it, the keyed and counted columns sit near 0.300 for all ten items. The pooled column shows about 0.600 for items 0 and 1 and about 0.225 for items 2 to 9, which matches the table.
Choosing Between the Methods
| Concern | Keyed merge | Count-based merge |
|---|---|---|
| Extra state per reservoir | One float per item | One integer per reservoir |
| Needs partition sizes | No | Yes, exact counts |
| Merge randomness | None (deterministic) | O(k) random numbers per merge |
| Supports weighted (A-Res) | Yes | No |
| Works with existing Algorithm R or L code | Needs keys added | Yes |
| Merge time | O(k log k) | O(k) |
Use keys when you control the samplers from the start or need weights. Use counts when you are combining reservoirs from existing Algorithm R or Algorithm L code and each worker can report an exact item count.
Failure Modes
Correlated random streams across workers
If every worker seeds its generator with the same value, for example random.Random(42), the workers draw the same key sequence. Item i of partition A gets the same key as item i of partition B, so the merge is no longer uniform. Derive a distinct seed for each worker, for example by hashing a job ID together with the partition ID, or seed from OS entropy. If you need reproducibility, log the seeds.
Wrong or approximate counts
The count-based merge is only as good as nA and nB. If a worker reports an estimate, a record count from metadata, or a count taken before filtering, the hypergeometric split is off and the sample drifts toward one partition. The count must be the number of items the sampler actually processed.
Discarding keys too early
A common pipeline bug is to strip keys after the first merge level and send bare items upward. Higher merge levels then have nothing to compare. Keep keys until the final result, and drop them only when you emit the sample.
Key ties and precision
random() returns floats with 53 bits of precision, so ties are rare until you reach billions of items. They don't bias the result as long as ties are broken by something unrelated to item content. If items might not be comparable, store (key, partition_id, index, item) so heapq never has to compare items. For weighted keys u^(1/w) with very small weights, the keys underflow to 0.0. Comparing log(u)/w instead keeps the ordering and avoids underflow.
Overlapping partitions
Both methods assume the partitions are disjoint. If a retry makes a worker reprocess records that another worker already read, those records are counted twice and become more likely to be sampled. With keys, you can make the key a deterministic hash of a record ID instead of a fresh random draw. Duplicates then get identical keys, and you can drop them during the merge.
Exercise
Workers report Algorithm R reservoirs with k = 5. Partition A saw 4 items, partition B saw 0 items, and partition C saw 1,000 items. Using the count-based merge, what is the size of merge(merge(A, B), C), and what is the expected number of items from A in the final sample?
Show answer
merge(A, B) has total count 4 and size min(5, 4) = 4, so it holds all of A. Merging with C gives size min(5, 1004) = 5. The number drawn from A is hypergeometric with 5 draws from 4 A-items among 1,004 items, so its expectation is 5 × 4/1004 ≈ 0.0199. That matches each item's correct inclusion probability of 5/1004.
Exercise
A team merges keyed reservoirs, but every worker calls random.Random(7). The partitions are equal in size. Explain why the merged sample is not uniform even though the pooled sizes are balanced.
Show answer
Every worker produces the same key sequence, so the j-th item of each partition gets the same key. The k smallest keys therefore come from the same positions in every partition, and the final sample is chosen by position. Other k-subsets, such as ones that contain item j from one partition but not from another, become impossible or less likely. Keys must be independent across all items, which requires distinct seeds or independent generators per worker.
Exercise
Why does the containment argument for keyed merging fail if each worker keeps only its k smallest keys among items that passed a local filter, while another worker applies no filter?
Show answer
The merged result is then a uniform sample of the union of the sets each worker actually sampled, which is filtered A together with unfiltered B. It is not a sample of the full A ∪ B, and it is not a sample of a consistently filtered stream either. The merge is correct only when every partition samples the same population definition, so apply the same filters to all partitions before sampling.