Files
seaweedfs/weed/filer/reader_cache_memory_test.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

555 lines
19 KiB
Go

package filer
import (
"context"
"fmt"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
)
func TestChunkGroupReaderCacheMemory(t *testing.T) {
budget := NewReaderCacheBudget(8 << 10)
groups := make([]*ChunkGroup, 32)
for i := range groups {
group, err := NewChunkGroup(func(context.Context, string) ([]string, error) { return []string{"unused"}, nil }, newMockChunkCacheForReaderCache(), nil, 128, nil, nil, budget)
if err != nil {
t.Fatal(err)
}
groups[i] = group
defer group.Close()
group.readerCache.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, _ string, _ util_http.RefreshUrlsFunc) (int, error) {
buffer[0] = 42
return len(buffer), nil
}
buffer := make([]byte, 1)
n, err := group.readerCache.ReadChunkAt(context.Background(), buffer, fmt.Sprint(i), nil, false, 0, 3<<10, false)
if err != nil || n != 1 || buffer[0] != 42 {
t.Fatalf("read %d: n=%d data=%v err=%v", i, n, buffer, err)
}
budget.Lock()
used := budget.used
budget.Unlock()
if used > 8<<10 {
t.Fatalf("shared budget used %d bytes", used)
}
}
groups[0].readerCache.Lock()
retained := len(groups[0].readerCache.downloaders)
groups[0].readerCache.Unlock()
if retained != 0 {
t.Fatalf("first file still retains %d downloaders", retained)
}
for _, group := range groups {
_ = group.Close()
}
budget.Lock()
defer budget.Unlock()
if budget.used != 0 {
t.Fatalf("closed files still reserve %d bytes", budget.used)
}
}
func TestReaderCacheBudgetInFlight(t *testing.T) {
for _, prefetch := range []bool{false, true} {
t.Run(fmt.Sprintf("prefetch=%t", prefetch), func(t *testing.T) {
budget := NewReaderCacheBudget(8 << 10)
started := make(chan struct{}, 4)
gate := make(chan struct{})
var readers sync.WaitGroup
var caches []*ReaderCache
for i := 0; i < 4; i++ {
rc := NewReaderCache(256, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) { return []string{"unused"}, nil }, nil, budget)
caches = append(caches, rc)
defer rc.destroy()
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, _ string, _ util_http.RefreshUrlsFunc) (int, error) {
started <- struct{}{}
<-gate
buffer[0] = 42
return len(buffer), nil
}
if prefetch {
rc.MaybeCache(&Interval[*ChunkView]{Value: &ChunkView{FileId: "chunk", ViewSize: 3 << 10, ChunkSize: 3 << 10}}, 1)
} else {
readers.Add(1)
go func() {
defer readers.Done()
buffer := make([]byte, 1)
n, err := rc.ReadChunkAt(context.Background(), buffer, "chunk", nil, false, 0, 3<<10, false)
if err != nil || n != 1 || buffer[0] != 42 {
t.Errorf("read: n=%d data=%v err=%v", n, buffer, err)
}
}()
}
}
for i := 0; i < 2; i++ {
<-started
}
select {
case <-started:
t.Error("third download allocated before budget was released")
case <-time.After(50 * time.Millisecond):
}
budget.Lock()
used := budget.used
budget.Unlock()
if used != 8<<10 {
t.Errorf("in-flight reservations = %d, want 8192", used)
}
close(gate)
readers.Wait()
for i := 0; i < 2; i++ {
select {
case <-started:
case <-time.After(5 * time.Second):
t.Fatal("download did not resume after eviction")
}
}
for _, rc := range caches {
rc.destroy()
}
budget.Lock()
defer budget.Unlock()
if budget.used != 0 {
t.Errorf("reservations leaked: %d", budget.used)
}
})
}
}
func TestReaderCacheBudgetOversizedChunk(t *testing.T) {
rc := NewReaderCache(256, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
t.Error("oversized chunk performed lookup")
return nil, nil
}, nil, NewReaderCacheBudget(3<<10))
defer rc.destroy()
_, err := rc.ReadChunkAt(context.Background(), make([]byte, 1), "chunk", nil, false, 0, 3<<10, false)
if err == nil {
t.Fatal("expected pooled buffer larger than budget to be rejected")
}
}
func TestReaderCacheEvictionDoesNotHoldCacheLock(t *testing.T) {
rc := NewReaderCache(2, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) { return []string{"unused"}, nil }, nil)
defer rc.destroy()
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, _ string, _ util_http.RefreshUrlsFunc) (int, error) {
return len(buffer), nil
}
if _, err := rc.ReadChunkAt(context.Background(), make([]byte, 1), "chunk", nil, false, 0, 1024, false); err != nil {
t.Fatal(err)
}
rc.Lock()
downloader := rc.downloaders["chunk"]
downloader.wg.Add(1)
rc.Unlock()
evicted := make(chan struct{})
go func() { rc.UnCache("chunk"); close(evicted) }()
deadline := time.Now().Add(5 * time.Second)
available := false
for time.Now().Before(deadline) {
if rc.TryLock() {
available = rc.downloaders["chunk"] == nil
rc.Unlock()
if available {
break
}
}
time.Sleep(time.Millisecond)
}
downloader.wg.Done()
<-evicted
if !available {
t.Fatal("cache lock held while eviction waited for a reader")
}
}
func TestReaderCacheFailedPrefetchReleasesBudget(t *testing.T) {
for _, lookupFailure := range []bool{false, true} {
t.Run(fmt.Sprintf("lookupFailure=%t", lookupFailure), func(t *testing.T) {
budget := NewReaderCacheBudget(1024)
rc := NewReaderCache(1, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
if lookupFailure {
return nil, fmt.Errorf("lookup failed")
}
return []string{"unused"}, nil
}, nil, budget)
defer rc.destroy()
rc.fetchChunkDataFn = func(_ context.Context, _ []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, _ string, _ util_http.RefreshUrlsFunc) (int, error) {
return 0, fmt.Errorf("fetch failed")
}
rc.MaybeCache(&Interval[*ChunkView]{Value: &ChunkView{FileId: "failed", ViewSize: 1024, ChunkSize: 1024}}, 1)
deadline := time.Now().Add(5 * time.Second)
for {
rc.Lock()
count := len(rc.downloaders)
rc.Unlock()
budget.Lock()
used := budget.used
budget.Unlock()
if count == 0 && used == 0 {
break
}
if time.Now().After(deadline) {
t.Fatalf("failed prefetch retains %d slots and %d bytes", count, used)
}
time.Sleep(time.Millisecond)
}
})
}
}
func TestReaderCacheUnboundedWithoutBudget(t *testing.T) {
if strconv.IntSize == 32 {
// Proving the cache has no implicit memory budget needs more than 64
// in-flight 4 MiB buffers (>256 MiB) at once; the weed/filer test binary
// already runs near the 4 GiB address-space limit on 32-bit.
t.Skip("requires >256MiB of in-flight buffers; skipped on 32-bit")
}
const readers = 96 // more than 256MiB / 4MiB = 64 buffers
started := make(chan struct{}, readers)
gate := make(chan struct{})
rc := NewReaderCache(256, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
return []string{"unused"}, nil
}, nil)
defer rc.destroy()
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, _ string, _ util_http.RefreshUrlsFunc) (int, error) {
started <- struct{}{}
<-gate
buffer[0] = 42
return len(buffer), nil
}
var readersWg sync.WaitGroup
for i := 0; i < readers; i++ {
readersWg.Add(1)
go func(i int) {
defer readersWg.Done()
rc.ReadChunkAt(context.Background(), make([]byte, 1), fmt.Sprint(i), nil, false, 0, 4<<20, false)
}(i)
}
for i := 0; i < readers; i++ {
select {
case <-started:
case <-time.After(5 * time.Second):
close(gate)
readersWg.Wait()
t.Fatalf("only %d of %d downloads started; an implicit memory budget throttled the reader cache", i, readers)
}
}
close(gate)
readersWg.Wait()
}
func TestReaderCacheDropsConsumedChunks(t *testing.T) {
var fetchCount int32
rc := NewReaderCache(10, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
return []string{"unused"}, nil
}, nil)
defer rc.destroy()
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, _ string, _ util_http.RefreshUrlsFunc) (int, error) {
atomic.AddInt32(&fetchCount, 1)
return len(buffer), nil
}
buf := make([]byte, 4<<10)
if _, err := rc.ReadChunkAt(context.Background(), buf, "chunk", nil, false, 0, 4<<10, false); err != nil {
t.Fatal(err)
}
rc.Lock()
_, retained := rc.downloaders["chunk"]
rc.Unlock()
if retained {
t.Fatal("fully consumed chunk buffer still retained")
}
if _, err := rc.ReadChunkAt(context.Background(), buf, "chunk", nil, false, 0, 4<<10, false); err != nil {
t.Fatal(err)
}
if got := atomic.LoadInt32(&fetchCount); got != 2 {
t.Fatalf("consumed chunk was not refetched, fetchCount=%d", got)
}
}
// A prefetched chunk must survive until its reader arrives, then be dropped
// once consumed: the read hits the prefetched buffer (no second fetch) and a
// later read fetches again.
func TestReaderCachePrefetchBufferDroppedAfterRead(t *testing.T) {
var fetchCount int32
rc := NewReaderCache(10, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
return []string{"unused"}, nil
}, nil)
defer rc.destroy()
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, _ string, _ util_http.RefreshUrlsFunc) (int, error) {
atomic.AddInt32(&fetchCount, 1)
buffer[0] = 42
return len(buffer), nil
}
// Past the 1 MiB cache cutoff, so the prefetch does not land in the chunk cache.
rc.MaybeCache(&Interval[*ChunkView]{Value: &ChunkView{FileId: "chunk", ViewOffset: 2 << 20, ViewSize: 4 << 10, ChunkSize: 4 << 10}}, 1)
buf := make([]byte, 4<<10)
n, err := rc.ReadChunkAt(context.Background(), buf, "chunk", nil, false, 0, 4<<10, false)
if err != nil || n != len(buf) || buf[0] != 42 {
t.Fatalf("read of prefetched chunk: n=%d data=%d err=%v", n, buf[0], err)
}
if got := atomic.LoadInt32(&fetchCount); got != 1 {
t.Fatalf("read did not hit the prefetched buffer, fetchCount=%d", got)
}
rc.Lock()
_, retained := rc.downloaders["chunk"]
rc.Unlock()
if retained {
t.Fatal("consumed prefetch buffer still retained")
}
if _, err := rc.ReadChunkAt(context.Background(), buf, "chunk", nil, false, 0, 4<<10, false); err != nil {
t.Fatal(err)
}
if got := atomic.LoadInt32(&fetchCount); got != 2 {
t.Fatalf("consumed chunk was not refetched, fetchCount=%d", got)
}
}
// A consumed chunk survives while another reader is still attached; it is
// dropped once no readers remain, regardless of which reader reached the end.
func TestReaderCacheConsumedBufferSurvivesAttachedReader(t *testing.T) {
var fetchCount int32
rc := NewReaderCache(10, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
return []string{"unused"}, nil
}, nil)
defer rc.destroy()
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, _ string, _ util_http.RefreshUrlsFunc) (int, error) {
atomic.AddInt32(&fetchCount, 1)
buffer[0] = 42
return len(buffer), nil
}
// A partial read primes the cacher, then a second reader attaches.
rc.ReadChunkAt(context.Background(), make([]byte, 1), "chunk", nil, false, 0, 4<<10, false)
rc.Lock()
downloader := rc.downloaders["chunk"]
if downloader == nil {
rc.Unlock()
t.Fatal("cacher missing before attach")
}
downloader.wg.Add(1)
atomic.AddInt32(&downloader.readers, 1)
rc.Unlock()
buf := make([]byte, 4<<10)
if n, err := rc.ReadChunkAt(context.Background(), buf, "chunk", nil, false, 0, 4<<10, false); err != nil || n != len(buf) {
t.Fatalf("full read: n=%d err=%v", n, err)
}
rc.Lock()
_, retained := rc.downloaders["chunk"]
rc.Unlock()
if !retained {
t.Fatal("consumed chunk dropped while a reader was still attached")
}
// The attached reader detaches without reading: since the buffer was
// already consumed, the last detach drops it.
downloader.wg.Done()
atomic.AddInt32(&downloader.readers, -1)
rc.removeConsumed(downloader)
rc.Lock()
_, retained = rc.downloaders["chunk"]
rc.Unlock()
if retained {
t.Fatal("consumed chunk retained after last reader detached")
}
if got := atomic.LoadInt32(&fetchCount); got != 1 {
t.Fatalf("attached readers fetched more than once, fetchCount=%d", got)
}
}
func TestReaderCacheConsumedChunkReleasesBudget(t *testing.T) {
budget := NewReaderCacheBudget(4 << 10)
rc := NewReaderCache(10, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
return []string{"unused"}, nil
}, nil, budget)
defer rc.destroy()
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, _ string, _ util_http.RefreshUrlsFunc) (int, error) {
return len(buffer), nil
}
if _, err := rc.ReadChunkAt(context.Background(), make([]byte, 4<<10), "chunk", nil, false, 0, 4<<10, false); err != nil {
t.Fatal(err)
}
budget.Lock()
used := budget.used
budget.Unlock()
if used != 0 {
t.Fatalf("consumed chunk still reserves %d bytes", used)
}
}
// TestReaderCacheReReadAfterEviction verifies that a chunk evicted by budget
// pressure is transparently re-downloaded on the next read and returns the
// correct data. This is the core correctness property of eviction: a reader
// must never observe missing or stale data after a chunk has been evicted.
func TestReaderCacheReReadAfterEviction(t *testing.T) {
budget := NewReaderCacheBudget(4 << 10) // fits exactly one 4 KiB pooled chunk
rc := NewReaderCache(256, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
return []string{"unused"}, nil
}, nil, budget)
defer rc.destroy()
var fetchCount int32
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, _ string, _ util_http.RefreshUrlsFunc) (int, error) {
n := atomic.AddInt32(&fetchCount, 1)
buffer[0] = byte(n) // each download writes a distinct value
return len(buffer), nil
}
// Read chunk "a": triggers download #1, fills the budget.
buf := make([]byte, 1)
if n, err := rc.ReadChunkAt(context.Background(), buf, "a", nil, false, 0, 4<<10, false); err != nil || n != 1 || buf[0] != 1 {
t.Fatalf("first read of 'a': n=%d data=%d err=%v", n, buf[0], err)
}
// Read chunk "b": budget only fits one chunk, so "a" is evicted to make room.
if n, err := rc.ReadChunkAt(context.Background(), buf, "b", nil, false, 0, 4<<10, false); err != nil || n != 1 || buf[0] != 2 {
t.Fatalf("read of 'b': n=%d data=%d err=%v", n, buf[0], err)
}
// "a" should no longer be in the cache.
rc.Lock()
_, stillCached := rc.downloaders["a"]
rc.Unlock()
if stillCached {
t.Fatal("chunk 'a' was not evicted by budget pressure")
}
// Re-read "a": must trigger download #3 and return the fresh value.
if n, err := rc.ReadChunkAt(context.Background(), buf, "a", nil, false, 0, 4<<10, false); err != nil || n != 1 || buf[0] != 3 {
t.Fatalf("re-read of 'a': n=%d data=%d err=%v (expected re-download with value 3)", n, buf[0], err)
}
if got := atomic.LoadInt32(&fetchCount); got != 3 {
t.Fatalf("fetchCount=%d, want 3 (a, b, a-re-read)", got)
}
}
// A download still waiting for budget is cancelled when its last stream leaves.
func TestReaderCacheBudgetWaitStopsWithItsLastStream(t *testing.T) {
budget := NewReaderCacheBudget(4 << 10)
var lookups sync.Map
rc := NewReaderCache(256, newMockChunkCacheForReaderCache(), func(_ context.Context, fileId string) ([]string, error) {
lookups.Store(fileId, true)
return []string{"unused"}, nil
}, nil, budget)
defer rc.destroy()
holding := make(chan struct{})
var holdingOnce sync.Once
finish := make(chan struct{})
rc.fetchChunkDataFn = func(ctx context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, _ string, _ util_http.RefreshUrlsFunc) (int, error) {
holdingOnce.Do(func() { close(holding) })
select {
case <-ctx.Done():
return 0, ctx.Err()
case <-finish:
return len(buffer), nil
}
}
defer close(finish)
// "a" takes the whole budget and its download does not finish
go rc.ReadChunkAt(context.Background(), make([]byte, 1), "a", nil, false, 0, 3<<10, false)
<-holding
var stream chunkStream
ctx, cancel := context.WithCancel(context.Background())
readDone := make(chan error, 1)
go func() {
_, err := rc.readChunkAt(ctx, &stream, make([]byte, 1), "b", nil, true, 0, 3<<10, false)
readDone <- err
}()
time.Sleep(50 * time.Millisecond)
if _, looked := lookups.Load("b"); looked {
t.Fatal(`"b" did not wait for budget`)
}
cancel()
if err := <-readDone; err != context.Canceled {
t.Fatalf("cancelled read: got %v, want context.Canceled", err)
}
released := make(chan struct{})
go func() {
rc.releaseStream(&stream)
close(released)
}()
select {
case <-released:
case <-time.After(2 * time.Second):
t.Fatal("releasing the stream waited for budget nobody needs")
}
}
// TestReaderCacheBudgetLendsScratchToHedges: a hedged download borrows its
// buffer from the budget. It may evict idle chunks for it, as a download
// does, but it neither waits nor touches downloads in flight.
func TestReaderCacheBudgetLendsScratchToHedges(t *testing.T) {
budget := NewReaderCacheBudget(8 << 10)
gate := make(chan struct{})
rc := NewReaderCache(256, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) { return []string{"unused"}, nil }, nil, budget)
defer rc.destroy()
defer close(gate) // before destroy, which waits for the download held at the gate
var sawBudget atomic.Bool
rc.fetchChunkDataFn = func(ctx context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, fileId string, _ util_http.RefreshUrlsFunc) (int, error) {
if util_http.ScratchBudgetFrom(ctx) == budget {
sawBudget.Store(true)
}
if fileId == "inflight" {
<-gate
}
buffer[0] = 42
return len(buffer), nil
}
used := func() int64 {
budget.Lock()
defer budget.Unlock()
return budget.used
}
// two idle chunks fill the budget
for _, fid := range []string{"a", "b"} {
buffer := make([]byte, 1)
if n, err := rc.ReadChunkAt(context.Background(), buffer, fid, nil, false, 0, 3<<10, false); err != nil || n != 1 {
t.Fatalf("read %s: n=%d err=%v", fid, n, err)
}
}
if !sawBudget.Load() {
t.Fatal("the download's context does not carry the budget for its hedges")
}
if used() != 8<<10 {
t.Fatalf("used %d, want the budget full of idle chunks", used())
}
if !budget.TryReserveScratch(3<<10) || !budget.TryReserveScratch(3<<10) {
t.Fatal("hedge buffers did not evict the idle chunks")
}
if budget.TryReserveScratch(3 << 10) {
t.Fatal("a third hedge buffer fit into a full budget")
}
budget.ReleaseScratch(3 << 10)
budget.ReleaseScratch(3 << 10)
if used() != 0 {
t.Fatalf("used %d after returning the hedge buffers, want 0", used())
}
// downloads in flight are not evicted, and the hedge does not wait for them
rc.MaybeCache(&Interval[*ChunkView]{Value: &ChunkView{FileId: "inflight", ViewSize: 6 << 10, ChunkSize: 6 << 10}}, 1)
deadline := time.Now().Add(5 * time.Second)
for used() == 0 && time.Now().Before(deadline) {
time.Sleep(time.Millisecond)
}
start := time.Now()
if budget.TryReserveScratch(3 << 10) {
t.Fatal("a hedge buffer evicted a download in flight")
}
if took := time.Since(start); took > time.Second {
t.Fatalf("a hedge waited %v for room", took)
}
}