Skip to content
Recommended solution · HC-2 · Go

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

  1. Press Test first and read the failure, then read the cache and the sweeper against the task's rules.
  2. Name each failing family and its cause before you ask for any change.
  3. 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.
  4. Give the cases that must hold afterwards, each with its expected result, and press Test after the change.
  5. Ask the assistant to trace named cases through the final code, then Submit.
Stage 1 · bounded-ttl-cache

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

ExpiryA value is readable while the clock is before its expiry time and gone at the expiry time. A time to live of zero or less never expires.
CapacityWith a capacity above zero, a Set of a new key that would exceed it evicts the least recently used entry first. A Get hit and a Set of an existing key both count as a use.
CloseClose stops the sweeper, waits for it, closes Done and is safe to call twice; afterwards Get misses and Set does nothing.
ConcurrencyEvery method is safe for concurrent use, with the race detector on.

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

  1. An entry is live only while the clock is before its expiry time, and a zero expiry time means it never expires.
  2. 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.
  3. The sweeper waits on the stop channel or the ticker and calls Sweep, which takes the lock.
  4. 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

  1. Press Test. Test stops at the expiry boundary: the entry is still returned at exactly its expiry time.
  2. Your message 1

    Test stops at TestExpiryBoundary. Before any change, check my reading of src/cache.go and src/sweeper.go against the code and tell me where I'm wrong; no edits yet. (1) Expiry: Get and Sweep treat an entry as expired only when now.After(expiresAt), so at exactly its expiry time it is still returned (TestExpiryBoundary); and Set computes expiresAt whenever ttl >= 0, so a TTL of 0 expires at once instead of never (TestZeroTTLNeverExpires). (2) Lifecycle: the sweeper ranges over c.items without holding c.mu while Set and Get write the map, so TestConcurrentUse will report a race; Close closes stop but the sweeper never reads it, nothing waits for the goroutine, done is never closed, and a second Close panics on a closed channel (TestCloseLifecycle). (3) Eviction: evict is a TODO and nothing tracks recency, so Capacity is never enforced (TestEvictionOrder, TestGetRefreshesRecency).

    Name every failing family with the line that causes it, and ask for a check of your reading before any change.

    • Direction: Diagnosis: expiry, 2 points
    • Direction: Diagnosis: lifecycle, 2 points
    • Direction: Diagnosis: eviction, 2 points
    • Prompt quality: Named failing test, 6 points
    • Prompt quality: Failure follow-up, 4 points
    • Verification: Named cases: expiry, 2 points
    • Verification: Named cases: lifecycle, 2 points
  3. Your message 2

    Test fails at TestExpiryBoundary: for "advance to exactly 10s; Get a" it expected "<miss>" and got "1". That is the boundary bug from my reading: Get uses now.After(expiresAt). Now fix the three families in src/cache.go and src/sweeper.go, keeping the handler and the exported API: (1) an entry is live only while now.Before(expiresAt), in Get and Sweep; expiresAt stays the zero time when ttl <= 0, which never expires. (2) One sync.Mutex guards a map[string]*list.Element and a container/list in recency order, front = most recent: a Get hit and a Set of an existing key MoveToFront, and a Set of a new key inserts at the front and evicts from the back while Capacity > 0 and the length exceeds Capacity. No second lock and no RWMutex, because Get moves entries. (3) The sweeper selects on stop and the ticker and calls c.Sweep(), which takes the lock; Close uses a sync.Once to mark closed under the lock, close stop, wait for the sweeper with a sync.WaitGroup, then close done. No time.Sleep anywhere in the package. Afterwards these must hold: TTL 10s gives a hit after 9.999s and a miss at exactly 10s; TTL 0 is still a hit after 1000h; capacity 2 with Set a, b, Get a, Set c evicts b and keeps a and c; Close twice does not panic and Done is closed after it. Don't change the tests.

    Tie the failure to its cause, then decide the lock, the structure and the shutdown yourself and say what must hold afterwards.

    • Direction: Lock discipline, 6 points
    • Direction: Recency structure, 6 points
    • Direction: Lifecycle, 6 points
    • Prompt quality: Specified fix: expiry, 2 points
    • Prompt quality: Specified fix: lifecycle, 2 points
    • Prompt quality: Specified fix: eviction, 2 points
    • Prompt quality: Contract examples, 4 points
    • Verification: Named cases: eviction, 2 points
    • Verification: Reaction to failure, 4 points
  4. Press Test. All nine visible tests pass with the race detector after the change.
    • Verification: Run after last change, 6 points
  5. Your message 3

    Test passes. Before I submit, trace these cases through the final src/cache.go step by step and say which line decides each step, without editing: (a) Set k with TTL 10s, then Get k at exactly 10s returns a miss; (b) Set forever with TTL 0, advance 1000h, Get forever returns the value; (c) capacity 2: Set a, Set b, Set a again with value 10, Set c: b is evicted, Len is 2 and Get a returns 10; (d) Close called twice: the second call returns at once without a panic and Done stays closed.

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

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

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