mq: read flushed windows named with an offset suffix

Flushed windows are now named by start second and first offset, which the
readers did not expect. The disk reader dropped every file whose name
sorted after the stop second, which a window starting in that very second
now does, and log compaction parsed the whole name as a time and skipped
the new files. Both now look only at the start-second part, so files with
either naming are read. The partition fence that sorts first in a listing
is skipped by the disk reader and the query engine's live-log scans, and
topic truncation keeps it.
This commit is contained in:
Chris Lu committed 2026-11-30 18:54:52 -08:00
1 parent e808afac56
commit da15742525
7 files changed
+181 -9

No files matched your search

+1 -1
View File
@@ -164,7 +164,7 @@ func readAllLogFiles(filerClient filer_pb.FilerClient, partitionDir string, time
if entry.Attributes.Crtime > time.Now().Unix()-int64(timeAgo/time.Second) {
return nil
}
logTime, err := time.Parse(topic.TIME_FORMAT, entry.Name)
logTime, err := topic.ParseLogFileTime(entry.Name)
if err != nil {
// glog.Warningf("parse log time %s: %v", entry.Name, err)
return nil
+2 -2
View File
@@ -185,7 +185,7 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
glog.V(2).Infof("listing directory %s for offset %d startFileName=%q", partitionDir, startOffset, startFileName)
return filer_pb.SeaweedList(context.Background(), client, partitionDir, "", func(entry *filer_pb.Entry, isLast bool) error {
if entry.IsDirectory {
if entry.IsDirectory || entry.Name == topic.PartitionFenceName {
return nil
}
if strings.HasSuffix(entry.Name, ".parquet") {
@@ -194,7 +194,7 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
if strings.HasSuffix(entry.Name, ".offset") {
return nil
}
if stopTsNs != 0 && entry.Name > stopTime.UTC().Format(topic.TIME_FORMAT) {
if stopTsNs != 0 && topic.LogFileTimePrefix(entry.Name) > stopTime.UTC().Format(topic.TIME_FORMAT) {
return nil
}
+134
View File
@@ -0,0 +1,134 @@
package logstore
import (
"context"
"net"
"net/http"
"net/http/httptest"
"sort"
"strings"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/protobuf/proto"
)
type listingFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
entries []*filer_pb.Entry
volumeUrl string
}
func (f *listingFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream grpc.ServerStreamingServer[filer_pb.ListEntriesResponse]) error {
for _, entry := range f.entries {
if entry.Name < req.StartFromFileName || (!req.InclusiveStartFrom && entry.Name == req.StartFromFileName) {
continue
}
if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: entry}); err != nil {
return err
}
}
return nil
}
func (f *listingFiler) LookupVolume(_ context.Context, req *filer_pb.LookupVolumeRequest) (*filer_pb.LookupVolumeResponse, error) {
resp := &filer_pb.LookupVolumeResponse{LocationsMap: map[string]*filer_pb.Locations{}}
for _, vid := range req.VolumeIds {
resp.LocationsMap[vid] = &filer_pb.Locations{Locations: []*filer_pb.Location{{Url: f.volumeUrl}}}
}
return resp, nil
}
type listingFilerClient struct {
address pb.ServerAddress
}
func (c listingFilerClient) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error {
return pb.WithGrpcFilerClient(streamingMode, 0, c.address, grpc.WithTransportCredentials(insecure.NewCredentials()), security.FilerAdminToken, fn)
}
func (c listingFilerClient) AdjustedUrl(location *filer_pb.Location) string { return location.Url }
func (c listingFilerClient) GetDataCenter() string { return "" }
func logChunk(t *testing.T, tsNs ...int64) []byte {
var buf []byte
for _, ts := range tsNs {
data, err := proto.Marshal(&filer_pb.LogEntry{TsNs: ts, Key: []byte("k")})
if err != nil {
t.Fatal(err)
}
size := make([]byte, 4)
util.Uint32toBytes(size, uint32(len(data)))
buf = append(append(buf, size...), data...)
}
return buf
}
// A window flushed in the stop second is named after that second plus its offset,
// and must not be dropped as if it started later; the fence is never read.
func TestReadFromDiskKeepsAFileStartingInTheStopSecond(t *testing.T) {
second := time.Date(2026, 11, 30, 10, 0, 5, 0, time.UTC)
chunks := map[string][]byte{
"/3,01": logChunk(t, second.Add(-500*time.Millisecond).UnixNano()),
"/3,02": logChunk(t, second.Add(100*time.Millisecond).UnixNano()),
"/3,03": logChunk(t, second.Add(1100*time.Millisecond).UnixNano()),
}
var fetchedLock sync.Mutex
fetched := map[string]int{}
volume := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fetchedLock.Lock()
fetched[r.URL.Path]++
fetchedLock.Unlock()
w.Write(chunks[r.URL.Path])
}))
defer volume.Close()
file := func(name, fileId string) *filer_pb.Entry {
return &filer_pb.Entry{Name: name, Attributes: &filer_pb.FuseAttributes{},
Chunks: []*filer_pb.FileChunk{{FileId: fileId, Size: uint64(len(chunks["/"+fileId]))}}}
}
filer := &listingFiler{volumeUrl: strings.TrimPrefix(volume.URL, "http://"), entries: []*filer_pb.Entry{
{Name: topic.PartitionFenceName, Attributes: &filer_pb.FuseAttributes{}},
file("2026-11-30-10-00-04", "3,01"),
file(topic.LogFileName(second, 5), "3,02"),
file(topic.LogFileName(second.Add(time.Second), 9), "3,03"),
}}
sort.Slice(filer.entries, func(i, j int) bool { return filer.entries[i].Name < filer.entries[j].Name })
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
server := grpc.NewServer()
filer_pb.RegisterSeaweedFilerServer(server, filer)
go server.Serve(listener)
defer server.Stop()
client := listingFilerClient{address: pb.NewServerAddressWithGrpcPort(listener.Addr().String(), listener.Addr().(*net.TCPAddr).Port)}
read := GenLogOnDiskReadFunc(client, topic.NewTopic("test", "t"), topic.Partition{RingSize: 2520, RangeStop: 2520, UnixTimeNs: 1})
var got []int64
_, _, err = read(log_buffer.NewMessagePosition(second.Add(-10*time.Second).UnixNano(), -2), second.Add(500*time.Millisecond).UnixNano(), func(logEntry *filer_pb.LogEntry) (bool, error) {
got = append(got, logEntry.TsNs)
return false, nil
})
if err != nil {
t.Fatal(err)
}
want := []int64{second.Add(-500 * time.Millisecond).UnixNano(), second.Add(100 * time.Millisecond).UnixNano()}
if len(got) != len(want) || got[0] != want[0] || got[1] != want[1] {
t.Errorf("read %v, want %v", got, want)
}
fetchedLock.Lock()
defer fetchedLock.Unlock()
if fetched["/3,03"] != 0 {
t.Error("read a file starting after the stop second")
}
}
+19
View File
@@ -2,6 +2,8 @@ package topic
import (
"fmt"
"strconv"
"strings"
"time"
)
@@ -10,3 +12,20 @@ import (
func LogFileName(startTime time.Time, minOffset int64) string {
return fmt.Sprintf("%s.%020d", startTime.UTC().Format(TIME_FORMAT), max(minOffset, 0))
}
// LogFileTimePrefix is the start-second part of a log file name, which may carry an offset suffix.
func LogFileTimePrefix(name string) string {
return name[:min(len(name), len(TIME_FORMAT))]
}
// ParseLogFileTime reads the start second of a log file named with or without an offset suffix.
func ParseLogFileTime(name string) (time.Time, error) {
prefix := LogFileTimePrefix(name)
if suffix := name[len(prefix):]; suffix != "" {
digits, dotted := strings.CutPrefix(suffix, ".")
if _, err := strconv.ParseUint(digits, 10, 64); !dotted || err != nil {
return time.Time{}, fmt.Errorf("not a log file name: %q", name)
}
}
return time.Parse(TIME_FORMAT, prefix)
}
+18
View File
@@ -30,3 +30,21 @@ func TestLogFileNamesSortByTimeThenOffset(t *testing.T) {
}
}
}
func TestParseLogFileTimeAcceptsBothNamings(t *testing.T) {
second := time.Date(2026, 11, 30, 10, 0, 5, 0, time.UTC)
for _, name := range []string{"2026-11-30-10-00-05", LogFileName(second, 0), LogFileName(second, 123456)} {
got, err := ParseLogFileTime(name)
if err != nil || !got.Equal(second) {
t.Errorf("ParseLogFileTime(%q) = %v, %v", name, got, err)
}
if prefix := LogFileTimePrefix(name); prefix != "2026-11-30-10-00-05" {
t.Errorf("LogFileTimePrefix(%q) = %q", name, prefix)
}
}
for _, name := range []string{PartitionFenceName, "checkpoint.offset", "2026-11-30-10-00-05.parquet", "2026-11-30-10-00-05.", "2026-11-30-10-00-05x1", "2026-11-30-10-00"} {
if _, err := ParseLogFileTime(name); err == nil {
t.Errorf("ParseLogFileTime(%q) parsed a non-log file", name)
}
}
}
+4 -4
View File
@@ -1385,7 +1385,7 @@ func (e *SQLEngine) collectLiveLogFileNames(filerClient filer_pb.FilerClient, pa
if entry != nil && !entry.IsDirectory {
// Check if this is a log file (not a parquet file)
fileName := entry.Name
if !strings.HasSuffix(fileName, ".parquet") && !strings.HasSuffix(fileName, ".metadata") {
if !strings.HasSuffix(fileName, ".parquet") && !strings.HasSuffix(fileName, ".metadata") && fileName != topic.PartitionFenceName {
liveLogFiles = append(liveLogFiles, fileName)
}
}
@@ -3881,7 +3881,7 @@ func (e *SQLEngine) computeLiveLogMinMax(partitionPath string, columnName string
// Process each live log file
err = filer_pb.ReadDirAllEntries(context.Background(), filerClient, util.FullPath(partitionPath), "", func(entry *filer_pb.Entry, isLast bool) error {
// Skip parquet files and directories
if entry.IsDirectory || strings.HasSuffix(entry.Name, ".parquet") {
if entry.IsDirectory || strings.HasSuffix(entry.Name, ".parquet") || entry.Name == topic.PartitionFenceName {
return nil
}
// Skip files that have been converted to parquet (deduplication)
@@ -4164,8 +4164,8 @@ func (e *SQLEngine) countLiveLogRowsExcludingParquetSources(ctx context.Context,
totalRows := int64(0)
err = filer_pb.ReadDirAllEntries(context.Background(), filerClient, util.FullPath(partitionPath), "", func(entry *filer_pb.Entry, isLast bool) error {
if entry.IsDirectory || strings.HasSuffix(entry.Name, ".parquet") {
return nil // Skip directories and parquet files
if entry.IsDirectory || strings.HasSuffix(entry.Name, ".parquet") || entry.Name == topic.PartitionFenceName {
return nil // Skip directories, parquet files, and the partition fence
}
// Skip files that have been converted to parquet
+3 -2
View File
@@ -113,11 +113,12 @@ func (c *commandMqTopicTruncate) clearPartitionData(commandEnv *CommandEnv, part
fileName := entry.Name
// Preserve configuration files
// Preserve configuration files and the partition fence
if strings.HasSuffix(fileName, ".conf") ||
strings.HasSuffix(fileName, ".config") ||
fileName == "topic.conf" ||
fileName == "partition.conf" {
fileName == "partition.conf" ||
fileName == topic.PartitionFenceName {
fmt.Fprintf(writer, " Preserving config file: %s\n", fileName)
return nil
}