From 60c43f0a30b65c9dc6e790fc9e0229e7c97f0c07 Mon Sep 17 00:00:00 2001 From: Vsevolod Strukchinsky Date: Mon, 23 Nov 2026 15:52:46 +0500 Subject: [PATCH 1/2] Add expire, a wrapper that gives entries a time to live expire.Wrap(cache, ttl) puts a clock in front of any evict.Cache that holds expire.Entry values, and SetWithTTL gives one entry a time of its own. An expired entry is a miss for Get, Peek, GetMany, Delete and All, but stays until it is evicted, set again, deleted or cleared; Set hands it back like any entry. Readers look at a copy of the time that one shared timer updates every 10 ms, and at the time itself only within 50 ms of a deadline, so an entry is never a miss early and is found late only if the timer runs more than 40 ms late. On an Apple M3 Max with tinylfu, a Get that hits took 15% longer on one CPU and 11-13% on eight, and a Set 17 ns longer. The read path stays free of calls through a generic wrapper: expired is at inline cost 79, and inlinecheck has probes for it. Co-Authored-By: Claude Opus 5.5 --- README.md | 20 +- evict.go | 5 +- expire/bench_test.go | 166 ++++ expire/example_test.go | 49 ++ expire/expire.go | 355 ++++++++ expire/expire_test.go | 755 ++++++++++++++++++ expire/export_test.go | 89 +++ internal/inlinecheck/inline_test.go | 15 +- internal/inlinecheck/probe/expire/probe.go | 29 + .../inlinecheck/probe/expirewrap/probe.go | 23 + .../inlinecheck/probe/expirewrapuser/probe.go | 22 + 11 files changed, 1519 insertions(+), 9 deletions(-) create mode 100644 expire/bench_test.go create mode 100644 expire/example_test.go create mode 100644 expire/expire.go create mode 100644 expire/expire_test.go create mode 100644 expire/export_test.go create mode 100644 internal/inlinecheck/probe/expire/probe.go create mode 100644 internal/inlinecheck/probe/expirewrap/probe.go create mode 100644 internal/inlinecheck/probe/expirewrapuser/probe.go diff --git a/README.md b/README.md index 494d023..bb29d3d 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ Fixed-capacity in-memory caches for Go. - **Batch lookups.** `GetMany` loads up to 32 entries from memory in parallel. - **Evictions handed back.** `Set` returns the entry it replaced or evicted. - **Statistics.** `stats.Wrap` counts hits, misses and evictions. +- **Expiry.** `expire.Wrap` gives entries a time to live. - **Safe for concurrent use**, and depends only on the standard library. ## Install @@ -80,6 +81,20 @@ fmt.Println(s.HitRatio(), s.Evictions, s.Len, s.Cap) The counts only go up; `s.Sub(prev)` gives those of an interval. A `Get` that hits took 10–14% longer through the wrapper (`tinylfu`, Apple M3 Max). +### Expiry + +```go +cache := expire.Wrap(tinylfu.New[string, expire.Entry[int]](10_000), time.Minute) + +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). + ## Benchmarks

@@ -151,9 +166,8 @@ own. ## What it does not do -No expiry, no weights or sizes in bytes, no loading functions. If you need those, or if many -CPUs overwrite a tenth to a quarter of what they read, use -[otter](https://github.com/maypok86/otter). +No weights or sizes in bytes, no loading functions. If you need those, or if many CPUs +overwrite a tenth to a quarter of what they read, use [otter](https://github.com/maypok86/otter). ## License diff --git a/evict.go b/evict.go index eb8687e..5cdf542 100644 --- a/evict.go +++ b/evict.go @@ -43,14 +43,15 @@ // // This package holds what the caches have in common: the [Cache] interface. // [github.com/floatdrop/evict/stats] counts the hits, misses and evictions of -// any of them. +// any of them, and [github.com/floatdrop/evict/expire] gives their entries a +// time to live. package evict import "iter" // Cache is the behaviour common to every cache in this module. It is // implemented by *lru.Cache, *twoq.Cache, *sieve.Cache, *s3fifo.Cache and -// *tinylfu.Cache. +// *tinylfu.Cache, and by the wrappers *stats.Cache and *expire.Cache. // // All methods are safe for concurrent use. type Cache[K comparable, V any] interface { diff --git a/expire/bench_test.go b/expire/bench_test.go new file mode 100644 index 0000000..5c30c6a --- /dev/null +++ b/expire/bench_test.go @@ -0,0 +1,166 @@ +package expire_test + +import ( + "fmt" + "math/rand/v2" + "sync" + "testing" + "time" + + "github.com/floatdrop/evict" + "github.com/floatdrop/evict/expire" + "github.com/floatdrop/evict/internal/cachetest" + "github.com/floatdrop/evict/s3fifo" + "github.com/floatdrop/evict/tinylfu" +) + +const benchCapacity = 1 << 14 + +// fill sets the keys 0 to benchCapacity-1, through set. +func fill(set func(key, value int)) { + for key := range benchCapacity { + set(key, key) + } +} + +// benchGet reads entries that are all there, on every CPU at once. The loop is +// written out for each type, so that it makes the call it is about and no +// other. +func BenchmarkGet(b *testing.B) { + b.Run("direct", func(b *testing.B) { + c := tinylfu.New[int, int](benchCapacity) + fill(func(k, v int) { c.Set(k, v) }) + b.ReportAllocs() + b.RunParallel(func(pb *testing.PB) { + i := rand.Int() + for pb.Next() { + c.Get(i & (benchCapacity - 1)) + i++ + } + }) + }) + + b.Run("interface", func(b *testing.B) { + var c evict.Cache[int, int] = tinylfu.New[int, int](benchCapacity) + fill(func(k, v int) { c.Set(k, v) }) + b.ReportAllocs() + b.RunParallel(func(pb *testing.PB) { + i := rand.Int() + for pb.Next() { + c.Get(i & (benchCapacity - 1)) + i++ + } + }) + }) + + b.Run("expire", func(b *testing.B) { + c := expire.Wrap(tinylfu.New[int, expire.Entry[int]](benchCapacity), time.Hour) + fill(func(k, v int) { c.Set(k, v) }) + b.ReportAllocs() + b.RunParallel(func(pb *testing.PB) { + i := rand.Int() + for pb.Next() { + c.Get(i & (benchCapacity - 1)) + i++ + } + }) + }) + + // Every entry is due within 50 ms of the copy of the time, so every + // read reads the time itself. + b.Run("due", func(b *testing.B) { + clock := expire.NewRealClock() + c := expire.WrapWith(tinylfu.New[int, expire.Entry[int]](benchCapacity), time.Hour, clock) + fill(func(k, v int) { c.Set(k, v) }) + clock.SetCopy(clock.Read() + time.Hour - 30*time.Millisecond) + // Filling the cache takes about a millisecond. Had it taken 30, the + // first entries would have expired by the copy of the time. + for _, key := range []int{0, benchCapacity - 1} { + if _, ok := c.Get(key); !ok { + b.Fatalf("Get(%d) misses; the benchmark is for entries that are due", key) + } + } + b.ReportAllocs() + b.RunParallel(func(pb *testing.PB) { + i := rand.Int() + for pb.Next() { + c.Get(i & (benchCapacity - 1)) + i++ + } + }) + }) +} + +// BenchmarkSet replaces entries, on one CPU at a time: Set takes the lock of a +// shard either way, and reads the time through the wrapper. +func BenchmarkSet(b *testing.B) { + b.Run("direct", func(b *testing.B) { + c := tinylfu.New[int, int](benchCapacity) + fill(func(k, v int) { c.Set(k, v) }) + b.ReportAllocs() + i := 0 + for b.Loop() { + c.Set(i&(benchCapacity-1), i) + i++ + } + }) + + b.Run("expire", func(b *testing.B) { + c := expire.Wrap(tinylfu.New[int, expire.Entry[int]](benchCapacity), time.Hour) + fill(func(k, v int) { c.Set(k, v) }) + b.ReportAllocs() + i := 0 + for b.Loop() { + c.Set(i&(benchCapacity-1), i) + i++ + } + }) +} + +// BenchmarkGetMany looks up keys of a cache too large for the CPU's caches, on +// every CPU at once: with the GetMany of s3fifo, and with that of the wrapper, +// which looks them up in batches of its own. ns/key is the time per key. +func BenchmarkGetMany(b *testing.B) { + const entries = 1 << 20 + keys, seq := cachetest.UniformInts(entries) + + run := func(b *testing.B, n int, getMany func(keys, values []int, found []bool)) { + b.Helper() + mask := len(seq) - 1 + var ( + mu sync.Mutex + hits int + ) + b.ReportAllocs() + b.RunParallel(func(pb *testing.PB) { + values, found := make([]int, n), make([]bool, n) + i, h := rand.Int()&^(n-1), 0 + for pb.Next() { + getMany(seq[i&mask:i&mask+n], values, found) + for _, ok := range found { + if ok { + h++ + } + } + i += n + } + mu.Lock() + hits += h + mu.Unlock() + }) + total := float64(b.N * n) + b.ReportMetric(float64(b.Elapsed().Nanoseconds())/total, "ns/key") + b.ReportMetric(float64(hits)/total, "hits") + } + + direct := s3fifo.New[int, int](entries) + wrapped := expire.Wrap(s3fifo.New[int, expire.Entry[int]](entries), time.Hour) + for _, k := range keys { + direct.Set(k, k) + wrapped.Set(k, k) + } + for _, n := range []int{8, 32, 128} { + b.Run(fmt.Sprintf("keys=%d/direct", n), func(b *testing.B) { run(b, n, direct.GetMany) }) + b.Run(fmt.Sprintf("keys=%d/expire", n), func(b *testing.B) { run(b, n, wrapped.GetMany) }) + } +} diff --git a/expire/example_test.go b/expire/example_test.go new file mode 100644 index 0000000..9bfc62a --- /dev/null +++ b/expire/example_test.go @@ -0,0 +1,49 @@ +package expire_test + +import ( + "fmt" + "time" + + "github.com/floatdrop/evict/expire" + "github.com/floatdrop/evict/stats" + "github.com/floatdrop/evict/tinylfu" +) + +func Example() { + // The cache holds expire.Entry values, which are the values with the + // time at which they expire. + cache := expire.Wrap(tinylfu.New[string, expire.Entry[int]](10_000), time.Minute) + + cache.Set("a", 1) // Expires in a minute, + cache.SetWithTTL("b", 2, time.Hour) // this one in an hour, + cache.SetWithTTL("c", 3, 0) // and this one already has. + + for _, key := range []string{"a", "b", "c"} { + value, ok := cache.Get(key) + fmt.Println(key, value, ok) + } + + // Output: + // a 1 true + // b 2 true + // c 0 false +} + +// Wrapped in stats, a cache counts a key whose entry has expired as a miss. +func Example_stats() { + expiring := expire.Wrap(tinylfu.New[string, expire.Entry[int]](10_000), time.Minute) + cache := stats.Wrap(expiring) + + cache.Set("a", 1) + cache.Set("b", 2) + expiring.SetWithTTL("b", 3, 0) // Its time is up. + + cache.Get("a") + cache.Get("b") + + s := cache.Stats() + fmt.Println(s.Hits, "hit,", s.Misses, "miss") + + // Output: + // 1 hit, 1 miss +} diff --git a/expire/expire.go b/expire/expire.go new file mode 100644 index 0000000..fdc483d --- /dev/null +++ b/expire/expire.go @@ -0,0 +1,355 @@ +// Package expire gives the entries of a cache a time to live. +// +// [Wrap] puts a clock in front of any [evict.Cache] that holds [Entry] values: +// +// cache := expire.Wrap(tinylfu.New[string, expire.Entry[int]](10_000), time.Minute) +// cache.Set("a", 1) // Expires in a minute, +// cache.SetWithTTL("b", 2, 10*time.Second) // and this one in ten seconds. +// value, ok := cache.Get("a") +// +// # Expired entries +// +// An entry that has expired is not found: Get, Peek, GetMany and Delete report +// it missing, and All passes it over. 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. +// +// Set hands an expired entry back when it pushes it out or replaces it, as it +// does 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. +// +// 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. +// +// # Time +// +// An entry expires when its time to live is up, by a monotonic clock: it is +// found until then and not after. Reading the time takes about as long as a +// Get, so readers look at a copy of it instead, which a timer updates every +// 10 ms. Only an entry that is due to expire within 50 ms of that copy is +// checked against the time itself. If the program is so busy that the timer +// runs late by more than 40 ms, an entry may be found after it has expired, +// for as long as the delay exceeds those 40 ms. +// +// The timer starts with the first call to Wrap and keeps running after that, +// one for all caches. Each tick runs a goroutine, for which the runtime may +// start a thread, until it has enough of them. A test that counts allocations +// soon after the first Wrap may count those. +// +// # 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. +// +// # Cost +// +// On an Apple M3 Max, a Get of tinylfu that found its key took 15% longer +// through the wrapper on one CPU, and 11 to 13% on eight. One of an entry that +// was due to expire within 50 ms took 15 ns longer again, for reading the +// time. Set reads it every time, and took 17 ns longer. GetMany of a million +// entries of s3fifo took 3 to 9% longer per key in the median, in batches of 8 +// to 128 keys, though single runs varied by 20% either way. An entry takes 8 +// bytes more for the time at which it expires, and padding for a value whose +// size is not a multiple of 8. +// +// The wrapper reaches the cache through an interface, which the compiler +// cannot see through: a key that would otherwise stay where it is may have to +// move to the heap, as one converted from a []byte on the spot does. +package expire + +import ( + "iter" + "math" + "sync" + "sync/atomic" + "time" + + "github.com/floatdrop/evict" + "github.com/floatdrop/evict/internal/cslab" +) + +const ( + // tick is how often the copy of the time that readers look at is + // updated. + tick = 10 * time.Millisecond + + // near is how close to that copy an entry has to be due to expire for a + // reader to check it against the time itself. It leaves the timer 40 ms + // to be late by before an entry is found for longer than it should be. + near = 50 * time.Millisecond + + // cacheLine is a size that no two CPUs' cache lines straddle on the + // platforms Go runs on. + cacheLine = 128 +) + +// Entry is a value as the wrapped cache holds it, together with the time at +// which it expires. Create the cache with Entry[V] for its values and hand it +// to [Wrap]. An Entry that is made otherwise has expired. +type Entry[V any] struct { + value V + deadline int64 // in nanoseconds of the clock of the cache +} + +// Value returns the value of the entry, whether it has expired or not. +func (e Entry[V]) Value() V { return e.value } + +// Cache is an [evict.Cache] whose entries expire; see the package +// documentation. Its methods are safe for concurrent use as long as those of +// the cache it wraps are, as they are for every cache in this module. +type Cache[K comparable, V any] struct { + cache evict.Cache[K, Entry[V]] + many manyGetter[K, Entry[V]] // cache, if it has a GetMany + clock *clock + ttl time.Duration + + // batches holds arrays that GetMany looks up entries in. Its own + // would move to the heap, since the cache is behind an interface. + batches sync.Pool +} + +// manyGetter is a cache that looks up several keys at once, as sieve, s3fifo +// and tinylfu do. +type manyGetter[K comparable, V any] interface { + GetMany(keys []K, values []V, found []bool) +} + +// batch is as many entries as GetMany looks up at once: as many as the caches +// of this module load from memory at a time. +type batch[V any] = [cslab.Batch]Entry[V] + +// A clock tells the time in nanoseconds since it was made. +// +// The words that readers look at are plain integers that are only ever +// accessed with the functions of sync/atomic, which the compiler builds in +// wherever it compiles the methods of a Cache. The methods of the atomic +// types it would inline there only if a package that is imported there had +// inlined them itself; see the package internal/inlinecheck. +type clock struct { + _ [cacheLine]byte + + // now is the time of the last tick: what readers look at. + now int64 + + _ [cacheLine - 8]byte + + // The rest is read by writers, and by readers of entries that are due + // to expire, but changes only in tests. fake comes first, where a + // 32-bit platform has it aligned for atomic access. + fake int64 // the time, if it is fake; accessed like now + fixed bool // the time is fake, and moves only when a test says so + epoch time.Time + begin func() // starts the timer, the first time it is called + timer *time.Timer +} + +// system is the clock that every Cache made by Wrap goes by. +var system = newClock() + +func newClock() *clock { + c := &clock{epoch: time.Now()} + c.begin = sync.OnceFunc(func() { + atomic.StoreInt64(&c.now, c.read()) + // The timer is made first and set going after, so that the + // function finds it when it runs. + c.timer = time.AfterFunc(math.MaxInt64, c.advance) + c.timer.Reset(tick) + }) + return c +} + +// advance updates the time that readers look at, and is called by the timer. +func (c *clock) advance() { + atomic.StoreInt64(&c.now, c.read()) + c.timer.Reset(tick) +} + +// due reports whether an entry that expires at deadline has, given that it was +// left ahead of the copy of the time that readers look at, which is near. It +// is not inlined, so that Cache.expired stays small enough to be. +// +//go:noinline +func (c *clock) due(left, deadline int64) bool { return left <= 0 || c.read() >= deadline } + +// read returns the time. +func (c *clock) read() int64 { + if c.fixed { + return atomic.LoadInt64(&c.fake) + } + return int64(time.Since(c.epoch)) +} + +// deadline returns the time at which an entry expires that is set now with the +// given time to live. One whose time to live is not positive has expired at +// the start of the clock, so that no deadline is below zero, and one that +// would not expire before the clock runs out never does. +func (c *clock) deadline(ttl time.Duration) int64 { + if ttl <= 0 { + return 0 + } + now := c.read() + return now + min(int64(ttl), math.MaxInt64-now) +} + +// Wrap returns a Cache that keeps its entries in cache, and has them expire ttl +// after they are set, unless they are set with [Cache.SetWithTTL]. It panics if +// ttl is not positive. +// +// Using cache directly as well is fine: its entries are the ones the Cache +// holds, and its methods do not look at the time. They return entries that +// have expired, which those of the Cache do not. +func Wrap[K comparable, V any](cache evict.Cache[K, Entry[V]], ttl time.Duration) *Cache[K, V] { + if ttl <= 0 { + panic("expire: Wrap: ttl must be positive") + } + return wrap(cache, ttl, system) +} + +func wrap[K comparable, V any](cache evict.Cache[K, Entry[V]], ttl time.Duration, clock *clock) *Cache[K, V] { + clock.begin() + many, _ := cache.(manyGetter[K, Entry[V]]) + return &Cache[K, V]{cache: cache, many: many, clock: clock, ttl: ttl} +} + +// expired reports whether an entry that expires at deadline has. Neither the +// deadline nor the copy of the time is ever below zero, so the difference of +// the two cannot overflow. +func (c *Cache[K, V]) expired(deadline int64) bool { + left := deadline - atomic.LoadInt64(&c.clock.now) + return left <= int64(near) && c.clock.due(left, deadline) +} + +// Get returns the value stored under key, unless it has expired. Like the Get +// of the cache, it records the access with the eviction policy, also if the +// entry has expired. +func (c *Cache[K, V]) Get(key K) (value V, ok bool) { + e, ok := c.cache.Get(key) + if !ok || c.expired(e.deadline) { + return value, false + } + return e.value, true +} + +// GetMany does what Get does for each of keys, and stores the value it finds +// for keys[i] in values[i] and whether it found one in found[i]. It panics if +// values or found is shorter than keys. values and found may each be keys +// itself, but must not otherwise overlap it. +// +// If the cache has a GetMany of its own, as sieve, s3fifo and tinylfu do, +// GetMany uses it: for a cache that is too large for the CPU's caches it is +// faster than Get for each key. Otherwise it calls Get for each key. +func (c *Cache[K, V]) GetMany(keys []K, values []V, found []bool) { + if len(values) < len(keys) || len(found) < len(keys) { + panic("expire: GetMany: values and found must be at least as long as keys") + } + if c.many == nil { + for i, key := range keys { + values[i], found[i] = c.Get(key) + } + return + } + + b, _ := c.batches.Get().(*batch[V]) + if b == nil { + b = new(batch[V]) + } + for len(keys) > 0 { + n := min(len(keys), len(b)) + entries := b[:n] + c.many.GetMany(keys[:n], entries, found[:n]) + for i := range entries { + if found[i] && !c.expired(entries[i].deadline) { + values[i] = entries[i].value + } else { + var zero V + values[i], found[i] = zero, false + } + } + // What the batch holds must not be kept alive by the pool. + clear(entries) + keys, values, found = keys[n:], values[n:], found[n:] + } + c.batches.Put(b) +} + +// Peek returns the value stored under key, unless it has expired, without +// telling the eviction policy about it. +func (c *Cache[K, V]) Peek(key K) (value V, ok bool) { + e, ok := c.cache.Peek(key) + if !ok || c.expired(e.deadline) { + return value, false + } + return e.value, true +} + +// Set stores value under key, to expire after the time to live that the Cache +// was made with, and reports the entry that left the cache as a result, if +// there is one: the previous entry for key, or one that was evicted to make +// room, whether it had expired or not. See [evict.Cache]. +func (c *Cache[K, V]) Set(key K, value V) (oldKey K, oldValue V, displaced bool) { + oldKey, old, displaced := c.cache.Set(key, Entry[V]{value: value, deadline: c.clock.deadline(c.ttl)}) + return oldKey, old.value, displaced +} + +// SetWithTTL is Set with a time to live of its own for the entry. +// +// A time to live of zero or less has run out before the entry is stored. If key +// has an entry when SetWithTTL looks, the new one takes its place all the same, +// and is never found. If not, SetWithTTL stores nothing and hands the new entry +// straight back, as a cache without capacity does, rather than evict another +// entry for one that would never be found. An entry of key that leaves in +// between is stored as Set would store it. +func (c *Cache[K, V]) SetWithTTL(key K, value V, ttl time.Duration) (oldKey K, oldValue V, displaced bool) { + if ttl <= 0 { + if _, ok := c.cache.Peek(key); !ok { + return key, value, true + } + } + oldKey, old, displaced := c.cache.Set(key, Entry[V]{value: value, deadline: c.clock.deadline(ttl)}) + return oldKey, old.value, displaced +} + +// Delete removes key and returns the value it had, unless that had expired. +// An expired entry is removed all the same; delete it from the wrapped cache +// to have its value back. +func (c *Cache[K, V]) Delete(key K) (value V, ok bool) { + e, ok := c.cache.Delete(key) + if !ok || c.expired(e.deadline) { + return value, false + } + return e.value, 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() } + +// Cap returns the number of entries the cache can hold. +func (c *Cache[K, V]) Cap() int { return c.cache.Cap() } + +// Clear removes every entry, without reporting any of them. To release what +// they hold, go over the All of the wrapped cache first, which yields the +// entries that have expired as well. See [evict.Cache]. +func (c *Cache[K, V]) Clear() { c.cache.Clear() } + +// All iterates over the entries that have not expired, as the All of the +// cache does over all of them. +func (c *Cache[K, V]) All() iter.Seq2[K, V] { + return func(yield func(K, V) bool) { + for key, e := range c.cache.All() { + if !c.expired(e.deadline) && !yield(key, e.value) { + return + } + } + } +} + +var _ evict.Cache[int, int] = (*Cache[int, int])(nil) diff --git a/expire/expire_test.go b/expire/expire_test.go new file mode 100644 index 0000000..99830c1 --- /dev/null +++ b/expire/expire_test.go @@ -0,0 +1,755 @@ +package expire_test + +import ( + "math" + "math/rand/v2" + "runtime" + "slices" + "strconv" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/floatdrop/evict" + "github.com/floatdrop/evict/expire" + "github.com/floatdrop/evict/internal/cachetest" + "github.com/floatdrop/evict/lru" + "github.com/floatdrop/evict/s3fifo" + "github.com/floatdrop/evict/sieve" + "github.com/floatdrop/evict/stats" + "github.com/floatdrop/evict/tinylfu" + "github.com/floatdrop/evict/twoq" +) + +// A wrapped cache must still be a cache, as long as nothing expires. One with +// a lock and one without get the suite. +var ( + lruFactories = cachetest.Factories{ + Int: func(capacity, shards int) evict.Cache[int, int] { + return expire.Wrap(lru.New[int, expire.Entry[int]](capacity, lru.WithShards(shards)), time.Hour) + }, + String: func(capacity, shards int) evict.Cache[string, string] { + return expire.Wrap(lru.New[string, expire.Entry[string]](capacity, lru.WithShards(shards)), time.Hour) + }, + Float: func(capacity, shards int) evict.Cache[float64, int] { + return expire.Wrap(lru.New[float64, expire.Entry[int]](capacity, lru.WithShards(shards)), time.Hour) + }, + Blob: func(capacity, shards int) evict.Cache[int, *cachetest.Blob] { + return expire.Wrap(lru.New[int, expire.Entry[*cachetest.Blob]](capacity, lru.WithShards(shards)), time.Hour) + }, + BlobKey: func(capacity, shards int) evict.Cache[*cachetest.Blob, int] { + return expire.Wrap(lru.New[*cachetest.Blob, expire.Entry[int]](capacity, lru.WithShards(shards)), time.Hour) + }, + Wide: func(capacity, shards int) evict.Cache[string, cachetest.Wide] { + return expire.Wrap(lru.New[string, expire.Entry[cachetest.Wide]](capacity, lru.WithShards(shards)), time.Hour) + }, + } + + s3fifoFactories = cachetest.Factories{ + Int: func(capacity, shards int) evict.Cache[int, int] { + return expire.Wrap(s3fifo.New[int, expire.Entry[int]](capacity, s3fifo.WithShards(shards)), time.Hour) + }, + String: func(capacity, shards int) evict.Cache[string, string] { + return expire.Wrap(s3fifo.New[string, expire.Entry[string]](capacity, s3fifo.WithShards(shards)), time.Hour) + }, + Float: func(capacity, shards int) evict.Cache[float64, int] { + return expire.Wrap(s3fifo.New[float64, expire.Entry[int]](capacity, s3fifo.WithShards(shards)), time.Hour) + }, + Blob: func(capacity, shards int) evict.Cache[int, *cachetest.Blob] { + return expire.Wrap(s3fifo.New[int, expire.Entry[*cachetest.Blob]](capacity, s3fifo.WithShards(shards)), time.Hour) + }, + BlobKey: func(capacity, shards int) evict.Cache[*cachetest.Blob, int] { + return expire.Wrap(s3fifo.New[*cachetest.Blob, expire.Entry[int]](capacity, s3fifo.WithShards(shards)), time.Hour) + }, + Wide: func(capacity, shards int) evict.Cache[string, cachetest.Wide] { + return expire.Wrap(s3fifo.New[string, expire.Entry[cachetest.Wide]](capacity, s3fifo.WithShards(shards)), time.Hour) + }, + Ghosts: 0.9, + } +) + +func TestCache(t *testing.T) { + t.Parallel() + + t.Run("lru", func(t *testing.T) { t.Parallel(); cachetest.Run(t, lruFactories) }) + t.Run("s3fifo", func(t *testing.T) { t.Parallel(); cachetest.Run(t, s3fifoFactories) }) +} + +// TestNoAllocs is not parallel: counting allocations needs the process to +// itself. +func TestNoAllocs(t *testing.T) { + warmClock(t) + t.Run("lru", func(t *testing.T) { cachetest.NoAllocs(t, lruFactories) }) + t.Run("s3fifo", func(t *testing.T) { cachetest.NoAllocs(t, s3fifoFactories) }) + + // GetMany takes its batch from a pool, which the collector empties now + // and then, and which a goroutine that has moved to another CPU may + // find empty. Once in a while is fine; once a call is not. + t.Run("GetMany", func(t *testing.T) { + c := expire.Wrap(s3fifo.New[int, expire.Entry[int]](1000), time.Hour) + keys := make([]int, 100) + for i := range keys { + keys[i] = i + c.Set(i, i) + } + values, found := make([]int, len(keys)), make([]bool, len(keys)) + if allocs := testing.AllocsPerRun(100, func() { c.GetMany(keys, values, found) }); allocs != 0 { + t.Errorf("%v allocations per GetMany, want 0", allocs) + } + }) +} + +// warmClock starts the clock that Wrap uses, if no test has yet, and waits for +// it to tick twice. Then it keeps every CPU busy for a moment. +// +// Each tick runs a goroutine, and the runtime may start a thread for it, which +// allocates. Threads are never stopped, so once there are enough of them to +// keep every CPU busy, the ticks need no new ones, and a test of the caches +// counts no allocations of theirs. +func warmClock(t *testing.T) { + t.Helper() + + expire.Wrap(lru.New[int, expire.Entry[int]](1), time.Hour) + start := time.Now() + for range 2 { + before := expire.SystemNow() + for expire.SystemNow() == before { + if time.Since(start) > 5*time.Second { + t.Fatal("the clock that Wrap uses has not ticked for seconds") + } + time.Sleep(time.Millisecond) + } + } + + var wg sync.WaitGroup + for range runtime.GOMAXPROCS(0) { + wg.Go(func() { + spin := time.Now() + for time.Since(spin) < 20*time.Millisecond { + runtime.Gosched() + } + }) + } + wg.Wait() +} + +// policies make a cache of each policy, of 100 entries in 4 shards. +var policies = map[string]func() evict.Cache[string, expire.Entry[int]]{ + "lru": func() evict.Cache[string, expire.Entry[int]] { + return lru.New[string, expire.Entry[int]](100, lru.WithShards(4)) + }, + "twoq": func() evict.Cache[string, expire.Entry[int]] { + return twoq.New[string, expire.Entry[int]](100, twoq.WithShards(4)) + }, + "sieve": func() evict.Cache[string, expire.Entry[int]] { + return sieve.New[string, expire.Entry[int]](100, sieve.WithShards(4)) + }, + "s3fifo": func() evict.Cache[string, expire.Entry[int]] { + return s3fifo.New[string, expire.Entry[int]](100, s3fifo.WithShards(4)) + }, + "tinylfu": func() evict.Cache[string, expire.Entry[int]] { + return tinylfu.New[string, expire.Entry[int]](100, tinylfu.WithShards(4)) + }, +} + +// found reports whether key is found, and checks that every way of reading +// agrees: Get, Peek, GetMany with a batch large enough to be looked up as one, +// and All. A key that is found must have the value want. +func found(t *testing.T, c *expire.Cache[string, int], key string, want int) bool { + t.Helper() + + v, ok := c.Get(key) + if pv, pok := c.Peek(key); pv != v || pok != ok { + t.Fatalf("Get(%q) = %d, %t but Peek gives %d, %t", key, v, ok, pv, pok) + } + keys := slices.Repeat([]string{key}, 8) + values, founds := make([]int, len(keys)), make([]bool, len(keys)) + c.GetMany(keys, values, founds) + for i := range keys { + if values[i] != v || founds[i] != ok { + t.Fatalf("Get(%q) = %d, %t but GetMany gives %d, %t", key, v, ok, values[i], founds[i]) + } + } + all := false + for k, av := range c.All() { + if k == key { + all = true + if av != v { + t.Fatalf("Get(%q) = %d but All yields %d", key, v, av) + } + } + } + if all != ok { + t.Fatalf("Get(%q) finds it: %t, but All yields it: %t", key, ok, all) + } + if ok && v != want { + t.Fatalf("Get(%q) = %d, want %d", key, v, want) + } + return ok +} + +// An entry is found until its time is up, and from then on not at all, by any +// policy, whatever way it is looked for. +func TestExpiry(t *testing.T) { + t.Parallel() + + for name, newCache := range policies { + t.Run(name, func(t *testing.T) { + t.Parallel() + + clock := expire.NewClock() + c := expire.WrapWith(newCache(), time.Minute, clock) + c.Set("a", 1) + c.SetWithTTL("b", 2, time.Second) + c.SetWithTTL("c", 3, 2*time.Second) + + clock.Advance(time.Second - 1) + if !found(t, c, "a", 1) || !found(t, c, "b", 2) || !found(t, c, "c", 3) { + t.Fatal("an entry is gone before its time") + } + + clock.Advance(1) + if found(t, c, "b", 2) { + t.Error("b is found when its second is up") + } + if !found(t, c, "a", 1) || !found(t, c, "c", 3) { + t.Fatal("an entry is gone before its time") + } + // It is still there, and takes up room. + if n := c.Len(); n != 3 { + t.Errorf("Len() = %d, want 3 with b expired", n) + } + + // Deleting it says it was not there, and removes it. + if v, ok := c.Delete("b"); ok || v != 0 { + t.Errorf("Delete(b) = %d, %t after it expired, want 0, false", v, ok) + } + if n := c.Len(); n != 2 { + t.Errorf("Len() = %d after b was deleted, want 2", n) + } + + // Setting it again starts it over. + c.SetWithTTL("b", 20, time.Second) + clock.Advance(time.Second / 2) + if !found(t, c, "b", 20) { + t.Error("b is not found after it was set again") + } + if v, ok := c.Delete("b"); !ok || v != 20 { + t.Errorf("Delete(b) = %d, %t, want 20, true", v, ok) + } + + clock.Advance(time.Minute) + if found(t, c, "a", 1) || found(t, c, "c", 3) { + t.Error("an entry is found when its time is up") + } + }) + } +} + +// 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) { + t.Parallel() + + clock := expire.NewClock() + c := expire.WrapWith(lru.New[string, expire.Entry[int]](1), time.Second, clock) + + c.Set("a", 1) + clock.Advance(time.Second) + if k, v, displaced := c.Set("a", 2); !displaced || k != "a" || v != 1 { + t.Errorf("Set(a) over an expired a = %q, %d, %t; want a, 1, true", k, v, displaced) + } + if !found(t, c, "a", 2) { + t.Error("a is not found after it was replaced") + } + + clock.Advance(time.Second) + if k, v, displaced := c.Set("b", 3); !displaced || k != "a" || v != 2 { + t.Errorf("Set(b) in place of an expired a = %q, %d, %t; want a, 2, true", k, v, displaced) + } +} + +// A time to live that is zero or less has run out before the entry is stored, +// and one that is too long for the clock never does. +func TestTTLBounds(t *testing.T) { + t.Parallel() + + clock := expire.NewClock() + c := expire.WrapWith(lru.New[string, expire.Entry[int]](10), time.Second, clock) + clock.Advance(time.Hour) // So that a negative time to live has room to go below zero. + + // For a key with an entry, expired or not, the new entry takes its + // place. Each round replaces the one that the round before stored, which + // had expired before it was stored. + c.Set("a", 1) + prev := 1 + for i, ttl := range []time.Duration{0, -1, -time.Hour, math.MinInt64} { + if k, v, displaced := c.SetWithTTL("a", 10+i, ttl); !displaced || k != "a" || v != prev { + t.Errorf("SetWithTTL(a, %d, %v) = %q, %d, %t; want a, %d, true", 10+i, ttl, k, v, displaced, prev) + } + if found(t, c, "a", 10+i) { + t.Errorf("a is found after it was set with a time to live of %v", ttl) + } + prev = 10 + i + } + + // For a key without an entry, nothing is stored, and the new entry comes + // straight back. Nothing is evicted for it either. + one := expire.WrapWith(lru.New[string, expire.Entry[int]](1), time.Second, clock) + one.Set("live", 1) + if k, v, displaced := one.SetWithTTL("dead", 2, 0); !displaced || k != "dead" || v != 2 { + t.Errorf("SetWithTTL(dead, 2, 0) = %q, %d, %t; want dead, 2, true", k, v, displaced) + } + if !found(t, one, "live", 1) || one.Len() != 1 { + t.Error("SetWithTTL with a time to live of 0 evicted an entry of another key") + } + + c.SetWithTTL("b", 2, math.MaxInt64) + c.SetWithTTL("c", 3, math.MaxInt64-2*time.Hour) + if d := expire.DeadlineOf(c, "b"); d != math.MaxInt64 { + t.Errorf("a time to live of MaxInt64 gives a deadline of %d, want MaxInt64", d) + } + clock.Advance(100 * 365 * 24 * time.Hour) + if !found(t, c, "b", 2) || !found(t, c, "c", 3) { + t.Error("an entry with a time to live too long for the clock expired") + } + + for _, ttl := range []time.Duration{0, -1} { + func() { + defer func() { + if recover() == nil { + t.Errorf("Wrap with a time to live of %v did not panic", ttl) + } + }() + expire.Wrap(lru.New[string, expire.Entry[int]](10), ttl) + }() + } +} + +// 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. +type hooked struct { + evict.Cache[string, expire.Entry[int]] + after func() +} + +func (h *hooked) Peek(key string) (expire.Entry[int], bool) { + e, ok := h.Cache.Peek(key) + if h.after != nil { + h.after() + } + return e, ok +} + +// 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 +// is handed back, as if it had come after. +func TestSetWithTTLRace(t *testing.T) { + t.Parallel() + + clock := expire.NewClock() + h := &hooked{Cache: lru.New[string, expire.Entry[int]](2)} + c := expire.WrapWith(h, time.Hour, clock) + + // x leaves and another key takes its place, so the cache is full. + c.Set("x", 1) + c.Set("live", 2) + h.after = func() { + h.after = nil + c.Delete("x") + c.Set("other", 3) + } + if k, v, displaced := c.SetWithTTL("x", 9, 0); !displaced || k != "live" || v != 2 { + t.Errorf("SetWithTTL(x, 9, 0) after x left = %q, %d, %t; want live to be evicted", k, v, displaced) + } + if found(t, c, "x", 9) { + t.Error("x is found after it was set with a time to live of 0") + } + + // y comes in: the new entry is handed back, and y's stays. + h.after = func() { + h.after = nil + c.Set("y", 4) + } + if k, v, displaced := c.SetWithTTL("y", 8, 0); !displaced || k != "y" || v != 8 { + t.Errorf("SetWithTTL(y, 8, 0) as y came in = %q, %d, %t; want y, 8, true", k, v, displaced) + } + if !found(t, c, "y", 4) { + t.Error("y is gone after SetWithTTL found no entry of it") + } +} + +// Readers look at a copy of the time that may lag behind. An entry that is due +// to expire within 50 ms of it is checked against the time itself, so a lag of +// up to 50 ms changes nothing. With more than that, an entry is found for up to +// as much longer. +func TestLag(t *testing.T) { + t.Parallel() + + clock := expire.NewClock() + c := expire.WrapWith(lru.New[string, expire.Entry[int]](10), time.Second, clock) + c.SetWithTTL("a", 1, 100*time.Millisecond) + c.SetWithTTL("b", 2, 150*time.Millisecond) + + // At 99 ms, nothing has expired, whatever the lag: the copy of the + // time is never ahead of it. + clock.Advance(99 * time.Millisecond) + for _, lag := range []time.Duration{0, 10 * time.Millisecond, 49 * time.Millisecond, 99 * time.Millisecond} { + clock.Lag(lag) + if !found(t, c, "a", 1) { + t.Errorf("a is gone 1 ms before its time, with the copy of the time %v behind", lag) + } + } + + // At 100 ms exactly, a has expired, also where the time itself has to + // tell. + clock.Advance(time.Millisecond) + clock.Lag(10 * time.Millisecond) + if found(t, c, "a", 1) { + t.Error("a is found at its deadline, with the copy of the time 10 ms behind") + } + clock.Lag(0) + if found(t, c, "a", 1) { + t.Error("a is found at its deadline") + } + + // At 120 ms, a has expired 20 ms ago. A copy of the time that lags by up + // to 50 ms shows it, and one that lags by 70 ms still does: a is due 50 + // ms after that copy, which is near enough to be checked. + clock.Advance(20 * time.Millisecond) + for _, lag := range []time.Duration{0, 10 * time.Millisecond, 50 * time.Millisecond, 70 * time.Millisecond} { + clock.Lag(lag) + if found(t, c, "a", 1) { + t.Errorf("a is found 20 ms after it expired, with the copy of the time %v behind", lag) + } + if !found(t, c, "b", 2) { + t.Errorf("b is gone 30 ms before its time, with the copy of the time %v behind", lag) + } + } + + // One that lags by 80 ms does not: a is due 60 ms after it, and taken + // to be there. + clock.Lag(80 * time.Millisecond) + if !found(t, c, "a", 1) { + t.Error("a was checked against the time when it was due 60 ms after the copy of it; the test expects it was not") + } +} + +// GetMany has to find what Peek finds, among entries of which some expired, +// with batches of every size, whether the cache has a GetMany of its own or +// not. +func TestGetMany(t *testing.T) { + t.Parallel() + + const capacity = 500 + for name, cache := range map[string]evict.Cache[int, expire.Entry[int]]{ + "lru": lru.New[int, expire.Entry[int]](capacity), + "s3fifo": s3fifo.New[int, expire.Entry[int]](capacity), + "tinylfu": tinylfu.New[int, expire.Entry[int]](capacity), + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + clock := expire.NewClock() + c := expire.WrapWith(cache, time.Hour, clock) + for k := range capacity / 2 { + // Every third entry expires in a second. + ttl := time.Hour + if k%3 == 0 { + ttl = time.Second + } + c.SetWithTTL(k, -k, ttl) + } + clock.Advance(time.Second) + + rng := rand.New(rand.NewPCG(1, 2)) + for _, n := range []int{0, 1, 3, 4, 31, 32, 33, 64, 100} { + keys := make([]int, n) + for i := range keys { + keys[i] = rng.IntN(capacity) + } + // The values and the found are filled with garbage, which + // GetMany must overwrite. + values, founds := make([]int, n), make([]bool, n) + for i := range values { + values[i], founds[i] = 1, true + } + c.GetMany(keys, values, founds) + for i, k := range keys { + v, ok := c.Peek(k) + if values[i] != v || founds[i] != ok { + t.Fatalf("GetMany of %d keys: key %d gave %d, %t; Peek gives %d, %t", n, k, values[i], founds[i], v, ok) + } + if want := k < capacity/2 && k%3 != 0; ok != want { + t.Fatalf("key %d found: %t, want %t", k, ok, want) + } + } + } + + // The values may be the keys themselves. + keys := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} + founds := make([]bool, len(keys)) + c.GetMany(keys, keys, founds) + want := []int{0, -1, -2, 0, -4, -5, 0, -7, -8, 0} + if !slices.Equal(keys, want) { + t.Errorf("GetMany into its own keys gives %v, want %v", keys, want) + } + + for _, short := range [][2]int{{9, 10}, {10, 9}} { + func() { + defer func() { + if recover() == nil { + t.Errorf("GetMany with %d values and %d found for 10 keys did not panic", short[0], short[1]) + } + }() + c.GetMany(make([]int, 10), make([]int, short[0]), make([]bool, short[1])) + }() + } + }) + } +} + +// The clock that Wrap uses keeps time: an entry is found until its time to +// live is up, and stops being found soon after. How soon depends on how busy +// the machine is, so the test gives it a few seconds. +func TestSystemClock(t *testing.T) { + t.Parallel() + + const ttl = 30 * time.Millisecond + c := expire.Wrap(lru.New[string, expire.Entry[int]](10), time.Hour) + + start := time.Now() + c.SetWithTTL("a", 1, ttl) + for { + // The copy of the time that readers look at is never ahead. + if now, read := expire.SystemNow(), expire.SystemRead(); now > read { + t.Fatalf("the copy of the time is %v, ahead of the time, %v", now, read) + } + if _, ok := c.Get("a"); !ok { + break + } + if time.Since(start) > 5*time.Second { + t.Fatalf("a is still found after %v, with a time to live of %v", time.Since(start), ttl) + } + time.Sleep(time.Millisecond) + } + if elapsed := time.Since(start); elapsed < ttl { + t.Errorf("a expired after %v, with a time to live of %v", elapsed, ttl) + } + + // The timer keeps the copy up to date: it lags by half a tick of 10 ms + // on average. A busy machine may hold the timer up now and then, so the + // test looks at the median of many samples, and allows for four ticks. + lags := make([]time.Duration, 200) + for i := range lags { + now := expire.SystemNow() + lags[i] = expire.SystemRead() - now + time.Sleep(time.Millisecond + time.Duration(i%7)*100*time.Microsecond) + } + slices.Sort(lags) + if median := lags[len(lags)/2]; median > 40*time.Millisecond { + t.Errorf("the copy of the time lags by %v in the median, want a few ms", median) + } +} + +// Goroutines that read and write while time passes must only ever find what +// was stored under a key, and nothing once the time to live of every entry is +// up. +func TestConcurrent(t *testing.T) { + t.Parallel() + + for _, name := range []string{"lru", "s3fifo", "tinylfu"} { + t.Run(name, func(t *testing.T) { + t.Parallel() + + const ( + goroutines = 8 + requests = 3000 + keys = 200 + ) + clock := expire.NewClock() + c := expire.WrapWith(policies[name](), time.Second, clock) + + var done atomic.Bool + var wg sync.WaitGroup + wg.Go(func() { + for !done.Load() { + clock.Advance(time.Millisecond) + time.Sleep(time.Microsecond) + } + }) + var workers sync.WaitGroup + for g := range goroutines { + workers.Go(func() { + rng := rand.New(rand.NewPCG(uint64(g), 3)) + batch, values, founds := make([]string, 8), make([]int, 8), make([]bool, 8) + for range requests { + k := rng.IntN(keys) + key := strconv.Itoa(k) + switch rng.IntN(4) { + case 0: + c.SetWithTTL(key, k, time.Duration(rng.IntN(20))*time.Millisecond) + case 1: + if v, ok := c.Delete(key); ok && v != k { + t.Errorf("Delete(%q) = %d", key, v) + } + case 2: + for i := range batch { + batch[i] = strconv.Itoa(rng.IntN(keys)) + } + c.GetMany(batch, values, founds) + for i, key := range batch { + if founds[i] && strconv.Itoa(values[i]) != key { + t.Errorf("GetMany found %d for %q", values[i], key) + } + } + default: + if v, ok := c.Get(key); ok && v != k { + t.Errorf("Get(%q) = %d", key, v) + } + } + } + }) + } + workers.Wait() + done.Store(true) + wg.Wait() + + clock.Advance(time.Second) + for k, v := range c.All() { + t.Errorf("All yields %q=%d after every entry expired", k, v) + } + }) + } +} + +// Wrapped in stats, an expired entry counts as a miss, through Get and +// GetMany alike. +func TestStats(t *testing.T) { + t.Parallel() + + clock := expire.NewClock() + c := stats.Wrap(expire.WrapWith(s3fifo.New[int, expire.Entry[int]](100), time.Second, clock)) + for k := range 10 { + c.Set(k, k) + } + clock.Advance(time.Second) + for k := 10; k < 20; k++ { + c.Set(k, k) + } + + c.Get(0) + c.Get(10) + keys := []int{1, 2, 3, 11, 12, 13, 14, 15} + c.GetMany(keys, make([]int, len(keys)), make([]bool, len(keys))) + + if s := c.Stats(); s.Hits != 6 || s.Misses != 4 { + t.Errorf("%d hits and %d misses, want 6 and 4", s.Hits, s.Misses) + } +} + +// Readers look at the copy of the time on every read. It has to have a cache +// line to itself, or whatever shares the line would take it away from the +// readers' CPUs when it is written to. The clock is not aligned to a line, so +// that takes 128 bytes on either side. +func TestClockLayout(t *testing.T) { + t.Parallel() + + if expire.NowOffset < 128 || expire.FakeOffset-expire.NowOffset < 128 { + t.Errorf("the copy of the time is at %d, and the next field at %d; want a line of 128 bytes to itself", + expire.NowOffset, expire.FakeOffset) + } +} + +// batcher is a cache with a GetMany of its own, which says how often it was +// called. +type batcher struct { + evict.Cache[int, expire.Entry[int]] + calls int +} + +func (b *batcher) GetMany(keys []int, values []expire.Entry[int], found []bool) { + b.calls++ + for i, k := range keys { + values[i], found[i] = b.Get(k) + } +} + +// GetMany has to go to the GetMany of the cache, in batches as large as those +// of the caches of this module. +func TestGetManyForwards(t *testing.T) { + t.Parallel() + + b := &batcher{Cache: lru.New[int, expire.Entry[int]](200)} + c := expire.WrapWith(b, time.Hour, expire.NewClock()) + keys := make([]int, 100) + for i := range keys { + keys[i] = i + c.Set(i, -i) + } + values, founds := make([]int, len(keys)), make([]bool, len(keys)) + c.GetMany(keys, values, founds) + if b.calls != 4 { + t.Errorf("GetMany of 100 keys called that of the cache %d times, want 4", b.calls) + } + for i, k := range keys { + if !founds[i] || values[i] != -k { + t.Fatalf("GetMany found %d, %t for %d", values[i], founds[i], k) + } + } +} + +// What GetMany looks up goes through a batch that it keeps for the next call. +// The batch must not keep the values alive until then. +func TestGetManyLetsGo(t *testing.T) { + t.Parallel() + + c := expire.WrapWith(s3fifo.New[int, expire.Entry[*cachetest.Blob]](100), time.Hour, expire.NewClock()) + keys := make([]int, 40) + for i := range keys { + keys[i] = i + c.Set(i, new(cachetest.Blob)) + } + values, founds := make([]*cachetest.Blob, len(keys)), make([]bool, len(keys)) + for range 10 { + c.GetMany(keys, values, founds) + clean, got := expire.PooledBatch(c) + if !got { + continue // Taken from another CPU's share of the pool; try again. + } + if !clean { + t.Error("the batch that GetMany keeps holds entries") + } + return + } + t.Skip("the pool never had a batch to hand") +} + +// The values of expired entries can be had from the wrapped cache, for those +// that need releasing. +func TestRelease(t *testing.T) { + t.Parallel() + + clock := expire.NewClock() + inner := lru.New[string, expire.Entry[int]](10) + c := expire.WrapWith(inner, time.Second, clock) + c.Set("a", 1) + c.Set("b", 2) + clock.Advance(time.Second) + + values := map[string]int{} + for k, e := range inner.All() { + values[k] = e.Value() + } + if len(values) != 2 || values["a"] != 1 || values["b"] != 2 { + t.Errorf("the wrapped cache yields %v, want a=1 and b=2", values) + } + if e, ok := inner.Delete("a"); !ok || e.Value() != 1 { + t.Errorf("the wrapped cache's Delete(a) = %d, %t; want 1, true", e.Value(), ok) + } + if v := (expire.Entry[int]{}).Value(); v != 0 { + t.Errorf("Entry{}.Value() = %d", v) + } +} diff --git a/expire/export_test.go b/expire/export_test.go new file mode 100644 index 0000000..40ee302 --- /dev/null +++ b/expire/export_test.go @@ -0,0 +1,89 @@ +package expire + +import ( + "sync/atomic" + "time" + "unsafe" + + "github.com/floatdrop/evict" +) + +// Clock is a fake clock for tests. It starts at zero, and has the time that +// readers look at lag behind the time itself only when told to. +type Clock struct{ c *clock } + +// NewClock returns a fake clock. +func NewClock() Clock { + return Clock{&clock{fixed: true, begin: func() {}}} +} + +// Advance moves the time on by d, and the copy that readers look at with it. +func (c Clock) Advance(d time.Duration) { + atomic.AddInt64(&c.c.fake, int64(d)) + atomic.AddInt64(&c.c.now, int64(d)) +} + +// Lag sets the copy of the time that readers look at to d behind the time, as +// if the timer that updates it were late, but no further back than zero, where +// it starts. +func (c Clock) Lag(d time.Duration) { + atomic.StoreInt64(&c.c.now, max(atomic.LoadInt64(&c.c.fake)-int64(d), 0)) +} + +// WrapWith is Wrap with a fake clock. +func WrapWith[K comparable, V any](cache evict.Cache[K, Entry[V]], ttl time.Duration, clock Clock) *Cache[K, V] { + return wrap(cache, ttl, clock.c) +} + +// NowOffset is where the time that readers look at lies in a clock. +const NowOffset = unsafe.Offsetof(clock{}.now) + +// FakeOffset is where the first field after the line of now lies in a clock. +const FakeOffset = unsafe.Offsetof(clock{}.fake) + +// SystemNow returns the time of the last tick of the clock that Wrap uses. +func SystemNow() time.Duration { return time.Duration(atomic.LoadInt64(&system.now)) } + +// SystemRead returns the time by the clock that Wrap uses. +func SystemRead() time.Duration { return time.Duration(system.read()) } + +// NewRealClock returns a clock that reads the time like the one Wrap uses, +// but has no timer: the copy of the time that readers look at stays where +// SetCopy puts it. +func NewRealClock() Clock { + return Clock{&clock{epoch: time.Now(), begin: func() {}}} +} + +// SetCopy sets the copy of the time that readers look at. +func (c Clock) SetCopy(d time.Duration) { atomic.StoreInt64(&c.c.now, int64(d)) } + +// Read returns the time by the clock. +func (c Clock) Read() time.Duration { return time.Duration(c.c.read()) } + +// PooledBatch takes a batch that GetMany has put back from the pool of c, and +// reports whether it holds nothing but zero entries. got is false if the pool +// had none to hand, which may happen when the goroutine has moved to another +// CPU since it called GetMany. +func PooledBatch[K, V comparable](c *Cache[K, V]) (clean, got bool) { + b, _ := c.batches.Get().(*batch[V]) + if b == nil { + return false, false + } + defer c.batches.Put(b) + for _, e := range b { + if e != (Entry[V]{}) { + return false, true + } + } + return true, true +} + +// DeadlineOf returns the deadline of the entry of key, as the wrapped cache +// holds it, or -1 if it has none. +func DeadlineOf[K comparable, V any](c *Cache[K, V], key K) int64 { + e, ok := c.cache.Peek(key) + if !ok { + return -1 + } + return e.deadline +} diff --git a/internal/inlinecheck/inline_test.go b/internal/inlinecheck/inline_test.go index eebf4c6..3a2dc56 100644 --- a/internal/inlinecheck/inline_test.go +++ b/internal/inlinecheck/inline_test.go @@ -25,7 +25,7 @@ import ( ) // hot matches the functions that every operation on a cache goes through. -var hot = regexp.MustCompile(`/(lru|twoq|sieve|s3fifo|tinylfu|stats)\.\(\*(Cache|shard)\[.*\]\)\.(Get|GetMany|Peek|Set|set|evict|Delete|look|victim|promote|asked)$|` + +var hot = regexp.MustCompile(`/(lru|twoq|sieve|s3fifo|tinylfu|stats|expire)\.\(\*(Cache|shard)\[.*\]\)\.(Get|GetMany|Peek|Set|SetWithTTL|set|evict|Delete|look|victim|promote|asked)$|` + `/c?slab\.\(\*Slab\[.*\]\)\.(Find|Lookup|Insert|Replace|Remove)$`) // slow matches the calls that must not show up in them: functions that are @@ -34,7 +34,7 @@ var slow = regexp.MustCompile(`^sync\.\(\*(RW)?Mutex\)\.|^sync/atomic\.|` + `slab\.\(\*Slab\[.*\]\)\.(MoveToFront|PushFront|Unlink|Len|Cap|Overdue|Hash|pin|preferred|Touch|TouchNode)$|` + `cslab\.\(\*Node\[.*\]\)\.(Meta|SetMeta)$|cslab\.\(\*Slot\)\.Unpin$|/s3fifo\.(tagOf|ghostOf)$|` + `/tinylfu\.(tagOf|kept|keep|printOf|printIn)$|/tinylfu\.\(\*climber\)\.(hit|miss)$|` + - `/stats\.\(\*Cache\[.*\]\)\.stripe$`) + `/stats\.\(\*Cache\[.*\]\)\.stripe$|/expire\.\(\*Cache\[.*\]\)\.expired$`) // read matches the functions that a read without a lock goes through, and // readSlow the calls that must not show up in them even where the compiler @@ -134,7 +134,7 @@ func TestHotPathsAreInlined(t *testing.T) { } // The test is only worth something if it has looked at the right code. - for _, pkg := range []string{"lru", "twoq", "sieve", "s3fifo", "tinylfu", "stats"} { + for _, pkg := range []string{"lru", "twoq", "sieve", "s3fifo", "tinylfu", "stats", "expire"} { for _, method := range []string{"Get", "Set", "Peek", "Delete"} { found := false for name := range seen { @@ -145,7 +145,7 @@ func TestHotPathsAreInlined(t *testing.T) { } } } - for _, pkg := range []string{"sieve", "s3fifo", "tinylfu", "stats"} { + for _, pkg := range []string{"sieve", "s3fifo", "tinylfu", "stats", "expire"} { found := false for name := range seen { found = found || strings.Contains(name, "/"+pkg+".(*Cache[") && strings.HasSuffix(name, ").GetMany") @@ -154,6 +154,13 @@ func TestHotPathsAreInlined(t *testing.T) { t.Errorf("the compiler's output has no code for %s.Cache.GetMany", pkg) } } + found := false + for name := range seen { + found = found || strings.Contains(name, "/expire.(*Cache[") && strings.HasSuffix(name, ").SetWithTTL") + } + if !found { + t.Error("the compiler's output has no code for expire.Cache.SetWithTTL") + } for _, want := range [][2]string{ {"sieve.(*Cache[", "Get"}, {"sieve.(*Cache[", "Peek"}, diff --git a/internal/inlinecheck/probe/expire/probe.go b/internal/inlinecheck/probe/expire/probe.go new file mode 100644 index 0000000..95e812f --- /dev/null +++ b/internal/inlinecheck/probe/expire/probe.go @@ -0,0 +1,29 @@ +// Package probe uses a cache whose entries expire the way a program does: with +// key and value types of its own, and without importing anything but the +// wrapper and a cache to wrap. The test two directories up compiles it and +// looks at what the compiler made of it. +package probe + +import ( + "time" + + "github.com/floatdrop/evict/expire" +) + +// Key is a key type that only this package instantiates the cache with. +type Key struct{ Tenant, ID string } + +// Value is a value type that only this package instantiates the cache with. +type Value struct{ Size, Hits int } + +// Use keeps the compiler from discarding the methods of the cache. +func Use(c *expire.Cache[Key, Value], k Key, v Value) (Value, bool) { + c.Set(k, v) + c.SetWithTTL(k, v, time.Second) + c.Peek(k) + c.Delete(k) + var values [2]Value + var found [2]bool + c.GetMany([]Key{k, k}, values[:], found[:]) + return c.Get(k) +} diff --git a/internal/inlinecheck/probe/expirewrap/probe.go b/internal/inlinecheck/probe/expirewrap/probe.go new file mode 100644 index 0000000..b2637c6 --- /dev/null +++ b/internal/inlinecheck/probe/expirewrap/probe.go @@ -0,0 +1,23 @@ +// Package probe is a generic type that wraps a cache whose entries expire, and +// instantiates nothing, like a program's own cache type might. The package that +// uses it, expirewrapuser, is where its methods and those of the wrapper are +// compiled, knowing only what this package has passed on, which is next to +// nothing. +package probe + +import "github.com/floatdrop/evict/expire" + +// Cache wraps a cache whose entries expire. +type Cache[K comparable, V any] struct{ C *expire.Cache[K, V] } + +// Get reads from the cache. +func (c Cache[K, V]) Get(key K) (V, bool) { return c.C.Get(key) } + +// GetMany reads several keys from the cache. +func (c Cache[K, V]) GetMany(keys []K, values []V, found []bool) { c.C.GetMany(keys, values, found) } + +// Peek reads from the cache without recording the access. +func (c Cache[K, V]) Peek(key K) (V, bool) { return c.C.Peek(key) } + +// Set writes to the cache. +func (c Cache[K, V]) Set(key K, value V) { c.C.Set(key, value) } diff --git a/internal/inlinecheck/probe/expirewrapuser/probe.go b/internal/inlinecheck/probe/expirewrapuser/probe.go new file mode 100644 index 0000000..ee8ea17 --- /dev/null +++ b/internal/inlinecheck/probe/expirewrapuser/probe.go @@ -0,0 +1,22 @@ +// Package probe uses a cache whose entries expire through expirewrap, a generic +// type of another package that instantiates nothing. The test two directories +// up compiles it and looks at what the compiler made of it. +package probe + +import wrap "github.com/floatdrop/evict/internal/inlinecheck/probe/expirewrap" + +// Key is a key type that only this package instantiates the cache with. +type Key struct{ Tenant, ID string } + +// Value is a value type that only this package instantiates the cache with. +type Value struct{ Size, Hits int } + +// Use keeps the compiler from discarding the methods of the cache. +func Use(c wrap.Cache[Key, Value], k Key, v Value) (Value, bool) { + c.Set(k, v) + c.Peek(k) + var values [2]Value + var found [2]bool + c.GetMany([]Key{k, k}, values[:], found[:]) + return c.Get(k) +} From bde54ab40b67330cdb91fd82468f607853366aa9 Mon Sep 17 00:00:00 2001 From: Vsevolod Strukchinsky Date: Mon, 23 Nov 2026 15:52:47 +0500 Subject: [PATCH 2/2] List what the module does not do, one limit per bullet Sizes in bytes, a loader, cleanup of expired entries and overwrites that scale, each pointing to otter. The note that a wrapper could count bytes from what Set and Delete hand back is gone: through expire, Delete hands back nothing for an expired entry, so the count would drift. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bb29d3d..d6d505c 100644 --- a/README.md +++ b/README.md @@ -166,8 +166,12 @@ own. ## What it does not do -No weights or sizes in bytes, no loading functions. If you need those, or if many CPUs -overwrite a tenth to a quarter of what they read, use [otter](https://github.com/maypok86/otter). +- **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). +- **Overwrites do not scale with CPUs**; otter's do ([Benchmarks](#benchmarks)). + +For any of these, use [otter](https://github.com/maypok86/otter). ## License