Search RU
Tasks / Logs / PII masking and sampling without losing errors
Statement hard

PII masking and sampling without losing errors

`prepare_logs(records, *, sample_rate)` prepares log records for shipping: it
masks PII and thins out ordinary records without dropping errors.

A record is a dict with the fields:

- `level` — a non-empty string (`"ERROR"`, `"INFO"`, ...), compared
case-insensitively;
- `request_id` — a non-empty string; required for non-`ERROR` records;
- `message` and any other values may contain PII.

Masking applies to every string value recursively, including nested dicts and
lists:

- email `ann.lee@example.com` → `a***@example.com` (first character of the local
part, domain unchanged);
- phone `+7 (999) 123-45-67` or `8-999-123-45-67` → `***4567`;
- card `1234 5678 9012 3456` or `1234567890123456` →
`**** **** **** 3456`.

Order matters: card first, then phone, then email.

Sampling:

- records with `level == "ERROR"` (case-insensitive) are always kept,
`request_id` is not required for them;
- other records are kept when
`int.from_bytes(sha256(request_id.encode()).digest()[:4], "big") / 2**32 < sample_rate`;
- `sample_rate=0` keeps only errors, `sample_rate=1` keeps everything;
- the same `request_id` gives the same decision on every run.

The function returns a new list of new dicts; the input is not mutated. Record
order is preserved.

Errors:

- `sample_rate` is not a number or is outside `[0, 1]` — `ValueError`;
- a record is not a dict, `level` is empty or not a string — `ValueError`;
- a non-`ERROR` record has no `request_id` — `ValueError`.

Write tests for: an error at zero sampling, the boundaries 0 and 1, a
deterministic set for a middle rate, email/phone/card masking in nested fields,
input immutability, and configuration errors.

logspiisamplingobservabilityprivacy
test_solution.py Python 3.14
AI mentor

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 ask
Hints 1 of 3 unlocked · attempts: 0
Hint 1

Why can't errors be thinned out together with ordinary logs, and why must
masking cover more than `message`?

Hint 2 — unlocks after 1 attempt
Hint 3 — unlocks after 3 attempts