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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

<p>
Expand Down Expand Up @@ -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)).

Expand Down
7 changes: 4 additions & 3 deletions evict.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
14 changes: 11 additions & 3 deletions internal/inlinecheck/inline_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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 {
Expand All @@ -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"},
Expand Down
27 changes: 27 additions & 0 deletions internal/inlinecheck/probe/load/probe.go
Original file line number Diff line number Diff line change
@@ -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)
}
113 changes: 113 additions & 0 deletions load/bench_test.go
Original file line number Diff line number Diff line change
@@ -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++
}
}
38 changes: 38 additions & 0 deletions load/example_test.go
Original file line number Diff line number Diff line change
@@ -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 <nil>
// no "b" in the database
// 10
}
56 changes: 56 additions & 0 deletions load/export_test.go
Original file line number Diff line number Diff line change
@@ -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
Loading