Module: AllStak::Sampling

Defined in:
lib/allstak/sampling.rb

Overview

Deterministic head-sampling helper.

Sampling is “deterministic” in the sense that a rate of 1.0 always keeps an event and a rate of 0.0 always drops it — no RNG is consulted at the boundaries. For intermediate rates a single random draw in [0.0, 1.0) is compared against the rate: kept when ‘draw < rate`.

The RNG is a seam: tests inject a deterministic value via Sampling.rng= so the keep/drop decision is fully controllable without monkeypatching Kernel.

Class Method Summary collapse

Class Method Details

.rngObject



20
21
22
# File 'lib/allstak/sampling.rb', line 20

def rng
  @rng || ->(*) { rand }
end

.rng=(callable) ⇒ Object

Override the random source used by sampled?. Pass a callable returning a Float in [0.0, 1.0). Pass nil to restore the default (Kernel#rand).



16
17
18
# File 'lib/allstak/sampling.rb', line 16

def rng=(callable)
  @rng = callable
end

.sampled?(rate) ⇒ Boolean

Returns true when an event should be KEPT under the given rate.

nil rate is treated as “no sampling configured” → keep. Rates are clamped to [0.0, 1.0]. 1.0 always keeps; 0.0 always drops.

Returns:

  • (Boolean)


28
29
30
31
32
33
34
35
36
# File 'lib/allstak/sampling.rb', line 28

def sampled?(rate)
  return true if rate.nil?
  r = rate.to_f
  r = 0.0 if r < 0.0
  r = 1.0 if r > 1.0
  return true  if r >= 1.0
  return false if r <= 0.0
  rng.call < r
end