Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,12 @@ cache.Set("a", 1) // Expires in a minute,
cache.SetWithTTL("b", 2, 10*time.Second) // and this one in ten seconds.
```

An expired entry is a miss, but takes up room until it is evicted, set again, deleted or
cleared, and reads of it still count with the policy. Reads look at a copy of the time that a
timer updates every 10 ms, and at the time itself near a deadline. A `Get` that hits took
11–15% longer through the wrapper, and a `Set` 17 ns longer (`tinylfu`, Apple M3 Max).
Expired entries are misses but still count toward `Len`. Call `cache.PurgeExpired(nil)` to
remove them, or pass a function that releases what they hold.

Reads still count with the policy, even for expired entries. They look at a copy of the time
that a timer updates every 10 ms, and at the time itself near a deadline. A `Get` that hits
took 11–15% longer through the wrapper, and a `Set` 17 ns longer (`tinylfu`, Apple M3 Max).

## Benchmarks

Expand Down Expand Up @@ -163,7 +165,7 @@ own.

- **No sizes in bytes or weights.** Capacity counts entries; set it from a typical entry size.
- **No loader** that fetches a missing key once for all the callers that ask for it.
- **No cleanup of expired entries**; see [Expiry](#expiry).
- **No background expiry**: call `PurgeExpired` yourself ([Expiry](#expiry)).
- **Overwrites do not scale with CPUs**; otter's do ([Benchmarks](#benchmarks)).

For any of these, use [otter](https://github.com/maypok86/otter).
Expand Down
13 changes: 12 additions & 1 deletion evict.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@
//
// Keys are compared with ==, as in a map. A key that is not equal to itself,
// which is to say one with a NaN in it, can be set but not found again: its
// entry is out of reach until it is evicted or the cache is cleared.
// entry stays until it is evicted, removed by DeleteFunc, or the cache is
// cleared.
//
// # Capacity and shards
//
Expand Down Expand Up @@ -94,6 +95,16 @@ type Cache[K comparable, V any] interface {
// Delete removes key and returns the value it had.
Delete(key K) (value V, ok bool)

// DeleteFunc removes the entries for which del returns true and reports
// how many it removed. It visits one shard at a time, without recording
// accesses, and tests and removes each entry at once with respect to
// writes to its key; the pass as a whole is not a snapshot.
//
// del runs with the shard locked: it must not call back into the cache,
// and should return promptly. If it panics, the entries removed before
// stay removed.
DeleteFunc(del func(K, V) bool) int

// Len returns the number of entries in the cache. While the cache is
// being written to, the shards are counted one after the other and
// the sum may be one that the cache never held at any one moment.
Expand Down
73 changes: 56 additions & 17 deletions expire/expire.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,24 @@
//
// An entry that has expired is not found: Get, Peek, GetMany and Delete report
// it missing, All passes it over, and SetIfAbsent stores a new entry in its
// place. It stays in the cache all the same, until it is evicted, replaced or
// deleted, or the cache is cleared. Until then it takes up room, Len counts
// it, and what it holds on to is not garbage.
// place. It stays in the cache all the same, until it is evicted, replaced,
// deleted or purged, or the cache is cleared. Until then it takes up room and
// Len counts it. Call [Cache.PurgeExpired] to remove expired entries; the
// cache does not run a background sweep.
//
// Set and SetIfAbsent hand an expired entry back when they push it out or
// replace it, as they do any entry, so that what it holds on to can be
// released. Delete and Clear do not. Where values have to be released, use the
// wrapped cache for those: its Delete and All return entries whether they have
// expired or not, and [Entry.Value] gives their values.
// replace it, as they do any entry, and PurgeExpired hands those it removes to
// a function of yours, so that what they hold on to can be released. Delete
// and Clear do not. Where values have to be released, use the wrapped cache
// for those: its Delete and All return entries whether they have expired or
// not, and [Entry.Value] gives their values.
//
// A read that finds an expired entry leaves it there, for the Set that usually
// follows: that replaces the entry in place, and the policy goes on treating
// it as the entry it was, which it would not after a Delete. Reads count with
// the policy, expired or not, so an entry that is still asked for but never set
// again stays; delete its key when there is no new value for it. Expired or
// not, there are never more entries than the capacity of the cache.
// it as the entry it was, which it would not after a Delete or a purge. Reads
// count with the policy, expired or not, so an entry that is still asked for
// but never set again stays until it is deleted or purged. Expired or not,
// there are never more entries than the capacity of the cache.
//
// # Time
//
Expand All @@ -46,9 +48,10 @@
// # Statistics
//
// Wrapped in stats, as stats.Wrap(expire.Wrap(...)), a cache counts a read of
// an expired entry as a miss. The stats.Cache has no SetWithTTL: call that of
// the expire.Cache, and the entries it evicts go uncounted. Wrapped the other
// way around, a read of an expired entry counts as a hit.
// an expired entry as a miss. The stats.Cache has no SetWithTTL or
// PurgeExpired: call those of the expire.Cache, and the entries that
// SetWithTTL evicts go uncounted. Wrapped the other way around, a read of an
// expired entry counts as a hit.
//
// # Cost
//
Expand Down Expand Up @@ -348,9 +351,9 @@ func (c *Cache[K, V]) SetWithTTL(key K, value V, ttl time.Duration) (oldKey K, o
// expires in between. Those that find an expired entry take turns replacing
// it, and look again first. The exception is a value stored just after one of
// them has looked: by a Set of key, or by a SetIfAbsent that found no entry
// because the expired one had just left the cache. That value is replaced and
// handed back, with oldKey == key, so two goroutines may each be told that
// they stored theirs.
// because the expired one had just left the cache, which PurgeExpired makes
// more likely. That value is replaced and handed back, with oldKey == key, so
// two goroutines may each be told that they stored theirs.
func (c *Cache[K, V]) SetIfAbsent(key K, value V) (actual V, present bool, oldKey K, oldValue V, evicted bool) {
e := Entry[V]{value: value, deadline: c.clock.deadline(c.ttl)}
a, present, oldKey, old, evicted := c.cache.SetIfAbsent(key, e)
Expand Down Expand Up @@ -401,6 +404,42 @@ func (c *Cache[K, V]) Delete(key K) (value V, ok bool) {
return e.value, true
}

// DeleteFunc calls del only for entries that have not expired, removing those
// for which it returns true, and reports how many it removed. Expired entries
// are left for [Cache.PurgeExpired]. del runs with a shard of the wrapped
// cache locked; see [evict.Cache].
func (c *Cache[K, V]) DeleteFunc(del func(K, V) bool) int {
return c.cache.DeleteFunc(func(k K, e Entry[V]) bool {
return !c.expired(e.deadline) && del(k, e.value)
})
}

// PurgeExpired removes entries whose deadlines are at or before the time the
// call began and returns the number removed. It checks the current entry as
// it visits each shard: a value refreshed past the cutoff is not removed.
// Entries that expire during the scan are left for the next call. A key that
// is set again after its entry was purged comes in as a new entry, as after
// Delete.
//
// Unless removed is nil, PurgeExpired calls it with the key and the value of
// each entry it removes, so that what they hold on to can be released. It
// runs with a shard of the wrapped cache locked, as the del of DeleteFunc
// does: it must not call back into the cache, and should return promptly;
// collect what takes longer and deal with it after PurgeExpired returns. If
// it panics, the entry it was called with stays.
func (c *Cache[K, V]) PurgeExpired(removed func(K, V)) int {
cutoff := c.clock.read()
return c.cache.DeleteFunc(func(k K, e Entry[V]) bool {
if e.deadline > cutoff {
return false
}
if removed != nil {
removed(k, e.value)
}
return true
})
}

// Len returns the number of entries in the cache, those that have expired
// included.
func (c *Cache[K, V]) Len() int { return c.cache.Len() }
Expand Down
152 changes: 149 additions & 3 deletions expire/expire_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package expire_test

import (
"maps"
"math"
"math/rand/v2"
"runtime"
Expand Down Expand Up @@ -247,6 +248,71 @@ func TestExpiry(t *testing.T) {
}
}

func TestPurgeExpired(t *testing.T) {
t.Parallel()

for name, newCache := range policies {
t.Run(name, func(t *testing.T) {
t.Parallel()

clock := expire.NewClock()
inner := stats.Wrap(newCache())
c := expire.WrapWith(inner, time.Second, clock)
c.Set("due", 1)
c.SetWithTTL("later", 2, time.Second+1)
inner.Set("zero", expire.Entry[int]{}) // A zero Entry is already expired.
clock.Advance(time.Second)
clock.Lag(time.Second) // Purging must use the clock, not the readers' copy.

removed := map[string]int{}
n := c.PurgeExpired(func(k string, v int) {
if _, ok := removed[k]; ok {
t.Errorf("PurgeExpired handed over %q twice", k)
}
removed[k] = v
})
if n != 2 {
t.Fatalf("PurgeExpired = %d, want 2", n)
}
if want := map[string]int{"due": 1, "zero": 0}; !maps.Equal(removed, want) {
t.Errorf("PurgeExpired handed over %v, want %v", removed, want)
}
if s := inner.Stats(); s.Len != 1 || s.Evictions != 0 || s.Hits != 0 || s.Misses != 0 {
t.Errorf("stats after purge = %+v, want one entry and no hits, misses or evictions", s)
}
if v, ok := c.Peek("later"); !ok || v != 2 {
t.Errorf("Peek(later) = %d, %t, want 2, true", v, ok)
}
if n := c.PurgeExpired(nil); n != 0 {
t.Errorf("repeat PurgeExpired = %d, want 0", n)
}
})
}
}

func TestDeleteFuncSkipsExpired(t *testing.T) {
t.Parallel()

clock := expire.NewClock()
inner := lru.New[string, expire.Entry[int]](2)
c := stats.Wrap(expire.WrapWith(inner, time.Second, clock))
c.Set("expired", 1)
clock.Advance(time.Second)
c.Set("live", 2)
n := c.DeleteFunc(func(k string, v int) bool {
if k != "live" || v != 2 {
t.Errorf("DeleteFunc visited %s=%d, want live=2", k, v)
}
return true
})
if n != 1 {
t.Errorf("DeleteFunc = %d, want 1", n)
}
if e, ok := inner.Peek("expired"); !ok || e.Value() != 1 || inner.Len() != 1 {
t.Error("DeleteFunc did not leave just the expired entry")
}
}

// An expired entry that leaves the cache is handed back by Set, as any entry
// is, whether it is replaced or evicted.
func TestExpiredLeave(t *testing.T) {
Expand Down Expand Up @@ -328,11 +394,11 @@ func TestTTLBounds(t *testing.T) {
}

// hooked is a cache that runs a function after each Peek, to let an entry come
// or go between SetWithTTL's look and its Set, and another after each
// SetIfAbsent.
// or go between SetWithTTL's look and its Set. It can also interpose after a
// SetIfAbsent or before a DeleteFunc scan.
type hooked struct {
evict.Cache[string, expire.Entry[int]]
after, afterAbsent func()
after, afterAbsent, beforeScan func()
}

func (h *hooked) Peek(key string) (expire.Entry[int], bool) {
Expand All @@ -351,6 +417,72 @@ func (h *hooked) SetIfAbsent(key string, e expire.Entry[int]) (actual expire.Ent
return actual, present, oldKey, oldValue, evicted
}

func (h *hooked) DeleteFunc(del func(string, expire.Entry[int]) bool) int {
if h.beforeScan != nil {
h.beforeScan()
}
return h.Cache.DeleteFunc(del)
}

// A refresh between taking the cutoff and scanning a shard must survive.
// A deadline that passes in that interval belongs to the next purge.
func TestPurgeExpiredCutoff(t *testing.T) {
t.Parallel()

clock := expire.NewClock()
h := &hooked{Cache: lru.New[string, expire.Entry[int]](3)}
c := expire.WrapWith(h, time.Second, clock)
c.Set("expired", 1)
c.Set("refresh", 2)
c.SetWithTTL("later", 3, 2*time.Second)
clock.Advance(time.Second)
h.beforeScan = func() {
clock.Advance(time.Second)
c.Set("refresh", 4)
}
if n := c.PurgeExpired(nil); n != 1 {
t.Fatalf("PurgeExpired = %d, want 1", n)
}
if v, ok := c.Peek("refresh"); !ok || v != 4 {
t.Error("purge removed the refreshed value")
}
if _, ok := h.Peek("later"); !ok {
t.Error("purge removed an entry that expired during the scan")
}
h.beforeScan = nil
if n := c.PurgeExpired(nil); n != 1 {
t.Errorf("next PurgeExpired = %d, want 1", n)
}
}

// A panic in the function that PurgeExpired hands entries to stops the purge,
// and the entry it was handed stays.
func TestPurgeExpiredPanics(t *testing.T) {
t.Parallel()

clock := expire.NewClock()
inner := lru.New[string, expire.Entry[int]](2, lru.WithShards(1))
c := expire.WrapWith(inner, time.Second, clock)
c.Set("a", 1)
c.Set("b", 2)
clock.Advance(time.Second)
const stop = "stop the purge"
func() {
defer func() {
if p := recover(); p != stop {
t.Errorf("PurgeExpired panic = %v, want %q", p, stop)
}
}()
c.PurgeExpired(func(string, int) { panic(stop) })
}()
if inner.Len() != 2 {
t.Errorf("Len() = %d after a panic in the first call, want 2", inner.Len())
}
if n := c.PurgeExpired(nil); n != 2 {
t.Errorf("PurgeExpired after a panic = %d, want 2", n)
}
}

// SetWithTTL with a time to live of zero or less decides by what it sees when
// it looks. An entry of key that leaves in between is stored as Set would
// store it: with eviction, if that is what it takes. One that comes in between
Expand Down Expand Up @@ -825,6 +957,16 @@ func TestConcurrent(t *testing.T) {
wg.Go(func() {
for !done.Load() {
clock.Advance(time.Millisecond)
calls := 0
n := c.PurgeExpired(func(k string, v int) {
calls++
if strconv.Itoa(v) != k {
t.Errorf("PurgeExpired handed over %q=%d", k, v)
}
})
if calls != n {
t.Errorf("PurgeExpired removed %d entries and handed over %d", n, calls)
}
time.Sleep(time.Microsecond)
}
})
Expand Down Expand Up @@ -873,6 +1015,10 @@ func TestConcurrent(t *testing.T) {
for k, v := range c.All() {
t.Errorf("All yields %q=%d after every entry expired", k, v)
}
c.PurgeExpired(nil)
if c.Len() != 0 {
t.Errorf("Len() = %d after purging every entry", c.Len())
}
})
}
}
Expand Down
Loading