# `Nous.Eval.Online.Sampler`
[🔗](https://github.com/nyo16/nous/blob/v0.21.1/lib/nous/eval/online/sampler.ex#L1)

The deterministic sampling decision of `Nous.Eval.Online`.

A trace is sampled at `rate` when its 56-bit randomness `r` is below
`trunc(rate * 2^56)`. For a Nous trace id (32 hex characters, 16 random
bytes) `r` is its rightmost 7 bytes, the randomness the OpenTelemetry
probability sampler uses; any other key (a session id, a trace id seeded
by the caller in another format) is hashed with SHA-256 and the first 7
bytes are used.

With a salt (`Nous.Eval.Online`'s `:sampling_salt`, applied to session
keys) `r` is instead the first 7 bytes of `HMAC-SHA-256(salt, key)`, for
any key. Without one the decision for a key is public: anyone who can
choose a session id can compute it with `sampled?/2` and keep their
sessions out of (or in) the sample. A secret salt makes the decision
unpredictable to them; changing the salt reshuffles which sessions are
sampled.

Consequences:

  * the same key (and salt) gets the same decision on every node, after
    every restart and on every replay
  * a lower rate samples a subset of a higher one: `sampled?(key, q)`
    implies `sampled?(key, p)` whenever `q <= p`, so a rule sampling at
    `q` within traces captured at `p` only ever needs captured traces
  * no random number generator is involved

    iex> Nous.Eval.Online.Sampler.sampled?("4bf92f3577b34da6a3ce929d0e0e4736", 1.0)
    true
    iex> Nous.Eval.Online.Sampler.sampled?("4bf92f3577b34da6a3ce929d0e0e4736", 0.0)
    false

# `randomness`

```elixir
@spec randomness(String.t(), binary() | nil) :: non_neg_integer()
```

The 56-bit randomness of `key` (see the moduledoc), salted when `salt` is
a binary.

# `sampled?`

```elixir
@spec sampled?(String.t(), number(), binary() | nil) :: boolean()
```

Whether `key` is sampled at `rate`, salted when `salt` is a binary.

# `threshold`

```elixir
@spec threshold(number()) :: non_neg_integer()
```

The sampling threshold for `rate` (`0.0..1.0`): `trunc(rate * 2^56)`.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
