Skip to content
Recommended solution · HC-7 · Go

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

  1. Press Test at the start of each stage and read the failure.
  2. Name the cause, give the stage's rules, and decide the structure yourself before you ask for the change.
  3. Say which cases must hold afterwards, each with its expected result, and press Test after the change.
  4. Ask the assistant to trace named cases through the code you changed, then Continue, or Submit after the last stage.
Stage 1 · 01-read-recency

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

HitsA hit makes the key the newest: the newest-first listing shows it first and the oldest key moves on.
MissesA miss returns the zero value and false, stores nothing and leaves the order as it was.
ExampleCapacity 3, Put a, b, c, then Get a: the newest-first order is a, c, b.

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

  1. 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

  1. Press Test. Test stops at the recency test: after Get a the order is still c, b, a.
  2. Your message 1

    Test fails at TestGetRefreshesRecency: for "capacity 3; Put a, b, c; Get a; EntriesNewestFirst" it expected ["a","c","b"] and got ["c","b","a"]. Get reads c.data but never calls markRecent, so a read does not count as a use and the order stays [c b a]. Change only Get: on a hit call c.markRecent(key) and return the value; on a miss return the zero value and false and change nothing, no insert and no reorder. Keep the storage, Put and markRecent as they are. Afterwards: capacity 3, Put a, b, c, Get a gives [a c b] and OldestKey b; Get zzz on [c b a] returns (0, false) and leaves Len 3 and the order unchanged.

    Name the failing test, its values and the line that causes it, then ask for the smallest fix and say what a miss must not do.

    • Direction: Diagnosis, 10 points
    • Direction: Minimal fix, 8 points
    • Direction: Miss rule, 6 points
    • Prompt quality: Named failing test, 6 points
    • Prompt quality: Specified fix, 8 points
    • Prompt quality: Contract examples, 6 points
    • Verification: Named cases, 6 points
  3. Press Test. Both visible tests pass after the change.
    • Verification: Run after last change, 8 points
  4. Your message 2

    Test passes. Trace these cases through the final Get and markRecent step by step, without editing, and say what each line does: (a) Put a, b, c, Get c twice: the order stays [c b a] with no duplicate key; (b) Put a with the value 0, then Get a returns (0, true) and makes a the newest; (c) Get zzz on [c b a] stores nothing and leaves the order.

    The files are fixed, so your own check is a trace of named cases through the code you changed.

    • Verification: Checks own, 6 points
  5. 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.

Direction30/30
Prompt quality20/20
Verification20/20
Correctness20/20
Code quality10/10
Stage total 100/100Grade S
Stage 2 · 02-capacity

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

EvictionOnly a new key in a full cache evicts, exactly one entry, the least recently used, and never the key being stored.
UpdatesReplacing a stored value evicts nothing and makes that key the newest.
CostGet and Put take constant time on average.

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

  1. Replace the slice with a map of keys to elements of a doubly linked list, the front the newest.
  2. 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

  1. Press Test. Test stops at the eviction test: b is still stored after c arrives in a full cache.
  2. Your message 1

    Test fails at TestPutEvictsLeastRecentlyUsed: for "capacity 2; Put a=1, b=2; Get a; Put c=3; Get b" it expected "<miss>" and got "2". Put never evicts, so Len grows past Capacity, and the recency slice makes every use a linear scan. The rules: only storing a new key into a full cache evicts, exactly one entry, the least recently used, before the insert; replacing a stored key's value evicts nothing and makes that key the newest; Get and Put take constant time. The change in src/cache.go: replace the slice with a map[K]*list.Element over container/list, front is the newest, each element holding the key and the value. A Get hit does MoveToFront. Put of a stored key updates the value and does MoveToFront with no eviction. Put of a new key into a full cache first calls one evictOldest helper that removes the back element from both the list and the map, then PushFront. EntriesNewestFirst and OldestKey read the list. Keep the exported API. Afterwards: capacity 2, Put a, b, Get a, Put c leaves a and c and b is gone; capacity 2, Put a, b, Put a=10 evicts nothing and the order is [a b]; capacity 1, Put a, b leaves only b.

    Follow the failing test with the two rules and the structure, decided by you, and the cases that must hold afterwards.

    • Direction: Eviction rule, 8 points
    • Direction: Update rule, 6 points
    • Direction: Constant-time choice, 10 points
    • Prompt quality: Specified eviction, 6 points
    • Prompt quality: Specified update, 4 points
    • Prompt quality: Complexity stated, 5 points
    • Prompt quality: Failure follow-up, 5 points
    • Verification: Named cases: eviction, 5 points
    • Verification: Named cases: update, 4 points
  3. Press Test. All four visible tests pass after the change.
    • Verification: Run after last change, 6 points
  4. Your message 2

    Test passes. Trace through the final Put step by step, without editing: (a) capacity 2, Put a, b, Put a=10: which branch runs, why nothing is evicted, and the order after it; (b) capacity 2, Put a, b, Get a, Put c: which element evictOldest removes from the list and the map.

    The files are fixed, so your own check is a trace of named cases through the code you changed.

    • Verification: Checks own, 5 points
  5. 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.

Direction30/30
Prompt quality20/20
Verification20/20
Correctness20/20
Code quality10/10
Stage total 100/100Grade S
Stage 3 · 03-resize

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

Invalid sizesA capacity below one returns the invalid-capacity error and changes nothing: not the capacity, not the entries, not their order.
ShrinkingThe least recently used entries leave until the size fits, and the rest keep their order.
GrowingNothing is evicted, and later Puts fill the cache up to the new capacity.

Where the code you start with falls short

  • Resize is a stub, so every call fails, the valid ones included.

The fix

  1. Check the capacity first and return before any change.
  2. 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

  1. Press Test. Test stops at the shrink test: Resize returns its not-implemented error.
  2. Your message 1

    Test fails at TestShrinkKeepsMostRecentlyUsed: for "capacity 4; Put a, b, c, d; Get b; Get d; Resize(2) error" it expected "<nil>" and got "recency: Resize is not implemented". Resize is still the stub. The rules: a capacity below 1 returns ErrInvalidCapacity and changes nothing; otherwise set the capacity and evict least recently used entries until Len <= Capacity, keeping the others in their order; growing evicts nothing. Implement it in src/resize.go: if capacity < 1 return ErrInvalidCapacity before touching anything; otherwise set c.capacity and call the same evictOldest helper Put uses while Len() > capacity. No second eviction loop and no MoveToFront: resizing is not a use. Afterwards: capacity 4, Put a, b, c, d, Get b, Get d, Resize(2) returns nil and leaves [d b]; capacity 3 with a, b, c, Resize(0) returns ErrInvalidCapacity and leaves Capacity 3 and [c b a]; capacity 3 with a, b, c, Resize(3) evicts nothing; capacity 2 with a, b, Resize(4) then Put c, d holds 4 entries.

    State the three rules, decide the order of the check and the shared eviction yourself, and name the cases that must hold.

    • Direction: Validation first, 8 points
    • Direction: Shrink rule, 8 points
    • Direction: Eviction reuse, 8 points
    • Prompt quality: Specified resize, 8 points
    • Prompt quality: Contract examples, 6 points
    • Prompt quality: Failure follow-up, 6 points
    • Verification: Named cases, 8 points
  3. Press Test. All six visible tests pass after the change.
    • Verification: Run after last change, 6 points
  4. Your message 2

    Test passes. Trace through the final Resize step by step, without editing: (a) capacity 3 with a, b, c, Resize(0): the line that returns before anything changes; (b) capacity 4 with a, b, c, d, Get b, Get d, Resize(2): which entries evictOldest removes and in which order, and why [d b] keeps its order.

    The files are fixed, so your own check is a trace of named cases through the code you changed.

    • Verification: Checks own, 6 points
  5. 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.

Direction30/30
Prompt quality20/20
Verification20/20
Correctness20/20
Code quality10/10
Stage total 100/100Grade S
Stage 4 · 04-loading

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

LockingEvery method of the concurrent type is safe for concurrent use and behaves as on the plain cache.
One load per keyA miss runs the load once; callers that arrive meanwhile wait and get its result; a hit, a stored zero value included, never loads.
FailuresA failed load stores nothing, its caller and every waiter get the error, and the next call loads again.
Other keysA load holds up only its own key, and the load itself may call the cache.

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

  1. Replace the embedding with a private field, and give every method its own body that takes one mutex.
  2. 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.
  3. 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.err

Tests 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

  1. Press Test. Test stops at the concurrent-miss test: the loader is still the stub.
  2. Your message 1

    Test fails at TestGetOrComputeLoadsOnceForConcurrentMiss: for "capacity 4; 8 goroutines call GetOrCompute(session) at once; the load takes 20ms; load calls" it expected 1 and got 0. ConcurrentRecencyCache embeds *RecencyCache, so Get, Put, Resize, EntriesNewestFirst, OldestKey, Len and Capacity are promoted with no locking, and Get moves the key, so an RWMutex read lock would be wrong. The rules: one load per key, shared by every caller that waits on it; a failed load stores nothing, its error reaches the loading caller and every waiter, and the next call loads again; a load holds up only its own key; no time.Sleep in the package. Now src/concurrent.go: replace the embedding with an unexported cache field and give ConcurrentRecencyCache its own Get, Put, Resize, EntriesNewestFirst, OldestKey, Len and Capacity, each taking the one sync.Mutex. GetOrCompute: lock; on a hit return the value; keep a map[K]*loadCall of in-flight loads with a done channel, the value and the error. If the key is in flight, unlock, wait on done and return its value and error. Otherwise register a call, unlock, run load with no lock held, then lock, delete the in-flight entry, Put the value only when err == nil, unlock, and close done. Afterwards: a load of key k that blocks and then fails with errBoom while 3 more callers wait on k gives all 4 errBoom, and the next GetOrCompute(k) loads again; while a load of a is blocked, Get(b), Put(c) and GetOrCompute(d) all return at once; a stored nil value is a hit and does not load.

    Name the embedding trap and the rules, decide the locking, the per-key record and the failure path yourself, and give the concurrent cases that must hold.

    • Direction: Promoted methods, 8 points
    • Direction: Per-key loading, 10 points
    • Direction: Error policy, 6 points
    • Prompt quality: Specified single flight, 6 points
    • Prompt quality: Specified locking, 5 points
    • Prompt quality: Specified errors, 4 points
    • Prompt quality: Failure follow-up, 5 points
    • Verification: Concurrent case, 7 points
    • Verification: Reaction to failure, 3 points
  3. Press Test. All eight visible tests pass with the race detector after the change.
    • Verification: Run after last change, 5 points
  4. Your message 2

    Test passes with the race detector. Trace through the final GetOrCompute step by step, without editing: (a) a load of k fails with errBoom while 3 callers wait on k: what each waiter returns, and what the next call for k does; (b) while the load of a is running, a call to Get(b): which lock it takes and why it does not wait for the load.

    The files are fixed, so your own check is a trace of named cases through the code you changed.

    • Verification: Checks own, 5 points
  5. 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.

Direction30/30
Prompt quality20/20
Verification20/20
Correctness20/20
Code quality10/10
Stage total 100/100Grade S
Recency Cache Solution — Go Walkthrough | Hunicode