Hot/warm/cold/delete retention policy
Implement a log lifecycle retention policy.
`apply_retention(records, now, policy)` assigns records to the
`hot`/`warm`/`cold`/`delete` tiers and computes the stored volume and cost.
A record is a dict:
- `id` — a non-empty string;
- `log_type` — a non-empty string, must be a key of `policy["types"]`;
- `level` — a non-empty string; `ERROR` is compared case-insensitively;
- `ts` — an aware `datetime`;
- `size_bytes` — an integer `>= 0`, `bool` is not accepted;
- every other field is preserved.
Policy:
```python
{
"hot_days": 7,
"warm_days": 30,
"cold_days": 90,
"error_extra_days": 30,
"types": {
"app": {},
"access": {"hot_days": 3, "warm_days": 14, "cold_days": 30},
"audit": {"hot_days": 30, "warm_days": 180, "cold_days": 365},
},
"rates": {"hot": 2.0, "warm": 0.5, "cold": 0.25},
}
```
- `hot_days`, `warm_days`, `cold_days` are the defaults;
- a type may override any of the three; the rest come from the defaults;
- every type must satisfy `0 <= hot_days < warm_days < cold_days`;
- `error_extra_days` is added to all three boundaries when
`level.upper() == "ERROR"`;
- `rates` is the price per GiB per month for each tier.
Age: `age_days = (now - ts).total_seconds() / 86400`.
Tier:
- `age_days < hot` — `hot`;
- `age_days < warm` — `warm`;
- `age_days < cold` — `cold`;
- otherwise — `delete`.
That is, exactly at a boundary the record moves to the next tier, and exactly
at `cold` it is deleted.
Cost:
- `bytes` — the sum of `size_bytes` per tier, including `deleted`;
- `cost_kopeks` — the monthly hot/warm/cold cost in kopecks:
`sum(size_bytes * rate)` over the three tiers, divided by `2**30` and
multiplied by 100, rounded **up** to a whole kopeck; `delete` is free;
- compute with `Decimal`, not with float.
Result:
```python
{
"records": [{"id": "...", "tier": "hot", ...}],
"bytes": {"hot": int, "warm": int, "cold": int, "deleted": int},
"cost_kopeks": int,
}
```
Record order is preserved, the input is not mutated, and the result contains
copies of the dicts with an added `tier`.
Errors — `RetentionError`, a subclass of `ValueError`:
- `now` is not an aware `datetime`;
- `ts` is not an aware `datetime`, or is later than `now` (negative age);
- unknown `log_type`;
- a malformed record or policy: types, negative values, a broken
`hot < warm < cold`, an unknown key in a type override, a missing rate, or
`NaN`/`inf` in a rate.
An empty record list returns a zero plan, but the policy is still validated.
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
Why does a record exactly at a boundary move to the next tier, and why is a
future `ts` an error rather than a negative age?