"""Go: an in-memory TTL cache split across files. Set() stores expireAt = now instead of now.Add(ttl), so Get() right after Set() misses; it only makes sense once Set() and ttl.go's isExpired() are both read. Was agentic-fix v1's only item; its `// BUG:` comment is gone (v3).""" import re ITEM_ID = "go-kvstore-ttl" LANG = "go" TOOL = "go" PROJECT = { "go.mod": "module kvstore\n\ngo 1.26\n", "doc.go": '''// Package kvstore is a small concurrency-safe in-memory key/value cache with // per-entry TTL expiry and a background sweeper that evicts expired entries. // // Typical use: // // s := kvstore.New(kvstore.WithSweepInterval(time.Second)) // defer s.Close() // s.Set("session:42", token, 30*time.Minute) // v, ok := s.Get("session:42") // // Expiry is lazy (checked on Get) and eager (the sweeper). Both paths agree on // one definition of "expired": see ttl.go. package kvstore ''', "store.go": '''package kvstore import ( "sync" "time" ) // entry is a single stored value plus its bookkeeping. See ttl.go for the // expiry predicate that reads expireAt. type entry struct { value any expireAt time.Time created time.Time } // Store is a concurrency-safe TTL cache. type Store struct { mu sync.RWMutex items map[string]*entry stats *Stats opts options stopCh chan struct{} closed bool } // New builds a Store and starts its background sweeper. func New(optFns ...Option) *Store { o := defaultOptions() for _, fn := range optFns { fn(&o) } s := &Store{ items: make(map[string]*entry), stats: &Stats{}, opts: o, stopCh: make(chan struct{}), } go s.sweepLoop() return s } // Set stores value under key with a time-to-live. A ttl <= 0 means the entry // never expires (expireAt stays the zero time, which isExpired treats as live). func (s *Store) Set(key string, value any, ttl time.Duration) { s.mu.Lock() defer s.mu.Unlock() now := time.Now() e := &entry{value: value, created: now} if ttl > 0 { e.expireAt = now } s.items[key] = e } // Get returns the value for key. The second result is false if the key is // absent or has expired (a lazily-expired entry is deleted on read). func (s *Store) Get(key string) (any, bool) { s.mu.Lock() defer s.mu.Unlock() e, ok := s.items[key] if !ok { s.stats.recordMiss() return nil, false } if isExpired(e, time.Now()) { delete(s.items, key) s.stats.recordMiss() return nil, false } s.stats.recordHit() return e.value, true } // Delete removes key if present, reporting whether it existed. func (s *Store) Delete(key string) bool { s.mu.Lock() defer s.mu.Unlock() _, ok := s.items[key] delete(s.items, key) return ok } // Len returns the number of entries currently held (including any not-yet-swept // expired ones). func (s *Store) Len() int { s.mu.RLock() defer s.mu.RUnlock() return len(s.items) } // Keys returns a snapshot of the current keys in unspecified order. func (s *Store) Keys() []string { s.mu.RLock() defer s.mu.RUnlock() ks := make([]string, 0, len(s.items)) for k := range s.items { ks = append(ks, k) } return ks } // Close stops the background sweeper. Safe to call more than once. func (s *Store) Close() { s.mu.Lock() defer s.mu.Unlock() if !s.closed { close(s.stopCh) s.closed = true } } ''', "ttl.go": '''package kvstore import "time" // isExpired reports whether e is past its time-to-live as of now. The zero // expireAt (used for never-expire entries) is always live. This is the single // source of truth for expiry, shared by Get (lazy) and the sweeper (eager). func isExpired(e *entry, now time.Time) bool { if e.expireAt.IsZero() { return false } return now.After(e.expireAt) } // remaining returns how long until e expires, or 0 if already expired / never. func remaining(e *entry, now time.Time) time.Duration { if e.expireAt.IsZero() { return 0 } d := e.expireAt.Sub(now) if d < 0 { return 0 } return d } ''', "sweeper.go": '''package kvstore import "time" // sweepLoop runs until Close, evicting expired entries every SweepInterval so // memory does not grow unbounded when callers never re-Get expired keys. func (s *Store) sweepLoop() { t := time.NewTicker(s.opts.sweepInterval) defer t.Stop() for { select { case <-s.stopCh: return case <-t.C: s.sweepOnce() } } } // sweepOnce evicts every currently-expired entry in one pass. func (s *Store) sweepOnce() { now := time.Now() s.mu.Lock() defer s.mu.Unlock() for k, e := range s.items { if isExpired(e, now) { delete(s.items, k) s.stats.recordEviction() } } } ''', "stats.go": '''package kvstore import "sync/atomic" // Stats holds cache counters. All methods are safe for concurrent use. type Stats struct { hits atomic.Int64 misses atomic.Int64 evictions atomic.Int64 } func (s *Stats) recordHit() { s.hits.Add(1) } func (s *Stats) recordMiss() { s.misses.Add(1) } func (s *Stats) recordEviction() { s.evictions.Add(1) } // Snapshot returns the current counter values. func (s *Stats) Snapshot() (hits, misses, evictions int64) { return s.hits.Load(), s.misses.Load(), s.evictions.Load() } // Stats exposes the live counters for this store. func (s *Store) Stats() *Stats { return s.stats } ''', "options.go": '''package kvstore import "time" // options is the internal, fully-resolved configuration for a Store. type options struct { sweepInterval time.Duration } // Option customizes a Store at construction time. type Option func(*options) func defaultOptions() options { return options{sweepInterval: 30 * time.Second} } // WithSweepInterval sets how often the background sweeper runs. Values <= 0 are // ignored and the default is kept. func WithSweepInterval(d time.Duration) Option { return func(o *options) { if d > 0 { o.sweepInterval = d } } } ''', "store_test.go": '''package kvstore import ( "testing" "time" ) // A value set with a long TTL must be readable immediately afterwards. func TestSetThenGetWithinTTL(t *testing.T) { s := New(WithSweepInterval(time.Hour)) defer s.Close() s.Set("k", "v", time.Hour) got, ok := s.Get("k") if !ok { t.Fatalf("Get right after Set: want hit, got miss") } if got != "v" { t.Fatalf("Get value = %v, want v", got) } } // A short-TTL value must expire after enough time passes. func TestExpiresAfterTTL(t *testing.T) { s := New(WithSweepInterval(time.Hour)) defer s.Close() s.Set("k", "v", 10*time.Millisecond) time.Sleep(25 * time.Millisecond) if _, ok := s.Get("k"); ok { t.Fatalf("Get after TTL: want miss, got hit") } } // ttl <= 0 means never expire. func TestZeroTTLNeverExpires(t *testing.T) { s := New(WithSweepInterval(time.Hour)) defer s.Close() s.Set("k", "v", 0) time.Sleep(15 * time.Millisecond) if _, ok := s.Get("k"); !ok { t.Fatalf("zero-ttl entry: want hit, got miss") } } ''', } HIDDEN = ("store_test.go",) FIX = {"store.go": PROJECT["store.go"].replace("\t\te.expireAt = now\n", "\t\te.expireAt = now.Add(ttl)\n")} TEST_CMD = ["go", "test", "-v", "./..."] PASS_RE = r"--- PASS: (\S+)" TESTS = tuple(re.findall(r"^func (Test\w+)\(", PROJECT["store_test.go"], re.M)) WRONG = [{"ttl.go": PROJECT["ttl.go"].replace("return now.After(e.expireAt)", "return false")}]