carlos / platform Public

assetcache: fair-share eviction and Retain

Reserve's makeRoom evicts the least recently used entry of the app
furthest over its share (budget over apps with entries, at most a quarter),
through drop so leased bytes stay counted. Per-app LRU lists live in the
index and Get moves a hit to the front. Retain deletes the entries a
predicate rejects.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 32143c6bb1c2ef715ca0da2fbb247a172ae17c98 parent 245891d
5 files changed, +411 −33
  • internal/assetcache/entry_test.go +13 −9
  • internal/assetcache/evict.go +92 −0
  • internal/assetcache/evict_test.go +272 −0
  • internal/assetcache/fill.go +0 −4
  • internal/assetcache/store.go +34 −20

CI failed — run details

diff --git a/internal/assetcache/entry_test.go b/internal/assetcache/entry_test.go
index 75c222b15..e39613e6d 100644
--- a/internal/assetcache/entry_test.go
+++ b/internal/assetcache/entry_test.go
@@ -352,23 +352,28 @@ func TestCommitOfAFailedFillAborts(t *testing.T) {
}
// heldBytesRefuse checks that, with a reader holding retired bytes, a fill
-// that fits only by counting them as free is refused, and that it is admitted
-// once the reader closes.
+// that fits only by counting them as free is refused (after evicting every
+// other entry), and that it is admitted once the reader closes.
func heldBytesRefuse(t *testing.T, s *Store, held int64, r *Reader, wantBody []byte) {
t.Helper()
st := s.Stats()
if st.Retired != held {
t.Fatalf("Retired = %d, want %d", st.Retired, held)
}
- // The smallest fill that does not fit while the held bytes are counted.
- n := (s.cfg.Budget-st.Bytes-st.Reserved-metaReserve)/2 + 1
- if n < 0 || 2*n+metaReserve > s.cfg.Budget-(st.Bytes-held)-st.Reserved {
+ // The smallest fill that does not fit while the held bytes are counted,
+ // even after eviction has freed every other entry.
+ n := (s.cfg.Budget-held-st.Reserved-metaReserve)/2 + 1
+ if n < 0 || 2*n+metaReserve > s.cfg.Budget-st.Reserved {
t.Fatalf("test budget leaves no room for the probe: Stats %+v", st)
}
probe := testKey("blog", "/probe")
if _, err := s.Reserve(probe, n); !errors.Is(err, ErrNoRoom) {
t.Fatalf("Reserve(%d) with %d bytes held = %v, want ErrNoRoom", n, held, err)
}
+ // The refused fill evicted what it could; the held bytes remain.
+ if st1 := s.Stats(); st1.Entries != 0 || st1.Bytes != held || st1.Retired != held {
+ t.Fatalf("Stats after the refusal = %+v, want no entries and only the %d held bytes", st1, held)
+ }
// The reader still reads the unlinked bytes.
got, err := io.ReadAll(r)
if err != nil || !bytes.Equal(got, wantBody) {
@@ -377,8 +382,8 @@ func heldBytesRefuse(t *testing.T, s *Store, held int64, r *Reader, wantBody []b
if err := r.Close(); err != nil {
t.Fatal(err)
}
- if st2 := s.Stats(); st2.Retired != 0 || st2.Bytes != st.Bytes-held {
- t.Fatalf("Stats after Close = %+v, want Retired 0 and Bytes %d", st2, st.Bytes-held)
+ if st2 := s.Stats(); st2.Retired != 0 || st2.Bytes != 0 {
+ t.Fatalf("Stats after Close = %+v, want nothing held", st2)
}
f, err := s.Reserve(probe, n)
if err != nil {
@@ -388,8 +393,7 @@ func heldBytesRefuse(t *testing.T, s *Store, held int64, r *Reader, wantBody []b
}
// TestEvictedBodyStaysCountedWhileAReaderHoldsIt is not acceptance: it uses a
-// fake FS. Eviction itself is Task 5; this drives drop, the function eviction
-// calls.
+// fake FS. It drives drop, the function eviction calls.
func TestEvictedBodyStaysCountedWhileAReaderHoldsIt(t *testing.T) {
s, _, dir := entryStore(t, 70000)
k := testKey("shop", "/a.css")
diff --git a/internal/assetcache/evict.go b/internal/assetcache/evict.go
new file mode 100644
index 000000000..a7877eccb
--- /dev/null
+++ b/internal/assetcache/evict.go
@@ -0,0 +1,92 @@
+package assetcache
+
+// makeRoom evicts entries until a reservation of need bytes fits the budget
+// beside what the store holds and has promised (used + reserved + need <=
+// Budget), or until nothing is left to evict. Each round takes the least
+// recently used entry of the app furthest over its share. Bytes that open
+// Readers hold stay counted (drop keeps them), so room can stay short; the
+// caller's budget check decides. It is called without s.mu held and takes
+// s.mu only to choose a victim, never across the deletion.
+func (s *Store) makeRoom(need int64) {
+ var failed map[*entry]bool // victims drop could not delete; not chosen again
+ for {
+ s.mu.Lock()
+ if s.used <= s.cfg.Budget-s.reserved-need {
+ s.mu.Unlock()
+ return
+ }
+ victim := s.victimLocked(failed)
+ s.mu.Unlock()
+ if victim == nil {
+ return
+ }
+ if !s.drop(victim) {
+ if failed == nil {
+ failed = make(map[*entry]bool)
+ }
+ failed[victim] = true
+ }
+ }
+}
+
+// victimLocked returns the least recently used entry, outside skip, of the
+// app with the largest bytes - share, or nil when no entry qualifies. Equal
+// excess goes to the app whose candidate was used longest ago. The caller
+// holds s.mu.
+func (s *Store) victimLocked(skip map[*entry]bool) *entry {
+ share := s.shareOf(len(s.apps))
+ var victim *entry
+ var victimOver int64
+ for _, app := range s.apps {
+ var cand *entry
+ for el := app.lru.Back(); el != nil; el = el.Prev() {
+ if e := el.Value.(*entry); !skip[e] {
+ cand = e
+ break
+ }
+ }
+ if cand == nil {
+ continue
+ }
+ over := app.bytes - share
+ if victim == nil || over > victimOver || (over == victimOver && cand.used < victim.used) {
+ victim, victimOver = cand, over
+ }
+ }
+ return victim
+}
+
+// shareOf is the bytes each of apps apps may hold before eviction takes
+// from them: the budget divided among them, never more than a quarter of it
+// for one app.
+func (s *Store) shareOf(apps int) int64 {
+ if apps < 1 {
+ apps = 1
+ }
+ share := s.cfg.Budget / int64(apps)
+ if limit := s.cfg.Budget / 4; share > limit {
+ share = limit
+ }
+ return share
+}
+
+// Retain deletes every entry whose key keep rejects and returns how many it
+// deleted. keep is called without any store lock held, once per entry that
+// was indexed when Retain began; an entry committed meanwhile is not judged.
+// An entry a Reader holds is deleted like any other: its files go at once
+// and its bytes stay counted until the Reader closes.
+func (s *Store) Retain(keep func(Key) bool) int {
+ s.mu.Lock()
+ all := make([]*entry, 0, len(s.entries))
+ for _, e := range s.entries {
+ all = append(all, e)
+ }
+ s.mu.Unlock()
+ n := 0
+ for _, e := range all {
+ if !keep(e.meta.Key) && s.drop(e) {
+ n++
+ }
+ }
+ return n
+}
diff --git a/internal/assetcache/evict_test.go b/internal/assetcache/evict_test.go
new file mode 100644
index 000000000..ef96231d3
--- /dev/null
+++ b/internal/assetcache/evict_test.go
@@ -0,0 +1,272 @@
+package assetcache
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+// The eviction tests use a budget of 1000000 bytes and 20000-byte bodies. A
+// committed entry holds its body plus a .meta of a few hundred bytes, and a
+// fill of such a body reserves 2*20000 + metaReserve, so a store can be
+// filled to a little over 90% before the next fill has to evict. A test
+// that wants the next fill to evict reserves for bigBody instead.
+
+const evictBudget = 1000000
+
+var (
+ evictBody = []byte(strings.Repeat("x", 20000))
+ bigBody = []byte(strings.Repeat("y", 100000))
+)
+
+// evictStore opens a store with the eviction budget over a fake FS with
+// plenty of room. Tests using it are not acceptance.
+func evictStore(t *testing.T) (*Store, string) {
+ t.Helper()
+ s, _, dir := entryStore(t, evictBudget)
+ return s, dir
+}
+
+// commitN commits n entries /<prefix>0 .. /<prefix>n-1 for app, oldest first.
+func commitN(t *testing.T, s *Store, app, prefix string, n int) {
+ t.Helper()
+ for i := 0; i < n; i++ {
+ commit(t, s, testKey(app, fmt.Sprintf("/%s%d", prefix, i)), evictBody, cssHeader("1"), false)
+ }
+}
+
+// present reports whether the entry is indexed, without marking it used.
+func present(s *Store, app, path string) bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ e := s.entries[testKey(app, path).ID()]
+ return e != nil
+}
+
+func mustBePresent(t *testing.T, s *Store, app, path string) {
+ t.Helper()
+ if !present(s, app, path) {
+ t.Fatalf("%s %s was evicted, want kept", app, path)
+ }
+}
+
+func mustBeGone(t *testing.T, s *Store, app, path string) {
+ t.Helper()
+ if present(s, app, path) {
+ t.Fatalf("%s %s survived, want evicted", app, path)
+ }
+}
+
+func mustFitBudget(t *testing.T, s *Store) {
+ t.Helper()
+ if st := s.Stats(); st.Bytes+st.Reserved > evictBudget {
+ t.Fatalf("Stats = %+v, over the budget %d", st, evictBudget)
+ }
+}
+
+// TestEvictionTakesFromTheAppFurthestOverItsShare is not acceptance: it uses
+// a fake FS.
+func TestEvictionTakesFromTheAppFurthestOverItsShare(t *testing.T) {
+ s, _ := evictStore(t)
+ commitN(t, s, "shop", "s", 36) // about 73% of the budget
+ commitN(t, s, "blog", "b", 5) // about 10%
+ // Use shop's oldest: it is no longer the least recently used.
+ mustGet(t, s, testKey("shop", "/s0"))
+
+ f, err := s.Reserve(testKey("blog", "/b5"), int64(len(bigBody)))
+ if err != nil {
+ t.Fatalf("Reserve: %v", err)
+ }
+ defer f.Abort()
+
+ mustBePresent(t, s, "shop", "/s0") // used since: spared
+ mustBeGone(t, s, "shop", "/s1")
+ mustBeGone(t, s, "shop", "/s2")
+ mustBePresent(t, s, "shop", "/s35")
+ for i := 0; i < 5; i++ {
+ mustBePresent(t, s, "blog", fmt.Sprintf("/b%d", i))
+ }
+ mustFitBudget(t, s)
+}
+
+// TestOneAppWalkingUniqueQueriesEvictsItself is not acceptance: it uses a
+// fake FS.
+func TestOneAppWalkingUniqueQueriesEvictsItself(t *testing.T) {
+ s, _ := evictStore(t)
+ commitN(t, s, "blog", "b", 1)
+ for i := 0; i < 70; i++ {
+ commit(t, s, testKey("shop", fmt.Sprintf("/q%d", i)), evictBody, cssHeader("1"), false)
+ mustFitBudget(t, s)
+ }
+ mustBePresent(t, s, "blog", "/b0")
+ mustBeGone(t, s, "shop", "/q0")
+ mustBePresent(t, s, "shop", "/q69")
+ if st := s.Stats(); st.Entries < 20 {
+ t.Fatalf("Stats = %+v, want shop to keep filling its own room", st)
+ }
+}
+
+// TestNewAppEvictsTheAppOverItsShare is not acceptance: it uses a fake FS.
+// The second app has no entries yet. Its fill is admitted by evicting the
+// first app's oldest entries, not refused.
+func TestNewAppEvictsTheAppOverItsShare(t *testing.T) {
+ s, _ := evictStore(t)
+ commitN(t, s, "shop", "s", 40) // about 80% of the budget
+ mustFitBudget(t, s)
+
+ commit(t, s, testKey("blog", "/b0"), bigBody, cssHeader("1"), false)
+
+ mustBePresent(t, s, "blog", "/b0")
+ mustBeGone(t, s, "shop", "/s0")
+ mustBeGone(t, s, "shop", "/s1")
+ mustBePresent(t, s, "shop", "/s39")
+ mustFitBudget(t, s)
+}
+
+// TestShareNeverExceedsAQuarter is not acceptance: it uses a fake FS. One app
+// alone has the whole budget to itself by division, but its share stops at a
+// quarter.
+func TestShareNeverExceedsAQuarter(t *testing.T) {
+ s, _ := evictStore(t)
+ for apps, want := range map[int]int64{1: evictBudget / 4, 2: evictBudget / 4, 4: evictBudget / 4, 8: evictBudget / 8, 100: evictBudget / 100} {
+ if got := s.shareOf(apps); got != want {
+ t.Errorf("shareOf(%d) = %d, want %d", apps, got, want)
+ }
+ }
+
+ // One app alone passes 25% and is evicted (itself) when room is needed.
+ commitN(t, s, "shop", "s", 40)
+ commit(t, s, testKey("shop", "/new"), bigBody, cssHeader("1"), false)
+ mustBeGone(t, s, "shop", "/s0")
+ mustBePresent(t, s, "shop", "/new")
+ mustFitBudget(t, s)
+}
+
+// TestEvictionKeepsLeasedBytesCounted is not acceptance: it uses a fake FS.
+// Eviction goes through drop, so a body a Reader holds stays counted and
+// makeRoom stops when nothing is left to evict.
+func TestEvictionKeepsLeasedBytesCounted(t *testing.T) {
+ s, _ := evictStore(t)
+ commitN(t, s, "shop", "s", 3)
+ var readers []*Reader
+ for i := 0; i < 3; i++ {
+ r, err := mustGet(t, s, testKey("shop", fmt.Sprintf("/s%d", i))).Open(false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ readers = append(readers, r)
+ }
+ s.makeRoom(10 * evictBudget) // cannot fit; evicts everything it can
+ st := s.Stats()
+ if st.Entries != 0 || st.Retired != 3*int64(len(evictBody)) || st.Bytes != st.Retired {
+ t.Fatalf("Stats = %+v, want no entries and the three leased bodies counted", st)
+ }
+ for _, r := range readers {
+ r.Close()
+ }
+ if st := s.Stats(); st.Bytes != 0 || st.Retired != 0 {
+ t.Fatalf("Stats after Close = %+v, want 0", st)
+ }
+}
+
+// TestRetainDeletesRejectedKeys is not acceptance: it uses a fake FS.
+func TestRetainDeletesRejectedKeys(t *testing.T) {
+ s, dir := evictStore(t)
+ commitN(t, s, "shop", "s", 3)
+ commitN(t, s, "blog", "b", 2)
+
+ n := s.Retain(func(k Key) bool { return k.App == "blog" || k.Path == "/s1" })
+ if n != 2 {
+ t.Fatalf("Retain = %d, want 2", n)
+ }
+ mustBeGone(t, s, "shop", "/s0")
+ mustBePresent(t, s, "shop", "/s1")
+ mustBeGone(t, s, "shop", "/s2")
+ mustBePresent(t, s, "blog", "/b0")
+ mustBePresent(t, s, "blog", "/b1")
+ if st := s.Stats(); st.Entries != 3 || st.Retired != 0 {
+ t.Fatalf("Stats = %+v, want 3 entries", st)
+ }
+ // Nothing of the deleted entries is left on disk: three entries' files.
+ if got := listDir(t, dir); len(got) != 6 {
+ t.Fatalf("files = %v, want .meta and .body for 3 entries", got)
+ }
+ if n := s.Retain(func(Key) bool { return true }); n != 0 {
+ t.Fatalf("second Retain = %d, want 0", n)
+ }
+ if n := s.Retain(func(Key) bool { return false }); n != 3 {
+ t.Fatalf("reject-all Retain = %d, want 3", n)
+ }
+ if st := s.Stats(); st.Entries != 0 || st.Bytes != 0 || st.Apps != 0 {
+ t.Fatalf("Stats = %+v, want empty", st)
+ }
+}
+
+// TestEvictionRacesFillsGetsAndRetain is not acceptance: it uses a fake FS.
+// Fills in two apps, Gets and Retain run together under -race; afterwards
+// the per-app lists and byte counts agree with the index.
+func TestEvictionRacesFillsGetsAndRetain(t *testing.T) {
+ s, _ := evictStore(t)
+ body := evictBody
+ var wg sync.WaitGroup
+ for _, app := range []string{"shop", "blog"} {
+ for w := 0; w < 3; w++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for i := 0; i < 15; i++ {
+ k := testKey(app, fmt.Sprintf("/w%d-%d", w, i))
+ f, err := s.Reserve(k, int64(len(body)))
+ if err != nil {
+ if !errors.Is(err, ErrNoRoom) && !errors.Is(err, ErrBusy) {
+ t.Errorf("Reserve: %v", err)
+ }
+ continue
+ }
+ if _, err := f.Write(body); err != nil {
+ t.Errorf("Write: %v", err)
+ }
+ if err := f.Commit(Meta{Header: cssHeader("1"), Lifetime: time.Hour, Expires: testNow.Add(time.Hour)}, false); err != nil {
+ t.Errorf("Commit: %v", err)
+ }
+ s.Get(testKey(app, fmt.Sprintf("/w%d-%d", w, i/2)))
+ }
+ }()
+ }
+ }
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for i := 0; i < 10; i++ {
+ s.Retain(func(k Key) bool { return k.Path != "/w0-3" })
+ }
+ }()
+ wg.Wait()
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.reserved != 0 || s.used > evictBudget {
+ t.Fatalf("reserved %d used %d, want 0 and within %d", s.reserved, s.used, evictBudget)
+ }
+ listed := 0
+ for scope, app := range s.apps {
+ var sum int64
+ for el := app.lru.Front(); el != nil; el = el.Next() {
+ e := el.Value.(*entry)
+ if s.entries[e.id] != e || e.elem != el || e.meta.Key.AppScope() != scope {
+ t.Fatalf("list of %s holds an entry the index does not", scope)
+ }
+ sum += e.bytes()
+ listed++
+ }
+ if sum != app.bytes {
+ t.Fatalf("%s bytes = %d, its entries hold %d", scope, app.bytes, sum)
+ }
+ }
+ if listed != len(s.entries) {
+ t.Fatalf("lists hold %d entries, index %d", listed, len(s.entries))
+ }
+}
diff --git a/internal/assetcache/fill.go b/internal/assetcache/fill.go
index 7c8bf4d7f..fb4d7b78e 100644
--- a/internal/assetcache/fill.go
+++ b/internal/assetcache/fill.go
@@ -158,10 +158,6 @@ func (s *Store) admit(scope string, r int64, total, free uint64) error {
return nil
}
-// makeRoom frees budget for a reservation of need bytes by evicting entries.
-// It is called without s.mu held.
-func (s *Store) makeRoom(need int64) {}
-
// open creates the identity temporary. Its name carries ".tmp-", so a crash
// leaves something Open removes.
func (f *Fill) open() error {
diff --git a/internal/assetcache/store.go b/internal/assetcache/store.go
index 2a6b96cb2..979958926 100644
--- a/internal/assetcache/store.go
+++ b/internal/assetcache/store.go
@@ -6,6 +6,7 @@
package assetcache
import (
+ "container/list"
"errors"
"fmt"
"math"
@@ -43,9 +44,16 @@ type Stats struct {
type entry struct {
id string
meta Meta
- metaSize int64 // bytes of the .meta file
- ver *version // the body files meta names
- used uint64 // the store's use counter when last returned by Get
+ metaSize int64 // bytes of the .meta file
+ ver *version // the body files meta names
+ used uint64 // the store's use counter when indexed or last returned by Get
+ elem *list.Element // its place in its app's LRU list, front most recent; guarded by s.mu
+}
+
+// appIndex is one app's indexed entries, most recently used first.
+type appIndex struct {
+ lru *list.List // of *entry
+ bytes int64 // the sum of its entries' bytes()
}
func newEntry(id string, m Meta, metaSize int64) *entry {
@@ -81,16 +89,16 @@ type Store struct {
cfg Config
mu sync.Mutex
- entries map[string]*entry // by id
- apps map[string]map[string]*entry // AppScope -> id -> entry
- used int64 // bytes held by entries and retired versions
- retired int64 // the part of used no indexed entry names
- reserved int64 // bytes promised to fills in flight
- fills int // fills in flight on this box
- fillsByApp map[string]int // fills in flight by AppScope
- useCount uint64 // ticks once per Get hit
- idLocks map[string]*idLock // by id, while held or awaited
- stuck map[*version]struct{} // retired versions whose unlink failed
+ entries map[string]*entry // by id
+ apps map[string]*appIndex // by AppScope, for apps with entries
+ used int64 // bytes held by entries and retired versions
+ retired int64 // the part of used no indexed entry names
+ reserved int64 // bytes promised to fills in flight
+ fills int // fills in flight on this box
+ fillsByApp map[string]int // fills in flight by AppScope
+ useCount uint64 // ticks once per index and per Get hit
+ idLocks map[string]*idLock // by id, while held or awaited
+ stuck map[*version]struct{} // retired versions whose unlink failed
}
// Open creates the directory if needed and rebuilds the index from it.
@@ -116,7 +124,7 @@ func Open(cfg Config) (*Store, error) {
s := &Store{
cfg: cfg,
entries: make(map[string]*entry),
- apps: make(map[string]map[string]*entry),
+ apps: make(map[string]*appIndex),
fillsByApp: make(map[string]int),
idLocks: make(map[string]*idLock),
@@ -243,10 +251,13 @@ func (s *Store) index(e *entry) {
scope := e.meta.Key.AppScope()
app := s.apps[scope]
if app == nil {
- app = make(map[string]*entry)
+ app = &appIndex{lru: list.New()}
s.apps[scope] = app
}
- app[e.id] = e
+ s.useCount++
+ e.used = s.useCount
+ e.elem = app.lru.PushFront(e)
+ app.bytes += e.bytes()
e.ver.indexed = true
e.ver.counted = true
s.used += e.bytes()
@@ -261,11 +272,13 @@ func (s *Store) unindexLocked(e *entry) {
delete(s.entries, e.id)
scope := e.meta.Key.AppScope()
if app := s.apps[scope]; app != nil {
- delete(app, e.id)
- if len(app) == 0 {
+ app.lru.Remove(e.elem)
+ app.bytes -= e.bytes()
+ if app.lru.Len() == 0 {
delete(s.apps, scope)
}
}
+ e.elem = nil
s.used -= e.metaSize
v := e.ver
v.indexed = false
@@ -346,8 +359,8 @@ func (s *Store) lockID(id string) (unlock func()) {
// leaves only orphan bodies that Open removes, then its bodies, subject to
// leases. It deletes nothing and reports false when e is no longer the
// indexed entry for its id, or when its .meta cannot be removed (the entry
-// then stays indexed and counted). Get's expiry uses it; eviction, Retain and
-// the sweep are to use it too. It is called without s.mu held.
+// then stays indexed and counted). Get's expiry, eviction and Retain use it, and
+// the sweep is to. It is called without s.mu held.
func (s *Store) drop(e *entry) bool {
unlock := s.lockID(e.id)
s.mu.Lock()
@@ -398,6 +411,7 @@ func (s *Store) Get(k Key) (*Entry, bool) {
}
s.useCount++
e.used = s.useCount
+ s.apps[e.meta.Key.AppScope()].lru.MoveToFront(e.elem)
out := &Entry{Meta: e.meta, s: s, ver: e.ver}
out.Meta.Header = e.meta.Header.Clone()
s.mu.Unlock()