Design an LRU cache
medium 85 minDesign an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.
Watch lesson4:49
Testing
A slow twin, unlucky orders, and stress
The point: the best test of a clever structure is a stupid one that does the same. Run both with random calls and compare after every step.
The slow twin
import randomfrom collections import OrderedDictclass Naive: # so simple that it is obviously right def __init__(self, capacity): self.capacity, self.pairs = capacity, [] # front is most recent def get(self, key): for pair in self.pairs: if pair[0] == key: self.pairs.remove(pair) self.pairs.insert(0, pair) return pair[1] return None def put(self, key, value): self.pairs = [p for p in self.pairs if p[0] != key] self.pairs.insert(0, (key, value)) del self.pairs[self.capacity:] def keys(self): return [k for k, _ in self.pairs]class Fast: # put your own class here def __init__(self, capacity): self.capacity, self.data = capacity, OrderedDict() def get(self, key): if key not in self.data: return None self.data.move_to_end(key) return self.data[key] def put(self, key, value): if key in self.data: self.data.move_to_end(key) elif len(self.data) == self.capacity: self.data.popitem(last=False) self.data[key] = value def keys(self): return list(reversed(self.data))for seed in range(200): rng = random.Random(seed) # a failure can be repeated capacity = rng.randint(1, 4) naive, fast = Naive(capacity), Fast(capacity) for step in range(200): key = rng.randint(0, 5) # few keys: hits, updates and evictions all happen if rng.random() < 0.5: assert naive.get(key) == fast.get(key), (seed, step) else: naive.put(key, step) fast.put(key, step) assert naive.keys() == fast.keys(), (seed, step)print("40,000 steps agree")Would the tests notice?
| Break this on purpose | Found by |
|---|---|
| Remove the touch in get | The twin, within a few steps |
| Remove the touch in the update branch | The twin |
| Forget to delete the map entry | check, at the first eviction |
| Swap the last two lines of push_front | check, or a hang: run tests with a time limit |
| Ask full before known | The twin, on an update of a full cache |
> instead of >= or == | check, size above capacity |
Time without waiting
class Clock: def __init__(self): self.t = 0 def __call__(self): return self.tdef alive(written, ttl, now): return now < written + ttlclock = Clock()for moment, expected in [(0, True), (9, True), (10, False), (11, False)]: clock.t = moment assert alive(0, 10, clock()) == expected, momentprint("the edge is tested, and no test slept")The unlucky order, on purpose
A race does not appear because you run a test often. The generators on the pages One lock and Concurrent map play the bad order every time. Do the same for your own fix: put a hook between the lookup and the touch, let the test evict there, and assert that no ghost appears.
Then stress
import sysfrom collections import OrderedDictfrom threading import Barrier, Lock, Threadclass LockedLru: def __init__(self, capacity): self.capacity, self.data, self.lock = capacity, OrderedDict(), Lock() def get(self, key): with self.lock: if key not in self.data: return None self.data.move_to_end(key) return self.data[key] def put(self, key, value): with self.lock: if key in self.data: self.data.move_to_end(key) elif len(self.data) == self.capacity: self.data.popitem(last=False) self.data[key] = valuesys.setswitchinterval(1e-6) # switch threads as often as possiblecache, errors, start = LockedLru(8), [], Barrier(8)def work(me): start.wait() # all at once for i in range(3000): key = (me + i) % 16 cache.put(key, (key, me, i)) seen = cache.get((key + 5) % 16) if seen is not None and seen[0] != (key + 5) % 16: errors.append(seen) # a value of another keythreads = [Thread(target=work, args=(n,)) for n in range(8)]for t in threads: t.start()for t in threads: t.join()print("errors", errors, "size", len(cache.data)) # errors [] size 8Five things worth a test under threads
- 1
Never above capacity
Sample the size while others write.
- 2
No foreign values
The value of key k always says k.
- 3
One load for each key
Count calls of the loader, with a loader that waits for a signal.
- 4
A failing load frees the key
First call fails, second succeeds, nobody hangs.
- 5
A listener that calls back
With a timeout, because the bug is a hang.
How do you show that your cache is thread-safe?
BreaksRun it with many threads, no error
- How
- It passed a hundred times.
- Limit
- The bad order may need a pause of microseconds.
- Choose when
- Never alone.
WorksArgue from the lock
- How
- Every access to map and list is inside one private lock.
- Limit
- Only as good as the reading.
- Choose when
- One lock: this is a full proof.
StrongArgue, force the known bad orders, then stress with checks
- How
- Invariants inside the lock, seeds, time limits.
- Limit
- Work.
- Choose when
- Anything cleverer than one lock.