Fix the stale read check for a cache layer
Your task
An agent wrote the cache invalidation layer for a busy Go service. Coherency bugs rarely show up in unit tests, so you ship a shadow check: on reads, compare what the cache served with the source of truth, and report every mismatch as a metric. To test that check, you replay recorded traces through a model of the cache.
An assistant wrote stale_read_indexes(events). It is in the editor. It has a bug. Find it and fix it.
Input and output:
events: the trace, one event per string:write <key> <value>,invalidate <key>orread <key>.- Return the indexes of the reads that served a stale value, in increasing order.
Rules the tests check:
- Split each event on single spaces. The first part is the verb. Ignore an event with any other verb, a
writewith fewer than 3 parts, and aninvalidateorreadwith fewer than 2. Extra parts are ignored. writesets the key's value in the source of truth. It does not touch the cache.invalidateremoves the key from the cache, if it is there.read: the current value is the key's value in the source of truth, or""if it was never written. If the cache holds the key, the read serves the cached value. Otherwise it serves the current value and stores it in the cache.- A read is stale when the value it served differs from the current value. Report every stale read, including repeated ones on the same key.
Examples
stale_read_indexes(events: list[str]) -> list[int]Example 1
Input
stale_read_indexes(["write k1 v1", "read k1", "write k1 v2", "read k1"])Output
[3]Example 2
Input
stale_read_indexes(["write k1 v1", "read k1", "write k1 v2", "invalidate k1", "read k1"])Output
[]Example 3
Input
stale_read_indexes(["write a v1", "write b v1", "read a", "read b", "write a v2", "write b v2", "invalidate a", "read a", "read b"])Output
[8]