23LRU cache, then make it survive a crash

hardpython
60:00

23 LRU cache, then make it survive a crash

Anthropic candidates report an LRU cache round that comes in parts. First a key for a function and its arguments, with the cache used the way functools.lru_cache is (2 reports), in one report starting from a given cache that mishandled *args and **kwargs (1 report). Then getting the cache back after a crash: candidates describe a write-ahead log, and one was handed a file path, had to write to disk on every append, and lost time working out how to split the file back into records (2 reports). Others were asked how to make it persistent (1 report) and what the serialization tradeoffs are (1 report). The plain LRU cache is on Netflix's and OpenAI's LeetCode tag lists (2 sources) and in a Netflix senior loop (1 report). This is practice in that shape, not a leaked question.

Set a 60-minute timer. Read one level at a time, and run only that level's tests until they pass: pytest problems/23_lru_persistent -k level1. Earlier levels must keep passing.

Level 1. LRUCache(capacity) holds at most capacity entries, and a capacity below 1 raises ValueError. get(key, default=None) returns the value and makes key the most recent, or returns default and changes nothing. put(key, value) inserts or updates, and makes key the most recent. When a new key overflows the cache, the least recent entry goes. Updating a key never evicts. items() returns a list of (key, value) pairs, least recent first, and len(cache) counts the entries. OrderedDict is fine here, but be ready to build the hash map plus doubly linked list version when an interviewer asks for it.

Level 2. make_key(args, kwargs) turns one call's positional tuple and keyword dict into a hashable key. Arguments are JSON-style data: None, bools, numbers, strings, and lists and dicts (with string keys) nested to any depth.

  • Same call, same key: equal positional arguments in the same order, and equal keyword arguments in any order. Two dicts with the same items are equal whatever order their keys are in, at any depth.
  • Different calls, different keys. f(1, 2) and f(1, b=2) are different calls, and so are f(["b", 2]) and f(b=2). A dict is never the same argument as a list of its pairs.

CachedFunction(func, capacity) is called like func. A hit returns the cached result without calling func. A miss calls func once and caches what it returns, None included. If func raises, nothing is cached and the exception reaches the caller.

Level 3. CachedFunction(func, capacity, path) keeps a log at path so the cache survives a crash. Every call that returns appends exactly one record, a line ending in a newline, and flushes it before the call returns. A miss records the key and the result. A hit records the key, because a hit changes which entry is most recent. A call where func raises caches nothing, so it writes nothing. path can be a string or a pathlib.Path. The tests crash a cache by opening a new CachedFunction on the same path and never closing the old one. The new one replays the log: same entries, same recency order, and no calls to func for them. Results are JSON-style values, and strings can hold newlines and tabs. Opening a log leaves its records as they are.

Level 4. Crashes in the middle of a write, and a log that grows forever.

  • A crash can cut the last write short, leaving a final line with no newline. Loading ignores that partial line and cuts it off the file, so the next record starts on a line of its own.
  • compact() rewrites the log as one record per cached entry, least recent first. Write the new log to a temporary file and swap it in with os.replace, so a crash during compaction leaves the old log or the new one, never half of each. One test stands in for os.replace to cut the power just before the swap, so call it by that name. Records written after a compaction must survive a restart.
  • With max_records, a call that leaves the log holding more than max_records records compacts it. Records already in the file when it was opened count.

Be ready to talk through the choices. Pickle stores any object, but its bytes make a poor key, and loading a file you don't trust can run code. JSON is safe and readable, and sorted keys give the same call the same text, but it has no tuples, sets or non-string dict keys. flush gets a record past a crash of the process. os.fsync asks the system to put it on the disk, which is what a crash of the machine needs, and costs you on every call. On macOS that call only hands the data to the drive: the full flush there is fcntl.F_FULLFSYNC, and it costs far more. A disk write on every hit isn't free either: what would you trade for it? And what changes when two processes share one log?

solution.py
Run the tests to see which pass.