#65 · Caching and state

Find the bug · #65 · Caching and state Hard Python

The cache throws out what you just used

An LRU cache keeps evicting the pages people use most.

On this page

The report

Bug report

An LRU (least recently used) cache keeps the most-used pages in memory. Monitoring shows the home page, the most visited page of all, is constantly being evicted and rebuilt.

The code

Read it first: what should it do? Then click the line where you think the bug is.

PythonClick the line you think is wrong
from collections import OrderedDict

class LRUCache:
    """Keeps the `capacity` most recently used items; evicts the least recently used."""
    def __init__(self, capacity):
        self.capacity = capacity
        self.items = OrderedDict()

    def get(self, key):
        return self.items.get(key)

    def put(self, key, value):
        self.items[key] = value
        self.items.move_to_end(key)
        if len(self.items) > self.capacity:
            self.items.popitem(last=False)

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
cache = LRUCache(2)
cache.put("home", "<home page>")
cache.put("cart", "<cart page>")
cache.get("home")
cache.put("deals", "<deals page>")
print(list(cache.items))

It prints

['cart', 'deals']

It should print

['home', 'deals']
Show the answer: the bug, the fix, and how you’d find it

The bug (line 10)

Line 10 returns the item but doesn’t mark it as recently used. The cache’s order only changes on put, so it evicts the item that was written longest ago, even if it was read a moment ago. A popular page that is read constantly but rarely rewritten is exactly what gets thrown out. get must move the key to the end.

The fix

7        self.items = OrderedDict()8 9    def get(self, key):10        return self.items.get(key)10        if key not in self.items:11            return None12        self.items.move_to_end(key)13        return self.items[key]11 12    def put(self, key, value):13        self.items[key] = value

How you’d find it

  1. Reproduce: put home, put cart, read home, put deals. Home is evicted, though it was just used.
  2. Print the order after the read: home is still first, the “oldest”. So reading doesn’t update recency.
  3. Compare get with put: only put calls move_to_end.

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

c = LRUCache(2)
c.put("a", 1)
c.put("b", 2)
assert c.get("a") == 1
c.put("c", 3)
assert c.get("a") == 1
assert c.get("b") is None

Where else this bites

  • LeetCode’s LRU Cache problem: exactly this, in any language.
  • Java’s LinkedHashMap needs accessOrder = true to act as an LRU.
Your progress stays on this device.