Bounded TTL Cache
A debugging task on a small Go cache with a time to live, a background sweeper and a capacity bound. Six of the nine supplied tests fail, and they fall into three families: the expiry boundary, a sweeper that races and never stops, and eviction that was never written.
On this page
The codebase
The package is an in-memory key/value store. Every entry has a time to live read from an injected clock, a background goroutine sweeps expired entries, and a capacity bound must evict the least recently used entry. An HTTP handler sits on top of it.
The nine visible tests run with the race detector, and Test stops at the first failure. Verification after Submit adds five hidden tests.
The assistant explains the code and Go on request and makes the changes you direct. 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.goSet, Get, Delete, Len, Sweep, Close and the eviction stub: where the expiry rule, the lock and the recency order live.src/sweeper.goThe background goroutine that calls into the cache on a ticker.src/handler.goThe HTTP handler over the cache. Its behaviour must stay as shipped.tests/The visible tests, read-only: the cache, the handler and the race test.Rules that shape every fix
- Keep the handler's behaviour and the exported API.
- Go 1.23, standard library only: no module can be added.
- Every method is safe for concurrent use, and nothing in the package sleeps to order goroutines.
How to work the fix
- Press Test first and read the failure, then read the cache and the sweeper against the task's rules.
- Name each failing family and its cause before you ask for any change.
- Decide the design yourself: one lock for the map and the recency order, a list plus map for constant-time recency, and a Close that stops, waits and can be called twice.
- Give the cases that must hold afterwards, each with its expected result, and press Test after the change.
- Ask the assistant to trace named cases through the final code, then Submit.
Fix the cache
What the ticket asks
Six of the nine supplied tests fail on the shipped cache. Find out why, fix the package, and finish the capacity bound with least-recently-used eviction.
Keep the handler's behaviour as it is, and keep to the standard library.
Where to look
src/cache.goGet and Sweep decide expiry, Set computes the expiry time, and the eviction is an empty stub.src/sweeper.goThe goroutine reads the map without the lock and never looks at the stop channel.tests/race_test.goEight workers call Set, Get and Sweep while the sweeper runs: the race detector names the unlocked read.What the tests pin down
Where the shipped cache goes wrong
- Get and Sweep treat an entry as expired only after its expiry time, so it is still returned at that instant, and Set gives a time to live of zero an expiry time, so it expires at once.
- The sweeper ranges over the map without the cache's lock while Set and Get write it, and Close closes the stop channel that nothing reads, waits for nothing, never closes Done and panics when called twice.
- Eviction is a stub and nothing records recency, so the capacity is never enforced.
The fix
- An entry is live only while the clock is before its expiry time, and a zero expiry time means it never expires.
- One mutex guards a map of keys to list elements and a list in recency order: a hit or a replace moves the entry to the front, and a new key evicts from the back.
- The sweeper waits on the stop channel or the ticker and calls Sweep, which takes the lock.
- Close runs once: it marks the cache closed under the lock, closes the stop channel, waits for the sweeper and closes Done.
src/cache.goExpiry is decided with Before, and a time to live of zero or less keeps the zero expiry time.- expiresAt := time.Time{}- if ttl >= 0 {+ var expiresAt time.Time+ if ttl > 0 { expiresAt = c.opts.Now().Add(ttl) }src/cache.goRecency is a list in front of the map: a replace moves the entry to the front, and a new key evicts from the back while the cache is full.- if e, ok := c.items[key]; ok {- e.value = value- e.expiresAt = expiresAt+ if el, ok := c.items[key]; ok {+ e := el.Value.(*entry)+ e.value, e.expiresAt = value, expiresAt+ c.order.MoveToFront(el) return }- c.evict()- c.items[key] = &entry{value: value, expiresAt: expiresAt}+ for c.opts.Capacity > 0 && len(c.items) >= c.opts.Capacity {+ c.removeElement(c.order.Back())+ }+ c.items[key] = c.order.PushFront(&entry{key: key, value: value, expiresAt: expiresAt})src/sweeper.goThe sweeper stops on the stop channel and sweeps through the locked Sweep.- for range ticker.C {- now := c.opts.Now()- for key, e := range c.items {+ for {+ select {+ case <-c.stop:+ return+ case <-ticker.C:+ c.Sweep() } }src/cache.goClose runs once, waits for the sweeper and closes Done. func (c *Cache) Close() {- c.mu.Lock()- c.closed = true- c.mu.Unlock()- close(c.stop)+ c.once.Do(func() {+ c.mu.Lock()+ c.closed = true+ c.mu.Unlock()+ close(c.stop)+ c.sweeper.Wait()+ close(c.done)+ }) }Tests that prove it
- The expiry boundary one tick before and exactly at the expiry time, and a time to live of zero that is still readable after a long advance.
- Capacity two evicting the least recently used key, a Get hit protecting a key, and a replace that keeps one slot.
- Close twice, Done closed, and Get and Set after Close.
- Eight workers against the running sweeper with the race detector on, and a hidden stress test of Sweep and Close together.
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 expiry boundary: the entry is still returned at exactly its expiry time.
- Press Test. All nine visible tests pass with the race detector after the change.
- Verification: Run after last change, 6 points
- Submit. The stage closes. Scope, the fourteen visible and 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.