A new key in a full cache sweeps first, and evicts only if it's still full
Capacity 2. At time 0, put("a", 1, ttl=100), then put("b", 2, ttl=5). At time 10, put("c", 3):
| Step | Stored, oldest use first |
|---|---|
| before | a (expires at 100), b (expires at 5): full |
1. purge() | a (expires at 100): b expired at 5 |
| 2. still full? | no, so nothing live is evicted |
| 3. store c | a (expires at 100), c (never): put returns None |
The rule for a put of a new key into a full cache is sweep first, then evict. An expired entry still takes a slot until something removes it. Expired entries are dead weight, so they all go before anything live. Only if the cache is still full does the least recently used entry go.
When it does evict, it goes by last use, not by expiry. The least recently used entry goes even when another live entry expires sooner.
A put of a key that's already stored never evicts, expired or not. A get that finds a live entry moves it to the newest end, the same as before.
The heap may hold extra entries, but it must never miss a real one
The invariants grow by one:
len(entries) <= capacity.- The
OrderedDictis in order of last use. - Every stored entry with an
expires_athas a heap entry with the same key and time. The heap can hold extra, stale entries. It must never miss a real one, or that entry is never swept.
The third is what lets len(cache) count only live entries without walking them: purge first, and whatever is still stored is live.
The editor holds TTLCache with a capacity, and its purge and get are done. Fill in the two gaps in put: sweep, then evict if it's still full, and make the key the newest.