Files
seaweedfs/weed/filer/reader_cache_budget.go
T
e32f1aa20e filer: don't evict a chunk a stream is still reading (#13276)
* filer: don't evict a chunk a stream is still reading

The reader cache map and the budget fell back to evicting a chunk a
stream was in as soon as they found no idle one, even while a running
download held the rest and would become evictable once it finished. The
stream then fetched its chunk again. They now evict a pinned chunk only
once pinned chunks alone fill the limit or the budget. A budget wait
wakes when a stream enters or leaves a chunk, and when a pinned
download reserves.

A read across a chunk boundary leaves the stream's chunk before making
room, or its pin would count against another stream's chunk, and carries
the stream to its last chunk. Its reads of the chunk it leaves hold that
download, start first and take no concurrency slot, as evicting the
chunk waits for them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: wait for the budget waiter in reader cache tests instead of sleeping

A reservation that reaches the budget only after the sleep sees the new
state on its first check, so these tests could pass with the wakeup or
the wait rule they cover removed. Wait until the reservation is parked
in reserve, and fail at once if it finishes without waiting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: release blocked test fetches when a boundary read test fails

A t.Fatal before the gate closed left the deferred cache destroy waiting
for the blocked fetch, so the test hung instead of failing. The wait for
the head read to pin chunk0 is now bounded too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: hold the chunk a boundary read leaves from one look at the stream

The hold pass looked up the stream's chunk per task and the leave looked
again, so a concurrent read on the same reader that moved the stream in
between got its new chunk detached and unheld, and the boundary read could
download that chunk again. Take the stream's chunk once, hold it for the
views reading it, and detach only that chunk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: tie the budget-wait test check to the test's own reservation

waitForBudgetWaiter now starts the reservation itself and only accepts a
goroutine parked in reserve that is that goroutine or a download it
started, so an unrelated waiter cannot let a test move on early. The
direct budget tests cancel their waiter on cleanup, since destroy() does
not reach a cacher outside the map.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-02 03:52:46 -08:00

238 lines
6.0 KiB
Go

package filer
import (
"container/list"
"fmt"
"sync"
"sync/atomic"
"github.com/seaweedfs/seaweedfs/weed/util/mem"
)
const DefaultReaderCacheMemoryLimit = 256 << 20
type ReaderCacheBudget struct {
sync.Mutex
limit int64
used int64
reservations map[*SingleChunkCacher]int64
idle list.List
idleEntries map[*SingleChunkCacher]*list.Element
changed chan struct{}
}
func NewReaderCacheBudget(limit int64) *ReaderCacheBudget {
if limit <= 0 {
limit = DefaultReaderCacheMemoryLimit
}
return &ReaderCacheBudget{
limit: limit,
reservations: make(map[*SingleChunkCacher]int64),
idleEntries: make(map[*SingleChunkCacher]*list.Element),
changed: make(chan struct{}),
}
}
func (b *ReaderCacheBudget) reserve(s *SingleChunkCacher) error {
if s.chunkSize < 0 {
return fmt.Errorf("invalid chunk size %d", s.chunkSize)
}
if b == nil {
return nil
}
size := int64(mem.AllocationSize(s.chunkSize))
if size > b.limit {
return fmt.Errorf("chunk buffer needs %d bytes, exceeding reader cache budget %d; increase the readerCacheSizeMB budget", size, b.limit)
}
for {
// a cancelled download must not evict a chunk for itself
if err := s.ctx.Err(); err != nil {
return err
}
b.Lock()
if size <= b.limit-b.used {
b.used += size
b.reservations[s] = size
if atomic.LoadInt32(&s.pins) > 0 {
// a stream pins its download before it reserves, so pinsChanged
// missed it, and pinned chunks now hold more of the budget
b.signalLocked()
}
b.Unlock()
return nil
}
// Prefer evicting an idle chunk no stream is positioned in. Fall back
// to the oldest pinned one once pinned chunks alone leave no room, so
// abandoned pins cannot block the budget. Below that, a download no
// stream is in holds the rest and becomes idle when it finishes.
var victim *SingleChunkCacher
var entry *list.Element
pinnedVictim := false
for e := b.idle.Front(); e != nil; e = e.Next() {
c := e.Value.(*SingleChunkCacher)
if atomic.LoadInt32(&c.pins) == 0 {
victim, entry = c, e
pinnedVictim = false
break
}
if victim == nil {
victim, entry = c, e
pinnedVictim = true
}
}
if pinnedVictim && size <= b.limit-b.pinnedLocked() {
entry = nil
}
if entry != nil {
b.idle.Remove(entry)
delete(b.idleEntries, victim)
b.Unlock()
if !victim.parent.evictForBudget(victim, pinnedVictim) {
// The victim was pinned between selection and removal: keep it
// evictable so a pin abandoned in that gap cannot wedge the
// budget, then retry the selection.
b.Lock()
if _, ok := b.reservations[victim]; ok && b.idleEntries[victim] == nil {
b.idleEntries[victim] = b.idle.PushBack(victim)
b.signalLocked()
}
b.Unlock()
}
continue
}
changed := b.changed
b.Unlock()
select {
case <-changed:
case <-s.ctx.Done():
return s.ctx.Err()
}
}
}
// pinnedLocked sums the reservations of chunks a stream is positioned in.
func (b *ReaderCacheBudget) pinnedLocked() (n int64) {
for s, size := range b.reservations {
if atomic.LoadInt32(&s.pins) > 0 {
n += size
}
}
return n
}
// canFit reports whether a whole-chunk buffer of this size can ever be
// reserved. A chunk bigger than the budget cannot be read through the
// whole-chunk path at all, so callers must fall back to range fetches.
func (b *ReaderCacheBudget) canFit(size int) bool {
return b == nil || int64(mem.AllocationSize(size)) <= b.limit
}
// TryReserveScratch takes size bytes for a buffer that a hedged chunk read
// borrows while it races the download holding the chunk's own reservation.
// Like a download it evicts idle chunks no stream is positioned in, but it
// never waits and never evicts a pinned chunk: a hedge that does not fit is
// simply not sent. A nil budget has room for anything.
func (b *ReaderCacheBudget) TryReserveScratch(size int) bool {
if b == nil {
return true
}
n := int64(mem.AllocationSize(size))
if n > b.limit {
return false
}
for {
b.Lock()
if n <= b.limit-b.used {
b.used += n
b.Unlock()
return true
}
var victim *SingleChunkCacher
var entry *list.Element
for e := b.idle.Front(); e != nil; e = e.Next() {
if c := e.Value.(*SingleChunkCacher); atomic.LoadInt32(&c.pins) == 0 {
victim, entry = c, e
break
}
}
if entry == nil {
b.Unlock()
return false
}
b.idle.Remove(entry)
delete(b.idleEntries, victim)
b.Unlock()
if !victim.parent.evictForBudget(victim, false) {
// pinned meanwhile: keep it evictable, as reserve does, and give up
b.Lock()
if _, ok := b.reservations[victim]; ok && b.idleEntries[victim] == nil {
b.idleEntries[victim] = b.idle.PushBack(victim)
b.signalLocked()
}
b.Unlock()
return false
}
}
}
// ReleaseScratch returns what TryReserveScratch took.
func (b *ReaderCacheBudget) ReleaseScratch(size int) {
if b == nil {
return
}
b.Lock()
defer b.Unlock()
b.used -= int64(mem.AllocationSize(size))
b.signalLocked()
}
func (b *ReaderCacheBudget) complete(s *SingleChunkCacher) {
if b == nil {
return
}
b.Lock()
defer b.Unlock()
if _, found := b.reservations[s]; found && b.idleEntries[s] == nil {
b.idleEntries[s] = b.idle.PushBack(s)
b.signalLocked()
}
}
func (b *ReaderCacheBudget) release(s *SingleChunkCacher) {
if b == nil {
return
}
b.Lock()
defer b.Unlock()
if size, found := b.reservations[s]; found {
b.used -= size
delete(b.reservations, s)
if entry := b.idleEntries[s]; entry != nil {
b.idle.Remove(entry)
delete(b.idleEntries, s)
}
b.signalLocked()
}
}
// pinsChanged wakes reservations waiting for room when a stream first enters
// s or the last one leaves it. Whether they wait or evict a pinned chunk
// depends on which chunks have a stream in them, and a chunk out of the map
// isn't released when its last stream leaves.
func (b *ReaderCacheBudget) pinsChanged(s *SingleChunkCacher) {
if b == nil {
return
}
b.Lock()
defer b.Unlock()
if _, found := b.reservations[s]; found {
b.signalLocked()
}
}
func (b *ReaderCacheBudget) signalLocked() {
close(b.changed)
b.changed = make(chan struct{})
}