Files
seaweedfs/weed/filer/reader_at_test.go
T
25e0c6080a filer: resume chunk reads where the last one ended (#13393)
* filer: resume chunk reads where the last one ended

ChunkReadAt walked the chunk views from the front on every ReadAt, so
reading a file of n chunks front to back took time proportional to n
squared. S3 GETs (256 KiB reads) and WebDAV downloads (32 KiB reads)
both read whole files through it: a 32 KiB read near the end of a file
of 100,000 chunks took 164 µs instead of 8 µs.

Keep where the last read ended and start the next walk there when it is
at or before the new offset. The mount merges new chunks into a live
reader's views, so the interval list now counts its edits and a kept
position is only used while the count is unchanged.

* filer: benchmark ChunkReadAt reads

Whole-file sequential reads at 1 to 100,000 chunks, one-chunk files read
with a new reader, and random reads, all served by mockChunkCache so they
measure the reader itself.

* filer: trim the resume-point comments

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

---------

Co-authored-by: Denis Maier <denis@dAir.lab>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 11:22:53 -08:00

352 lines
11 KiB
Go

package filer
import (
"bytes"
"context"
"errors"
"io"
"math"
"strconv"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
type mockChunkCache struct {
}
func (m *mockChunkCache) GetChunk(fileId string, minSize uint64) (data []byte) {
x, _ := strconv.Atoi(fileId)
data = make([]byte, minSize)
for i := 0; i < int(minSize); i++ {
data[i] = byte(x)
}
return data
}
func (m *mockChunkCache) ReadChunkAt(data []byte, fileId string, offset uint64) (n int, err error) {
x, _ := strconv.Atoi(fileId)
for i := 0; i < len(data); i++ {
data[i] = byte(x)
}
return len(data), nil
}
func (m *mockChunkCache) SetChunk(fileId string, data []byte) {
}
func (m *mockChunkCache) GetMaxFilePartSizeInCache() uint64 {
return 0
}
func (m *mockChunkCache) IsInCache(fileId string, lockNeeded bool) (answer bool) {
return false
}
func TestReaderAt(t *testing.T) {
visibles := NewIntervalList[*VisibleInterval]()
addVisibleInterval(visibles, &VisibleInterval{
start: 1,
stop: 2,
fileId: "1",
chunkSize: 9,
})
addVisibleInterval(visibles, &VisibleInterval{
start: 3,
stop: 4,
fileId: "3",
chunkSize: 1,
})
addVisibleInterval(visibles, &VisibleInterval{
start: 5,
stop: 6,
fileId: "5",
chunkSize: 2,
})
addVisibleInterval(visibles, &VisibleInterval{
start: 7,
stop: 9,
fileId: "7",
chunkSize: 2,
})
addVisibleInterval(visibles, &VisibleInterval{
start: 9,
stop: 10,
fileId: "9",
chunkSize: 2,
})
readerAt := &ChunkReadAt{
chunkViews: ViewFromVisibleIntervals(visibles, 0, math.MaxInt64),
fileSize: 10,
readerCache: NewReaderCache(3, &mockChunkCache{}, nil, nil),
readerPattern: NewReaderPattern(),
}
testReadAt(t, readerAt, 0, 10, 10, io.EOF, nil, nil)
testReadAt(t, readerAt, 0, 12, 10, io.EOF, nil, nil)
testReadAt(t, readerAt, 2, 8, 8, io.EOF, nil, nil)
testReadAt(t, readerAt, 3, 6, 6, nil, nil, nil)
}
func testReadAt(t *testing.T, readerAt *ChunkReadAt, offset int64, size int, expectedN int, expectedErr error, data, expectedData []byte) {
if data == nil {
data = make([]byte, size)
}
n, _, err := readerAt.doReadAt(context.Background(), data, offset)
if expectedN != n {
t.Errorf("unexpected read size: %d, expect: %d", n, expectedN)
}
if err != expectedErr {
t.Errorf("unexpected read error: %v, expect: %v", err, expectedErr)
}
if expectedData != nil && !bytes.Equal(data, expectedData) {
t.Errorf("unexpected read data: %v, expect: %v", data, expectedData)
}
}
func TestReaderAt0(t *testing.T) {
visibles := NewIntervalList[*VisibleInterval]()
addVisibleInterval(visibles, &VisibleInterval{
start: 2,
stop: 5,
fileId: "1",
chunkSize: 9,
})
addVisibleInterval(visibles, &VisibleInterval{
start: 7,
stop: 9,
fileId: "2",
chunkSize: 9,
})
readerAt := &ChunkReadAt{
chunkViews: ViewFromVisibleIntervals(visibles, 0, math.MaxInt64),
fileSize: 10,
readerCache: NewReaderCache(3, &mockChunkCache{}, nil, nil),
readerPattern: NewReaderPattern(),
}
testReadAt(t, readerAt, 0, 10, 10, io.EOF, nil, nil)
testReadAt(t, readerAt, 3, 16, 7, io.EOF, nil, nil)
testReadAt(t, readerAt, 3, 5, 5, nil, nil, nil)
testReadAt(t, readerAt, 11, 5, 0, io.EOF, nil, nil)
testReadAt(t, readerAt, 10, 5, 0, io.EOF, nil, nil)
}
func TestReaderAt1(t *testing.T) {
visibles := NewIntervalList[*VisibleInterval]()
addVisibleInterval(visibles, &VisibleInterval{
start: 2,
stop: 5,
fileId: "1",
chunkSize: 9,
})
readerAt := &ChunkReadAt{
chunkViews: ViewFromVisibleIntervals(visibles, 0, math.MaxInt64),
fileSize: 20,
readerCache: NewReaderCache(3, &mockChunkCache{}, nil, nil),
readerPattern: NewReaderPattern(),
}
testReadAt(t, readerAt, 0, 20, 20, io.EOF, nil, nil)
testReadAt(t, readerAt, 1, 7, 7, nil, nil, nil)
testReadAt(t, readerAt, 0, 1, 1, nil, nil, nil)
testReadAt(t, readerAt, 18, 4, 2, io.EOF, nil, nil)
testReadAt(t, readerAt, 12, 4, 4, nil, nil, nil)
testReadAt(t, readerAt, 4, 20, 16, io.EOF, nil, nil)
testReadAt(t, readerAt, 4, 10, 10, nil, nil, nil)
testReadAt(t, readerAt, 1, 10, 10, nil, nil, nil)
}
func TestReaderAtGappedChunksDoNotLeak(t *testing.T) {
visibles := NewIntervalList[*VisibleInterval]()
addVisibleInterval(visibles, &VisibleInterval{
start: 2,
stop: 3,
fileId: "1",
chunkSize: 5,
})
addVisibleInterval(visibles, &VisibleInterval{
start: 7,
stop: 9,
fileId: "1",
chunkSize: 4,
})
readerAt := &ChunkReadAt{
chunkViews: ViewFromVisibleIntervals(visibles, 0, math.MaxInt64),
fileSize: 9,
readerCache: NewReaderCache(3, &mockChunkCache{}, nil, nil),
readerPattern: NewReaderPattern(),
}
testReadAt(t, readerAt, 0, 9, 9, io.EOF, []byte{2, 2, 2, 2, 2, 2, 2, 2, 2}, []byte{0, 0, 1, 0, 0, 0, 0, 1, 1})
testReadAt(t, readerAt, 1, 8, 8, io.EOF, []byte{2, 2, 2, 2, 2, 2, 2, 2}, []byte{0, 1, 0, 0, 0, 0, 1, 1})
}
func TestReaderAtSparseFileDoesNotLeak(t *testing.T) {
readerAt := &ChunkReadAt{
chunkViews: ViewFromVisibleIntervals(NewIntervalList[*VisibleInterval](), 0, math.MaxInt64),
fileSize: 3,
readerCache: NewReaderCache(3, &mockChunkCache{}, nil, nil),
readerPattern: NewReaderPattern(),
}
testReadAt(t, readerAt, 0, 3, 3, io.EOF, []byte{2, 2, 2}, []byte{0, 0, 0})
testReadAt(t, readerAt, 1, 2, 2, io.EOF, []byte{2, 2}, []byte{0, 0})
}
// holeChunkCache serves every chunk but one, so that chunk falls through to a
// lookup that fails.
type holeChunkCache struct {
mockChunkCache
missingFileId string
}
func (c *holeChunkCache) ReadChunkAt(data []byte, fileId string, offset uint64) (int, error) {
if fileId == c.missingFileId {
return 0, nil
}
return c.mockChunkCache.ReadChunkAt(data, fileId, offset)
}
func (c *holeChunkCache) GetMaxFilePartSizeInCache() uint64 {
return math.MaxUint64
}
// The parallel reads place their bytes directly in the output buffer, so a
// failing middle chunk leaves a hole with valid data after it. Reporting that
// length would hand the caller bytes it never read.
func TestReaderAtParallelFailureReturnsContiguousPrefix(t *testing.T) {
visibles := NewIntervalList[*VisibleInterval]()
for i, fileId := range []string{"1", "2", "3"} {
addVisibleInterval(visibles, &VisibleInterval{
start: int64(i) * 4,
stop: int64(i)*4 + 4,
fileId: fileId,
chunkSize: 4,
})
}
readerAt := &ChunkReadAt{
ctx: context.Background(),
chunkViews: ViewFromVisibleIntervals(visibles, 0, math.MaxInt64),
fileSize: 12,
readerCache: NewReaderCache(3, &holeChunkCache{missingFileId: "2"}, func(ctx context.Context, fileId string) ([]string, error) {
return nil, errors.New("volume down")
}, nil),
readerPattern: NewReaderPattern(),
prefetchCount: 3,
}
buf := make([]byte, 12)
n, err := readerAt.ReadAt(buf, 0)
require.Error(t, err)
assert.Equal(t, 4, n, "only the bytes before the failed chunk are readable")
assert.Equal(t, []byte{1, 1, 1, 1}, buf[:n])
}
// A read whose caller went away (an S3 client hanging up mid-GET) is canceled,
// not failed, and stays out of the error log.
func TestReaderAtCanceledReadIsNotAnError(t *testing.T) {
visibles := NewIntervalList[*VisibleInterval]()
addVisibleInterval(visibles, &VisibleInterval{start: 0, stop: 8, fileId: "1", chunkSize: 8})
readerAt := &ChunkReadAt{
ctx: context.Background(),
chunkViews: ViewFromVisibleIntervals(visibles, 2, 4),
fileSize: 8,
readerCache: NewReaderCache(3, &holeChunkCache{missingFileId: "1"}, func(ctx context.Context, fileId string) ([]string, error) {
return nil, ctx.Err()
}, nil),
readerPattern: NewReaderPattern(),
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
errorsBefore := glog.Stats.Error.Lines()
_, _, err := readerAt.ReadAtWithTime(ctx, make([]byte, 4), 2)
require.ErrorIs(t, err, context.Canceled)
assert.Equal(t, int64(0), glog.Stats.Error.Lines()-errorsBefore, "ERROR lines logged for a canceled read")
}
// resumeTestReader has n chunks of 10 bytes with a 5-byte hole after each;
// chunk i reads as bytes of value i+1.
func resumeTestReader(n int) (*ChunkReadAt, []byte) {
visibles := NewIntervalList[*VisibleInterval]()
want := make([]byte, n*15)
for i := 0; i < n; i++ {
start := int64(i * 15)
addVisibleInterval(visibles, &VisibleInterval{start: start, stop: start + 10, fileId: strconv.Itoa(i + 1), chunkSize: 10})
for j := start; j < start+10; j++ {
want[j] = byte(i + 1)
}
}
return &ChunkReadAt{
chunkViews: ViewFromVisibleIntervals(visibles, 0, math.MaxInt64),
fileSize: int64(len(want)),
readerCache: NewReaderCache(3, &mockChunkCache{}, nil, nil),
readerPattern: NewReaderPattern(),
}, want
}
// A sequential read starts where the previous one ended instead of walking
// the chunk views from the front, and holes and chunk edges still read right.
func TestReaderAtResumesSequentialReads(t *testing.T) {
readerAt, want := resumeTestReader(100)
for off := 0; off < len(want); off += 7 {
size := int(min(7, int64(len(want)-off)))
buf := make([]byte, size)
n, _, err := readerAt.ReadAtWithTime(context.Background(), buf, int64(off))
require.Equal(t, size, n, "read at %d", off)
if err != nil {
require.ErrorIs(t, err, io.EOF)
}
require.Equal(t, want[off:off+size], buf, "read at %d", off)
r := readerAt.resumeAt.Load()
if off+size < 15 {
require.Nil(t, r, "a read in the first chunk keeps no resume point")
continue
}
require.NotNil(t, r)
require.Equal(t, readerAt.chunkViews.changes, readerAt.resumeChanges.Load())
require.LessOrEqual(t, r.Value.ViewOffset, int64(off+size))
require.GreaterOrEqual(t, r.Value.ViewOffset+int64(r.Value.ViewSize)+5, int64(off+size), "resume point lags behind the read at %d", off)
}
}
// A read before the resume point walks from the front.
func TestReaderAtReadsBackwardAfterResume(t *testing.T) {
readerAt, want := resumeTestReader(10)
testReadAt(t, readerAt, 130, 10, 10, nil, nil, want[130:140])
testReadAt(t, readerAt, 3, 20, 20, nil, nil, want[3:23])
testReadAt(t, readerAt, 0, 150, 150, io.EOF, nil, want)
}
// The mount merges new chunks into a live reader's views; a resume point
// kept before that must not be used, or the read returns replaced bytes.
func TestReaderAtDropsResumeWhenViewsChange(t *testing.T) {
readerAt, want := resumeTestReader(10)
testReadAt(t, readerAt, 75, 2, 2, nil, nil, want[75:77])
MergeIntoChunkViews(readerAt.chunkViews, 70, 90, &filer_pb.FileChunk{FileId: "200", Offset: 70, Size: 20})
expected := append([]byte{}, want[77:100]...)
for i := 77; i < 90; i++ {
expected[i-77] = 200
}
testReadAt(t, readerAt, 77, 23, 23, nil, nil, expected)
}