From 25e0c6080a8795124f5faea257a39f86319c5f3b Mon Sep 17 00:00:00 2001 From: "D.Maier" <73213965+denMaier@users.noreply.github.com> Date: Fri, 4 Dec 2026 20:22:53 +0100 Subject: [PATCH] filer: resume chunk reads where the last one ended (#13393) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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 --------- Co-authored-by: Denis Maier Co-authored-by: Chris Lu Co-authored-by: Claude Opus 5.5 --- weed/filer/interval_list.go | 5 ++ weed/filer/reader_at.go | 27 ++++++- weed/filer/reader_at_benchmark_test.go | 104 +++++++++++++++++++++++++ weed/filer/reader_at_test.go | 67 ++++++++++++++++ 4 files changed, 201 insertions(+), 2 deletions(-) create mode 100644 weed/filer/reader_at_benchmark_test.go diff --git a/weed/filer/interval_list.go b/weed/filer/interval_list.go index 27720231d3..02f7f0b040 100644 --- a/weed/filer/interval_list.go +++ b/weed/filer/interval_list.go @@ -28,6 +28,8 @@ type IntervalList[T IntervalValue] struct { head *Interval[T] tail *Interval[T] Lock sync.RWMutex + // changes counts edits, so a reader can tell a kept interval may be gone + changes uint64 } func NewIntervalList[T IntervalValue]() *IntervalList[T] { @@ -51,6 +53,7 @@ func (list *IntervalList[T]) Front() (interval *Interval[T]) { func (list *IntervalList[T]) AppendInterval(interval *Interval[T]) { list.Lock.Lock() defer list.Lock.Unlock() + list.changes++ if list.head.Next == nil { list.head.Next = interval @@ -75,6 +78,7 @@ func (list *IntervalList[T]) Overlay(startOffset, stopOffset, tsNs int64, value list.Lock.Lock() defer list.Lock.Unlock() + list.changes++ list.overlayInterval(interval) } @@ -89,6 +93,7 @@ func (list *IntervalList[T]) InsertInterval(startOffset, stopOffset, tsNs int64, list.Lock.Lock() defer list.Lock.Unlock() + list.changes++ value.SetStartStop(startOffset, stopOffset) list.insertInterval(interval) diff --git a/weed/filer/reader_at.go b/weed/filer/reader_at.go index 033cbfe1b1..bf72fc7638 100644 --- a/weed/filer/reader_at.go +++ b/weed/filer/reader_at.go @@ -6,6 +6,7 @@ import ( "io" "math/rand" "sync" + "sync/atomic" "time" "golang.org/x/sync/errgroup" @@ -40,6 +41,12 @@ type ChunkReadAt struct { streamEnd int64 // file offset that read stopped at prefetchCount int // Number of chunks to prefetch ahead during sequential reads ctx context.Context // Context used for cancellation during chunk read operations + // resumeAt is the chunk view the last read ended in, valid while + // chunkViews.changes equals resumeChanges. Both are accessed under + // chunkViews.Lock.RLock; resumeAt is stored before resumeChanges and + // loaded after it. + resumeAt atomic.Pointer[Interval[*ChunkView]] + resumeChanges atomic.Uint64 } var _ = io.ReaderAt(&ChunkReadAt{}) @@ -251,14 +258,25 @@ func (c *ChunkReadAt) doReadAt(ctx context.Context, p []byte, offset int64) (n i var gaps []struct{ start, length int64 } // gaps that need zero-filling startOffset, remaining := offset, int64(len(p)) - var lastChunk *Interval[*ChunkView] + var lastChunk, resume *Interval[*ChunkView] - for x := c.chunkViews.Front(); x != nil; x = x.Next { + front := c.chunkViews.Front() + first := front + changes := c.chunkViews.changes + keptChanges := c.resumeChanges.Load() + kept := c.resumeAt.Load() + if kept != nil && keptChanges == changes && kept.Value.ViewOffset <= offset { + first = kept + } + for x := first; x != nil; x = x.Next { chunk := x.Value if remaining <= 0 { break } lastChunk = x + if chunk.ViewOffset <= offset+int64(len(p)) { + resume = x + } // Handle gap before this chunk if startOffset < chunk.ViewOffset { @@ -285,6 +303,11 @@ func (c *ChunkReadAt) doReadAt(ctx context.Context, p []byte, offset int64) (n i startOffset, remaining = chunkStop, remaining-(chunkStop-chunkStart) } + // a read that ends in the first view has nothing to skip next time + if resume != nil && resume != front && (kept != resume || keptChanges != changes) { + c.resumeAt.Store(resume) + c.resumeChanges.Store(changes) + } // Zero-fill gaps for _, gap := range gaps { diff --git a/weed/filer/reader_at_benchmark_test.go b/weed/filer/reader_at_benchmark_test.go new file mode 100644 index 0000000000..b16d40f6c1 --- /dev/null +++ b/weed/filer/reader_at_benchmark_test.go @@ -0,0 +1,104 @@ +package filer + +import ( + "context" + "fmt" + "io" + "math" + "math/rand" + "strconv" + "testing" +) + +// benchReader returns a reader over a file of n chunks of chunkSize bytes, +// served by mockChunkCache, so the benchmarks measure ChunkReadAt itself. +func benchReader(n int, chunkSize int64) func() *ChunkReadAt { + visibles := NewIntervalList[*VisibleInterval]() + for i := 0; i < n; i++ { + start := int64(i) * chunkSize + addVisibleInterval(visibles, &VisibleInterval{start: start, stop: start + chunkSize, fileId: strconv.Itoa(i + 1), chunkSize: uint64(chunkSize)}) + } + views := ViewFromVisibleIntervals(visibles, 0, math.MaxInt64) + readerCache := NewReaderCache(3, &mockChunkCache{}, nil, nil) + return func() *ChunkReadAt { + return &ChunkReadAt{ + chunkViews: views, + fileSize: int64(n) * chunkSize, + readerCache: readerCache, + readerPattern: NewReaderPattern(), + ctx: context.Background(), + } + } +} + +func benchReadAt(b *testing.B, r *ChunkReadAt, buf []byte, offset int64) { + if n, err := r.ReadAt(buf, offset); n != len(buf) || (err != nil && err != io.EOF) { + b.Fatalf("read at %d: %d bytes, %v", offset, n, err) + } +} + +// BenchmarkReaderAtSequential reads a whole file front to back in 32 KiB +// reads, as S3 and WebDAV GETs do, with a new reader per file. +func BenchmarkReaderAtSequential(b *testing.B) { + const chunkSize, readSize = 64 * 1024, 32 * 1024 + for _, chunks := range []int{1, 100, 1000, 10000, 100000} { + b.Run(fmt.Sprintf("chunks=%d", chunks), func(b *testing.B) { + newReader := benchReader(chunks, chunkSize) + fileSize := int64(chunks) * chunkSize + buf := make([]byte, readSize) + b.SetBytes(fileSize) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + r := newReader() + for off := int64(0); off < fileSize; off += readSize { + benchReadAt(b, r, buf, off) + } + r.ReleaseStream() + } + }) + } +} + +// BenchmarkReaderAtSmallFile reads a one-chunk file with a new reader, the +// way a GET of a small object does. +func BenchmarkReaderAtSmallFile(b *testing.B) { + for _, size := range []int64{4 * 1024, 64 * 1024, 1024 * 1024} { + b.Run(fmt.Sprintf("size=%dKiB", size/1024), func(b *testing.B) { + newReader := benchReader(1, size) + readSize := min(size, 32*1024) + buf := make([]byte, readSize) + b.SetBytes(size) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + r := newReader() + for off := int64(0); off < size; off += readSize { + benchReadAt(b, r, buf, off) + } + r.ReleaseStream() + } + }) + } +} + +// BenchmarkReaderAtRandom makes 32 KiB reads at random offsets on one reader, +// where a kept position helps only when the next read is further on. +func BenchmarkReaderAtRandom(b *testing.B) { + const chunkSize, readSize = 64 * 1024, 32 * 1024 + for _, chunks := range []int{100, 10000} { + b.Run(fmt.Sprintf("chunks=%d", chunks), func(b *testing.B) { + r := benchReader(chunks, chunkSize)() + defer r.ReleaseStream() + reads := int64(chunks) * chunkSize / readSize + rnd := rand.New(rand.NewSource(1)) + buf := make([]byte, readSize) + b.SetBytes(readSize) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + benchReadAt(b, r, buf, rnd.Int63n(reads)*readSize) + } + }) + } +} diff --git a/weed/filer/reader_at_test.go b/weed/filer/reader_at_test.go index a88eff710b..abe48b8f7e 100644 --- a/weed/filer/reader_at_test.go +++ b/weed/filer/reader_at_test.go @@ -13,6 +13,7 @@ import ( "github.com/stretchr/testify/require" "github.com/seaweedfs/seaweedfs/weed/glog" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" ) type mockChunkCache struct { @@ -282,3 +283,69 @@ func TestReaderAtCanceledReadIsNotAnError(t *testing.T) { 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) +}