From 3c105b5ea4bbaf8fd03f7e82f96b60b2a43016ba Mon Sep 17 00:00:00 2001 From: Vsevolod Strukchinsky Date: Wed, 25 Nov 2026 08:52:33 +0500 Subject: [PATCH] Add load, which shares one load among the callers of a key load.Wrap puts a loader in front of any evict.Cache, and Fetch loads what the cache does not hold. Fetch calls for one key at the same time wait for a single load, which runs in a goroutine of its own with the values of the first caller's context but not its cancellation. A caller whose context ends stops waiting; the load is canceled, and its value dropped, once nobody waits. Errors are not stored. A loader's panic is raised again in the waiting callers as a *PanicError. A Set, SetIfAbsent, Delete, DeleteFunc or Clear through the wrapper keeps a load in progress from storing what it may have read before the change. Writes lock a stripe for that, which made a Set of tinylfu 60% slower on eight CPUs of an M3 Max; a Fetch that hits took 20-23% longer than a Get. The README loses "No loader" from what the module does not do. Co-Authored-By: Claude Opus 5.5 --- README.md | 15 +- evict.go | 7 +- internal/inlinecheck/inline_test.go | 14 +- internal/inlinecheck/probe/load/probe.go | 27 + load/bench_test.go | 113 +++ load/example_test.go | 38 + load/export_test.go | 56 ++ load/load.go | 412 +++++++++++ load/load_test.go | 856 +++++++++++++++++++++++ 9 files changed, 1531 insertions(+), 7 deletions(-) create mode 100644 internal/inlinecheck/probe/load/probe.go create mode 100644 load/bench_test.go create mode 100644 load/example_test.go create mode 100644 load/export_test.go create mode 100644 load/load.go create mode 100644 load/load_test.go diff --git a/README.md b/README.md index 556151d..07954fe 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,20 @@ Reads still count with the policy, even for expired entries. They look at a copy 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). +### Loading + +```go +// db.User(ctx, id) reads a user from the database. +users := load.Wrap(tinylfu.New[string, User](10_000), db.User) + +u, err := users.Fetch(ctx, "42") // Loads 42 if the cache does not hold it. +``` + +`Fetch` calls for one key at the same time share a single load, and errors are not stored. A +`Set` or `Delete` through the wrapper during a load keeps it from storing what it read +before the change. A `Fetch` that hits took 20–23% longer than a `Get`, and a `Set` 10 ns +longer on one CPU and 60% longer on eight (`tinylfu`, Apple M3 Max). + ## Benchmarks

@@ -163,7 +177,6 @@ Every package takes `WithShards`. `s3fifo` also has options for tuning its queue ## What it does not do - **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 background expiry**: call `PurgeExpired` yourself ([Expiry](#expiry)). - **Overwrites do not scale with CPUs**; otter's do ([Benchmarks](#benchmarks)). diff --git a/evict.go b/evict.go index 34bcb41..5186ace 100644 --- a/evict.go +++ b/evict.go @@ -41,15 +41,16 @@ // // 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, and [github.com/floatdrop/evict/expire] gives their entries a -// time to live. +// any of them, [github.com/floatdrop/evict/expire] gives their entries a time +// to live, and [github.com/floatdrop/evict/load] fills them from a source, +// with one load for the goroutines that ask for a key at the same time. package evict import "iter" // Cache is the behaviour common to every cache in this module. It is // implemented by *lru.Cache, *sieve.Cache, *s3fifo.Cache and *tinylfu.Cache, -// and by the wrappers *stats.Cache and *expire.Cache. +// and by the wrappers *stats.Cache, *expire.Cache and *load.Cache. // // All methods are safe for concurrent use. type Cache[K comparable, V any] interface { diff --git a/internal/inlinecheck/inline_test.go b/internal/inlinecheck/inline_test.go index c8394c1..07dc321 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|sieve|s3fifo|tinylfu|stats|expire)\.\(\*(Cache|shard)\[.*\]\)\.(Get|GetMany|Peek|Set|SetWithTTL|set|SetIfAbsent|add|evict|Delete|look|victim|promote|asked)$|` + +var hot = regexp.MustCompile(`/(lru|sieve|s3fifo|tinylfu|stats|expire|load)\.\(\*(Cache|shard)\[.*\]\)\.(Get|GetMany|Peek|Set|SetWithTTL|set|SetIfAbsent|add|evict|Delete|look|victim|promote|asked|Fetch)$|` + `/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,8 @@ 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$|/expire\.\(\*Cache\[.*\]\)\.expired$`) + `/stats\.\(\*Cache\[.*\]\)\.stripe$|/expire\.\(\*Cache\[.*\]\)\.expired$|` + + `/load\.\(\*Cache\[.*\]\)\.stripe$|/load\.\(\*stripe\[.*\]\)\.forget$`) // 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 +135,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", "sieve", "s3fifo", "tinylfu", "stats", "expire"} { + for _, pkg := range []string{"lru", "sieve", "s3fifo", "tinylfu", "stats", "expire", "load"} { for _, method := range []string{"Get", "Set", "SetIfAbsent", "Peek", "Delete"} { found := false for name := range seen { @@ -161,6 +162,13 @@ func TestHotPathsAreInlined(t *testing.T) { if !found { t.Error("the compiler's output has no code for expire.Cache.SetWithTTL") } + found = false + for name := range seen { + found = found || strings.Contains(name, "/load.(*Cache[") && strings.HasSuffix(name, ").Fetch") + } + if !found { + t.Error("the compiler's output has no code for load.Cache.Fetch") + } for _, want := range [][2]string{ {"sieve.(*Cache[", "Get"}, {"sieve.(*Cache[", "Peek"}, diff --git a/internal/inlinecheck/probe/load/probe.go b/internal/inlinecheck/probe/load/probe.go new file mode 100644 index 0000000..a7a2601 --- /dev/null +++ b/internal/inlinecheck/probe/load/probe.go @@ -0,0 +1,27 @@ +// Package probe uses a loading cache the way a program does: with key and +// value types of its own, and without importing anything but the loader, not +// even a cache of this module. The test two directories up compiles it and +// looks at what the compiler made of it. +package probe + +import ( + "context" + + "github.com/floatdrop/evict/load" +) + +// 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(ctx context.Context, c *load.Cache[Key, Value], k Key, v Value) (Value, error) { + c.Set(k, v) + c.SetIfAbsent(k, v) + c.Peek(k) + c.Get(k) + c.Delete(k) + return c.Fetch(ctx, k) +} diff --git a/load/bench_test.go b/load/bench_test.go new file mode 100644 index 0000000..7f83748 --- /dev/null +++ b/load/bench_test.go @@ -0,0 +1,113 @@ +package load_test + +import ( + "context" + "math/rand/v2" + "testing" + + "github.com/floatdrop/evict" + "github.com/floatdrop/evict/load" + "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) + } +} + +// BenchmarkFetch reads entries that are all there, on every CPU at once: with +// the Get of tinylfu, through an interface, and with the Fetch of the +// wrapper, which calls Get through one. The loop is written out for each, so +// that it makes the call it is about and no other. +func BenchmarkFetch(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("load", func(b *testing.B) { + c := load.Wrap(tinylfu.New[int, int](benchCapacity), never[int, int]) + fill(func(k, v int) { c.Set(k, v) }) + ctx := b.Context() + b.ReportAllocs() + b.RunParallel(func(pb *testing.PB) { + i := rand.Int() + for pb.Next() { + _, _ = c.Fetch(ctx, i&(benchCapacity-1)) + i++ + } + }) + }) +} + +// BenchmarkSet replaces entries, on every CPU at once: directly, and through +// the wrapper, which hashes the key once more and locks a stripe around the +// Set of tinylfu. +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() + b.RunParallel(func(pb *testing.PB) { + i := rand.Int() + for pb.Next() { + c.Set(i&(benchCapacity-1), i) + i++ + } + }) + }) + + b.Run("load", func(b *testing.B) { + c := load.Wrap(tinylfu.New[int, int](benchCapacity), never[int, int]) + fill(func(k, v int) { c.Set(k, v) }) + b.ReportAllocs() + b.RunParallel(func(pb *testing.PB) { + i := rand.Int() + for pb.Next() { + c.Set(i&(benchCapacity-1), i) + i++ + } + }) + }) +} + +// BenchmarkLoad is a Fetch that loads, on one CPU: a miss, a goroutine for +// the load, and the Set that stores its value. The loader returns at once, as +// no source does. +func BenchmarkLoad(b *testing.B) { + c := load.Wrap(tinylfu.New[int, int](benchCapacity), func(_ context.Context, key int) (int, error) { + return key, nil + }) + ctx := context.Background() + b.ReportAllocs() + i := 0 + for b.Loop() { + _, _ = c.Fetch(ctx, i) + i++ + } +} diff --git a/load/example_test.go b/load/example_test.go new file mode 100644 index 0000000..b2b07a9 --- /dev/null +++ b/load/example_test.go @@ -0,0 +1,38 @@ +package load_test + +import ( + "context" + "fmt" + + "github.com/floatdrop/evict/load" + "github.com/floatdrop/evict/tinylfu" +) + +func Example() { + // db stands for where the values come from, such as a database. + db := map[string]int{"a": 1} + cache := load.Wrap(tinylfu.New[string, int](10_000), func(_ context.Context, key string) (int, error) { + v, ok := db[key] + if !ok { + return 0, fmt.Errorf("no %q in the database", key) + } + return v, nil + }) + ctx := context.Background() + + v, err := cache.Fetch(ctx, "a") // Loads a and stores it. + fmt.Println(v, err) + _, err = cache.Fetch(ctx, "b") // An error is not stored. + fmt.Println(err) + + // After a change to the source, delete the key from the cache: a load of + // it that is under way then does not store what it read before. + db["a"] = 10 + cache.Delete("a") + v, _ = cache.Fetch(ctx, "a") + fmt.Println(v) + // Output: + // 1 + // no "b" in the database + // 10 +} diff --git a/load/export_test.go b/load/export_test.go new file mode 100644 index 0000000..4df0cd0 --- /dev/null +++ b/load/export_test.go @@ -0,0 +1,56 @@ +package load + +import ( + "context" + "hash/maphash" + + "github.com/floatdrop/evict" +) + +// WrapNotify is Wrap with functions that are called whenever a load starts, +// before the Fetch that starts it waits, and whenever one is over, once its +// value has been stored or not. Either may be nil. +func WrapNotify[K comparable, V any](cache evict.Cache[K, V], load func(context.Context, K) (V, error), started, finished func()) *Cache[K, V] { + c := Wrap(cache, load) + c.started, c.finished = started, finished + return c +} + +// Loading returns how many loads are in progress whose values are still to be +// stored. +func Loading[K comparable, V any](c *Cache[K, V]) int { + n := 0 + for i := range c.stripes { + s := &c.stripes[i] + s.mu.Lock() + n += len(s.loads) + s.mu.Unlock() + } + return n +} + +// Waiting returns how many Fetch calls wait for the load of key whose value +// is still to be stored, or -1 if there is no such load. +func Waiting[K comparable, V any](c *Cache[K, V], key K) int { + s := c.stripe(maphash.Comparable(c.seed, key)) + s.mu.Lock() + defer s.mu.Unlock() + if l := s.loads[key]; l != nil { + return l.waiters + } + return -1 +} + +// Held reports whether the stripe of key is locked. A goroutine that holds the +// lock gets true as well: the lock is not reentrant. +func Held[K comparable, V any](c *Cache[K, V], key K) bool { + s := c.stripe(maphash.Comparable(c.seed, key)) + if s.mu.TryLock() { + s.mu.Unlock() + return false + } + return true +} + +// ErrGoexit is what a load returns if its loader calls runtime.Goexit. +var ErrGoexit = errGoexit diff --git a/load/load.go b/load/load.go new file mode 100644 index 0000000..8688270 --- /dev/null +++ b/load/load.go @@ -0,0 +1,412 @@ +// Package load fills a cache from a source, and has the goroutines that ask +// for a key at the same time share one load of it. +// +// [Wrap] puts a loader in front of any [evict.Cache]: +// +// users := load.Wrap(tinylfu.New[string, User](10_000), func(ctx context.Context, id string) (User, error) { +// return db.User(ctx, id) +// }) +// u, err := users.Fetch(ctx, "42") +// +// [Cache.Fetch] returns the value stored under a key. If there is none, it +// calls the loader, stores what that returns, and returns it. The goroutines +// that fetch a key while it is loading wait for that load, and get its value +// or its error. An error is not stored: the next Fetch loads again. The other +// methods are those of [evict.Cache], and none of them loads. +// +// # Waiting +// +// A load runs in a goroutine of its own. Its context has the values of the +// context of the Fetch that started it, but not its deadline or its +// cancellation. A Fetch whose context ends stops waiting and returns the +// context's error. The load goes on for the others. When none is left, its +// context is canceled, and a value that it gets all the same is not stored; +// the next Fetch starts a load of its own, which may run alongside it. A +// loader must not fetch the key it loads: it would wait for itself. +// +// # Writes during a load +// +// A Set, SetIfAbsent or Delete of a key that is loading, and any DeleteFunc or +// Clear, keep the load from storing its value: it may have been read from the +// source before the change that the write is for. The Fetch calls that wait +// for the load still get the value. Those that come after a Delete, DeleteFunc +// or Clear start a load of their own. Writes to the wrapped cache itself do +// not count. +// +// Storing a loaded value may evict an entry, which is not handed back as Set +// hands it back. +// +// # Panics +// +// A panic in the loader is raised again in every Fetch that waits for the +// load, as a [*PanicError] that holds the value and the stack of the panic. +// If none is waiting, the panic ends the program, as a panic in any goroutine +// does. A loader that calls runtime.Goexit leaves the waiting Fetch calls +// with an error. +// +// # Other wrappers +// +// Wrapped around stats, as load.Wrap(stats.Wrap(...)), a cache counts a Fetch +// as a hit if it finds the key and as a miss if it does not, and storing a +// loaded value as a Set. Wrapped around expire, it loads expired keys again, +// and the loaded values get the time to live of the expire.Cache. +// +// The wrapped cache must not call back into the Cache: the Cache holds a lock +// of its own around its calls of Set, SetIfAbsent and Delete of the wrapped +// cache, and of the Peek with which it looks once more before a load. +// +// # Cost +// +// On an Apple M3 Max, a Fetch of tinylfu that found its key took 20% longer +// than a Get on one CPU, and 23% on eight. A Set took 10 ns longer on one CPU, +// and 60% longer on eight. A load takes a goroutine and six allocations, 352 +// bytes in all with int keys and values, on top of what the loader takes: 0.56 +// µs with one that returns at once. +package load + +import ( + "context" + "errors" + "fmt" + "hash/maphash" + "iter" + "math/bits" + "runtime" + "runtime/debug" + "sync" + "unsafe" + + "github.com/floatdrop/evict" +) + +// cacheLine is a size that no two CPUs' cache lines straddle on the +// platforms Go runs on. +const cacheLine = 128 + +// minStripes is the fewest stripes a Cache has, however few CPUs there are. +const minStripes = 64 + +// Cache is an [evict.Cache] that loads what it does not hold when asked with +// [Cache.Fetch]; 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, V] + load func(ctx context.Context, key K) (V, error) + + // A key belongs to the stripe that its hash picks. The stripe's lock + // orders the writes of the key with the loads of it. + stripes []stripe[K, V] + shift uint8 // 64 minus log2 of the number of stripes + seed maphash.Seed + + // For tests: called, if not nil, when a load starts and when it is over. + started, finished func() +} + +// A stripe holds the loads in progress of its keys, in a cache line of its +// own. +type stripe[K comparable, V any] struct { + mu sync.Mutex + + // loads has the loads whose values are still to be stored. A write of + // the key takes its load out. + loads map[K]*call[V] + + _ [cacheLine - unsafe.Sizeof(sync.Mutex{}) - unsafe.Sizeof(uintptr(0))]byte +} + +// A call is a load in progress, and what it got once it is done. +type call[V any] struct { + done chan struct{} // closed when the load is over + cancel context.CancelFunc + + // waiters is the number of Fetch calls that wait for the load. It is + // read and written under the lock of the stripe. + waiters int + + // The result is written before done is closed, and read after. + value V + err error + panicked *PanicError +} + +// PanicError is what Fetch panics with when the loader has panicked. +type PanicError struct { + // Value is what the loader panicked with. + Value any + + // Stack is the stack of the goroutine that ran the loader, as it was + // when it panicked. + Stack []byte +} + +func (e *PanicError) Error() string { + return fmt.Sprintf("load: the loader panicked: %v\n\n%s", e.Value, e.Stack) +} + +// Unwrap returns the value that the loader panicked with if it is an error. +func (e *PanicError) Unwrap() error { + err, _ := e.Value.(error) + return err +} + +// errGoexit is what a load returns if its loader calls runtime.Goexit. +var errGoexit = errors.New("load: the loader called runtime.Goexit") + +// Wrap returns a Cache that keeps its entries in cache, and fills it by calling +// load with the key that a Fetch did not find. It panics if load is nil. +// +// Using cache directly as well is fine, but its writes do not keep a load +// from storing a value that they have made out of date; see the package +// documentation. +func Wrap[K comparable, V any](cache evict.Cache[K, V], load func(ctx context.Context, key K) (V, error)) *Cache[K, V] { + if load == nil { + panic("load: Wrap: load must not be nil") + } + // Eight stripes per CPU make it unlikely that writers to different + // keys wait for each other, as the shards of the caches do. + n := max(minStripes, 8*runtime.GOMAXPROCS(0)) + log := bits.Len(uint(n - 1)) + return &Cache[K, V]{ + cache: cache, + load: load, + stripes: make([]stripe[K, V], 1<>c.shift] +} + +// Fetch returns the value stored under key, and records the access with the +// eviction policy as Get does. If there is none, Fetch loads it, unless key is +// loading already, in which case it waits for that load. It returns the value +// that the load got, which it has stored unless a write came in between, or +// its error, which it has not. If ctx ends first, Fetch returns its error. +// +// A value that is stored is returned whatever the state of ctx. A key that is +// not equal to itself, one with a NaN in it, is never stored, since it could +// not be found: every Fetch of it calls the loader itself, with ctx, as a +// plain function call. +func (c *Cache[K, V]) Fetch(ctx context.Context, key K) (V, error) { + if value, ok := c.cache.Get(key); ok { + return value, nil + } + return c.fetch(ctx, key) +} + +// fetch is Fetch for a key that the cache did not have. +func (c *Cache[K, V]) fetch(ctx context.Context, key K) (value V, err error) { + if err := ctx.Err(); err != nil { + return value, err + } + if key != key { //nolint:gocritic // Only a key with a NaN in it is not equal to itself. + return c.load(ctx, key) + } + + s := c.stripe(maphash.Comparable(c.seed, key)) + s.mu.Lock() + l := s.loads[key] + if l != nil { + l.waiters++ + } else { + // The load of another goroutine may have stored the key since Get + // missed it. + if value, ok := c.cache.Peek(key); ok { + s.mu.Unlock() + return value, nil + } + l = c.start(ctx, s, key) + } + s.mu.Unlock() + + return c.wait(ctx, s, key, l) +} + +// start starts a load of key, which belongs to stripe s, whose lock the caller +// holds. +func (c *Cache[K, V]) start(ctx context.Context, s *stripe[K, V], key K) *call[V] { + // finish calls cancel, or the last Fetch to give up on the load does. + ctx, cancel := context.WithCancel(context.WithoutCancel(ctx)) //nolint:gosec // See above. + l := &call[V]{done: make(chan struct{}), cancel: cancel, waiters: 1} + if s.loads == nil { + s.loads = make(map[K]*call[V]) + } + s.loads[key] = l + if c.started != nil { + c.started() + } + go c.run(ctx, s, key, l) + return l +} + +// run loads key for l, and finishes l whichever way the loader ends. +func (c *Cache[K, V]) run(ctx context.Context, s *stripe[K, V], key K, l *call[V]) { + returned := false + defer func() { + if !returned { + // recover stops a panic, but not runtime.Goexit, which goes + // on once this function is done. + if p := recover(); p != nil { + l.panicked = &PanicError{Value: p, Stack: debug.Stack()} + } else { + l.err = errGoexit + } + } + waiters := c.finish(s, key, l) + if c.finished != nil { + c.finished() + } + if waiters == 0 && l.panicked != nil { + panic(l.panicked) + } + }() + l.value, l.err = c.load(ctx, key) + returned = true +} + +// finish stores what load l of key got, unless the load was taken out, wakes +// up the Fetch calls that wait for it, and returns how many there are. +func (c *Cache[K, V]) finish(s *stripe[K, V], key K, l *call[V]) int { + defer l.cancel() + s.mu.Lock() + defer s.mu.Unlock() + // Closing done with the stripe locked lets a Fetch that gives up see + // that the load is over, and take its result, before it counts itself + // out: else a panic could reach nobody. + defer close(l.done) + + if s.loads[key] == l { + delete(s.loads, key) + if l.err == nil && l.panicked == nil { + c.cache.Set(key, l.value) + } + } + return l.waiters +} + +// wait waits for load l of key, which belongs to stripe s, or for ctx to end. +func (c *Cache[K, V]) wait(ctx context.Context, s *stripe[K, V], key K, l *call[V]) (value V, err error) { + select { + case <-l.done: + return l.result() + case <-ctx.Done(): + } + + s.mu.Lock() + select { + case <-l.done: + // The load is over after all. + s.mu.Unlock() + return l.result() + default: + } + l.waiters-- + if l.waiters == 0 { + // Nobody wants the value any more. + if s.loads[key] == l { + delete(s.loads, key) + } + l.cancel() + } + s.mu.Unlock() + return value, ctx.Err() +} + +// result returns what the load got, or raises the panic of its loader again. +func (l *call[V]) result() (V, error) { + if l.panicked != nil { + panic(l.panicked) + } + return l.value, l.err +} + +// forget takes the load of key, if there is one, out of stripe s, whose lock +// the caller holds. The load goes on for the Fetch calls that wait for it, but +// its value is not stored. +func (s *stripe[K, V]) forget(key K) { + if len(s.loads) != 0 { + delete(s.loads, key) + } +} + +// forgetAll takes every load out. +func (c *Cache[K, V]) forgetAll() { + for i := range c.stripes { + s := &c.stripes[i] + s.mu.Lock() + clear(s.loads) + s.mu.Unlock() + } +} + +// Get returns the value stored under key and records the access with the +// eviction policy. It does not load. +func (c *Cache[K, V]) Get(key K) (value V, ok bool) { return c.cache.Get(key) } + +// Peek returns the value stored under key without telling the eviction policy +// about it. It does not load. +func (c *Cache[K, V]) Peek(key K) (value V, ok bool) { return c.cache.Peek(key) } + +// Set stores value under key, and keeps a load of key that is in progress from +// storing its value. See [evict.Cache]. +func (c *Cache[K, V]) Set(key K, value V) (oldKey K, oldValue V, displaced bool) { + s := c.stripe(maphash.Comparable(c.seed, key)) + s.mu.Lock() + defer s.mu.Unlock() + s.forget(key) + return c.cache.Set(key, value) +} + +// SetIfAbsent stores value under key unless the cache holds key, and keeps a +// load of key that is in progress from storing its value. It does not load. +// See [evict.Cache]. +func (c *Cache[K, V]) SetIfAbsent(key K, value V) (actual V, present bool, oldKey K, oldValue V, evicted bool) { + s := c.stripe(maphash.Comparable(c.seed, key)) + s.mu.Lock() + defer s.mu.Unlock() + s.forget(key) + return c.cache.SetIfAbsent(key, value) +} + +// Delete removes key and returns the value it had, and keeps a load of key +// that is in progress from storing its value. +func (c *Cache[K, V]) Delete(key K) (value V, ok bool) { + s := c.stripe(maphash.Comparable(c.seed, key)) + s.mu.Lock() + defer s.mu.Unlock() + s.forget(key) + return c.cache.Delete(key) +} + +// DeleteFunc removes the entries for which del returns true and reports how +// many it removed. It keeps every load in progress from storing its value, +// since del cannot be asked about one that is not there yet. See +// [evict.Cache]. +func (c *Cache[K, V]) DeleteFunc(del func(K, V) bool) int { + c.forgetAll() + return c.cache.DeleteFunc(del) +} + +// Len returns the number of entries in the cache. +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, and keeps every load in progress from storing its +// value. See [evict.Cache]. +func (c *Cache[K, V]) Clear() { + c.forgetAll() + c.cache.Clear() +} + +// All iterates over the entries of the cache. It does not load. +func (c *Cache[K, V]) All() iter.Seq2[K, V] { return c.cache.All() } + +var _ evict.Cache[int, int] = (*Cache[int, int])(nil) diff --git a/load/load_test.go b/load/load_test.go new file mode 100644 index 0000000..3794b74 --- /dev/null +++ b/load/load_test.go @@ -0,0 +1,856 @@ +package load_test + +import ( + "bytes" + "context" + "errors" + "math" + "math/rand/v2" + "os" + "os/exec" + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/floatdrop/evict" + "github.com/floatdrop/evict/expire" + "github.com/floatdrop/evict/internal/cachetest" + "github.com/floatdrop/evict/load" + "github.com/floatdrop/evict/lru" + "github.com/floatdrop/evict/s3fifo" + "github.com/floatdrop/evict/stats" +) + +// never is a loader for caches that are only read and written. +func never[K comparable, V any](context.Context, K) (V, error) { + var zero V + return zero, errors.New("loaded a key") +} + +// A wrapped cache must still be a cache. One with a lock and one without get +// the suite. +var ( + lruFactories = cachetest.Factories{ + Int: func(capacity, shards int) evict.Cache[int, int] { + return load.Wrap(lru.New[int, int](capacity, lru.WithShards(shards)), never[int, int]) + }, + String: func(capacity, shards int) evict.Cache[string, string] { + return load.Wrap(lru.New[string, string](capacity, lru.WithShards(shards)), never[string, string]) + }, + Float: func(capacity, shards int) evict.Cache[float64, int] { + return load.Wrap(lru.New[float64, int](capacity, lru.WithShards(shards)), never[float64, int]) + }, + Blob: func(capacity, shards int) evict.Cache[int, *cachetest.Blob] { + return load.Wrap(lru.New[int, *cachetest.Blob](capacity, lru.WithShards(shards)), never[int, *cachetest.Blob]) + }, + BlobKey: func(capacity, shards int) evict.Cache[*cachetest.Blob, int] { + return load.Wrap(lru.New[*cachetest.Blob, int](capacity, lru.WithShards(shards)), never[*cachetest.Blob, int]) + }, + Wide: func(capacity, shards int) evict.Cache[string, cachetest.Wide] { + return load.Wrap(lru.New[string, cachetest.Wide](capacity, lru.WithShards(shards)), never[string, cachetest.Wide]) + }, + } + + s3fifoFactories = cachetest.Factories{ + Int: func(capacity, shards int) evict.Cache[int, int] { + return load.Wrap(s3fifo.New[int, int](capacity, s3fifo.WithShards(shards)), never[int, int]) + }, + String: func(capacity, shards int) evict.Cache[string, string] { + return load.Wrap(s3fifo.New[string, string](capacity, s3fifo.WithShards(shards)), never[string, string]) + }, + Float: func(capacity, shards int) evict.Cache[float64, int] { + return load.Wrap(s3fifo.New[float64, int](capacity, s3fifo.WithShards(shards)), never[float64, int]) + }, + Blob: func(capacity, shards int) evict.Cache[int, *cachetest.Blob] { + return load.Wrap(s3fifo.New[int, *cachetest.Blob](capacity, s3fifo.WithShards(shards)), never[int, *cachetest.Blob]) + }, + BlobKey: func(capacity, shards int) evict.Cache[*cachetest.Blob, int] { + return load.Wrap(s3fifo.New[*cachetest.Blob, int](capacity, s3fifo.WithShards(shards)), never[*cachetest.Blob, int]) + }, + Wide: func(capacity, shards int) evict.Cache[string, cachetest.Wide] { + return load.Wrap(s3fifo.New[string, cachetest.Wide](capacity, s3fifo.WithShards(shards)), never[string, cachetest.Wide]) + }, + 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) { + t.Run("lru", func(t *testing.T) { cachetest.NoAllocs(t, lruFactories) }) + t.Run("s3fifo", func(t *testing.T) { cachetest.NoAllocs(t, s3fifoFactories) }) + + t.Run("Fetch", func(t *testing.T) { + c := load.Wrap(s3fifo.New[int, int](1000), never[int, int]) + c.Set(1, 1) + ctx := t.Context() + if allocs := testing.AllocsPerRun(100, func() { _, _ = c.Fetch(ctx, 1) }); allocs != 0 { + t.Errorf("%v allocations per Fetch that finds its key, want 0", allocs) + } + }) +} + +func TestNilLoader(t *testing.T) { + t.Parallel() + + defer func() { + if recover() == nil { + t.Error("Wrap with a nil loader did not panic") + } + }() + load.Wrap[int, int](lru.New[int, int](1), nil) +} + +// until waits until cond holds, which some other goroutine is to bring about. +func until(t *testing.T, what string, cond func() bool) { + t.Helper() + + for deadline := time.Now().Add(10 * time.Second); !cond(); { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting until %s", what) + } + time.Sleep(10 * time.Microsecond) + } +} + +// gated is a loader whose loads wait until gate is closed, and that counts +// them. The nth load of key returns 100 key + n. +type gated struct { + gate chan struct{} + calls atomic.Int32 +} + +func newGated() *gated { return &gated{gate: make(chan struct{})} } + +func (g *gated) load(_ context.Context, key int) (int, error) { + n := g.calls.Add(1) + <-g.gate + return 100*key + int(n), nil +} + +// fetch starts a Fetch of key and returns where its result goes. +func fetch(ctx context.Context, c *load.Cache[int, int], key int) <-chan result { + out := make(chan result, 1) + go func() { + v, err := c.Fetch(ctx, key) + out <- result{v, err} + }() + return out +} + +type result struct { + value int + err error +} + +func TestFetch(t *testing.T) { + t.Parallel() + + calls := 0 + c := load.Wrap(lru.New[int, int](10), func(_ context.Context, key int) (int, error) { + calls++ + return -key, nil + }) + c.Set(1, 10) + if v, err := c.Fetch(t.Context(), 1); v != 10 || err != nil || calls != 0 { + t.Errorf("Fetch of a stored key = %d, %v after %d loads, want 10, nil after none", v, err, calls) + } + if v, err := c.Fetch(t.Context(), 2); v != -2 || err != nil || calls != 1 { + t.Errorf("Fetch of a missing key = %d, %v after %d loads, want -2, nil after one", v, err, calls) + } + if v, ok := c.Peek(2); !ok || v != -2 { + t.Errorf("Peek after the load = %d, %t, want -2, true", v, ok) + } + if v, err := c.Fetch(t.Context(), 2); v != -2 || err != nil || calls != 1 { + t.Errorf("Fetch of a loaded key = %d, %v after %d loads, want -2, nil after one", v, err, calls) + } + if n := load.Loading(c); n != 0 { + t.Errorf("%d loads in progress after the last one returned", n) + } +} + +// The goroutines that fetch a key while it loads wait for that one load. +func TestFetchOnce(t *testing.T) { + t.Parallel() + + const fetches = 16 + g := newGated() + c := load.Wrap(lru.New[int, int](10), g.load) + results := make([]<-chan result, fetches) + for i := range results { + results[i] = fetch(t.Context(), c, 1) + } + until(t, "every Fetch waits", func() bool { return load.Waiting(c, 1) == fetches }) + close(g.gate) + for _, r := range results { + if r := <-r; r.value != 101 || r.err != nil { + t.Errorf("Fetch = %d, %v, want 101, nil", r.value, r.err) + } + } + if n := g.calls.Load(); n != 1 { + t.Errorf("%d loads, want 1", n) + } + if v, ok := c.Peek(1); !ok || v != 101 { + t.Errorf("Peek after the load = %d, %t, want 101, true", v, ok) + } +} + +// An error goes to every Fetch that waits for the load, and is not stored. +func TestFetchError(t *testing.T) { + t.Parallel() + + errDown := errors.New("the source is down") + gate, calls := make(chan struct{}), atomic.Int32{} + c := load.Wrap(lru.New[int, int](10), func(context.Context, int) (int, error) { + calls.Add(1) + <-gate + return 0, errDown + }) + a, b := fetch(t.Context(), c, 1), fetch(t.Context(), c, 1) + until(t, "both Fetch calls wait", func() bool { return load.Waiting(c, 1) == 2 }) + close(gate) + for _, r := range []result{<-a, <-b} { + if !errors.Is(r.err, errDown) { + t.Errorf("Fetch = %d, %v, want the loader's error", r.value, r.err) + } + } + if _, ok := c.Peek(1); ok || c.Len() != 0 { + t.Error("the error stored an entry") + } + if _, err := c.Fetch(t.Context(), 1); !errors.Is(err, errDown) || calls.Load() != 2 { + t.Errorf("Fetch after the error = %v after %d loads, want the loader's error after 2", err, calls.Load()) + } +} + +// A Fetch whose context ends stops waiting, and the load goes on for the +// others until none is left. +func TestFetchCanceled(t *testing.T) { + t.Parallel() + + gate, contexts := make(chan struct{}), make(chan context.Context, 2) + finished := make(chan struct{}, 2) + c := load.WrapNotify(lru.New[int, int](10), func(ctx context.Context, key int) (int, error) { + contexts <- ctx + <-gate + return 10 * key, nil // Stored unless the load was given up on. + }, nil, func() { finished <- struct{}{} }) + + // Of two, the one that gives up gets the error of its context, and the + // other the value. + ctx, cancel := context.WithCancel(t.Context()) + quitter := fetch(ctx, c, 1) + loading := <-contexts + stayer := fetch(t.Context(), c, 1) + until(t, "both Fetch calls wait", func() bool { return load.Waiting(c, 1) == 2 }) + cancel() + if r := <-quitter; !errors.Is(r.err, context.Canceled) { + t.Errorf("Fetch with a canceled context = %d, %v, want context.Canceled", r.value, r.err) + } + if err := loading.Err(); err != nil { + t.Errorf("the load's context ended (%v) while a Fetch was still waiting", err) + } + if n := load.Waiting(c, 1); n != 1 { + t.Errorf("%d Fetch calls wait after one gave up, want 1", n) + } + + // When the last one gives up, the load's context ends, and its value is + // not stored. + ctx, cancel = context.WithCancel(t.Context()) + quitter = fetch(ctx, c, 2) + abandoned := <-contexts + until(t, "the Fetch waits", func() bool { return load.Waiting(c, 2) == 1 }) + cancel() + if r := <-quitter; !errors.Is(r.err, context.Canceled) { + t.Errorf("Fetch with a canceled context = %d, %v, want context.Canceled", r.value, r.err) + } + if abandoned.Err() == nil { + t.Error("the load's context did not end when no Fetch was left") + } + if n := load.Waiting(c, 2); n != -1 { + t.Errorf("the abandoned load is still there, with %d waiting", n) + } + + close(gate) + if r := <-stayer; r.value != 10 || r.err != nil { + t.Errorf("Fetch that stayed = %d, %v, want 10, nil", r.value, r.err) + } + <-finished + <-finished + if v, ok := c.Peek(1); !ok || v != 10 { + t.Errorf("Peek(1) = %d, %t, want the value that was waited for", v, ok) + } + if v, ok := c.Peek(2); ok { + t.Errorf("Peek(2) = %d, want the abandoned load not stored", v) + } +} + +// A load has the values of the context of the Fetch that started it, but not +// its deadline. +func TestFetchContext(t *testing.T) { + t.Parallel() + + type ctxKey struct{} + started := 0 // Counted in the goroutine of the Fetch that starts the load. + c := load.WrapNotify(lru.New[int, int](10), func(ctx context.Context, key int) (int, error) { + if v := ctx.Value(ctxKey{}); v != "trace" { + t.Errorf("the load's context has %v, want the Fetch's value", v) + } + if d, ok := ctx.Deadline(); ok { + t.Errorf("the load's context has the Fetch's deadline %v", d) + } + return key, nil + }, func() { started++ }, nil) + ctx, cancel := context.WithTimeout(context.WithValue(t.Context(), ctxKey{}, "trace"), time.Hour) + defer cancel() + if _, err := c.Fetch(ctx, 1); err != nil { + t.Fatal(err) + } + + // A context that has ended stops a load from starting, but not a stored + // value from being returned. + ctx, cancel = context.WithCancel(t.Context()) + cancel() + if v, err := c.Fetch(ctx, 1); v != 1 || err != nil { + t.Errorf("Fetch of a stored key with an ended context = %d, %v, want 1, nil", v, err) + } + if _, err := c.Fetch(ctx, 2); !errors.Is(err, context.Canceled) || started != 1 { + t.Errorf("Fetch of a missing key with an ended context = %v after %d loads, want context.Canceled after 1", err, started) + } +} + +// A write during a load keeps it from storing its value, but the Fetch calls +// that wait for it get the value all the same. +func TestWriteDuringLoad(t *testing.T) { + t.Parallel() + + for _, tt := range []struct { + name string + write func(c *load.Cache[int, int]) + stored bool // the write stores 7 under key 1 + }{ + {"Set", func(c *load.Cache[int, int]) { c.Set(1, 7) }, true}, + {"SetIfAbsent", func(c *load.Cache[int, int]) { c.SetIfAbsent(1, 7) }, true}, + {"Delete", func(c *load.Cache[int, int]) { c.Delete(1) }, false}, + {"DeleteFunc", func(c *load.Cache[int, int]) { c.DeleteFunc(func(int, int) bool { return false }) }, false}, + {"Clear", func(c *load.Cache[int, int]) { c.Clear() }, false}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + g := newGated() + c := load.Wrap(lru.New[int, int](10), g.load) + waiter := fetch(t.Context(), c, 1) + until(t, "the Fetch waits", func() bool { return load.Waiting(c, 1) == 1 }) + tt.write(c) + if n := load.Waiting(c, 1); n != -1 { + t.Errorf("the load is still there after %s, with %d waiting", tt.name, n) + } + close(g.gate) + if r := <-waiter; r.value != 101 || r.err != nil { + t.Errorf("Fetch = %d, %v, want the loaded 101, nil", r.value, r.err) + } + v, ok := c.Peek(1) + switch { + case tt.stored && (!ok || v != 7): + t.Errorf("Peek after the load = %d, %t, want what %s stored", v, ok, tt.name) + case !tt.stored && ok: + t.Errorf("Peek after the load = %d, want the load not stored", v) + } + }) + } +} + +// A Fetch after a Delete does not wait for the load that the Delete made out +// of date: it loads anew, and its value is the one that is stored. +func TestFetchAfterDelete(t *testing.T) { + t.Parallel() + + g := newGated() + c := load.Wrap(lru.New[int, int](10), g.load) + before := fetch(t.Context(), c, 1) + until(t, "the first load runs", func() bool { return load.Waiting(c, 1) == 1 && g.calls.Load() == 1 }) + c.Delete(1) + after := fetch(t.Context(), c, 1) + until(t, "the second Fetch waits", func() bool { return load.Waiting(c, 1) == 1 && g.calls.Load() == 2 }) + close(g.gate) + if r := <-before; r.value != 101 || r.err != nil { + t.Errorf("Fetch before the Delete = %d, %v, want 101, nil", r.value, r.err) + } + if r := <-after; r.value != 102 || r.err != nil { + t.Errorf("Fetch after the Delete = %d, %v, want 102, nil", r.value, r.err) + } + if v, ok := c.Peek(1); !ok || v != 102 { + t.Errorf("Peek = %d, %t, want the value of the second load", v, ok) + } +} + +// A Fetch that gives up on a load that a Delete took out leaves the load that +// came after the Delete alone. +func TestGiveUpAfterDelete(t *testing.T) { + t.Parallel() + + g := newGated() + c := load.Wrap(lru.New[int, int](10), g.load) + ctx, cancel := context.WithCancel(t.Context()) + before := fetch(ctx, c, 1) + until(t, "the first load runs", func() bool { return load.Waiting(c, 1) == 1 && g.calls.Load() == 1 }) + c.Delete(1) + after := fetch(t.Context(), c, 1) + until(t, "the second load runs", func() bool { return load.Waiting(c, 1) == 1 && g.calls.Load() == 2 }) + cancel() + if r := <-before; !errors.Is(r.err, context.Canceled) { + t.Errorf("Fetch that gave up = %d, %v, want context.Canceled", r.value, r.err) + } + if n := load.Waiting(c, 1); n != 1 { + t.Errorf("Waiting = %d after the first Fetch gave up, want the second load still there", n) + } + close(g.gate) + if r := <-after; r.value != 102 || r.err != nil { + t.Errorf("Fetch after the Delete = %d, %v, want 102, nil", r.value, r.err) + } + if v, ok := c.Peek(1); !ok || v != 102 { + t.Errorf("Peek = %d, %t, want the value of the second load", v, ok) + } +} + +// A load's context ends when the load is over. +func TestLoadContextEnds(t *testing.T) { + t.Parallel() + + contexts := make(chan context.Context, 1) + c := load.Wrap(lru.New[int, int](10), func(ctx context.Context, key int) (int, error) { + contexts <- ctx + return key, nil + }) + if _, err := c.Fetch(t.Context(), 1); err != nil { + t.Fatal(err) + } + ctx := <-contexts + until(t, "the load's context ends", func() bool { return ctx.Err() != nil }) +} + +// locked is a cache that checks that the Cache writes to it with the stripe of +// the key locked, so that a write through the Cache and the store of a load +// cannot interleave. +type locked struct { + evict.Cache[int, int] + t *testing.T + c *load.Cache[int, int] +} + +func (l *locked) check(op string, key int) { + if !load.Held(l.c, key) { + l.t.Errorf("%s(%d) of the wrapped cache with the stripe unlocked", op, key) + } +} + +func (l *locked) Set(key, value int) (oldKey, oldValue int, displaced bool) { + l.check("Set", key) + return l.Cache.Set(key, value) +} + +func (l *locked) SetIfAbsent(key, value int) (actual int, present bool, oldKey, oldValue int, evicted bool) { + l.check("SetIfAbsent", key) + return l.Cache.SetIfAbsent(key, value) +} + +func (l *locked) Delete(key int) (int, bool) { + l.check("Delete", key) + return l.Cache.Delete(key) +} + +// Peek is called only by a Fetch that looks once more before it loads. +func (l *locked) Peek(key int) (int, bool) { + l.check("Peek", key) + return l.Cache.Peek(key) +} + +func TestWritesLockTheStripe(t *testing.T) { + t.Parallel() + + inner := &locked{Cache: lru.New[int, int](10), t: t} + c := load.Wrap[int, int](inner, func(_ context.Context, key int) (int, error) { return key, nil }) + inner.c = c + c.Set(1, 1) + c.SetIfAbsent(2, 2) + c.Delete(1) + if _, err := c.Fetch(t.Context(), 3); err != nil { // Stores what it loads. + t.Fatal(err) + } +} + +// purging is a cache that runs a function at the end of its Clear and +// DeleteFunc. +type purging struct { + evict.Cache[int, int] + after func() +} + +func (p *purging) Clear() { + p.Cache.Clear() + p.after() +} + +func (p *purging) DeleteFunc(del func(int, int) bool) int { + n := p.Cache.DeleteFunc(del) + p.after() + return n +} + +// A load that ends just after the Clear or DeleteFunc of the wrapped cache, +// before the one of the Cache returns, has been taken out already. +func TestLoadEndsDuringPurge(t *testing.T) { + t.Parallel() + + for name, purge := range map[string]func(c *load.Cache[int, int]){ + "Clear": func(c *load.Cache[int, int]) { c.Clear() }, + "DeleteFunc": func(c *load.Cache[int, int]) { c.DeleteFunc(func(int, int) bool { return true }) }, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + g, finished := newGated(), make(chan struct{}, 1) + inner := &purging{Cache: lru.New[int, int](10)} + c := load.WrapNotify[int, int](inner, g.load, nil, func() { finished <- struct{}{} }) + waiter := fetch(t.Context(), c, 1) + until(t, "the load runs", func() bool { return load.Waiting(c, 1) == 1 && g.calls.Load() == 1 }) + inner.after = func() { + close(g.gate) + <-finished + } + purge(c) + if r := <-waiter; r.value != 101 || r.err != nil { + t.Errorf("Fetch = %d, %v, want 101, nil", r.value, r.err) + } + if v, ok := c.Peek(1); ok { + t.Errorf("Peek after %s = %d, want the load not stored", name, v) + } + }) + } +} + +// ending is a context that ends when its Done is first asked for, and lets +// the load panic before that. +type ending struct { + context.Context + once sync.Once + before func() + done chan struct{} +} + +func (e *ending) Done() <-chan struct{} { + e.once.Do(func() { + e.before() + close(e.done) + }) + return e.done +} + +func (e *ending) Err() error { + select { + case <-e.done: + return context.Canceled + default: + return nil + } +} + +// A Fetch whose context ends just as the load panics gets the panic all the +// same. Which of the two it sees first is up to select, so this tries often. +func TestPanicAsContextEnds(t *testing.T) { + t.Parallel() + + for range 64 { + gate, finished := make(chan struct{}), make(chan struct{}, 1) + c := load.WrapNotify(lru.New[int, int](10), func(context.Context, int) (int, error) { + <-gate + panic("late") + }, nil, func() { finished <- struct{}{} }) + ctx := &ending{Context: t.Context(), done: make(chan struct{}), before: func() { + close(gate) + <-finished + }} + func() { + defer func() { + if p, _ := recover().(*load.PanicError); p == nil || p.Value != "late" { + t.Fatalf("Fetch did not panic with the loader's panic, but with %v", p) + } + }() + v, err := c.Fetch(ctx, 1) + t.Fatalf("Fetch = %d, %v, want a panic", v, err) + }() + } +} + +// late is a cache that stores a key just after a Get has missed it, as the +// load of another goroutine may. +type late struct { + evict.Cache[int, int] +} + +func (l late) Get(key int) (int, bool) { + v, ok := l.Cache.Get(key) + if !ok { + l.Set(key, -key) + } + return v, ok +} + +// A Fetch that misses a key just before it is stored does not load it again. +func TestFetchStoredMeanwhile(t *testing.T) { + t.Parallel() + + calls := 0 + c := load.Wrap[int, int](late{lru.New[int, int](10)}, func(_ context.Context, key int) (int, error) { + calls++ + return key, nil + }) + if v, err := c.Fetch(t.Context(), 1); v != -1 || err != nil || calls != 0 { + t.Errorf("Fetch = %d, %v after %d loads, want the stored -1, nil after none", v, err, calls) + } +} + +// A panic in the loader is raised again in every Fetch that waits for it. +func TestPanic(t *testing.T) { + t.Parallel() + + errBoom := errors.New("boom") + gate := make(chan struct{}) + c := load.Wrap(lru.New[int, int](10), func(context.Context, int) (int, error) { + <-gate + panic(errBoom) + }) + var wg sync.WaitGroup + for range 2 { + wg.Go(func() { + defer func() { + p, _ := recover().(*load.PanicError) + switch { + case p == nil: + t.Error("Fetch did not panic with a *PanicError") + case !errors.Is(p, errBoom): + t.Errorf("PanicError has %v, want the loader's value", p.Value) + case !bytes.Contains(p.Stack, []byte("TestPanic")): + t.Errorf("PanicError's stack is not the loader's:\n%s", p.Stack) + case !strings.Contains(p.Error(), "boom"): + t.Errorf("PanicError says %q", p.Error()) + } + }() + _, _ = c.Fetch(t.Context(), 1) + }) + } + until(t, "both Fetch calls wait", func() bool { return load.Waiting(c, 1) == 2 }) + close(gate) + wg.Wait() + if _, ok := c.Peek(1); ok || load.Loading(c) != 0 { + t.Error("the panic left an entry or a load behind") + } +} + +// A panic that no Fetch waits for ends the program. +func TestPanicUnwaited(t *testing.T) { + t.Parallel() + + if os.Getenv("LOAD_TEST_PANIC") == "1" { + gate := make(chan struct{}) + c := load.Wrap(lru.New[int, int](10), func(context.Context, int) (int, error) { + <-gate + panic("nobody waits") + }) + ctx, cancel := context.WithCancel(context.Background()) + r := fetch(ctx, c, 1) + until(t, "the Fetch waits", func() bool { return load.Waiting(c, 1) == 1 }) + cancel() + <-r + close(gate) + time.Sleep(time.Minute) + return + } + if testing.Short() { + t.Skip("runs the test binary again") + } + //nolint:gosec // The command is this test binary. + cmd := exec.CommandContext(t.Context(), os.Args[0], "-test.run=^TestPanicUnwaited$") + cmd.Env = append(os.Environ(), "LOAD_TEST_PANIC=1") + out, err := cmd.CombinedOutput() + if err == nil || !bytes.Contains(out, []byte("load: the loader panicked: nobody waits")) { + t.Errorf("the program went on after a panic that no Fetch waited for (%v):\n%s", err, out) + } +} + +// A loader that calls runtime.Goexit does not leave the Fetch calls waiting. +func TestGoexit(t *testing.T) { + t.Parallel() + + c := load.Wrap(lru.New[int, int](10), func(context.Context, int) (int, error) { + runtime.Goexit() + return 0, nil + }) + if _, err := c.Fetch(t.Context(), 1); !errors.Is(err, load.ErrGoexit) { + t.Errorf("Fetch = %v, want ErrGoexit", err) + } + if _, ok := c.Peek(1); ok || load.Loading(c) != 0 { + t.Error("Goexit left an entry or a load behind") + } +} + +// A key that is not equal to itself is loaded by every Fetch and never stored. +func TestNaN(t *testing.T) { + t.Parallel() + + calls := 0 + c := load.Wrap(lru.New[float64, int](10), func(ctx context.Context, _ float64) (int, error) { + if _, ok := ctx.Deadline(); !ok { + t.Error("the load of NaN does not have the context of its Fetch") + } + calls++ + return calls, nil + }) + ctx, cancel := context.WithTimeout(t.Context(), time.Hour) + defer cancel() + nan := math.NaN() + for want := 1; want <= 2; want++ { + if v, err := c.Fetch(ctx, nan); v != want || err != nil { + t.Errorf("Fetch(NaN) = %d, %v, want %d, nil", v, err, want) + } + } + if c.Len() != 0 || load.Loading(c) != 0 { + t.Errorf("Fetch(NaN) left %d entries and %d loads", c.Len(), load.Loading(c)) + } +} + +// Wrapped around stats, a Fetch counts as a hit or a miss, and storing what +// it loaded counts as a Set. +func TestStats(t *testing.T) { + t.Parallel() + + s := stats.Wrap(lru.New[int, int](1)) + c := load.Wrap[int, int](s, func(_ context.Context, key int) (int, error) { return key, nil }) + for _, key := range []int{1, 1, 1, 2} { // The load of 2 evicts 1. + if _, err := c.Fetch(t.Context(), key); err != nil { + t.Fatal(err) + } + } + if got := s.Stats(); got.Hits != 2 || got.Misses != 2 || got.Evictions != 1 { + t.Errorf("stats = %+v, want 2 hits, 2 misses and 1 eviction", got) + } +} + +// Wrapped around expire, a Fetch loads an expired key again. +func TestExpire(t *testing.T) { + t.Parallel() + + e := expire.Wrap(lru.New[int, expire.Entry[int]](10), time.Hour) + calls := 0 + c := load.Wrap[int, int](e, func(_ context.Context, key int) (int, error) { + calls++ + return 10*key + calls, nil + }) + if v, err := c.Fetch(t.Context(), 1); v != 11 || err != nil { + t.Fatalf("Fetch = %d, %v, want 11, nil", v, err) + } + e.SetWithTTL(1, 5, 0) // Replaces the entry with one that has expired. + if v, err := c.Fetch(t.Context(), 1); v != 12 || err != nil || c.Len() != 1 { + t.Errorf("Fetch of an expired key = %d, %v, Len() = %d, want 12, nil, 1", v, err, c.Len()) + } +} + +// source is what the caches of TestConcurrent load from. Writers change it and +// then write the cache, as a program that keeps a cache in front of a database +// would. The value of a key is 1000 times the key plus its version. +type source struct { + mu sync.Mutex + version map[int]int +} + +func (s *source) load(_ context.Context, key int) (int, error) { + s.mu.Lock() + v := 1000*key + s.version[key] + s.mu.Unlock() + runtime.Gosched() // Leaves time for a write to come in before the load is over. + return v, nil +} + +// update changes key in the source and writes the cache to match, with the +// source locked, so that the writes of a key reach the cache in order. +func (s *source) update(c *load.Cache[int, int], key int, del bool) { + s.mu.Lock() + defer s.mu.Unlock() + s.version[key]++ + if del { + c.Delete(key) + } else { + c.Set(key, 1000*key+s.version[key]) + } +} + +// Under any mix of fetches, writes, purges and Fetch calls that give up, no +// load stores a value that a write has made out of date. +func TestConcurrent(t *testing.T) { + t.Parallel() + + for name, inner := range map[string]func() evict.Cache[int, int]{ + "lru": func() evict.Cache[int, int] { return lru.New[int, int](64) }, + "s3fifo": func() evict.Cache[int, int] { return s3fifo.New[int, int](64) }, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + const ( + goroutines = 8 + requests = 2000 + keys = 8 + ) + src := &source{version: map[int]int{}} + c := load.Wrap(inner(), src.load) + var wg sync.WaitGroup + for g := range goroutines { + wg.Go(func() { + rng := rand.New(rand.NewPCG(uint64(g), 7)) + for range requests { + key := rng.IntN(keys) + switch rng.IntN(20) { + case 0, 1: + src.update(c, key, false) + case 2, 3: + src.update(c, key, true) + case 4: + c.Clear() + case 5: + c.DeleteFunc(func(k, _ int) bool { return k == key }) + case 6, 7: + ctx, cancel := context.WithTimeout(t.Context(), time.Duration(rng.IntN(20))*time.Microsecond) + if v, err := c.Fetch(ctx, key); err == nil && v/1000 != key { + t.Errorf("Fetch(%d) = %d", key, v) + } + cancel() + default: + if v, err := c.Fetch(t.Context(), key); err != nil || v/1000 != key { + t.Errorf("Fetch(%d) = %d, %v", key, v, err) + } + } + } + }) + } + wg.Wait() + + // Every load that a Fetch still waited for is over; the ones + // that were given up on never store. + for key, v := range c.All() { + if want := 1000*key + src.version[key]; v != want { + t.Errorf("the cache holds %d for %d, the source %d", v, key, want) + } + } + }) + } +}