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

Test it against a brute-force version too simple to be wrong

A brute-force version keeps a plain list, filters out expired entries before it does anything, and finds keys by scanning. It's slow and obviously right. Run both on the same random calls and compare every answer:

import random


def brute_force(capacity, clock):
    # [key, value, expires_at], least recent first
    items = []

    def live():
        items[:] = [it for it in items if it[2] is None or clock() < it[2]]

    def get(key, default=None):
        live()
        for i, it in enumerate(items):
            if it[0] == key:
                items.append(items.pop(i))
                return it[1]
        return default

    def put(key, value, ttl=None):
        new = [key, value, None if ttl is None else clock() + ttl]
        for i, it in enumerate(items):
            if it[0] == key:
                items.pop(i)
                items.append(new)
                return None
        live()
        evicted = items.pop(0)[0] if len(items) >= capacity else None
        items.append(new)
        return evicted

    return get, put


mismatches = 0
for seed in range(300):
    rng, clock = random.Random(seed), FakeClock()
    capacity = rng.choice([1, 2, 3, 5])
    cache, (get, put) = TTLCache(capacity, clock=clock), brute_force(capacity, clock)
    for step in range(200):
        clock.now += rng.choice([0, 0, 1, 2])
        key, ttl = rng.choice("abcdefg"), rng.choice([None, 1, 2, 5, 10])
        if rng.random() < 0.5:
            same = cache.put(key, step, ttl=ttl) == put(key, step, ttl=ttl)
        else:
            same = cache.get(key, "miss") == get(key, "miss")
        cache.check()
        if not same:
            mismatches += 1
            break
print("seeds with a mismatch:", mismatches)

It printed seeds with a mismatch: 0. To be sure the comparison can fail, break one line at a time and run it again:

Predict

Break one line at a time. Which bug did the random test catch in all 300 seeds?

Pick an answer above to see the rest