Recency Cache
Four stages on a small generic Go cache that forgets the least recently used entry: make reads count as a use, enforce the capacity in constant time, add a resize, then make it safe for many goroutines with one load per missing key. Each stage's supplied test fails on the code you start it with.
On this page
The codebase
The package is a bounded key/value cache. It starts as a map plus a slice that records the order of use, and each stage adds a rule and, from stage 3, a file.
Each stage adds a read-only test file that fails on the code you start with, and hidden tests that run after Continue or Submit. Tests run with the race detector, and Test stops at the first failure.
The assistant explains the code and Go on request and makes the changes you direct; it does not see the stage's question, so its rules are yours to give. The session's files are fixed, so a check of your own is a trace or a run you ask the assistant for.
Where things live
src/cache.goThe cache: Get, Put, the order of use and, from stage 2, eviction.src/resize.goAdded in stage 3: Resize.src/concurrent.goAdded in stage 4: the concurrent cache and its loader.tests/The visible tests, read-only: one file per stage.Rules that shape every fix
- Keep the exported API: the types, the methods and their signatures.
- Build on the code you have rather than rewriting the package.
- Go 1.23, standard library only, and no sleep in the package to order goroutines.
How to work each stage
- Press Test at the start of each stage and read the failure.
- Name the cause, give the stage's rules, and decide the structure yourself before you ask for the change.
- Say which cases must hold afterwards, each with its expected result, and press Test after the change.
- Ask the assistant to trace named cases through the code you changed, then Continue, or Submit after the last stage.
Reads count as a use
What the ticket asks
A read must count as a use of the key, as a write does. The supplied test of that fails on the code you start with: find out why and fix it without changing the exported API.
A hit makes the key the most recently used one; a miss changes nothing. The capacity is not part of this stage.
Where to look
src/cache.goGet reads the map and returns, while Put marks the key as recent: compare the two.What the stage pins down
Where the code you start with falls short
- Get never calls the cache's own recency update, so a read leaves the order where the last write put it.
The fix
- Change only Get: on a hit, mark the key as recent with the existing helper; on a miss, return at once and change nothing.
src/cache.goA hit marks the key as recent; nothing else changes. func (c *RecencyCache[K, V]) Get(key K) (V, bool) { value, ok := c.data[key]+ if ok {+ c.markRecent(key)+ } return value, ok }Tests that prove it
- A hit on the oldest key making it the newest, and the oldest key following reads.
- Repeated hits without a duplicate key, and a stored zero value that is still a hit.
- A miss that changes neither the size nor the order, and an empty cache.
The conversation
Only your side is shown: the assistant reads, writes and runs between your messages. Each chip is a rubric item the step earns.
DirectionPrompt qualityVerificationCorrectnessCode quality
- Press Test. Test stops at the recency test: after Get a the order is still c, b, a.
- Press Test. Both visible tests pass after the change.
- Verification: Run after last change, 8 points
- Continue. The stage closes. Scope, the hidden tests and code quality are judged on the stage's final code.
- Direction: Scope, 6 points
- Correctness: Hidden tests, 20 points
- Code quality: Code quality, 10 points
Where the stage lands
Measured when this conversation was played on the platform. A+ needs 92, S needs 95.
A capacity in constant time
What the ticket asks
Put must keep the cache within its capacity: storing a new key in a full cache evicts the least recently used entry first, and replacing a stored value evicts nothing.
Get and Put take constant time on average, whatever the capacity.
Where to look
src/cache.goPut stores and marks the key but never evicts, and every recency update scans the slice.What the stage pins down
Where the code you start with falls short
- Put has no eviction at all, so the size grows past the capacity.
- The order is a slice that is scanned and shifted on every use, so each operation is linear in the size.
The fix
- Replace the slice with a map of keys to elements of a doubly linked list, the front the newest.
- A replace moves the element to the front; a new key into a full cache first removes the back element from both the list and the map, in one helper.
src/cache.goThe map holds list elements, and the list keeps the order. type RecencyCache[K comparable, V any] struct { capacity int- data map[K]V- // recency lists the stored keys, least recently used first.- recency []K+ data map[K]*list.Element+ // recency holds the entries, most recently used at the front.+ recency *list.List }src/cache.goPut replaces in place, or evicts the oldest before it stores a new key. func (c *RecencyCache[K, V]) Put(key K, value V) {- c.data[key] = value- c.markRecent(key)+ if element, ok := c.data[key]; ok {+ element.Value.(*entry[K, V]).value = value+ c.recency.MoveToFront(element)+ return+ }+ if len(c.data) >= c.capacity {+ c.evictOldest()+ }+ c.data[key] = c.recency.PushFront(&entry[K, V]{key: key, value: value}) }Tests that prove it
- A full cache evicting exactly one entry, capacity one, and an evicted key coming back.
- Updates at capacity evicting nothing, also for a newer key.
- A random sequence of operations checked against a model at four capacities.
The conversation
Only your side is shown: the assistant reads, writes and runs between your messages. Each chip is a rubric item the step earns.
DirectionPrompt qualityVerificationCorrectnessCode quality
- Press Test. Test stops at the eviction test: b is still stored after c arrives in a full cache.
- Press Test. All four visible tests pass after the change.
- Verification: Run after last change, 6 points
- Continue. The stage closes. Scope, the hidden tests and code quality are judged on the stage's final code.
- Direction: Scope, 6 points
- Correctness: Hidden tests, 20 points
- Code quality: Code quality, 10 points
Where the stage lands
Measured when this conversation was played on the platform. A+ needs 92, S needs 95.
Resize without surprises
What the ticket asks
Implement Resize, which this stage added as a stub: an invalid capacity is refused and changes nothing; otherwise the capacity is set and the least recently used entries leave until the cache fits.
Resizing is not a use of any key, and growing evicts nothing.
Where to look
src/resize.goThe stub returns an error for every call.src/cache.goThe eviction helper from stage 2 is the one place an entry leaves.What the stage pins down
Where the code you start with falls short
- Resize is a stub, so every call fails, the valid ones included.
The fix
- Check the capacity first and return before any change.
- Set the capacity and evict through the same helper Put uses while the cache is over it.
src/resize.goValidate first, then evict through the shared helper. func (c *RecencyCache[K, V]) Resize(capacity int) error {- return errors.New("recency: Resize is not implemented")+ if capacity < 1 {+ return ErrInvalidCapacity+ }+ c.capacity = capacity+ for len(c.data) > c.capacity {+ c.evictOldest()+ }+ return nil }Tests that prove it
- A refused resize that changes nothing, and a resize of an empty cache.
- Shrinking that keeps the newest entries in order, shrinking to exactly the size, and shrink, grow and Put together.
- Growing then filling, and a resize that never refreshes recency.
The conversation
Only your side is shown: the assistant reads, writes and runs between your messages. Each chip is a rubric item the step earns.
DirectionPrompt qualityVerificationCorrectnessCode quality
- Press Test. Test stops at the shrink test: Resize returns its not-implemented error.
- Press Test. All six visible tests pass after the change.
- Verification: Run after last change, 6 points
- Continue. The stage closes. Scope, the hidden tests and code quality are judged on the stage's final code.
- Direction: Scope, 6 points
- Correctness: Hidden tests, 20 points
- Code quality: Code quality, 10 points
Where the stage lands
Measured when this conversation was played on the platform. A+ needs 92, S needs 95.
Concurrent loading
What the ticket asks
Implement the concurrent cache this stage added as a stub: every method is safe for many goroutines at once, and a missing value is loaded once per key and shared by every caller that waits for it.
A failed load stores nothing and its error reaches every waiter; a load holds up only its own key; nothing in the package sleeps to order goroutines.
Where to look
src/concurrent.goThe type embeds the plain cache, so its methods are promoted with no lock, and the loader is a stub.tests/concurrent_test.goEight goroutines missing the same key at once, and a slow load beside a cached key.What the stage pins down
Where the code you start with falls short
- The embedding promotes Get, Put, Resize and the rest with no lock, and Get moves the entry, so even a read lock would be wrong.
- The loader is a stub, so nothing loads, shares or reports an error.
The fix
- Replace the embedding with a private field, and give every method its own body that takes one mutex.
- Keep a map of in-flight loads per key with a done channel, the value and the error: waiters release the lock and wait on the channel.
- Run the load with no lock held, then store the value only on success, remove the record on every path and close the channel.
src/concurrent.goA private cache field, one mutex and a map of in-flight loads. type ConcurrentRecencyCache[K comparable, V any] struct {- *RecencyCache[K, V]- mu sync.Mutex+ mu sync.Mutex+ cache *RecencyCache[K, V]+ inflight map[K]*loadCall[V] }src/concurrent.goOne load per key, run with the lock released, shared through the call's channel.+ if call, ok := c.inflight[key]; ok {+ c.mu.Unlock()+ <-call.done+ return call.value, call.err+ }+ call := &loadCall[V]{done: make(chan struct{})}+ c.inflight[key] = call+ c.mu.Unlock()++ call.value, call.err = load()++ c.mu.Lock()+ delete(c.inflight, key)+ if call.err == nil {+ c.cache.Put(key, call.value)+ }+ c.mu.Unlock()+ close(call.done)+ return call.value, call.errTests that prove it
- One load for many concurrent misses over several rounds, hits that never load, and nil and zero results that are cached.
- A failed load whose error is shared and not cached, with the next call loading again.
- Loads of different keys overlapping, a slow load beside other keys, a load that calls the cache, and a mixed stress run under the race detector.
The conversation
Only your side is shown: the assistant reads, writes and runs between your messages. Each chip is a rubric item the step earns.
DirectionPrompt qualityVerificationCorrectnessCode quality
- Press Test. Test stops at the concurrent-miss test: the loader is still the stub.
- Press Test. All eight visible tests pass with the race detector after the change.
- Verification: Run after last change, 5 points
- Submit. The last stage closes. Scope, the hidden tests and code quality are judged on the final code.
- Direction: Scope, 6 points
- Correctness: Hidden tests, 20 points
- Code quality: Code quality, 10 points
Where the stage lands
Measured when this conversation was played on the platform. A+ needs 92, S needs 95.