Sampling plan and log storage cost estimate
`plan_sampling(events, rate, keep_errors=True)` builds a log sampling plan and
estimates the stored volume and its cost.
An event is a dict with the fields:
- `level` — a non-empty string; `ERROR` is compared case-insensitively;
- `request_id` — a non-empty string, required for every event;
- `size_bytes` — a non-negative integer number of bytes;
- every other field is preserved unchanged.
Selection:
- an `ERROR` event is always kept when `keep_errors=True`;
- other events, and errors when `keep_errors=False`, are kept when
`bucket(request_id) < rate`, where `bucket` is the first 4 bytes of
`sha256(request_id.encode("utf-8"))` read as big-endian and divided by
`2**32`;
- `rate=0` with `keep_errors=True` keeps only errors, `rate=1` keeps everything;
- event order is preserved, the input list and dicts are not mutated;
- `kept` contains copies of the dicts, not the original objects.
Volume estimate:
- `kept_bytes` — the sum of `size_bytes` over kept events;
- `guaranteed_bytes` — the sum of `size_bytes` over errors that bypassed
sampling (`keep_errors=True`);
- `sampled_bytes = kept_bytes - guaranteed_bytes`;
- `estimated_bytes = guaranteed_bytes + ceil(sampled_bytes / rate)` when
`rate > 0`, otherwise `guaranteed_bytes`.
The cost uses the training tariff `2 RUB per GiB per month`
(`GIB = 2**30`) and rounds **up** to the next kopeck:
```
estimated_cost = ceil(estimated_bytes / GIB * 2.0 * 100) / 100
```
The function returns a dict:
```python
{
"kept": [...],
"total_events": int,
"kept_events": int,
"kept_bytes": int,
"estimated_bytes": int,
"estimated_cost": float,
}
```
Errors — `ValueError`:
- `rate` is not a number, is a `bool`, or is outside `[0, 1]`;
- `keep_errors` is not a `bool`;
- `events` is not a list or a tuple;
- an event is not a dict;
- `level` is empty or not a string;
- `request_id` is empty or not a string;
- `size_bytes` is missing, not an integer, a `bool`, or negative.
Write tests for: the deterministic hash-based sample, errors at `rate=0`,
`keep_errors=False`, the boundaries `0` and `1`, empty input, rounding the
estimate up, errors not being scaled, cost on a kopeck boundary, input
immutability, and validation.
The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.
Log in and askHint 1
Почему ошибки нельзя делить на `rate` вместе с обычными событиями, и почему
стоимость округляют вверх, а не по правилам математики?