Keeping a Fair Few from an Endless Many
Suppose people enter a theatre one at a time, but only three seats are reserved for a final interview. The total number of arrivals is unknown. Filling the seats with the first three people is easy, but unfair to everyone who arrives later. A streaming sampler must continually reconsider the seats so that, after any number of arrivals, every person has the correct chance of being represented.
This deep dive builds on the prerequisite chapter about approximate counting and sampling. That foundation explains why a sample can replace a full stream for some questions. The missing layer is algorithmic: how do we maintain a fixed-size uniform sample in one pass, support weights, assign stable random ranks, merge samples from partitions, and calculate valid inclusion probabilities for estimation?
Reservoir sampling keeps exactly $k$ items from a stream of unknown length. In Algorithm R, the first $k$ items fill the reservoir. When item $t$ arrives, where $t\gt k$, include it with probability $k/t$ and, if included, replace one uniformly chosen reservoir position. After processing $t$ distinct positions, every item is present with probability $k/t$ and every $k$-subset is equally likely.
Bottom-$k$ sampling gives each item an independent continuous rank $u_i\sim\operatorname{Uniform}(0,1)$ and retains the $k$ smallest ranks. This produces the same uniform fixed-size sample but makes selection deterministic once ranks are attached. It is naturally mergeable: the global bottom $k$ are the bottom $k$ of the union of local bottom-$k$ samples, provided every partition uses the same stable rank function and item identity.
Priority sampling adapts ranking to positive weights. A common construction draws $u_i\sim\operatorname{Uniform}(0,1)$, forms priority $q_i=w_i/u_i$, and keeps the $k$ largest priorities. The next-largest priority becomes a threshold used to estimate weighted subset sums. Weighted sampling is not uniform sampling with a decorative weight column: it changes inclusion probabilities and the estimators required downstream.
For a tiny reservoir example with $k=2$, items A and B fill the sample. Item C is admitted with probability $2/3$ and then replaces A or B with probability $1/2$. Thus C has probability $2/3$ of inclusion, while A survives with probability $1-(2/3)(1/2)=2/3$; the same holds for B. Fairness is restored after just one update.
The questions that drive a design are therefore specific. Are stream positions or distinct entities being sampled? Is the target uniform over items, proportional to weight, or optimized for subset-sum estimation? Must partitions merge exactly? Can the same entity appear repeatedly? Are ranks secret from an adversary? Which inclusion probability belongs in the estimator?
A streaming sample is valid only relative to a declared population, random-key model, and estimator. Reservoir, bottom-$k$, and weighted priority schemes can all keep $k$ records, but they do not create the same inclusion probabilities or support the same merge and inference rules.
| Concept | Intuitive meaning | Exact example | Non-example or boundary | Main assumption | Question answered |
|---|---|---|---|---|---|
| Reservoir invariant | Every seen position remains equally likely | After $t$ items, inclusion probability is $k/t$ | Keeping the first $k$ arrivals | Uniform admission and replacement draws | Is the current sample uniform? |
| Priority key | Random score fixes selection order | Uniform bottom-$k$ uses key $u_i$ | Arrival time used as a supposedly random key | Independent continuous keys or a proved hash model | Which records outrank others? |
| Bottom-$k$ order statistic | Keep items below the $k$-th rank | Ranks $.08,.21,.55$ selected for $k=3$ | Fixed probability sample with random size | Stable uniform ranks and deterministic tie rule | Which fixed-size sample is retained? |
| Inclusion probability | Chance a population item is sampled | Uniform bottom-$k$: $\pi_i=k/n$ | Assuming $k/n$ under weighted sampling | Population and design are defined | How should observations be reweighted? |
| Weighted priority sampling | Larger weights tend to get larger priorities | $q_i=w_i/u_i$, retain top $k$ | Replicating a record $w_i$ times without semantic justification | Positive weights and independent uniforms | How can weighted subset sums be estimated? |
| Mergeability | Local summaries combine into global summary | Bottom $k$ of union of local bottom-$k$ sets | Concatenating local reservoirs of unequal partitions | Same rank function, identity, and parameters | Can distributed samples combine exactly? |
| Horvitz–Thompson principle | Divide observed contribution by inclusion chance | Estimate total with $y_i/\pi_i$ when selected | Unweighted sample mean under unequal inclusion | Known positive inclusion probabilities | How is selection bias corrected? |
Keeping a Fair Few from an Endless Many
Use Algorithm R with reservoir size $k=2$. A and B fill the reservoir. C arrives at position $t=3$.
- C is admitted with probability $2/3$.
- Conditional on admission, C replaces A or B with probability $1/2$ each.
- $\Pr[C\text{ retained}]=2/3$.
- $\Pr[A\text{ retained}]=1-(2/3)(1/2)=2/3$; similarly for B.
- The three possible two-item samples AB, AC, BC each have probability $1/3$.
Expected result: every item has inclusion probability $2/3$, and every pair is equally likely. Reflection: if the replacement position always chose slot zero, which item would be disadvantaged and which invariant would fail?
Reservoir Invariants and Priority Keys
The reservoir proof is an induction. Immediately after the first $k$ items, each is included with probability 1, equal to $k/k$. Assume that after $t-1$ items, every earlier item is included with probability $k/(t-1)$. At time $t$, the new item is included with probability $k/t$. An earlier item survives unless the new item is admitted and replaces its particular slot:
$$ \Pr[\text{survive step }t]=1-\frac{k}{t}\frac1k=1-\frac1t=\frac{t-1}{t}. $$
Multiplying by its previous inclusion probability gives
$$ \frac{k}{t-1}\frac{t-1}{t}=\frac kt. $$
Thus old and new items share the same marginal inclusion probability. A stronger induction shows every $k$-subset of the first $t$ positions has probability $1/\binom tk$. The proof uses exact uniform choices and treats stream positions as population units. Duplicate values at different positions remain different units unless preprocessing defines entity-level deduplication.
Bottom-$k$ provides another view. Assign independent continuous uniform ranks $u_i$ and retain the $k$ smallest. Symmetry makes every ordering of ranks equally likely, so every $k$-subset is equally likely. Algorithm R and bottom-$k$ therefore produce the same distribution for a single uniform sample, but their operational properties differ. Algorithm R needs only arrival count and reservoir state; bottom-$k$ stores ranks and supports deterministic recomputation and exact distributed merging.
For weighted data, define $q_i=w_i/u_i$ with $w_i\gt0$ and keep the $k$ largest priorities. Let $\tau$ be the $(k+1)$-st largest priority. A retained item receives adjusted weight $\widehat w_i=\max(w_i,\tau)$. Conditional on the other items' threshold, item $i$ is selected when $u_i\lt w_i/\tau$, so its inclusion chance is $\min(1,w_i/\tau)$ and $w_i/\pi_i=\max(w_i,\tau)$. This is the Horvitz–Thompson correction underlying priority estimates of totals and subset sums. The leave-one-out threshold logic matters; treating the observed threshold as an ordinary fixed probability without the priority-sampling proof is unsafe.
Boundary cases expose the assumptions. Discrete or truncated ranks can tie, so the implementation needs a deterministic secondary key that preserves an analyzed ordering. Zero or negative weights are invalid for $w_i/u_i$. Reusing a rank per occurrence instead of per entity changes the population. Public predictable ranks allow an adaptive adversary to manufacture unusually small or large keys.
flowchart TD
A[Define population units] --> B[Choose uniform or weighted target]
B --> C{Uniform fixed-size?}
C -->|arrival update| D[Admit item t with probability k over t]
D --> E[Replace uniform reservoir slot]
E --> F[Induction gives inclusion k over t]
C -->|stable ranks| G[Assign independent uniform keys]
G --> H[Keep bottom k]
H --> I[Order symmetry gives uniform k-subset]
B --> J[Weighted subset sums]
J --> K[Priority q equals w over u]
K --> L[Keep top k and threshold next priority]
L --> M[Adjusted weights via inclusion probability]
A --> X{Identity randomness and ties specified?}
X -->|no| Y[Proof invalid or target population changed]
X -->|yes| B
classDef navy fill:#17365D,color:#fff,stroke:#17365D;
classDef teal fill:#147D84,color:#fff,stroke:#0D565B;
classDef purple fill:#6C3BAA,color:#fff,stroke:#472675;
classDef crimson fill:#C6284D,color:#fff,stroke:#861B35;
class A,B,C navy;
class D,E,G,H,J,K purple;
class F,I,L,M teal;
class X,Y crimson;
Algorithm R preserves $k/t$ inclusion because each old item survives the next update with probability $(t-1)/t$; bottom-$k$ obtains the same uniform sample by rank symmetry. Weighted priority sampling changes the target and requires threshold-based adjusted weights—uniform-sample formulas cannot be carried over unchanged.
Bottom-k Inclusion Probabilities
Let $n$ distinct items receive independent continuous uniform ranks and let $U_{(k)}$ be the $k$-th smallest rank. Symmetry gives each item inclusion probability $k/n$. For cardinality estimation, the order statistic contains more information than the retained identities. Its density is Beta$(k,n-k+1)$, and for $k\gt1$,
$$ \mathbb E\!\left[\frac1{U_{(k)}}\right]=\frac{n}{k-1}. $$
Therefore
$$ \widehat n=\frac{k-1}{U_{(k)}} $$
is unbiased for $n$. When $k\gt2$, its variance is $n(n-k+1)/(k-2)$ under the ideal continuous-rank model. The estimator is undefined for $k=1$ and has infinite variance at $k=2$, showing why tiny bottom-$k$ samples can be mathematically fragile even though inclusion remains uniform.
For estimating a total $T=\sum_i y_i$ from a uniform fixed-size sample, each $\pi_i=k/n$, so the Horvitz–Thompson estimate is $(n/k)\sum_{i\in S}y_i$ when $n$ is known. If $n$ is itself inferred from the same threshold, covariance and estimator design must be handled rather than plugging an estimated $n$ into a formula and assuming unbiasedness.
Rank generation is part of the theorem. Ideal ranks are independent and continuous. Hash-derived finite ranks create ties and limited independence; a stable composite key such as (rank, canonical_item_id) resolves order but does not manufacture missing randomness. Repeated entities require a decision: sample occurrences with fresh keys, or sample entities with one stable key.
Bottom-k Inclusion Probabilities
Five items have stable ranks A: $0.62$, B: $0.11$, C: $0.47$, D: $0.29$, E: $0.83$. Let $k=3$.
- Sort ranks: B $(0.11)$, D $(0.29)$, C $(0.47)$, A $(0.62)$, E $(0.83)$.
- Retain B, D, C. The observed threshold is $U_{(3)}=0.47$.
- Every item had design inclusion probability $k/n=3/5=0.6$ before ranks were drawn.
- Cardinality estimate: $(k-1)/U_{(k)}=2/0.47\approx4.255$. It is not exact on this draw; averaging over rank assignments yields 5.
- If sampled values are B:$4$, D:$10$, C:$1$ and $n=5$ is known, the uniform Horvitz–Thompson total estimate is $(5/3)(4+10+1)=25$.
Perturbed case: replace E's rank by $0.20$. The sample becomes B, E, D and the threshold becomes $0.29$, producing cardinality estimate $2/0.29\approx6.897$. One changed rank can move the threshold sharply; this is sampling variation, not an implementation bug.
| Method | Sampling target | Inclusion/estimation fact | Time and state | Strength | Failure mode | Prefer when |
|---|---|---|---|---|---|---|
| Algorithm R reservoir | Uniform $k$-subset of stream positions | $\pi_i=k/n$ after $n$ arrivals | $O(1)$ expected update; $O(k)$ state | Simple, unknown stream length | Not directly mergeable from reservoirs alone | One sequential stream, uniform occurrences |
| Bottom-$k$ uniform ranks | Uniform $k$-subset of stable items | $\pi_i=k/n$; $(k-1)/U_{(k)}$ estimates $n$ | $O(\log k)$ heap update; ranks stored | Exactly mergeable by taking global bottom $k$ | Ties, unstable identity, exposed ranks | Distributed uniform entity sampling |
| Bernoulli sampling | Independent inclusion with fixed probability $p$ | $\pi_i=p$; sample size random | $O(1)$ update; variable state | Easy composition and HT weighting | Memory spikes or empty samples | Fixed inclusion probability is desired |
| Weighted priority $q=w/u$ | Weight-sensitive fixed-size sample | Threshold-adjusted weights estimate subset sums | $O(\log k)$; priority heap | Strong weighted total estimates | Invalid weights or wrong threshold handling | Weighted subset-sum analytics |
| Exponential race key $-\ln u/w$ | Weighted random order without replacement | Sequential selection proportional to remaining weights | $O(\log k)$ | Clear weighted-without-replacement semantics | Not the same estimator as priority sampling | Need weighted item sample, not priority estimates |
| Stratified reservoirs | Fixed capacity within declared strata | Inclusion depends on stratum size and allocation | Sum of stratum capacities | Protects rare known groups | Wrong post-stratification weights; new strata | Rare groups known before sampling |
Sampling Merges, Weights and Rare Events
In a teaching case, Algorithm R makes invariants visible: learners can enumerate all random branches for $n=4,k=2$ and verify that all six subsets have probability $1/6$. Bottom-$k$ then reframes the same distribution as an ordering problem and introduces order statistics.
At professional scale, a distributed observability platform may need a reproducible sample of unique traces across hundreds of shards. Stable hash-derived ranks and global bottom-$k$ merging are attractive because each shard sends only its local bottom-$k$ candidates. The contract must fix canonical trace identity, hash version, seed, rank width, tie-breaking, deduplication, and window boundaries. If shards use different seeds, their local thresholds are incomparable and the merge guarantee disappears.
Weights arise when bytes, cost, or business impact matter more than record count. Priority sampling can estimate weighted subset sums, while exponential-race keys produce a weighted sample without replacement. These are related but answer different questions. The implementation must retain the threshold information required by its estimator; returning only item IDs may make later unbiased estimation impossible.
Rare events expose a limitation of globally uniform sampling. If errors occur in one per million traces and $k=1000$, many windows contain no errors. Increasing weights after observing outcomes can bias analysis. Better designs predeclare strata, maintain a dedicated error reservoir, or use inclusion probabilities driven by features available at selection time, then apply the corresponding estimator.
Adversarial inputs create another boundary. If clients can predict rank hashes, they may search for IDs with exceptionally small ranks and dominate bottom-$k$. A keyed pseudorandom function and rotation policy may be required, but rotation changes stable identities across windows and complicates merges. Evidence that invalidates deployment includes inclusion-rate drift, rank collisions beyond expectation, shard-dependent sampling rates, lost threshold metadata, merge disagreement with a centralized oracle, or rare-group coverage below its declared requirement.
flowchart TD
A[Define population and target statistic] --> B{Uniform or weighted?}
B -->|uniform sequential| C[Reservoir Algorithm R]
B -->|uniform distributed| D[Stable bottom-k ranks]
B -->|weighted estimates| E[Priority sampling with threshold]
A --> F{Rare groups require coverage?}
F -->|yes| G[Predeclare strata and allocate capacity]
F -->|no| B
C --> H[Validate inclusion frequencies]
D --> I[Validate centralized merge oracle]
E --> J[Validate adjusted-weight estimates]
G --> K[Validate per-stratum coverage]
H --> L{All contracts pass?}
I --> L
J --> L
K --> L
L -->|yes| M[Deploy and monitor]
L -->|no| N[Reject or redesign]
M --> O{Drift attack or metadata loss?}
O -->|yes| N
O -->|no| M
classDef navy fill:#17365D,color:#fff,stroke:#17365D;
classDef teal fill:#147D84,color:#fff,stroke:#0D565B;
classDef purple fill:#6C3BAA,color:#fff,stroke:#472675;
classDef crimson fill:#C6284D,color:#fff,stroke:#861B35;
class A,B,F navy;
class C,D,E,G purple;
class H,I,J,K,M teal;
class L,N,O crimson;
Sampling Merges, Weights and Rare Events: Reservoir, Priority & Bottom-k Sampling
Scenario. A trace platform receives $2\times10^9$ unique traces per day across 200 shards. It needs a reproducible global sample of $k=20{,}000$, weighted cost estimates, and at least 200 sampled error traces when the error rate may be $10^{-5}$.
- Uniform mergeable sample: assign a keyed 128-bit rank to canonical trace ID and retain local bottom $20{,}000$. Merge all candidates and retain the global bottom $20{,}000$. Store rank, ID, window, seed version, and tie-break rule.
- Inclusion: every unique trace has probability $k/n=10^{-5}$ under the ideal model. A uniform sample would contain only about $200$ errors in expectation when there are $20{,}000$ errors total, with substantial probability of falling below 200.
- Rare-event protection: maintain a separately budgeted error stratum selected from an error label available at sampling time. Record its stratum population or inclusion probabilities for downstream weighting. Do not retroactively label and claim the original design guaranteed coverage.
- Weights: for cost subset sums, run a distinct priority sample with positive cost weights and preserve the $(k+1)$-st threshold. Do not reuse uniform bottom-$k$ estimates as though inclusion were proportional to cost.
- Validation: compare distributed merge against a centralized rank sort; test duplicate IDs, cross-shard duplicates, rank ties, seed mismatch, empty shards, giant weights, zero weights, and chosen-ID attacks. Run Monte Carlo coverage and estimator-bias checks.
- Expected observations: compatible local bottom-$k$ samples merge exactly; seed mismatch changes winners; the rare stratum stabilizes error coverage; losing the priority threshold prevents valid adjusted-weight estimates.
Selection decision: deploy stable bottom-$k$ for reproducible uniform trace inspection, a separate priority sample for weighted cost analytics, and a declared error stratum for coverage. Reject a single universal sample because its target and capacity cannot simultaneously guarantee all three requirements.
Choose and Verify a Sampling Scheme
The disciplined workflow begins with the population and query, not the data structure. State whether units are occurrences, entities, or weighted entities; whether sample size or inclusion probability must be fixed; whether distribution and reproducibility matter; and which estimator consumes the sample. Only then choose reservoir replacement, bottom-$k$ ranks, priority keys, Bernoulli sampling, or stratification.
This bridges backward to Bernoulli sampling, expectations, and unbiased estimators. It bridges forward to distinct counting, similarity sketches, distributed summaries, adaptive sampling, survey estimation, and rare-event monitoring. Across those topics, random selection and statistical correction must be designed together.
Practice: Choose and Verify a Sampling Scheme
Starter data: stream positions A–H, sample size $k=3$, values $(2,5,1,8,3,9,4,6)$, and stable ranks $(.72,.14,.55,.31,.09,.88,.43,.20)$.
Tier 1 — Trace and vocabulary
- Select bottom-$3$: E $(.09)$, B $(.14)$, H $(.20)$.
- Compute each design inclusion probability $3/8$.
- With known $n=8$, estimate the value total as $(8/3)(3+5+6)=112/3\approx37.33$; the exact total is 38.
- Explain why closeness on one draw does not prove unbiasedness.
Expected artifact: sorted-rank table with selected flags, inclusion probabilities, and contributions.
Tier 2 — Prove reservoir fairness
Write the induction for a general old item and the new item at step $t$. Extend it from marginal inclusion to the claim that each $k$-subset is equally likely, or enumerate all paths for $n=4,k=2$.
Debugging prompt: if an old item's survival probability is written as $1-k/t$, you forgot that admission replaces only one of $k$ slots.
Tier 3 — Threshold estimation
For ideal bottom-$k$ ranks, derive $\mathbb E[1/U_{(k)}]=n/(k-1)$ from the Beta density and obtain $(k-1)/U_{(k)}$. State why $k=1$ is undefined and $k=2$ has infinite variance.
Tier 4 — Weighted and distributed verification
Implement priority $q=w/u$ for positive weights, retain the threshold, and compare estimated totals with exact totals over many seeds. Partition inputs five ways and verify bottom-$k$ merge equals centralized selection. Inject duplicate identities, mismatched seeds, 16-bit rank ties, zero weights, and missing threshold metadata.
Completion criterion: valid configurations match the oracle; every invalid configuration is rejected or produces a documented failing test.
Tier 5 — Professional judgment
Choose schemes for a sequential log inspector, a distributed unique-user sample, weighted cloud-cost totals, and rare fraud cases. For each, specify population, sample contract, inclusion probabilities, estimator, merge rule, privacy/threat model, and measurable invalidation evidence.
Stretch goal: compare stable entity ranks with fresh occurrence ranks when users generate unequal numbers of events. Explain which population each samples and how the difference changes interpretation.
Rubric (10 points): definitions and trace 2; reservoir proof 2; bottom-$k$ estimator 2; executable merge/weight tests 2; production selection and failure analysis 2. Mastery requires at least 8 points and no use of a uniform estimator on unequal-probability data.
Reflection: if two methods retain the same number of rows, what evidence proves that they sample the same population with the same probabilities?
Decision checklist: define population identity, choose uniform or weighted selection, preserve ranks and thresholds, calculate inclusion probabilities, pair the sample with its estimator, specify ties and merge metadata, protect rare strata, and test adaptive inputs. Never infer representativeness from sample size alone; the next step is connecting these sampling contracts to downstream sketches, joins, and confidence guarantees.