Back to Streaming Sketching

Reservoir, Priority & Bottom-k Sampling

September 27, 2026 Wasil Zafar 22 min read

Compare uniform and weighted one-pass sampling strategies.

Table of Contents

  1. Keeping a Fair Few from an Endless Many
  2. Reservoir Invariants and Priority Keys
  3. Bottom-k Inclusion Probabilities
  4. Sampling Merges, Weights and Rare Events
  5. Choose and Verify a Sampling Scheme

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?

From fair seats to three streaming sampling methods A stream flows to a fixed set of seats selected by replacement probability, smallest stable ranks, or largest weight-adjusted priorities. Endless arrivalsunknown final lengthkeep only k recordsfirst-k is biased Selection rulereservoir • admit with k/tbottom-k • smallest uniform rankspriority • largest w/u values Sample contractinclusion probabilitythreshold / estimatormerge ruleauditable evidence uniform reservoirstable ranksweighted priority
ConceptIntuitive meaningExact exampleNon-example or boundaryMain assumptionQuestion answered
Reservoir invariantEvery seen position remains equally likelyAfter $t$ items, inclusion probability is $k/t$Keeping the first $k$ arrivalsUniform admission and replacement drawsIs the current sample uniform?
Priority keyRandom score fixes selection orderUniform bottom-$k$ uses key $u_i$Arrival time used as a supposedly random keyIndependent continuous keys or a proved hash modelWhich records outrank others?
Bottom-$k$ order statisticKeep items below the $k$-th rankRanks $.08,.21,.55$ selected for $k=3$Fixed probability sample with random sizeStable uniform ranks and deterministic tie ruleWhich fixed-size sample is retained?
Inclusion probabilityChance a population item is sampledUniform bottom-$k$: $\pi_i=k/n$Assuming $k/n$ under weighted samplingPopulation and design are definedHow should observations be reweighted?
Weighted priority samplingLarger weights tend to get larger priorities$q_i=w_i/u_i$, retain top $k$Replicating a record $w_i$ times without semantic justificationPositive weights and independent uniformsHow can weighted subset sums be estimated?
MergeabilityLocal summaries combine into global summaryBottom $k$ of union of local bottom-$k$ setsConcatenating local reservoirs of unequal partitionsSame rank function, identity, and parametersCan distributed samples combine exactly?
Horvitz–Thompson principleDivide observed contribution by inclusion chanceEstimate total with $y_i/\pi_i$ when selectedUnweighted sample mean under unequal inclusionKnown positive inclusion probabilitiesHow is selection bias corrected?
Warm-up

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$.

  1. C is admitted with probability $2/3$.
  2. Conditional on admission, C replaces A or B with probability $1/2$ each.
  3. $\Pr[C\text{ retained}]=2/3$.
  4. $\Pr[A\text{ retained}]=1-(2/3)(1/2)=2/3$; similarly for B.
  5. 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.

Reservoir, Priority & Bottom-k Sampling: Reservoir Invariants and Priority 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;
One reservoir update preserves uniform inclusion An old item enters the step with probability k over t minus one and survives with probability t minus one over t, while the new item enters with probability k over t. Before item told item includedprobability k/(t−1)induction hypothesis Update stepadmit new item with k/treplace this slot with 1/kold survives: 1 − (k/t)(1/k)= (t−1)/t After item told: k/(t−1) × (t−1)/tprobability k/tnew item also k/t prior invariantrandom updatepreserved fairness

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.

Worked Example

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$.

  1. Sort ranks: B $(0.11)$, D $(0.29)$, C $(0.47)$, A $(0.62)$, E $(0.83)$.
  2. Retain B, D, C. The observed threshold is $U_{(3)}=0.47$.
  3. Every item had design inclusion probability $k/n=3/5=0.6$ before ranks were drawn.
  4. Cardinality estimate: $(k-1)/U_{(k)}=2/0.47\approx4.255$. It is not exact on this draw; averaging over rank assignments yields 5.
  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.

from itertools import combinations
from math import comb
from random import Random

def reservoir(items, k, seed=0):
    if not isinstance(k, int) or k < 0:
        raise ValueError("k must be a nonnegative integer")
    rng = Random(seed)
    sample = []
    for t, item in enumerate(items, start=1):
        if t <= k:
            sample.append(item)
        else:
            j = rng.randrange(t)
            if j < k:
                sample[j] = item
    return sample

def bottom_k(items, k, seed=0):
    if not 0 < k <= len(items):
        raise ValueError("k must satisfy 0 < k <= number of items")
    rng = Random(seed)
    ranked = [(rng.random(), index, item)
              for index, item in enumerate(items)]
    return sorted(ranked)[:k]

def merge_bottom_k(local_samples, k):
    candidates = [entry for sample in local_samples for entry in sample]
    return sorted(candidates)[:k]

#Normal deterministic traces.
items = list("ABCDE")
print("reservoir:", reservoir(items, 3, seed=27))
ranked = bottom_k(items, 3, seed=27)
print("bottom-k:", ranked)

#Merge invariant: local bottom-k candidates contain the global bottom-k.
rng = Random(91)
all_ranked = sorted((rng.random(), i, i) for i in range(100))
partitions = [all_ranked[0::4], all_ranked[1::4],
              all_ranked[2::4], all_ranked[3::4]]
locals_ = [sorted(part)[:10] for part in partitions]
assert merge_bottom_k(locals_, 10) == all_ranked[:10]

#Simulation checks uniform inclusion and unbiased threshold estimation.
n, k, trials = 20, 5, 50_000
inclusions = [0] * n
estimates = []
for trial in range(trials):
    sample = bottom_k(list(range(n)), k, seed=trial)
    for _, _, item in sample:
        inclusions[item] += 1
    threshold = sample[-1][0]
    estimates.append((k - 1) / threshold)
rates = [count / trials for count in inclusions]
print("inclusion range / target:", min(rates), max(rates), k / n)
print("mean cardinality estimate:", sum(estimates) / trials)
assert max(abs(rate - k / n) for rate in rates) < 0.008
assert abs(sum(estimates) / trials - n) < 0.3

#Boundary and invalid cases.
assert reservoir([], 3, seed=1) == []
for bad_k in (-1, 0, 6):
    try:
        bottom_k(items, bad_k, seed=1)
    except ValueError as error:
        print("invalid test passed:", error)
MethodSampling targetInclusion/estimation factTime and stateStrengthFailure modePrefer when
Algorithm R reservoirUniform $k$-subset of stream positions$\pi_i=k/n$ after $n$ arrivals$O(1)$ expected update; $O(k)$ stateSimple, unknown stream lengthNot directly mergeable from reservoirs aloneOne sequential stream, uniform occurrences
Bottom-$k$ uniform ranksUniform $k$-subset of stable items$\pi_i=k/n$; $(k-1)/U_{(k)}$ estimates $n$$O(\log k)$ heap update; ranks storedExactly mergeable by taking global bottom $k$Ties, unstable identity, exposed ranksDistributed uniform entity sampling
Bernoulli samplingIndependent inclusion with fixed probability $p$$\pi_i=p$; sample size random$O(1)$ update; variable stateEasy composition and HT weightingMemory spikes or empty samplesFixed inclusion probability is desired
Weighted priority $q=w/u$Weight-sensitive fixed-size sampleThreshold-adjusted weights estimate subset sums$O(\log k)$; priority heapStrong weighted total estimatesInvalid weights or wrong threshold handlingWeighted subset-sum analytics
Exponential race key $-\ln u/w$Weighted random order without replacementSequential selection proportional to remaining weights$O(\log k)$Clear weighted-without-replacement semanticsNot the same estimator as priority samplingNeed weighted item sample, not priority estimates
Stratified reservoirsFixed capacity within declared strataInclusion depends on stratum size and allocationSum of stratum capacitiesProtects rare known groupsWrong post-stratification weights; new strataRare 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.

Distributed bottom-k and weighted sampling system Canonical items receive stable ranks or priorities on shards, local samples merge through a shared contract, and estimators plus rare-event monitoring sit behind explicit trust boundaries. Incoming recordscanonical identityweight / stratumadaptive IDstrust boundary Shard samplesshard A • local bottom kshard B • same key contractglobal bottom k + thresholdreject incompatible seed/version Inference layerHT / priority estimatesrare-stratum monitoralert on coverage failure contractlocal samplevalid estimatefailure boundary
Reservoir, Priority & Bottom-k Sampling: Sampling Merges, Weights and Rare Events
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;
Case Study

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}$.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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

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

  1. Select bottom-$3$: E $(.09)$, B $(.14)$, H $(.20)$.
  2. Compute each design inclusion probability $3/8$.
  3. With known $n=8$, estimate the value total as $(8/3)(3+5+6)=112/3\approx37.33$; the exact total is 38.
  4. 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.