s LearnSqueak.com

STREAMS · BOUNDED MEMORY

Reservoir sampling: keep a fair sample of a stream

Build a native Squeak streaming sampler with three slots, seeded random choices, a visual trace and twelve deterministic SUnit tests.

8 native steps12 deterministic tests3 retained records

Install the native streaming lab

A log can arrive one record at a time without telling you its final length. Keeping the first three records favors the beginning; keeping the latest three favors the end. A reservoir keeps a fixed number of records while giving every received position the same inclusion probability. This is sampling without replacement of positions, not sorting, counting frequencies, or rolling dice to estimate a probability.

  1. Use a copy of Squeak 6.1 with matching changes and sources files. This lab is native-only; its classes are not installed in the SqueakJS playground.
  2. Download reservoir-sampling.st. Open it in Squeak’s File List and choose fileIn. The chunk-format file is not a single Workspace expression.
  3. The model and teaching view are now installed. Use the Workspace commands below in order, keeping the same Workspace. Read the method definitions in the Browser; they are not Workspace commands.

SUnit tests · Complete source kit

Prerequisites: collections, blocks and closures, and SUnit. Keep the native window at least 980 × 620 pixels. Closing it cleans up the view; there are no timers, file writes, or network requests in the app.

01 · Make room for three records

capacity is the limit, seen counts received positions, and slots holds only the retained objects. The model accepts items one at a time and never asks the input for its size. The seven-item row belongs to the teaching view, not the sampler. A nonnegative integer capacity is required; zero is allowed.

LSReservoir method · read in Browser
capacity: k chooser: drawBlock
 (k isInteger and: [k >= 0]) ifFalse: [self error: 'Capacity must be a nonnegative integer'].
 capacity := k. chooser := drawBlock. seen := 0.
 slots := OrderedCollection new. lastChoice := nil. lastAction := 'Nothing received'. ^ self
Same Workspace · select and Do it
view := LSReservoirView open.

Expected: An empty reservoir: received 0, with three empty slots.

Inspect view model. Notice the empty OrderedCollection and seen = 0. The drawing is deliberately fixed-size, but the model can use any nonnegative capacity.

NATIVE SQUEAK CAPTURE
Native Squeak reservoir experiment 1: An empty reservoir: received 0, with three empty slots.
Genuine native Squeak Morphic capture after step 1.

02 · Fill the first empty slot

Until the reservoir is full, every incoming item belongs in the sample. The first branch adds the item and returns immediately. Incrementing seen before this branch means the count includes every position, whether it is kept or skipped later. The return symbol ^ exits this method, not the whole application.

LSReservoir method · read in Browser
accept: item
 | choice |
 seen := seen + 1. lastChoice := nil.
 slots size < capacity ifTrue: [slots add: item. lastAction := 'Fill an empty slot'. ^ self].
 capacity = 0 ifTrue: [lastAction := 'Zero capacity: keep nothing'. ^ self].
 choice := chooser value: seen.
 (choice isInteger and: [choice between: 1 and: seen]) ifFalse: [self error: 'Draw outside 1..seen'].
 lastChoice := choice.
 choice <= capacity
  ifTrue: [slots at: choice put: item. lastAction := 'Replace slot ', choice printString]
  ifFalse: [lastAction := 'Skip this item'].
 ^ self
Same Workspace · select and Do it
view next.

Expected: A is retained. No random choice is needed.

Print view model sample and expect #('A'). Here A is a String, not a Symbol. The sampler can hold other objects too; it stores references rather than serializing them.

NATIVE SQUEAK CAPTURE
Native Squeak reservoir experiment 2: A is retained. No random choice is needed.
Genuine native Squeak Morphic capture after step 2.

03 · Read a snapshot, not the storage

sample answers an Array made from the private collection. Clients may replace elements in that returned Array without replacing the model’s slots. This is a shallow copy: mutating a retained object itself remains visible through that object’s shared identity. Snapshot isolation of the container is not a deep clone.

LSReservoir method · read in Browser
sample
 ^ slots asArray
Same Workspace · select and Do it
view next.

Expected: The retained values are A and B; received is 2.

Print view model sample and expect #('A' 'B'). Keep inspection separate from mutation: accept: is the public operation that changes this model.

NATIVE SQUEAK CAPTURE
Native Squeak reservoir experiment 3: The retained values are A and B; received is 2.
Genuine native Squeak Morphic capture after step 3.

04 · Reach capacity without drawing

Exactly three positions have arrived, so all three must be kept. Starting random replacement too early would introduce unnecessary choices and complicate the invariant. Once more than k items have arrived, the sample size remains k. Before that point its size is the smaller of k and the received count.

LSReservoir method · read in Browser
seen
 ^ seen
Same Workspace · select and Do it
view next.

Expected: The sample is A, B, C and received is 3.

Print view model seen and expect 3. Print view model capacity and expect 3. The two values happen to match now, but they have different jobs. Later seen keeps growing while capacity stays fixed.

NATIVE SQUEAK CAPTURE
Native Squeak reservoir experiment 4: The sample is A, B, C and received is 3.
Genuine native Squeak Morphic capture after step 4.

05 · Choose among all positions seen so far

The factory creates one Random object and captures it in a block. Each later invocation advances that same generator. Re-creating Random with the same seed inside the block would repeatedly restart it and spoil the intended sequence. nextInt: uses inclusive bounds, matching Smalltalk’s one-based slot indexes.

LSReservoir class method · read in Browser
capacity: k seed: seed
 | random |
 random := Random seed: seed.
 ^ self new capacity: k chooser: [:bound | random nextInt: bound]
Same Workspace · select and Do it
view next.

Expected: For D, seed 42 draws 3 from 1..4. D replaces C in slot 3.

Print view model sample and expect #('A' 'B' 'D'). The fourth item has a 3/4 chance of entering: draws 1, 2 or 3 select a slot; draw 4 skips it. A fixed seed reproduces a demonstration, not genuine unpredictability.

NATIVE SQUEAK CAPTURE
Native Squeak reservoir experiment 5: For D, seed 42 draws 3 from 1..4. D replaces C in slot 3.
Genuine native Squeak Morphic capture after step 5.

06 · Skip an item without storing its history

A draw above capacity discards the incoming item. This is intentional, not a missed update. The count still increases, so the next item gets the correct probability. lastChoice and lastAction are small diagnostic fields; the model does not retain every skipped object or an ever-growing decision log.

LSReservoir method · read in Browser
lastChoice
 ^ lastChoice
Same Workspace · select and Do it
view next.

Expected: For E, the draw is 5 from 1..5. The sample stays A, B, D.

Print view model seen and expect 5; print view model lastChoice and expect 5. Contrast this with a rolling queue: a rolling queue would now contain C, D, E and would not give early records a continuing chance.

NATIVE SQUEAK CAPTURE
Native Squeak reservoir experiment 6: For E, the draw is 5 from 1..5. The sample stays A, B, D.
Genuine native Squeak Morphic capture after step 6.

07 · Replace a different slot

A new item is selected with probability k/n. Each old item survives this step with probability 1 − 1/n: exactly one of the n equally likely draws targets its slot. If its earlier inclusion chance was k/(n−1), multiplying by (n−1)/n gives k/n. This establishes the equal-inclusion invariant inductively, assuming independent uniform draws.

LSReservoir method · read in Browser
lastAction
 ^ lastAction
Same Workspace · select and Do it
view next.

Expected: For F, the draw is 2 from 1..6. F replaces B, leaving A, F, D.

Print view model lastAction and expect 'Replace slot 2'. Equal individual inclusion probabilities alone do not prove that every possible subset is equally likely; the exhaustive small-case test below checks the stronger property for a tiny stream.

NATIVE SQUEAK CAPTURE
Native Squeak reservoir experiment 7: For F, the draw is 2 from 1..6. F replaces B, leaving A, F, D.
Genuine native Squeak Morphic capture after step 7.

08 · Finish, reset, and reproduce

A second pass is not required. At this point the three stored positions are the result. The teaching view stops at G; the model itself can keep accepting objects indefinitely. Reset reconstructs the model with seed 42, so Next item repeats the same trace in this Squeak version. A different seed can produce a different sample, but is not guaranteed to.

LSReservoirView method · read in Browser
reset
 model := LSReservoir capacity: 3 seed: 42. stage := 0.
 stream := #('A' 'B' 'C' 'D' 'E' 'F' 'G'). self changed
Same Workspace · select and Do it
view next.

Expected: For G, draw 3 from 1..7 produces A, F, G. Received is 7.

Print view model sample and expect #('A' 'F' 'G'). Send view reset to return to the first screenshot. The order of reservoir slots is not source order or sorted order; sort a copy only if your application needs a presentation order.

NATIVE SQUEAK CAPTURE
Native Squeak reservoir experiment 8: For G, draw 3 from 1..7 produces A, F, G. Received is 7.
Genuine native Squeak Morphic capture after step 8.

Replay the eight native states

NATIVE SQUEAK CAPTURE
Empty native reservoir before seven items arrive
Eight genuine imageForm captures after scripted lesson commands, assembled into a replay. This is not a recording of mouse interaction.

Use the model without the window

Fresh Workspace · select entire block and Print it
| sampler |
sampler := LSReservoir capacity: 3 seed: 42.
1 to: 100 do: [:number | sampler accept: number].
sampler sample

Expected in the tested Squeak 6.1 generator: #(12 72 78), a three-element Array from positions 1 through 100. The sample is reproducible in that generator. In a real application replace the numeric loop with a callback that sends accept: for each new record; no whole-input Array is necessary. Repeated equal values are distinct input positions, so a sample may contain equal values. This is not a unique-values filter.

The algorithm performs one decision per item after filling, so processing N items is O(N); the retained references occupy O(k) space. The ever-growing counter requires O(log N) bits. The supplied teaching view keeps a short fixed input list solely to explain the trace. This implementation is the straightforward Algorithm R pattern, not the faster skip-based algorithms in Vitter’s paper.

Test exact decisions, not lucky frequencies

File in the test source first · select and Print it
LSReservoirTest suite run

Expected: 12 tests, 12 passes, 0 failures and 0 errors. Verified in native Squeak 6.1 build 23976. Tests cover the empty and short streams, filling, forced replacement, forced skip, zero and invalid capacity, an invalid draw, same-seed reproducibility, and the copied result container.

The chooser block is an injection point. Tests can provide a known answer rather than relying on chance. It must return an integer in 1..seen. An invalid answer raises an Error after the received count has advanced; discard that test instance rather than continuing a corrupted random source.

LSReservoirTest method · read in Browser
testUniformSmallCase
 | counts r key |
 counts := Dictionary new.
 1 to: 3 do: [:a | 1 to: 4 do: [:b |
  r := LSReservoir new capacity: 2 chooser: [:n | n = 3 ifTrue: [a] ifFalse: [b]].
  #(1 2 3 4) do: [:x | r accept: x].
  key := r sample asSortedCollection asArray.
  counts at: key put: (counts at: key ifAbsent: [0]) + 1]].
 self assert: counts size = 6.
 self assert: (counts values allSatisfy: [:count | count = 2])

For capacity 2 and four input positions, there are 3 × 4 = 12 equally likely draw histories after filling. The test enumerates every history and counts the sorted resulting pairs: all six possible pairs occur exactly twice. This is an exhaustive finite check, not a statistical experiment and not a proof for arbitrary stream lengths.

Try next: set capacity to 1 and verify that each of four positions occurs six times among the 2 × 3 × 4 draw histories. Then change the factory seed and compare a few traces without claiming that a small frequency table proves fairness.

Limits and source reading

Uniform sampling depends on uniform, independent random choices. Squeak Random is a seeded pseudorandom generator, suitable for this teaching lab, not a cryptographic lottery or security-sensitive selection. Neither the retained records nor the generator state are persisted. The model is not synchronized for concurrent writers and does not handle weighted samples, deletion, sliding time windows, or merging samples from different machines.

NIST’s Dictionary of Algorithms and Data Structures: reservoir sampling describes the selection rule. Jeffrey Scott Vitter, Random Sampling with a Reservoir (1985) studies this problem and more efficient algorithms. This tutorial’s Smalltalk model, visual trace, and tests are original.

Continue with the dice probability lab for observed frequencies, stacks and queues for order-based retention, or collection transformations.