From 29c6325bb9328cb442822c7d2396631d2bf0b3c6 Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Mon, 30 Nov 2026 23:56:35 -0800 Subject: [PATCH] mq logstore: start an offset read at the indexed file holding the offset A disk read by offset listed the whole partition directory on every call and filtered the files by their offset ranges, so a lagging consumer paid for the partition's entire history on each read. The reader's sparse index of log file names now also keeps each mark's first offset, and an offset read lists from the last mark starting at or before its offset; offsets grow with names, so no earlier file can hold it. The index is extended by every listing past the last name it has seen, so after the first read a call lists at most one stride of files before its own plus the files after it. When no mark with an offset range is at or before the offset, as with files that record none, the read still lists from the first file. Co-Authored-By: Claude Opus 5.5 --- weed/mq/logstore/read_log_from_disk.go | 48 ++++--- weed/mq/logstore/read_log_from_disk_test.go | 139 +++++++++++++++++++- 2 files changed, 167 insertions(+), 20 deletions(-) diff --git a/weed/mq/logstore/read_log_from_disk.go b/weed/mq/logstore/read_log_from_disk.go index 9a2d7bb201..ed6fa3a2e2 100644 --- a/weed/mq/logstore/read_log_from_disk.go +++ b/weed/mq/logstore/read_log_from_disk.go @@ -28,26 +28,33 @@ const logFileIndexStride = 64 // read can list from near its position instead of from the first file. type logFileIndex struct { sync.Mutex - marks []string + marks []logFileMark lastName string unmarked int } -// add records log file names in listing order, as listed from a mark or from the start. -func (x *logFileIndex) add(names []string) { +type logFileMark struct { + name string + minOffset int64 + hasOffsets bool +} + +// add records log files in listing order, as listed from a mark or from the start. +func (x *logFileIndex) add(entries []*filer_pb.Entry) { x.Lock() defer x.Unlock() - for _, name := range names { - if name <= x.lastName { + for _, entry := range entries { + if entry.Name <= x.lastName { continue } if len(x.marks) == 0 || x.unmarked >= logFileIndexStride-1 { - x.marks = append(x.marks, name) + minOffset, _, hasOffsets := logFileOffsets(entry) + x.marks = append(x.marks, logFileMark{name: entry.Name, minOffset: minOffset, hasOffsets: hasOffsets}) x.unmarked = 0 } else { x.unmarked++ } - x.lastName = name + x.lastName = entry.Name } } @@ -55,8 +62,21 @@ func (x *logFileIndex) add(names []string) { func (x *logFileIndex) markBefore(name string) string { x.Lock() defer x.Unlock() - if i := sort.SearchStrings(x.marks, name); i > 0 { - return x.marks[i-1] + if i := sort.Search(len(x.marks), func(i int) bool { return x.marks[i].name >= name }); i > 0 { + return x.marks[i-1].name + } + return "" +} + +// markAtOffset is the last marked file starting at or before offset, or "" for the start. +// Offsets grow with names, so no earlier file can hold offset, including one with no offset range. +func (x *logFileIndex) markAtOffset(offset int64) string { + x.Lock() + defer x.Unlock() + for i := len(x.marks) - 1; i >= 0; i-- { + if m := x.marks[i]; m.hasOffsets && m.minOffset <= offset { + return m.name + } } return "" } @@ -222,9 +242,7 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top var startOffset int64 if isOffsetBased { startOffset = startPosition.Offset - // CRITICAL FIX: For offset-based reads, ignore startFileName (which is based on Time) - // and list all files from the beginning to find the right offset - startFileName = "" + startFileName = index.markAtOffset(startOffset) glog.V(1).Infof("disk read start: topic=%s partition=%s startOffset=%d", t.Name, p, startOffset) } @@ -233,7 +251,7 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top // Then use binary search to find the right file, and skip files that don't contain the offset var candidateFiles []*filer_pb.Entry var foundStartFile bool - var listedNames []string + var listed []*filer_pb.Entry var beforeResume *filer_pb.Entry err = filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { @@ -250,7 +268,7 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top if strings.HasSuffix(entry.Name, ".offset") { return nil } - listedNames = append(listedNames, entry.Name) + listed = append(listed, entry) if stopTsNs != 0 && topic.LogFileTimePrefix(entry.Name) > stopTime.UTC().Format(topic.TIME_FORMAT) { return nil } @@ -295,7 +313,7 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top if beforeResume != nil { candidateFiles = append(candidateFiles, beforeResume) } - index.add(listedNames) + index.add(listed) glog.V(2).Infof("found %d candidate files for topic=%s partition=%s offset=%d", len(candidateFiles), t.Name, p, startOffset) diff --git a/weed/mq/logstore/read_log_from_disk_test.go b/weed/mq/logstore/read_log_from_disk_test.go index 7ea586abfb..a357067684 100644 --- a/weed/mq/logstore/read_log_from_disk_test.go +++ b/weed/mq/logstore/read_log_from_disk_test.go @@ -2,6 +2,8 @@ package logstore import ( "context" + "encoding/binary" + "fmt" "net" "net/http" "net/http/httptest" @@ -12,6 +14,7 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweedfs/weed/mq" "github.com/seaweedfs/seaweedfs/weed/mq/topic" "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" @@ -25,15 +28,38 @@ import ( type listingFiler struct { filer_pb.UnimplementedSeaweedFilerServer + sync.Mutex entries []*filer_pb.Entry volumeUrl string + listed int +} + +func (f *listingFiler) add(entries ...*filer_pb.Entry) { + f.Lock() + defer f.Unlock() + f.entries = append(f.entries, entries...) + sort.Slice(f.entries, func(i, j int) bool { return f.entries[i].Name < f.entries[j].Name }) +} + +func (f *listingFiler) takeListed() int { + f.Lock() + defer f.Unlock() + listed := f.listed + f.listed = 0 + return listed } func (f *listingFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream grpc.ServerStreamingServer[filer_pb.ListEntriesResponse]) error { - for _, entry := range f.entries { + f.Lock() + entries := slices.Clone(f.entries) + f.Unlock() + for _, entry := range entries { if entry.Name < req.StartFromFileName || (!req.InclusiveStartFrom && entry.Name == req.StartFromFileName) { continue } + f.Lock() + f.listed++ + f.Unlock() if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: entry}); err != nil { return err } @@ -60,9 +86,17 @@ func (c listingFilerClient) AdjustedUrl(location *filer_pb.Location) string { re func (c listingFilerClient) GetDataCenter() string { return "" } func logChunk(t *testing.T, tsNs ...int64) []byte { - var buf []byte + var entries []*filer_pb.LogEntry for _, ts := range tsNs { - data, err := proto.Marshal(&filer_pb.LogEntry{TsNs: ts, Key: []byte("k")}) + entries = append(entries, &filer_pb.LogEntry{TsNs: ts, Key: []byte("k")}) + } + return encodeLogEntries(t, entries...) +} + +func encodeLogEntries(t *testing.T, entries ...*filer_pb.LogEntry) []byte { + var buf []byte + for _, entry := range entries { + data, err := proto.Marshal(entry) if err != nil { t.Fatal(err) } @@ -104,8 +138,8 @@ func (c *chunkServer) file(name, fileId string) *filer_pb.Entry { } func serveFiler(t *testing.T, volume *chunkServer, entries ...*filer_pb.Entry) (*listingFiler, listingFilerClient) { - filer := &listingFiler{volumeUrl: strings.TrimPrefix(volume.URL, "http://"), entries: entries} - sort.Slice(filer.entries, func(i, j int) bool { return filer.entries[i].Name < filer.entries[j].Name }) + filer := &listingFiler{volumeUrl: strings.TrimPrefix(volume.URL, "http://")} + filer.add(entries...) listener, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) @@ -197,3 +231,98 @@ func TestReadFromDiskResumesInsideAnEarlierFile(t *testing.T) { }) } } + +// offsetLogFiles makes count log files of two offsets each, from file first on; +// legacy files are named by their second alone and record no offset range. +func offsetLogFiles(t *testing.T, volume *chunkServer, first, count int, legacy bool) (files []*filer_pb.Entry) { + base := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC) + for i := first; i < first+count; i++ { + minOffset := int64(2 * i) + start := base.Add(time.Duration(i) * time.Second) + fileId := fmt.Sprintf("3,%04x", i) + volume.Lock() + volume.chunks["/"+fileId] = encodeLogEntries(t, + &filer_pb.LogEntry{TsNs: start.UnixNano(), Offset: minOffset}, + &filer_pb.LogEntry{TsNs: start.Add(time.Millisecond).UnixNano(), Offset: minOffset + 1}) + volume.Unlock() + if legacy { + files = append(files, volume.file(start.Format(topic.TIME_FORMAT), fileId)) + continue + } + file := volume.file(topic.LogFileName(start, minOffset), fileId) + file.Extended = map[string][]byte{ + mq.ExtendedAttrOffsetMin: binary.BigEndian.AppendUint64(nil, uint64(minOffset)), + mq.ExtendedAttrOffsetMax: binary.BigEndian.AppendUint64(nil, uint64(minOffset+1)), + } + files = append(files, file) + } + return files +} + +func readOffsets(t *testing.T, read log_buffer.LogReadFromDiskFuncType, startOffset int64) (got []int64) { + t.Helper() + if _, _, err := read(log_buffer.NewMessagePositionFromOffset(startOffset), 0, func(logEntry *filer_pb.LogEntry) (bool, error) { + got = append(got, logEntry.Offset) + return false, nil + }); err != nil { + t.Fatal(err) + } + return got +} + +func offsetsFrom(from, to int64) (offsets []int64) { + for o := from; o < to; o++ { + offsets = append(offsets, o) + } + return offsets +} + +// After its first read lists the partition, a reader starts later offset reads +// near the offset instead of listing every file again. +func TestReadFromDiskByOffsetListsFromNearTheOffset(t *testing.T) { + const files = 10 * logFileIndexStride + volume := serveChunks(t, map[string][]byte{}) + filer, client := serveFiler(t, volume, offsetLogFiles(t, volume, 0, files, false)...) + filer.add(&filer_pb.Entry{Name: topic.PartitionFenceName, Attributes: &filer_pb.FuseAttributes{}}) + read := testPartitionReader(client) + + if got := readOffsets(t, read, 2*files-4); !slices.Equal(got, offsetsFrom(2*files-4, 2*files)) { + t.Fatalf("cold read %v", got) + } + filer.takeListed() + + if got := readOffsets(t, read, 2*files-3); !slices.Equal(got, offsetsFrom(2*files-3, 2*files)) { + t.Errorf("read %v", got) + } + if listed := filer.takeListed(); listed > 2*logFileIndexStride { + t.Errorf("listed %d entries to read the last file of %d", listed, files) + } + + filer.add(offsetLogFiles(t, volume, files, 3, false)...) + if got := readOffsets(t, read, 2*files+1); !slices.Equal(got, offsetsFrom(2*files+1, 2*files+6)) { + t.Errorf("read after more flushes %v", got) + } + if listed := filer.takeListed(); listed > 2*logFileIndexStride { + t.Errorf("listed %d entries to read files flushed after the index was built", listed) + } + + if got := readOffsets(t, read, 5); !slices.Equal(got, offsetsFrom(5, 2*files+6)) { + t.Errorf("read from an early offset returned %d offsets", len(got)) + } +} + +// Files that record no offset range are still read by offset. +func TestReadFromDiskByOffsetReadsLegacyFiles(t *testing.T) { + volume := serveChunks(t, map[string][]byte{}) + _, client := serveFiler(t, volume, append(offsetLogFiles(t, volume, 0, 3, true), offsetLogFiles(t, volume, 3, 2*logFileIndexStride, false)...)...) + read := testPartitionReader(client) + end := int64(2 * (3 + 2*logFileIndexStride)) + for range 2 { + if got := readOffsets(t, read, 3); !slices.Equal(got, offsetsFrom(3, end)) { + t.Errorf("read %d offsets from 3, want %d", len(got), end-3) + } + } + if got := readOffsets(t, read, end-1); !slices.Equal(got, []int64{end - 1}) { + t.Errorf("read %v from the last offset", got) + } +}