Files
seaweedfs/weed/filer/reader_cache_budget.go
T
9a98047e2a util/http: hedge a chunk read whose location goes quiet (#12917)
* util/http: hedge a chunk read whose location goes quiet

A chunk read tried its locations one at a time and read each answer to the
end. A response that stops arriving holds the read for as long as TCP takes
to recover: on a lossy path a lost segment costs at least the 200 ms
retransmission timeout, doubled for every further loss, and nothing gives
up on the connection meanwhile. A sequential reader waits for its chunks in
order, so one stalled chunk stops it, although a replica could send the
chunk in milliseconds. A location that never answers holds the read for the
transport's response header timeout.

In production this showed up as 13 GB checkpoint verifications, read back
serially with O_DIRECT through weed mount, crawling at 25-65 MB/s instead
of 300 MB/s and more, while the hosts of the volume servers saw 2-5% TCP
retransmissions. The volume servers' own GET latency stayed at a few
milliseconds: the stall is on the wire, after the handler has written the
chunk into the socket buffer.

hedgedChunkPass keeps the order and the move-on-at-failure of the old
loops. In addition, once every request in flight has been quiet for longer
than it may be, the read is asked of the next location as well, or, once
every location has been asked, again over a new connection of a location
whose server answered. A request may be quiet for 200 ms before its
response headers, while the server may still be reading the needle from a
busy disk, and for 100 ms in the body, which a healthy server sends without
pauses: half the minimum retransmission timeout, ahead of every wait for a
retransmission, while shorter pauses that recover on their own go by. The first complete answer wins, and the other requests are
cancelled. A read hedges at most twice.

The first request reads straight into the caller's buffer, as before.
Hedges read into pooled buffers, and a winning hedge is copied over only
after the request writing the caller's buffer has ended, so the buffer has
one writer at a time and is not written after the call returns.

Hedging is budgeted: every read earns a tenth of a token, a hedge spends
one, and at most ten are saved up, so hedges stay below about a tenth of
the reads when the whole cluster is slow. A location that had sent no
response headers when another one delivered the chunk is recorded as
unreachable, which leaves it to the background probe of #12776 to put it
first again, and counts as a failure for the location refresh. A body that
stalled after its headers does neither.

Measured with two volume servers whose outgoing links drop packets (netem,
MTU 1500, 0.2 ms delay), reading a 1 GiB file of 2 MiB chunks through weed
mount with dd iflag=direct bs=4M, before and after:

  bursty loss ~2.3% on both replicas   26-76 MB/s   162-193 MB/s
  random loss 3% on both replicas     106-119 MB/s  147-170 MB/s
  random loss 5% on one replica only   71-81 MB/s   157-158 MB/s
  no loss                             no change, 0-2 hedges per 512 reads

Under loss 4-8% of the chunk reads were hedged. A 50 ms body limit did
better on random loss (179-220 MB/s with 3% on both) but worse and less
steadily on bursty loss (108-206 MB/s), where it spent the hedge budget on
pauses that recover by themselves.

Callers: RetriedFetchChunkData on the streaming and the direct path, which
weed mount, the S3 gateway and the WebDAV server read chunks through.
Readers that stream a chunk to a writer as it arrives are unchanged.

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

* util/http: account hedge buffers, go past a throttled hedge, cap hedges per read

Three review findings:

- A hedge reads into a buffer of its own, which weed mount's reader cache
  budget did not see, so stalled downloads could hold twice the configured
  memory. The reader cache now passes its budget in the context
  (WithScratchBudget), and a hedge first takes room for its buffer with
  ReaderCacheBudget.TryReserveScratch. Like a download, that evicts idle
  chunks no stream is positioned in, but it never waits and never evicts a
  pinned chunk or a download in flight: a hedge that does not fit is not
  sent. The room is returned when the buffer is freed, also for requests
  abandoned in the background.

- A hedge answered with 429 ended the asking, so the read waited out the
  stalled request although a third location was idle. The download limit
  behind a 429 is local to that server, so a throttled hedge now moves on to
  the next location; the 429 is still returned when nothing else delivers.

- Each retry pass earned a new budget share and started a new count of two
  hedges. Both now belong to the read (readHedges) and carry over its passes.

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

* util/http: note an error's headers as an answer, take a hedge token before room

Second round of review findings:

- A location that sent the headers of an error response (a 500, say) and
  then stalled its body was still taken for one that had not answered while
  StatusError waited for that body. Had another location delivered the chunk
  meanwhile, it was recorded as unreachable and the location list refreshed.
  The response headers are now noted as soon as Do returns, before the
  status is looked at.

- A hedge took room for its buffer before its token, and room can evict
  cached chunks. With no token left the room was given back, but the chunks
  were gone. The token now comes first, and is given back when there is no
  room.

- TestReaderCacheBudgetLendsScratchToHedges opens the gate of the download
  it holds in a defer, so a failed assertion cannot leave the cache's
  teardown waiting on it. TestChunkReadHedgeCapCoversRetries also checks that
  the read earned its budget share once.

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

* util/http: do not take a location asked again for unreachable

A location whose response stalled is asked again over a new connection.
When the first request then recovered and delivered the chunk, the new
request had not answered yet, so the host that just served the chunk was
recorded as unreachable and the location list refreshed. A location any
request of the read heard from is no longer counted.

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-11-23 13:29:07 -08:00

201 lines
4.9 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
b.Unlock()
return nil
}
// Prefer evicting an idle chunk no stream is positioned in; fall back
// to the oldest pinned one so abandoned pins cannot block the budget.
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 entry != nil {
b.idle.Remove(entry)
delete(b.idleEntries, victim)
b.Unlock()
if pinnedVictim {
victim.parent.remove(victim)
} else if !victim.parent.removeUnpinned(victim) {
// 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.Unlock()
}
continue
}
changed := b.changed
b.Unlock()
select {
case <-changed:
case <-s.ctx.Done():
return s.ctx.Err()
}
}
}
// 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.removeUnpinned(victim) {
// 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.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))
close(b.changed)
b.changed = make(chan struct{})
}
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)
close(b.changed)
b.changed = make(chan struct{})
}
}
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)
}
close(b.changed)
b.changed = make(chan struct{})
}
}