26/37
Part 5 of 6 · Both limitsLearn and do

State the costs, then write it

Say the class in a minute:

  • put(key, value, ttl=None) returns the evicted key or None. It costs O(log n) for the heap push, plus an occasional sweep.
  • get(key, default=None) is O(1) on average.
  • purge() is O(k log n) for the k heap entries it pops.
  • len(cache) sweeps, then counts.

The invariants are the three above. Then write it:

import heapq
import itertools
import time
from collections import OrderedDict


class TTLCache:
    def __init__(self, capacity, default_ttl=None, clock=time.monotonic):
        if capacity < 1:
            raise ValueError("capacity must be at least 1")
        if default_ttl is not None and default_ttl <= 0:
            raise ValueError("default_ttl must be positive")
        self.capacity, self.default_ttl, self.clock = capacity, default_ttl, clock
        # key -> (value, expires_at), least recently used first
        self.entries = OrderedDict()
        # (expires_at, count, key), soonest first
        self.heap = []
        # breaks ties, so two keys are never compared
        self.count = itertools.count()

    def get(self, key, default=None):
        entry = self.entries.get(key)
        if entry is None:
            return default
        value, expires_at = entry
        if expires_at is not None and self.clock() >= expires_at:
            # lazy expiry: a read that finds it dead drops it
            del self.entries[key]
            return default
        # a hit is a use
        self.entries.move_to_end(key)
        return value

    def put(self, key, value, ttl=None):
        ttl = self.default_ttl if ttl is None else ttl
        if ttl is not None and ttl <= 0:
            raise ValueError("ttl must be positive")
        now, evicted = self.clock(), None
        if key not in self.entries and len(self.entries) >= self.capacity:
            # the expired go first: they're dead anyway
            self.purge()
            if len(self.entries) >= self.capacity:
                evicted, _ = self.entries.popitem(last=False)
        expires_at = None if ttl is None else now + ttl
        self.entries[key] = (value, expires_at)
        self.entries.move_to_end(key)
        if expires_at is not None:
            heapq.heappush(self.heap, (expires_at, next(self.count), key))
        return evicted

    def purge(self):
        now, removed = self.clock(), 0
        while self.heap and self.heap[0][0] <= now:
            expires_at, _, key = heapq.heappop(self.heap)
            entry = self.entries.get(key)
            # skip stale heap entries
            if entry is not None and entry[1] == expires_at:
                del self.entries[key]
                removed += 1
        return removed

    def __len__(self):
        self.purge()
        return len(self.entries)

    def check(self):
        assert len(self.entries) <= self.capacity, "more entries than capacity"
        scheduled = {(key, expires_at) for expires_at, _, key in self.heap}
        for key, (_, expires_at) in self.entries.items():
            assert expires_at is None or (key, expires_at) in scheduled, f"{key!r} has no heap entry for its expiry"

A ttl of 0 or less raises before anything is stored, so a bad call leaves the cache as it was.

TTLStore in the editor is a small store with the TTL rules of put above: a default_ttl, and a ttl of 0 or less raises. Its put lets ttl=0 through. Find the line and fix it.