Compare commits

...
Author SHA1 Message Date
Chris LuandClaude Opus 5.5 e2e8af7890 mq logstore: read older parquet rows in a merged timestamp read
A merged timestamp read took the log files first and started parquet at the
latest time they delivered, so parquet rows older than the newest log message
were never read: a read from the beginning of a partition whose older offsets
were compacted and their logs removed returned only the log files' messages.

Both sources are now read from the read's start, parquet first and only below
the earliest offset the listed log files hold, as an offset read does, so each
message comes once and from its log file where one remains. A read stopped in
parquet resumes below the first message of every log file, a read stopped in
the log files resumes where they say, and a full read returns the later of the
two positions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:06:32 -08:00
Chris LuandClaude Opus 5.5 2b30b7112b mq logstore: resume a stopped offset read below every unread log file
A stopped offset read of the log files returned the offset after the last one
it delivered. Files are read by their first offset, but in a partition written
under clock skew their ranges can overlap, so after delivering 0, 1 and 4 from
one file the resume at 5 skipped 2 and 3 in the next. The next offset is now
kept at or below the first offset of every file the read did not reach, as for
parquet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:05:24 -08:00
Chris LuandClaude Opus 5.5 f88f59527f mq broker: bound older files' messages by their write time when seeding stamps
A loaded partition seeds its buffer's last timestamp from the newest ts_max its
files record, but files flushed before ts_max was recorded contributed nothing,
so a slow-clock leader could still stamp new messages below what such a file
holds. A data file recording no ts_max now bounds its messages by the end of the
second its mtime names, since it was written after they were stamped. A message
whose time a client set later than the file's write is still not bounded; the
doc comment says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 12:51:07 -08:00
Chris LuandClaude Opus 5.5 96fbacae68 mq logstore: compact a group's source logs in offset order
Compaction wrote a group's rows in the order its source logs are listed, by
name, and a window flushed under clock skew sorts before windows holding lower
offsets, so a compacted file could hold offsets 1000, 1001 and then 0 to 999.
Sources are now written in the order of their recorded offset ranges, and a log
file's own entries are already in offset order, so new files hold their rows in
offset order. The file keeps its name and source list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 12:48:11 -08:00
Chris LuandClaude Opus 5.5 fa2f554e8c mq logstore: deliver a parquet file's rows in offset order for an offset read
Compaction writes rows in the order it reads its source logs, which need not be
offset order, so a file could hold offsets 1000, 1001 and then 0 to 999. An
offset read that stopped after 1001 returned 1002 as the next offset and the
resume skipped 0 to 999. An offset read now delivers a file's eligible rows
sorted by offset, and a stopped or failed read resumes at the offset after its
last delivered row, kept at or below the first offset of every file it did not
finish.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 12:47:12 -08:00
Chris LuandClaude Opus 5.5 b2da504615 mq logstore: deliver a parquet file's rows in time order
Rows of windows flushed across a reload are not in time order within a
compacted file, so a timestamp read that stopped after the row at 9s returned
9s and the resume skipped the 7s row it had not reached. A timestamp read now
gathers a file's eligible rows and delivers them sorted by time, and a stopped
or failed read resumes no later than its last delivered row and below the first
row of every file it did not finish, so it never skips a row. The rows are
buffered past the next ReadRows call, so their key and value bytes are copied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 12:46:23 -08:00
Chris LuandClaude Opus 5.5 dc6f80c8c6 mq logstore: resume a stopped log read below every unread message
A timestamp read that the callback stopped returned the latest time it had
delivered. Files sort by name, and a later-named file can hold earlier
messages, so after delivering 100 from one file and 50 from the next, a resume
from 100 skipped the next file's 60. A stopped read now resumes from the last
time it delivered, kept below the first message of every file it did not reach,
and from the read's own start when one of those records no first message.
Messages only grow in time within a file, so this skips nothing and at most
redelivers. A read that ran to the end still returns the latest time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 12:45:13 -08:00
Chris Lu bf7927f756 mq logstore: fail a read that needs parquet when its reader cannot be set up
A topic whose schema cannot be laid out as parquet left the parquet
reader nil, and a merged read that reached parquet called it and
panicked. Such a read now returns the setup error; skipping the parquet
rows silently would hide stored messages.
2026-12-01 12:12:05 -08:00
Chris LuandClaude Opus 5.5 8c9a331568 mq logstore: read schemaless parquet rows back as their published bytes
Compaction stores a schemaless message's bytes in the _value column, but the
parquet reader handed out the whole row marshaled as a RecordValue, with _key,
_ts_ns and _offset wrapped around it, so a consumer reading compacted offsets
got different bytes than it would from the log files, and the query engine
showed that wrapping as the value. A schemaless topic's rows now carry the
_value bytes as Data; schematized topics keep the marshaled row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:53:08 -08:00
Chris LuandClaude Opus 5.5 6eeb764409 mq logstore: serve merged offset reads from log files where they exist
A merged offset read took parquet first and the log files from the offset after
the last row parquet delivered. Compaction keeps a parquet file's source logs
until retention removes them and drops messages with no key or no data, so that
skipped those messages although their logs were still there, and delivered
compacted rows in place of the messages as written.

The log reader now lists its files before reading them, and an offset read
finds the lowest offset the listed log files record. Parquet serves only the
offsets from the requested one up to that, and the log files everything from
there, so each offset is read once and from a log file whenever one holds it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:52:38 -08:00
Chris LuandClaude Opus 5.5 f94aaf6dc8 mq logstore: read parquet files first in a merged offset read
The merged read took the live log files first and, now that it honors the
callback's done, returned without reading parquet when the callback stopped.
The stateless fetch stops after a chunk's worth of entries outside the chunk it
fills, so with offsets 0-999 only in parquet and 1000-1999 in log files, a fetch
at 0 stopped on the log files' entries and never reached parquet.

Compaction turns the oldest windows into parquet, so an offset read now takes
the parquet files first and the log files after: the lower offsets arrive
first, and since each source skips what lies below its start, a bounded caller
only stops on entries past what it wants. Compaction leaves a parquet file's
source logs in place until retention removes them, so the log files are read
from the offset after the last one parquet delivered, and each offset is
delivered once. Timestamp reads keep their order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:42:53 -08:00
Chris LuandClaude Opus 5.5 d058214660 mq logstore: start an offset read of parquet files at the offset
An offset read of the parquet files delivered every row from the first one on,
and the stateless fetch fills a disk chunk with a callback that stops after a
chunk's worth of entries outside it. Now that the reader honors that stop, a
fetch at 1000 from a partition stored only in parquet stopped after rows 0-999
and returned nothing. An offset read now skips files whose recorded range ends
below the offset or that record none, reads the rest in offset order, and skips
rows below the offset before they reach the callback. It returns the offset
after the last row delivered, not a timestamp position.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:40:02 -08:00
Chris LuandClaude Opus 5.5 f720c0e584 mq logstore: drop a debug print from the disk read
A disk read bounded by stopTsNs printed the stop time and the first entry past
it to stdout on every such read. It was a leftover debug line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:21:43 -08:00
Chris LuandClaude Opus 5.5 7c0e2c39d4 mq logstore: read parquet rows at the stop time
The log reader treats stopTsNs as inclusive, delivering an entry at it and
reading a file whose first entry is at it, but the parquet reader stopped at a
row equal to it and skipped a file starting at it, so the same bounded read
returned that message from a log file and dropped it once compacted. Both
checks are now inclusive.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:21:36 -08:00
Chris LuandClaude Opus 5.5 49d6091e59 mq broker: stamp a loaded partition's messages after the newest stored one
Within one LogBuffer timestamps only increase, but a new buffer starts LastTsNs
at 0, so a leader whose clock is behind the previous leader's stamped new
messages earlier than what was already stored, and a subscriber resuming by
timestamp from the last stored message dropped them. OffsetRange now also
records the newest ts_max of the partition's log and parquet files, and loading
a partition seeds LastTsNs with it, so the buffer bumps new messages past it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:17:57 -08:00
Chris LuandClaude Opus 5.5 be7b803379 query: take MIN and MAX of _ts from the files' recorded time range
MIN and MAX of _ts without column statistics were computed from file names,
which are only the start second of a file's first source log: MIN rounded down
to that second and MAX was the start of the latest file rather than its last
row. Each file's stats already carry ts_min and ts_max as MinTimestampNs and
MaxTimestampNs, so those are used when set, and names only for files that
record no range.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:16:23 -08:00
Chris LuandClaude Opus 5.5 54a6c0dce1 mq logstore: read parquet files named before a timestamp resume
A parquet file is named after its first source log, and that log can start
seconds before rows the file holds, so listing parquet files from the resume
second skipped a file named earlier that still held later rows. The reader now
keeps the same sparse logFileIndex the log reader uses and lists from the last
mark before which every file ends before the resume time, deciding each file
by its ts_max.

Rows are not in time order once windows flushed across a reload are compacted
together, so stopping at the first row past stopTsNs dropped later rows still
inside it. Each row is now kept or skipped on its own, and the returned
position is the latest row delivered rather than the last row looked at.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:15:15 -08:00
Chris LuandClaude Opus 5.5 6860a6404e mq logstore: stop a parquet read when the callback is done
The parquet reader also ignored the callback's isDone and delivered every
remaining row of every compacted file, and the merged read cleared any done it
reported. It now stops at that row and skips the remaining files, which it
lists before reading instead of reading inside the listing. Its done now means
only that the callback asked to stop, so the merged read passes it on; the
no-op readers and a file starting at or after stopTsNs no longer report done,
which the merged read used to clear anyway.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:13:47 -08:00
Chris LuandClaude Opus 5.5 c9e84e4463 mq logstore: stop a disk read when the callback is done
GenLogOnDiskReadFunc ignored the isDone the per-entry callback returned, so it
kept fetching and delivering every later entry, chunk and file, and the merged
read then went on into the parquet files. The chunked offset read and the query
scanner's close path both return true and expect the read to stop. The reader
now stops at that entry, skips the remaining chunks and files, and returns done
with a position just past the entry: the next offset for an offset read, its
time for a timestamp read. The merged read returns there instead of reading
parquet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:12:29 -08:00
11 changed files with 879 additions and 116 deletions

No files matched your search

@@ -42,6 +42,46 @@ func TestLoadedPartitionStartsAtTheEarliestStoredOffset(t *testing.T) {
}
}
// A leader whose clock is behind the stored messages stamps new ones after them, so
// a timestamp resume from the last stored message still reads what it publishes. An
// older file recording no message times is bounded by when it was written.
func TestLoadedPartitionStampsAfterTheNewestStoredMessage(t *testing.T) {
for _, recordsTimes := range []bool{true, false} {
f, b := newFencingFiler(t)
// the flush on shutdown notifies the partition through the topic manager
b.localTopicManager = topic.NewLocalTopicManager()
stored := time.Now().Add(time.Hour)
name := f.putLogFile(stored.Truncate(time.Second), 0, 9, stored)
if recordsTimes {
entry := f.entry(topic.PartitionDir(fenceTestTopic, fenceTestPartition) + "/" + name)
f.mu.Lock()
entry.Extended[mq.ExtendedAttrTimestampMin] = binary.BigEndian.AppendUint64(nil, uint64(stored.Truncate(time.Second).UnixNano()))
entry.Extended[mq.ExtendedAttrTimestampMax] = binary.BigEndian.AppendUint64(nil, uint64(stored.UnixNano()))
f.mu.Unlock()
}
lp, err := b.newLeaderPartition(fenceTestTopic, fenceTestPartition, &mq_pb.BrokerPartitionAssignment{Partition: fenceTestPartition.ToPbPartition(), Epoch: 1})
if err != nil {
t.Fatal(err)
}
if _, err := lp.PublishWithOffset(&mq_pb.DataMessage{Key: []byte("k"), Value: []byte("new"), TsNs: time.Now().UnixNano()}); err != nil {
t.Fatal(err)
}
var got []string
if _, _, err := lp.LogBuffer.LoopProcessLogData("test", log_buffer.NewMessagePosition(stored.UnixNano(), -2), 0, func() bool { return false }, func(logEntry *filer_pb.LogEntry) (bool, error) {
got = append(got, string(logEntry.Data))
return true, nil
}); err != nil {
t.Fatal(err)
}
lp.Shutdown()
if len(got) != 1 || got[0] != "new" {
t.Errorf("file records message times %v: resumed after the stored messages, read %q, want the new message", recordsTimes, got)
}
}
}
// A loaded partition's buffer assigns offsets, so it is the high water mark.
func TestPartitionOffsetInfoFromLoadedBuffer(t *testing.T) {
b := newUnelectedBroker()
@@ -233,14 +233,17 @@ func (b *MessageQueueBroker) ensureTopicActiveAssignments(t topic.Topic, conf *m
}
// initializePartitionOffsetFromExistingData continues the partition's offsets above
// what is already stored, starts its log at the earliest stored offset, and names
// its windows no earlier than the newest stored log file. A partition whose stored
// offsets cannot be read is not served.
// what is already stored, starts its log at the earliest stored offset, names its
// windows no earlier than the newest stored log file, and stamps new messages after
// the newest stored one (see OffsetRange.NewestTsNs), which a leader with a slower
// clock would otherwise stamp earlier. A partition whose stored offsets cannot be
// read is not served.
func (b *MessageQueueBroker) initializePartitionOffsetFromExistingData(localPartition *topic.LocalPartition, t topic.Topic, partition topic.Partition) error {
var earliestOffset int64
err := localPartition.LogBuffer.InitializeOffsetFromExistingData(func() (int64, error) {
r, err := b.getOffsetRangeFromChunkMetadata(t, partition)
localPartition.Fence.NoteLogFileTime(r.NewestLogFileTime())
localPartition.LogBuffer.LastTsNs.Store(r.NewestTsNs())
var highWaterMark int64
earliestOffset, highWaterMark = r.Bounds()
return highWaterMark - 1, err
+378 -7
View File
@@ -9,6 +9,7 @@ import (
"net"
"net/http"
"net/http/httptest"
"slices"
"sort"
"strings"
"sync"
@@ -16,6 +17,7 @@ import (
"testing"
"time"
"github.com/parquet-go/parquet-go"
"github.com/seaweedfs/seaweedfs/weed/mq"
"github.com/seaweedfs/seaweedfs/weed/mq/schema"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
@@ -23,6 +25,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
"google.golang.org/grpc"
@@ -159,16 +162,29 @@ func (f *compactionFiler) putTopicConf(t *testing.T) {
// putLogFile stores a flushed window holding one message per timestamp, numbered from minOffset.
func (f *compactionFiler) putLogFile(t *testing.T, start time.Time, minOffset int64, tsNs ...int64) {
var buf []byte
var entries []*filer_pb.LogEntry
for i, ts := range tsNs {
offset := minOffset + int64(i)
data, err := proto.Marshal(&filer_pb.LogEntry{TsNs: ts, Key: []byte(fmt.Sprintf("k%d", offset)), Data: []byte(fmt.Sprintf("value-%d", offset)), Offset: offset})
entries = append(entries, &filer_pb.LogEntry{TsNs: ts, Key: []byte(fmt.Sprintf("k%d", offset)), Data: []byte(fmt.Sprintf("value-%d", offset)), Offset: offset})
}
f.putLogEntries(t, start, entries...)
}
// putLogEntries stores a flushed window holding entries, named by the first one's offset.
func (f *compactionFiler) putLogEntries(t *testing.T, start time.Time, entries ...*filer_pb.LogEntry) {
var buf []byte
for _, entry := range entries {
data, err := proto.Marshal(entry)
if err != nil {
t.Fatal(err)
}
buf = binary.BigEndian.AppendUint32(buf, uint32(len(data)))
buf = append(buf, data...)
}
minOffset, maxOffset := entries[0].Offset, entries[0].Offset
for _, entry := range entries {
minOffset, maxOffset = min(minOffset, entry.Offset), max(maxOffset, entry.Offset)
}
fileId := newCompactionFileId()
f.mu.Lock()
defer f.mu.Unlock()
@@ -180,7 +196,7 @@ func (f *compactionFiler) putLogFile(t *testing.T, start time.Time, minOffset in
Attributes: &filer_pb.FuseAttributes{Crtime: 1, Mtime: 1, FileSize: uint64(len(buf))},
Extended: map[string][]byte{
mq.ExtendedAttrOffsetMin: binary.BigEndian.AppendUint64(nil, uint64(minOffset)),
mq.ExtendedAttrOffsetMax: binary.BigEndian.AppendUint64(nil, uint64(minOffset+int64(len(tsNs))-1)),
mq.ExtendedAttrOffsetMax: binary.BigEndian.AppendUint64(nil, uint64(maxOffset)),
},
}
}
@@ -357,8 +373,8 @@ func TestCompactionKeepsOffsetsBesideALegacyLogFile(t *testing.T) {
}
}
// A schemaless topic's parquet rows keep their offsets, so a fetch by offset
// returns every record at its own offset.
// A schemaless topic's parquet rows keep their offsets and values, so a fetch by
// offset returns every record at its own offset with the bytes it was published with.
func TestCompactedSchemalessRowsKeepTheirOffsets(t *testing.T) {
f, client := newCompactionFiler(t)
f.putTopicConf(t)
@@ -371,8 +387,363 @@ func TestCompactedSchemalessRowsKeepTheirOffsets(t *testing.T) {
t.Fatalf("read %d records, want 10: %v", len(got), got)
}
for i, entry := range got {
if entry.Offset != int64(i) || string(entry.Key) != fmt.Sprintf("k%d", i) {
t.Errorf("record %d: offset %d key %q", i, entry.Offset, entry.Key)
if entry.Offset != int64(i) || string(entry.Key) != fmt.Sprintf("k%d", i) || string(entry.Data) != fmt.Sprintf("value-%d", i) {
t.Errorf("record %d: offset %d key %q data %q", i, entry.Offset, entry.Key, entry.Data)
}
}
}
// A callback that says it is done stops a read of compacted rows too.
func TestParquetReadStopsWhenTheCallbackIsDone(t *testing.T) {
f, client := newCompactionFiler(t)
f.putTopicConf(t)
f.putTenMessages(t)
compactSchemaless(t, client)
f.removeLogFiles()
var keys []string
_, isDone, err := GenMergedReadFunc(client, compactionTopic, compactionPartition)(log_buffer.NewMessagePosition(1, -2), 0, func(entry *filer_pb.LogEntry) (bool, error) {
keys = append(keys, string(entry.Key))
return len(keys) == 3, nil
})
if err != nil {
t.Fatal(err)
}
if len(keys) != 3 || !isDone {
t.Errorf("read %v done %v, want three rows and done", keys, isDone)
}
}
func readParquetTimestamps(t *testing.T, read log_buffer.LogReadFromDiskFuncType, startTsNs, stopTsNs int64) (got []int64) {
t.Helper()
if _, _, err := read(log_buffer.NewMessagePosition(startTsNs, -2), stopTsNs, func(entry *filer_pb.LogEntry) (bool, error) {
got = append(got, entry.TsNs)
return false, nil
}); err != nil {
t.Fatal(err)
}
return got
}
// A parquet file is named after its first source log, which can start seconds before
// rows it holds; a timestamp resume after its name still reads those rows, and rows
// out of time order are each kept or dropped by the stop time.
func TestParquetReadResumesInsideAnEarlierFile(t *testing.T) {
f, client := newCompactionFiler(t)
f.putTopicConf(t)
base := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
at := func(sec int) int64 { return base.Add(time.Duration(sec) * time.Second).UnixNano() }
f.putLogFile(t, base, 0, at(5), at(9))
f.putLogFile(t, base.Add(time.Second), 2, at(1), at(7))
compactSchemaless(t, client)
f.removeLogFiles()
read := GenParquetReadFunc(client, compactionTopic, compactionPartition)
// once from cold and once with the reader having listed the partition before
for range 2 {
if got, want := readParquetTimestamps(t, read, at(6), 0), []int64{at(7), at(9)}; !slices.Equal(got, want) {
t.Errorf("resumed at 6s, read %v, want %v", got, want)
}
}
if got, want := readParquetTimestamps(t, read, 1, at(8)), []int64{at(1), at(5), at(7)}; !slices.Equal(got, want) {
t.Errorf("stopping at 8s read %v, want %v", got, want)
}
// a read stopped after one row resumes without skipping the other
var got []int64
position, isDone, err := read(log_buffer.NewMessagePosition(at(6), -2), 0, func(entry *filer_pb.LogEntry) (bool, error) {
got = append(got, entry.TsNs)
return true, nil
})
if err != nil || !isDone {
t.Fatalf("stopped read: done %v err %v", isDone, err)
}
got = append(got, readParquetTimestamps(t, read, position.Time.UnixNano(), 0)...)
if want := []int64{at(7), at(9)}; !slices.Equal(got, want) {
t.Errorf("stopped after one row and resumed, read %v, want %v", got, want)
}
}
// The stop time is inclusive, as for log files: a row at it is read, and so is a
// file whose first row is at it.
func TestParquetReadIncludesARowAtTheStopTime(t *testing.T) {
f, client := newCompactionFiler(t)
f.putTopicConf(t)
base := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
at := func(sec int) int64 { return base.Add(time.Duration(sec) * time.Second).UnixNano() }
f.putLogFile(t, base, 0, at(1), at(5), at(9))
compactSchemaless(t, client)
f.removeLogFiles()
read := GenParquetReadFunc(client, compactionTopic, compactionPartition)
if got, want := readParquetTimestamps(t, read, 1, at(5)), []int64{at(1), at(5)}; !slices.Equal(got, want) {
t.Errorf("stopping at 5s read %v, want %v", got, want)
}
if got, want := readParquetTimestamps(t, read, 1, at(1)), []int64{at(1)}; !slices.Equal(got, want) {
t.Errorf("stopping at the file's first row read %v, want %v", got, want)
}
}
// putWindows stores count offsets from first in windows of size, one second apart.
func (f *compactionFiler) putWindows(t *testing.T, first, count, size int) {
base := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
for start := first; start < first+count; start += size {
var tsNs []int64
for o := start; o < start+size; o++ {
tsNs = append(tsNs, base.UnixNano()+int64(o))
}
f.putLogFile(t, base.Add(time.Duration(start/size)*time.Second), int64(start), tsNs...)
}
}
// fetchOffsets fetches through the broker's merged reader as a Kafka fetch does.
func fetchOffsets(t *testing.T, client listingFilerClient, end, start int64) (got []int64) {
t.Helper()
lb := log_buffer.NewLogBuffer("test", time.Hour, nil, GenMergedReadFunc(client, compactionTopic, compactionPartition), func() {})
t.Cleanup(lb.ShutdownLogBuffer)
if err := lb.InitializeOffsetFromExistingData(func() (int64, error) { return end - 1, nil }); err != nil {
t.Fatal(err)
}
messages, _, _, _, err := lb.ReadMessagesAtOffset(start, 3, 1<<20)
if err != nil {
t.Fatal(err)
}
for _, m := range messages {
got = append(got, m.Offset)
}
return got
}
// A fetch fills a whole disk chunk around its offset and stops after as many entries
// outside it; rows of compacted files below the offset must not count toward that.
func TestFetchFromCompactedFilesPastTheirFirstChunk(t *testing.T) {
f, client := newCompactionFiler(t)
f.putTopicConf(t)
f.putWindows(t, 0, 2000, 500)
compactSchemaless(t, client)
f.removeLogFiles()
if got := fetchOffsets(t, client, 2000, 1000); !slices.Equal(got, []int64{1000, 1001, 1002}) {
t.Errorf("fetch at 1000 returned %v", got)
}
}
// Compaction turns the oldest windows into parquet, so a fetch of them must reach the
// parquet files before later log files fill up the chunk's allowance of other offsets.
func TestFetchFromCompactedFilesBelowTheLogFiles(t *testing.T) {
f, client := newCompactionFiler(t)
f.putTopicConf(t)
f.putWindows(t, 0, 1000, 500)
compactSchemaless(t, client)
f.removeLogFiles()
f.putWindows(t, 1000, 1000, 500)
for _, start := range []int64{0, 500, 1000, 1999} {
want := offsetsFrom(start, min(start+3, 2000))
if got := fetchOffsets(t, client, 2000, start); !slices.Equal(got, want) {
t.Errorf("fetch at %d returned %v, want %v", start, got, want)
}
}
}
// Compaction leaves a parquet file's source logs in place until retention removes
// them, so a merged offset read must not deliver their offsets a second time.
func TestMergedOffsetReadDeliversCompactedOffsetsOnce(t *testing.T) {
f, client := newCompactionFiler(t)
f.putTopicConf(t)
f.putWindows(t, 0, 1000, 500)
compactSchemaless(t, client)
f.putWindows(t, 1000, 1000, 500)
for _, start := range []int64{0, 700} {
var got []int64
if _, _, err := GenMergedReadFunc(client, compactionTopic, compactionPartition)(log_buffer.NewMessagePositionFromOffset(start), 0, func(entry *filer_pb.LogEntry) (bool, error) {
got = append(got, entry.Offset)
return false, nil
}); err != nil {
t.Fatal(err)
}
if want := offsetsFrom(start, 2000); !slices.Equal(got, want) {
t.Errorf("read from %d delivered %d offsets, want %d once each in order", start, len(got), len(want))
}
}
// the source logs still hold these offsets, so they are read as written
var first *filer_pb.LogEntry
if _, _, err := GenMergedReadFunc(client, compactionTopic, compactionPartition)(log_buffer.NewMessagePositionFromOffset(0), 0, func(entry *filer_pb.LogEntry) (bool, error) {
first = entry
return true, nil
}); err != nil {
t.Fatal(err)
}
if first == nil || first.Offset != 0 || string(first.Data) != "value-0" {
t.Errorf("read %v at offset 0, want the logged value-0", first)
}
for _, start := range []int64{0, 500, 1000, 1999} {
want := offsetsFrom(start, min(start+3, 2000))
if got := fetchOffsets(t, client, 2000, start); !slices.Equal(got, want) {
t.Errorf("fetch at %d returned %v, want %v", start, got, want)
}
}
}
// Compaction drops a message with no key, so parquet lacks its offset; while its
// source log is present the message is still read from it.
func TestMergedOffsetReadKeepsAMessageCompactionDropped(t *testing.T) {
f, client := newCompactionFiler(t)
f.putTopicConf(t)
base := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC).UnixNano()
f.putLogEntries(t, time.Unix(0, base),
&filer_pb.LogEntry{TsNs: base + 1, Data: []byte("keyless"), Offset: 0},
&filer_pb.LogEntry{TsNs: base + 2, Key: []byte("k1"), Data: []byte("value-1"), Offset: 1},
&filer_pb.LogEntry{TsNs: base + 3, Key: []byte("k2"), Data: []byte("value-2"), Offset: 2})
compactSchemaless(t, client)
if len(f.parquetFiles()) != 1 {
t.Fatalf("%d parquet files, want 1", len(f.parquetFiles()))
}
var got []string
if _, _, err := GenMergedReadFunc(client, compactionTopic, compactionPartition)(log_buffer.NewMessagePositionFromOffset(0), 0, func(entry *filer_pb.LogEntry) (bool, error) {
got = append(got, fmt.Sprintf("%d:%s", entry.Offset, entry.Data))
return false, nil
}); err != nil {
t.Fatal(err)
}
if want := []string{"0:keyless", "1:value-1", "2:value-2"}; !slices.Equal(got, want) {
t.Errorf("read %v, want %v", got, want)
}
}
// A topic whose schema cannot be laid out as parquet fails a read that reaches
// parquet, rather than calling a reader that was never built.
func TestMergedReadFailsWhenParquetCannotBeSetUp(t *testing.T) {
f, client := newCompactionFiler(t)
conf, err := protojson.Marshal(&mq_pb.ConfigureTopicResponse{
MessageRecordType: &schema_pb.RecordType{Fields: []*schema_pb.Field{{Name: "v", Type: &schema_pb.Type{}}}},
})
if err != nil {
t.Fatal(err)
}
f.entries[compactionTopic.Dir()+"/topic.conf"] = &filer_pb.Entry{Name: "topic.conf", Content: conf, Attributes: &filer_pb.FuseAttributes{}}
read := GenMergedReadFunc(client, compactionTopic, compactionPartition)
_, _, err = read(log_buffer.NewMessagePositionFromOffset(0), 0, func(*filer_pb.LogEntry) (bool, error) { return false, nil })
if err == nil {
t.Fatal("a read reaching parquet with an unusable schema returned no error")
}
}
// Compaction writes rows in the order it reads its sources, which need not be offset
// order; a stopped offset read must not resume past an offset it did not deliver.
func TestParquetOffsetReadStoppedEarlySkipsNothing(t *testing.T) {
f, client := newCompactionFiler(t)
f.putTopicConf(t)
base := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC).UnixNano()
var entries []*filer_pb.LogEntry
for i, offset := range append([]int64{1000, 1001}, offsetsFrom(0, 1000)...) {
entries = append(entries, &filer_pb.LogEntry{TsNs: base + int64(i), Key: []byte(fmt.Sprintf("k%d", offset)), Data: []byte("v"), Offset: offset})
}
f.putLogEntries(t, time.Unix(0, base), entries...)
compactSchemaless(t, client)
f.removeLogFiles()
var got []int64
position, isDone, err := GenParquetReadFunc(client, compactionTopic, compactionPartition)(log_buffer.NewMessagePositionFromOffset(0), 0, func(entry *filer_pb.LogEntry) (bool, error) {
got = append(got, entry.Offset)
return len(got) == 2, nil
})
if err != nil || !isDone {
t.Fatalf("done %v err %v", isDone, err)
}
if !slices.Equal(got, []int64{0, 1}) || position.Offset != 2 {
t.Errorf("stopped after %v, resuming at %d", got, position.Offset)
}
}
// Compaction writes a file's rows in offset order though a source holding later
// offsets sorts first by name, as a window flushed under clock skew does.
func TestCompactionWritesRowsInOffsetOrder(t *testing.T) {
f, client := newCompactionFiler(t)
f.putTopicConf(t)
base := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
f.putLogFile(t, base.Add(-time.Hour), 3, base.UnixNano()+4, base.UnixNano()+5)
f.putLogFile(t, base, 0, base.UnixNano()+1, base.UnixNano()+2, base.UnixNano()+3)
compactSchemaless(t, client)
files := f.parquetFiles()
if len(files) != 1 {
t.Fatalf("%d parquet files, want 1", len(files))
}
f.mu.Lock()
blob := f.blobs["/"+files[0].Chunks[0].FileId]
f.mu.Unlock()
reader := parquet.NewReader(bytes.NewReader(blob))
column, ok := reader.Schema().Lookup(SW_COLUMN_NAME_OFFSET)
if !ok {
t.Fatal("no offset column")
}
var offsets []int64
rows := make([]parquet.Row, 16)
for {
n, err := reader.ReadRows(rows)
for _, row := range rows[:n] {
for _, value := range row {
if value.Column() == column.ColumnIndex {
offsets = append(offsets, value.Int64())
}
}
}
if err != nil || n == 0 {
break
}
}
if want := offsetsFrom(0, 5); !slices.Equal(offsets, want) {
t.Errorf("rows in offset order %v, want %v", offsets, want)
}
}
// A timestamp read takes the compacted rows below newer log files too, each message
// once, and a read stopped in either source resumes without skipping any.
func TestMergedTimestampReadIncludesOlderParquetRows(t *testing.T) {
for _, sourcesKept := range []bool{false, true} {
f, client := newCompactionFiler(t)
f.putTopicConf(t)
f.putWindows(t, 0, 10, 5)
compactSchemaless(t, client)
if !sourcesKept {
f.removeLogFiles()
}
f.putWindows(t, 10, 10, 5)
read := GenMergedReadFunc(client, compactionTopic, compactionPartition)
var got []int64
if _, _, err := read(log_buffer.NewMessagePosition(1, -2), 0, func(entry *filer_pb.LogEntry) (bool, error) {
got = append(got, entry.Offset)
return false, nil
}); err != nil {
t.Fatal(err)
}
if want := offsetsFrom(0, 20); !slices.Equal(got, want) {
t.Errorf("sources kept %v: read %v, want %v", sourcesKept, got, want)
}
for _, stopAfter := range []int{3, 13} {
delivered := map[int64]bool{}
position, isDone, err := read(log_buffer.NewMessagePosition(1, -2), 0, func(entry *filer_pb.LogEntry) (bool, error) {
delivered[entry.Offset] = true
return len(delivered) == stopAfter, nil
})
if err != nil || !isDone {
t.Fatalf("done %v err %v", isDone, err)
}
if _, _, err := read(position, 0, func(entry *filer_pb.LogEntry) (bool, error) {
delivered[entry.Offset] = true
return false, nil
}); err != nil {
t.Fatal(err)
}
if len(delivered) != 20 {
t.Errorf("sources kept %v: stopped after %d and resumed, read %d of 20", sourcesKept, stopAfter, len(delivered))
}
}
}
}
+4 -1
View File
@@ -278,7 +278,10 @@ func writeLogFilesToParquet(filerClient filer_pb.FilerClient, partitionDir strin
minOffset, maxOffset, hasOffsets := sourcesOffsetRange(logFileGroups)
isSchemaless := isSchemalessRecordType(recordType)
for _, logFile := range logFileGroups {
// rows go in offset order; source names follow offsets except under clock skew
inOffsetOrder := slices.Clone(logFileGroups)
sortByOffset(inOffsetOrder)
for _, logFile := range inOffsetOrder {
var rows []parquet.Row
if err := iterateLogEntries(filerClient, logFile, func(entry *filer_pb.LogEntry) error {
+44 -26
View File
@@ -1,50 +1,68 @@
package logstore
import (
"math"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
)
func GenMergedReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p topic.Partition) log_buffer.LogReadFromDiskFuncType {
fromParquetFn := GenParquetReadFunc(filerClient, t, p)
readLogDirectFn := GenLogOnDiskReadFunc(filerClient, t, p)
// Reversed order: live logs first (recent), then Parquet files (historical)
// This provides better performance for real-time analytics queries
return mergeReadFuncs(readLogDirectFn, fromParquetFn)
return mergeReadFuncs(newLogReader(filerClient, t, p), newParquetReader(filerClient, t, p))
}
func mergeReadFuncs(readLogDirectFn, fromParquetFn log_buffer.LogReadFromDiskFuncType) log_buffer.LogReadFromDiskFuncType {
func mergeReadFuncs(logs logReader, readParquet parquetReadFunc) log_buffer.LogReadFromDiskFuncType {
// CRITICAL FIX: Removed stateful closure variables (exhaustedLiveLogs, lastProcessedPosition)
// These caused the function to skip disk reads on subsequent calls, leading to
// Schema Registry timeout when data was flushed after the first read attempt.
// The function must be stateless and check for data on EVERY call.
return func(startPosition log_buffer.MessagePosition, stopTsNs int64, eachLogEntryFn log_buffer.EachLogEntryFuncType) (lastReadPosition log_buffer.MessagePosition, isDone bool, err error) {
// Always try reading from live logs first (recent data)
lastReadPosition, isDone, err = readLogDirectFn(startPosition, stopTsNs, eachLogEntryFn)
if isDone {
// For very early timestamps (like timestamp=1 for RESET_TO_EARLIEST),
// we want to continue to read from in-memory data
isDone = false
}
logFiles, err := logs.list(startPosition, stopTsNs)
if err != nil {
return
return startPosition, false, err
}
// If live logs returned data, update startPosition for parquet read
if lastReadPosition.Offset > startPosition.Offset || lastReadPosition.Time.After(startPosition.Time) {
startPosition = lastReadPosition
// compaction keeps the source logs until retention removes them, and drops some
// messages, so parquet serves only the offsets below every log file
end := earliestLogOffset(logFiles)
if startPosition.IsOffsetBased {
var parquetPosition log_buffer.MessagePosition
if startPosition.Offset < end {
parquetPosition, isDone, err = readParquet(startPosition, end, stopTsNs, eachLogEntryFn)
if err != nil || isDone {
return parquetPosition, isDone, err
}
}
lastReadPosition, isDone, err = logs.read(logFiles, startPosition, stopTsNs, eachLogEntryFn)
if err == nil && !isDone && parquetPosition.Offset > lastReadPosition.Offset {
lastReadPosition = parquetPosition
}
return lastReadPosition, isDone, err
}
// Then try reading from Parquet files (historical data)
lastReadPosition, isDone, err = fromParquetFn(startPosition, stopTsNs, eachLogEntryFn)
if isDone {
// For very early timestamps (like timestamp=1 for RESET_TO_EARLIEST),
// parquet files won't exist, but we want to continue to in-memory data reading
isDone = false
// both sources read from the start, so neither skips what the other holds earlier
parquetPosition, isDone, err := readParquet(startPosition, end, stopTsNs, eachLogEntryFn)
if err != nil || isDone {
// the log files are unread, and may hold messages before where parquet stopped
resumeTsNs := stoppedReadTsNs(startPosition.Time.UnixNano(), parquetPosition.Time.UnixNano(), logFiles)
return log_buffer.NewMessagePosition(resumeTsNs, -2), isDone, err
}
return
lastReadPosition, isDone, err = logs.read(logFiles, startPosition, stopTsNs, eachLogEntryFn)
if err == nil && !isDone && parquetPosition.Time.After(lastReadPosition.Time) {
lastReadPosition = parquetPosition
}
return lastReadPosition, isDone, err
}
}
// earliestLogOffset is the lowest offset the log files record, or MaxInt64 when none records one.
func earliestLogOffset(logFiles []*filer_pb.Entry) int64 {
earliest := int64(math.MaxInt64)
for _, file := range logFiles {
if minOffset, _, ok := logFileOffsets(file); ok {
earliest = min(earliest, minOffset)
}
}
return earliest
}
+84 -11
View File
@@ -158,6 +158,33 @@ func sortByOffset(files []*filer_pb.Entry) {
}
}
// stoppedReadTsNs is where a timestamp read that stopped after delivering a message at
// lastTsNs resumes without skipping anything: a file's messages only grow in time, but
// a later file can hold earlier ones, so it stays below every unread file's first message.
func stoppedReadTsNs(startTsNs, lastTsNs int64, unread []*filer_pb.Entry) int64 {
resumeTsNs := lastTsNs
for _, file := range unread {
firstTsNs, ok := logFileTsNs(file, mq.ExtendedAttrTimestampMin)
if !ok {
return startTsNs
}
resumeTsNs = min(resumeTsNs, firstTsNs-1)
}
return max(resumeTsNs, startTsNs)
}
// stoppedReadOffset is where an offset read that stopped after delivering lastOffset
// resumes without skipping anything, given that each file delivers in offset order.
func stoppedReadOffset(startOffset, lastOffset int64, unread []*filer_pb.Entry) int64 {
next := lastOffset + 1
for _, file := range unread {
if minOffset, _, ok := logFileOffsets(file); ok {
next = min(next, minOffset)
}
}
return max(next, startOffset)
}
// logFileTsNs is the message time a log file records under key, if it records one.
func logFileTsNs(entry *filer_pb.Entry, key string) (int64, bool) {
if b := entry.Extended[key]; len(b) == 8 {
@@ -166,7 +193,25 @@ func logFileTsNs(entry *filer_pb.Entry, key string) (int64, bool) {
return 0, false
}
// logReader lists the log files a read needs before reading them, so a merged read
// knows which offsets the log files hold before anything is delivered.
type logReader struct {
list func(startPosition log_buffer.MessagePosition, stopTsNs int64) ([]*filer_pb.Entry, error)
read func(candidateFiles []*filer_pb.Entry, startPosition log_buffer.MessagePosition, stopTsNs int64, eachLogEntryFn log_buffer.EachLogEntryFuncType) (log_buffer.MessagePosition, bool, error)
}
func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p topic.Partition) log_buffer.LogReadFromDiskFuncType {
logs := newLogReader(filerClient, t, p)
return func(startPosition log_buffer.MessagePosition, stopTsNs int64, eachLogEntryFn log_buffer.EachLogEntryFuncType) (log_buffer.MessagePosition, bool, error) {
candidateFiles, err := logs.list(startPosition, stopTsNs)
if err != nil {
return log_buffer.MessagePosition{}, false, err
}
return logs.read(candidateFiles, startPosition, stopTsNs, eachLogEntryFn)
}
}
func newLogReader(filerClient filer_pb.FilerClient, t topic.Topic, p topic.Partition) logReader {
partitionDir := topic.PartitionDir(t, p)
index := &logFileIndex{}
@@ -176,7 +221,7 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
lookupFileIdFn := filer.LookupFn(filerClient)
eachChunkFn := func(buf []byte, eachLogEntryFn log_buffer.EachLogEntryFuncType, starTsNs, stopTsNs int64, startOffset int64, isOffsetBased bool) (processedTsNs int64, err error) {
eachChunkFn := func(buf []byte, eachLogEntryFn log_buffer.EachLogEntryFuncType, starTsNs, stopTsNs int64, startOffset int64, isOffsetBased bool) (processedTsNs int64, isDone bool, err error) {
entriesSkipped := 0
entriesProcessed := 0
for pos := 0; pos+4 < len(buf); {
@@ -209,19 +254,21 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
continue
}
if stopTsNs != 0 && logEntry.TsNs > stopTsNs {
println("stopTsNs", stopTsNs, "logEntry.TsNs", logEntry.TsNs)
return
}
}
// fmt.Printf(" read logEntry: %v, ts %v\n", string(logEntry.Key), time.Unix(0, logEntry.TsNs).UTC())
if _, err = eachLogEntryFn(logEntry); err != nil {
if isDone, err = eachLogEntryFn(logEntry); err != nil {
err = fmt.Errorf("process log entry %v: %w", logEntry, err)
return
}
processedTsNs = logEntry.TsNs
entriesProcessed++
if isDone {
return
}
pos += 4 + int(size)
@@ -230,7 +277,7 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
return
}
eachFileFn := func(entry *filer_pb.Entry, eachLogEntryFn log_buffer.EachLogEntryFuncType, starTsNs, stopTsNs int64, startOffset int64, isOffsetBased bool) (processedTsNs int64, err error) {
eachFileFn := func(entry *filer_pb.Entry, eachLogEntryFn log_buffer.EachLogEntryFuncType, starTsNs, stopTsNs int64, startOffset int64, isOffsetBased bool) (processedTsNs int64, isDone bool, err error) {
if len(entry.Content) > 0 {
// skip .offset files
return
@@ -266,12 +313,15 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
}
// Positive cache hit - data exists
var chunkTsNs int64
chunkTsNs, err = eachChunkFn(cachedData, eachLogEntryFn, starTsNs, stopTsNs, startOffset, isOffsetBased)
chunkTsNs, isDone, err = eachChunkFn(cachedData, eachLogEntryFn, starTsNs, stopTsNs, startOffset, isOffsetBased)
processedTsNs = max(processedTsNs, chunkTsNs)
if err != nil {
glog.V(1).Infof("eachChunkFn failed on cached data: %v", err)
return
}
if isDone {
return
}
continue
}
@@ -289,12 +339,15 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
fileCache.Put(cacheKey, data, startOffset)
var chunkTsNs int64
chunkTsNs, err = eachChunkFn(data, eachLogEntryFn, starTsNs, stopTsNs, startOffset, isOffsetBased)
chunkTsNs, isDone, err = eachChunkFn(data, eachLogEntryFn, starTsNs, stopTsNs, startOffset, isOffsetBased)
processedTsNs = max(processedTsNs, chunkTsNs)
if err != nil {
glog.V(1).Infof("eachChunkFn failed: %v", err)
return
}
if isDone {
return
}
break
} else {
glog.V(2).Infof("failed to fetch from %s: %v", urlString, err)
@@ -312,12 +365,11 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
return
}
return func(startPosition log_buffer.MessagePosition, stopTsNs int64, eachLogEntryFn log_buffer.EachLogEntryFuncType) (lastReadPosition log_buffer.MessagePosition, isDone bool, err error) {
list := func(startPosition log_buffer.MessagePosition, stopTsNs int64) (candidateFiles []*filer_pb.Entry, err error) {
resumeFileName := startPosition.Time.UTC().Format(topic.TIME_FORMAT)
startTsNs := startPosition.Time.UnixNano()
startFileName := index.markBefore(startTsNs)
stopTime := time.Unix(0, stopTsNs)
var processedTsNs int64
// Check if this is an offset-based subscription
isOffsetBased := startPosition.IsOffsetBased
@@ -330,7 +382,6 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
}
// For offset-based reads, skip files whose offset range ends before the offset
var candidateFiles []*filer_pb.Entry
var foundStartFile bool
var listed []*filer_pb.Entry
var beforeResume *filer_pb.Entry
@@ -409,7 +460,17 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
glog.V(2).Infof("found %d candidate files for topic=%s partition=%s offset=%d",
len(candidateFiles), t.Name, p, startOffset)
return candidateFiles, nil
}
read := func(candidateFiles []*filer_pb.Entry, startPosition log_buffer.MessagePosition, stopTsNs int64, eachLogEntryFn log_buffer.EachLogEntryFuncType) (lastReadPosition log_buffer.MessagePosition, isDone bool, err error) {
startTsNs := startPosition.Time.UnixNano()
isOffsetBased := startPosition.IsOffsetBased
var startOffset int64
if isOffsetBased {
startOffset = startPosition.Offset
}
var processedTsNs int64
if len(candidateFiles) == 0 {
glog.V(2).Infof("no files found in %s", partitionDir)
return startPosition, isDone, nil
@@ -420,9 +481,14 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
// This prevents multiple ReadFromDiskFn calls with 1.127s overhead each
var filesProcessed int
var lastProcessedOffset int64
for _, entry := range candidateFiles {
var lastDeliveredOffset, lastDeliveredTsNs int64
deliver := func(logEntry *filer_pb.LogEntry) (bool, error) {
lastDeliveredOffset, lastDeliveredTsNs = logEntry.Offset, logEntry.TsNs
return eachLogEntryFn(logEntry)
}
for i, entry := range candidateFiles {
var fileTsNs int64
if fileTsNs, err = eachFileFn(entry, eachLogEntryFn, startTsNs, stopTsNs, startOffset, isOffsetBased); err != nil {
if fileTsNs, isDone, err = eachFileFn(entry, deliver, startTsNs, stopTsNs, startOffset, isOffsetBased); err != nil {
return lastReadPosition, isDone, err
}
if fileTsNs > 0 {
@@ -430,6 +496,12 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
processedTsNs = max(processedTsNs, fileTsNs)
filesProcessed++
}
if isDone {
if isOffsetBased {
return log_buffer.NewMessagePositionFromOffset(stoppedReadOffset(startOffset, lastDeliveredOffset, candidateFiles[i+1:])), true, nil
}
return log_buffer.NewMessagePosition(stoppedReadTsNs(startTsNs, lastDeliveredTsNs, candidateFiles[i+1:]), -2), true, nil
}
// For offset-based reads, track the last processed offset
// We need to continue reading ALL files to avoid multiple disk read calls
@@ -459,4 +531,5 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
}
return
}
return logReader{list: list, read: read}
}
+138
View File
@@ -321,6 +321,50 @@ func TestReadFromDiskReturnsTheLatestDeliveredTime(t *testing.T) {
}
}
// A read stopped early resumes without skipping what it did not deliver, though a
// later file holds messages earlier than those already delivered.
func TestReadFromDiskStoppedEarlySkipsNothing(t *testing.T) {
second := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
at := func(ms int) int64 { return second.Add(time.Duration(ms) * time.Millisecond).UnixNano() }
timeAttrs := func(minTs, maxTs int64) map[string][]byte {
return map[string][]byte{
mq.ExtendedAttrTimestampMin: binary.BigEndian.AppendUint64(nil, uint64(minTs)),
mq.ExtendedAttrTimestampMax: binary.BigEndian.AppendUint64(nil, uint64(maxTs)),
}
}
volume := serveChunks(t, map[string][]byte{
"/3,01": logChunk(t, at(100)),
"/3,02": logChunk(t, at(50), at(60)),
})
a := volume.file(topic.LogFileName(second, 0), "3,01")
a.Extended = timeAttrs(at(100), at(100))
b := volume.file(topic.LogFileName(second.Add(time.Second), 1), "3,02")
b.Extended = timeAttrs(at(50), at(60))
_, client := serveFiler(t, volume, a, b)
read := testPartitionReader(client)
for _, stopAfter := range []int{1, 2} {
delivered := map[int64]bool{}
var taken int
position, isDone, err := read(log_buffer.NewMessagePosition(1, -2), 0, func(logEntry *filer_pb.LogEntry) (bool, error) {
delivered[logEntry.TsNs] = true
taken++
return taken == stopAfter, nil
})
if err != nil || !isDone {
t.Fatalf("stop after %d: done %v err %v", stopAfter, isDone, err)
}
for _, ts := range readTimestamps(t, read, position, 0) {
delivered[ts] = true
}
for _, ts := range []int64{at(50), at(60), at(100)} {
if !delivered[ts] {
t.Errorf("stopped after %d and resumed at %v, never read %v", stopAfter, position.Time, time.Unix(0, ts).UTC())
}
}
}
}
// Resuming inside a window must read the rest of the file that started before the
// resume second, and nothing from files that ended before it.
func TestReadFromDiskResumesInsideAnEarlierFile(t *testing.T) {
@@ -519,3 +563,97 @@ func TestFetchByOffsetOverFilesSortingOutOfOffsetOrder(t *testing.T) {
}
}
}
// In an unordered partition a later file can hold offsets below ones already delivered;
// a stopped offset read resumes at or below them.
func TestReadFromDiskByOffsetStoppedEarlySkipsNothing(t *testing.T) {
volume := serveChunks(t, map[string][]byte{
"/3,01": encodeLogEntries(t, &filer_pb.LogEntry{TsNs: 1, Offset: 0}, &filer_pb.LogEntry{TsNs: 2, Offset: 1}, &filer_pb.LogEntry{TsNs: 3, Offset: 4}, &filer_pb.LogEntry{TsNs: 4, Offset: 5}),
"/3,02": encodeLogEntries(t, &filer_pb.LogEntry{TsNs: 5, Offset: 2}, &filer_pb.LogEntry{TsNs: 6, Offset: 3}),
})
ranged := func(file *filer_pb.Entry, minOffset, maxOffset int64) *filer_pb.Entry {
file.Extended = map[string][]byte{
mq.ExtendedAttrOffsetMin: binary.BigEndian.AppendUint64(nil, uint64(minOffset)),
mq.ExtendedAttrOffsetMax: binary.BigEndian.AppendUint64(nil, uint64(maxOffset)),
}
return file
}
second := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
_, client := serveFiler(t, volume,
ranged(volume.file(topic.LogFileName(second, 0), "3,01"), 0, 5),
ranged(volume.file(topic.LogFileName(second.Add(time.Second), 2), "3,02"), 2, 3))
var got []int64
position, isDone, err := testPartitionReader(client)(log_buffer.NewMessagePositionFromOffset(0), 0, func(logEntry *filer_pb.LogEntry) (bool, error) {
got = append(got, logEntry.Offset)
return logEntry.Offset == 4, nil
})
if err != nil || !isDone {
t.Fatalf("done %v err %v", isDone, err)
}
if !slices.Equal(got, []int64{0, 1, 4}) || position.Offset > 2 {
t.Errorf("stopped after %v, resuming at %d past the unread offsets 2 and 3", got, position.Offset)
}
}
// A callback that says it is done stops the read inside a chunk, before later chunks
// and files are fetched, and the returned position follows the last entry delivered.
func TestReadFromDiskStopsWhenTheCallbackIsDone(t *testing.T) {
volume := serveChunks(t, map[string][]byte{})
files := offsetLogFiles(t, volume, 0, 3, false)
// the first file holds offsets 0..3 in two chunks; the next file holds 4 and 5
volume.Lock()
volume.chunks["/3,00ff"] = volume.chunks["/3,0001"]
volume.Unlock()
files[0].Chunks = append(files[0].Chunks, &filer_pb.FileChunk{FileId: "3,00ff", Size: files[1].Chunks[0].Size})
files[0].Extended[mq.ExtendedAttrOffsetMax] = binary.BigEndian.AppendUint64(nil, 3)
files = []*filer_pb.Entry{files[0], files[2]}
_, client := serveFiler(t, volume, files...)
// parquet is read before the log files, and here holds nothing
noParquet := func(start log_buffer.MessagePosition, _, _ int64, _ log_buffer.EachLogEntryFuncType) (log_buffer.MessagePosition, bool, error) {
return start, false, nil
}
logs := func() logReader {
return newLogReader(client, topic.NewTopic("test", "t"), topic.Partition{RingSize: 2520, RangeStop: 2520, UnixTimeNs: 1})
}
for _, stopAt := range []int64{0, 2, 3} {
read := mergeReadFuncs(logs(), noParquet)
volume.Lock()
clear(volume.fetched)
volume.Unlock()
var got []int64
position, isDone, err := read(log_buffer.NewMessagePositionFromOffset(0), 0, func(logEntry *filer_pb.LogEntry) (bool, error) {
got = append(got, logEntry.Offset)
return logEntry.Offset == stopAt, nil
})
if err != nil {
t.Fatal(err)
}
if want := offsetsFrom(0, stopAt+1); !slices.Equal(got, want) || !isDone {
t.Errorf("stopping at %d read %v done %v, want %v done", stopAt, got, isDone, want)
}
if position.Offset != stopAt+1 {
t.Errorf("stopping at %d returned offset %d", stopAt, position.Offset)
}
if stopAt < 2 && volume.fetchCount("3,00ff") != 0 {
t.Errorf("stopping at %d fetched the next chunk", stopAt)
}
if volume.fetchCount("3,0002") != 0 {
t.Errorf("stopping at %d fetched the next file", stopAt)
}
}
var got []int64
position, isDone, err := mergeReadFuncs(logs(), noParquet)(log_buffer.NewMessagePosition(1, -2), 0, func(logEntry *filer_pb.LogEntry) (bool, error) {
got = append(got, logEntry.TsNs)
return len(got) == 3, nil
})
if err != nil {
t.Fatal(err)
}
// the unread files record no first message, so only the start is known to skip nothing
if len(got) != 3 || !isDone || position.Time.UnixNano() != 1 {
t.Errorf("by time read %v done %v, position %d", got, isDone, position.Time.UnixNano())
}
}
+129 -61
View File
@@ -1,11 +1,13 @@
package logstore
import (
"bytes"
"cmp"
"context"
"encoding/binary"
"fmt"
"io"
"math"
"slices"
"strings"
"github.com/parquet-go/parquet-go"
@@ -53,7 +55,18 @@ func isControlEntry(logEntry *filer_pb.LogEntry) bool {
return false
}
// parquetReadFunc reads a partition's parquet files, leaving out rows at or past
// endOffset; an offset read also leaves out those below startPosition's offset.
type parquetReadFunc func(startPosition log_buffer.MessagePosition, endOffset, stopTsNs int64, eachLogEntryFn log_buffer.EachLogEntryFuncType) (log_buffer.MessagePosition, bool, error)
func GenParquetReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p topic.Partition) log_buffer.LogReadFromDiskFuncType {
readParquet := newParquetReader(filerClient, t, p)
return func(startPosition log_buffer.MessagePosition, stopTsNs int64, eachLogEntryFn log_buffer.EachLogEntryFuncType) (log_buffer.MessagePosition, bool, error) {
return readParquet(startPosition, math.MaxInt64, stopTsNs, eachLogEntryFn)
}
}
func newParquetReader(filerClient filer_pb.FilerClient, t topic.Topic, p topic.Partition) parquetReadFunc {
partitionDir := topic.PartitionDir(t, p)
lookupFileIdFn := filer.LookupFn(filerClient)
@@ -66,8 +79,8 @@ func GenParquetReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p topic
return err
}); err != nil {
// Return a no-op function for test environments or when topic config can't be read
return func(startPosition log_buffer.MessagePosition, stopTsNs int64, eachLogEntryFn log_buffer.EachLogEntryFuncType) (log_buffer.MessagePosition, bool, error) {
return startPosition, true, nil
return func(startPosition log_buffer.MessagePosition, endOffset, stopTsNs int64, eachLogEntryFn log_buffer.EachLogEntryFuncType) (log_buffer.MessagePosition, bool, error) {
return startPosition, false, nil
}
}
// Get schema - prefer flat schema if available
@@ -79,10 +92,12 @@ func GenParquetReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p topic
if recordType == nil || len(recordType.Fields) == 0 {
// Return a no-op function if no schema is available
return func(startPosition log_buffer.MessagePosition, stopTsNs int64, eachLogEntryFn log_buffer.EachLogEntryFuncType) (log_buffer.MessagePosition, bool, error) {
return startPosition, true, nil
return func(startPosition log_buffer.MessagePosition, endOffset, stopTsNs int64, eachLogEntryFn log_buffer.EachLogEntryFuncType) (log_buffer.MessagePosition, bool, error) {
return startPosition, false, nil
}
}
// compaction keeps a schemaless message's bytes as they were in _value
isSchemaless := isSchemalessRecordType(recordType)
// files compacted before the _offset column existed lack it, and a row is read by column position
recordTypeWithoutOffset := schema.NewRecordTypeBuilder(proto.Clone(recordType).(*schema_pb.RecordType)).
WithField(SW_COLUMN_NAME_TS, schema.TypeInt64).
@@ -93,21 +108,25 @@ func GenParquetReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p topic
RecordTypeEnd()
parquetLevels, err := schema.ToParquetLevels(recordType)
if err != nil {
return nil
var parquetLevelsWithoutOffset *schema.ParquetLevels
if err == nil {
parquetLevelsWithoutOffset, err = schema.ToParquetLevels(recordTypeWithoutOffset)
}
parquetLevelsWithoutOffset, err := schema.ToParquetLevels(recordTypeWithoutOffset)
if err != nil {
return nil
// a read that needs these rows fails rather than skipping them
setupErr := fmt.Errorf("parquet schema of %s: %w", t, err)
return func(startPosition log_buffer.MessagePosition, endOffset, stopTsNs int64, eachLogEntryFn log_buffer.EachLogEntryFuncType) (log_buffer.MessagePosition, bool, error) {
return startPosition, false, setupErr
}
}
// eachFileFn reads a parquet file and calls eachLogEntryFn for each log entry
eachFileFn := func(entry *filer_pb.Entry, eachLogEntryFn log_buffer.EachLogEntryFuncType, starTsNs, stopTsNs int64) (processedTsNs int64, err error) {
eachFileFn := func(entry *filer_pb.Entry, eachLogEntryFn log_buffer.EachLogEntryFuncType, starTsNs, stopTsNs int64, startOffset, endOffset int64, isOffsetBased bool) (processedTsNs int64, isDone bool, err error) {
// create readerAt for the parquet file
fileSize := filer.FileSize(entry)
visibleIntervals, err := filer.NonOverlappingVisibleIntervals(context.Background(), lookupFileIdFn, entry.Chunks, 0, int64(fileSize))
if err != nil {
return 0, fmt.Errorf("resolve chunks of %s: %w", entry.Name, err)
return 0, false, fmt.Errorf("resolve chunks of %s: %w", entry.Name, err)
}
chunkViews := filer.ViewFromVisibleIntervals(visibleIntervals, 0, int64(fileSize))
readerCache := filer.NewReaderCache(32, chunkCache, lookupFileIdFn, nil)
@@ -122,6 +141,7 @@ func GenParquetReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p topic
}
// a row's offset is real only where the file records its range; -1 keeps it out of offset reads
hasOffsets := hasOffsetColumn && len(entry.Extended[mq.ExtendedAttrOffsetMin]) == 8
var eligible []*filer_pb.LogEntry
rows := make([]parquet.Row, 128)
for {
rowCount, readErr := parquetReader.ReadRows(rows)
@@ -132,29 +152,33 @@ func GenParquetReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p topic
// convert parquet row to schema_pb.RecordValue
recordValue, err := schema.ToRecordValue(fileRecordType, fileLevels, row)
if err != nil {
return processedTsNs, fmt.Errorf("ToRecordValue failed: %w", err)
return processedTsNs, false, fmt.Errorf("ToRecordValue failed: %w", err)
}
processedTsNs = recordValue.Fields[SW_COLUMN_NAME_TS].GetInt64Value()
if processedTsNs <= starTsNs {
tsNs := recordValue.Fields[SW_COLUMN_NAME_TS].GetInt64Value()
if tsNs <= starTsNs || (stopTsNs != 0 && tsNs > stopTsNs) {
continue
}
if stopTsNs != 0 && processedTsNs >= stopTsNs {
return processedTsNs, nil
}
data, marshalErr := proto.Marshal(recordValue)
if marshalErr != nil {
return processedTsNs, fmt.Errorf("marshal record value: %w", marshalErr)
}
offset := int64(-1)
if offsetValue := recordValue.Fields[SW_COLUMN_NAME_OFFSET]; hasOffsets && offsetValue != nil {
offset = offsetValue.GetInt64Value()
}
// rows below the offset must not reach a callback that stops after so many it cannot use
if (isOffsetBased && offset < startOffset) || offset >= endOffset {
continue
}
// rows are kept past the next ReadRows, which may reuse the bytes they point into
var data []byte
if isSchemaless {
data = bytes.Clone(recordValue.Fields[SW_COLUMN_NAME_VALUE].GetBytesValue())
} else if data, err = proto.Marshal(recordValue); err != nil {
return processedTsNs, false, fmt.Errorf("marshal record value: %w", err)
}
logEntry := &filer_pb.LogEntry{
Key: recordValue.Fields[SW_COLUMN_NAME_KEY].GetBytesValue(),
TsNs: processedTsNs,
Key: bytes.Clone(recordValue.Fields[SW_COLUMN_NAME_KEY].GetBytesValue()),
TsNs: tsNs,
Data: data,
Offset: offset,
}
@@ -164,33 +188,47 @@ func GenParquetReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p topic
continue
}
// fmt.Printf(" parquet entry %s ts %v\n", string(logEntry.Key), time.Unix(0, logEntry.TsNs).UTC())
if _, err = eachLogEntryFn(logEntry); err != nil {
return processedTsNs, fmt.Errorf("process log entry %v: %w", logEntry, err)
}
eligible = append(eligible, logEntry)
}
// Check for end conditions after processing rows
if readErr == io.EOF || (readErr == nil && rowCount == 0) {
break
}
if readErr != nil {
if readErr == io.EOF {
return processedTsNs, nil
}
return processedTsNs, readErr
}
if rowCount == 0 {
return processedTsNs, nil
return 0, false, readErr
}
}
// rows of windows flushed across a reload are not in time order, and compaction
// wrote sources in name order; delivered in order, what a stopped read delivered
// is all of the file up to where it stopped
if isOffsetBased {
slices.SortStableFunc(eligible, func(a, b *filer_pb.LogEntry) int { return cmp.Compare(a.Offset, b.Offset) })
} else {
slices.SortStableFunc(eligible, func(a, b *filer_pb.LogEntry) int { return cmp.Compare(a.TsNs, b.TsNs) })
}
for _, logEntry := range eligible {
if isDone, err = eachLogEntryFn(logEntry); err != nil {
return processedTsNs, false, fmt.Errorf("process log entry %v: %w", logEntry, err)
}
processedTsNs = max(processedTsNs, logEntry.TsNs)
if isDone {
return processedTsNs, true, nil
}
}
return processedTsNs, false, nil
}
return func(startPosition log_buffer.MessagePosition, stopTsNs int64, eachLogEntryFn log_buffer.EachLogEntryFuncType) (lastReadPosition log_buffer.MessagePosition, isDone bool, err error) {
startFileName := startPosition.Time.UTC().Format(topic.TIME_FORMAT)
index := &logFileIndex{}
return func(startPosition log_buffer.MessagePosition, endOffset, stopTsNs int64, eachLogEntryFn log_buffer.EachLogEntryFuncType) (lastReadPosition log_buffer.MessagePosition, isDone bool, err error) {
startTsNs := startPosition.Time.UnixNano()
isOffsetBased, startOffset := startPosition.IsOffsetBased, startPosition.Offset
var processedTsNs int64
var candidateFiles, listed []*filer_pb.Entry
// a file is named after its first source log, so one named before the resume
// second can still hold later rows; list from where every earlier file ends before it
err = filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
return filer_pb.SeaweedList(context.Background(), client, partitionDir, "", func(entry *filer_pb.Entry, isLast bool) error {
if entry.IsDirectory {
return nil
@@ -198,40 +236,70 @@ func GenParquetReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p topic
if !strings.HasSuffix(entry.Name, ".parquet") {
return nil
}
if len(entry.Extended) == 0 {
listed = append(listed, entry)
minTsNs, hasMin := logFileTsNs(entry, mq.ExtendedAttrTimestampMin)
maxTsNs, hasMax := logFileTsNs(entry, mq.ExtendedAttrTimestampMax)
if !hasMin || !hasMax {
return nil
}
// read minTs from the parquet file
minTsBytes := entry.Extended[mq.ExtendedAttrTimestampMin]
if len(minTsBytes) != 8 {
return nil
}
minTsNs := int64(binary.BigEndian.Uint64(minTsBytes))
// read max ts
maxTsBytes := entry.Extended[mq.ExtendedAttrTimestampMax]
if len(maxTsBytes) != 8 {
return nil
}
maxTsNs := int64(binary.BigEndian.Uint64(maxTsBytes))
if stopTsNs != 0 && stopTsNs <= minTsNs {
isDone = true
if stopTsNs != 0 && stopTsNs < minTsNs {
return nil
}
if maxTsNs < startTsNs {
return nil
}
if processedTsNs, err = eachFileFn(entry, eachLogEntryFn, startTsNs, stopTsNs); err != nil {
return err
minOffset, maxOffset, ok := logFileOffsets(entry)
if isOffsetBased && (!ok || maxOffset < startOffset) {
return nil
}
if ok && minOffset >= endOffset {
return nil
}
candidateFiles = append(candidateFiles, entry)
return nil
}, startFileName, true, math.MaxInt32)
}, index.markBefore(startTsNs), true, math.MaxInt32)
})
if err != nil {
return startPosition, false, err
}
index.add(listed)
if isOffsetBased {
sortByOffset(candidateFiles)
}
nextOffset := int64(-1)
lastDeliveredTsNs, lastDeliveredOffset := startTsNs, startOffset-1
deliver := func(logEntry *filer_pb.LogEntry) (bool, error) {
nextOffset = max(nextOffset, logEntry.Offset+1)
lastDeliveredTsNs, lastDeliveredOffset = logEntry.TsNs, logEntry.Offset
return eachLogEntryFn(logEntry)
}
for i, entry := range candidateFiles {
var fileTsNs int64
fileTsNs, isDone, err = eachFileFn(entry, deliver, startTsNs, stopTsNs, startOffset, endOffset, isOffsetBased)
processedTsNs = max(processedTsNs, fileTsNs)
if err != nil || isDone {
// a failed file may have delivered none of its rows
unread := candidateFiles[i+1:]
if err != nil {
unread = candidateFiles[i:]
}
if isOffsetBased {
return log_buffer.NewMessagePositionFromOffset(stoppedReadOffset(startOffset, lastDeliveredOffset, unread)), isDone, err
}
return log_buffer.NewMessagePosition(stoppedReadTsNs(startTsNs, lastDeliveredTsNs, unread), -2), isDone, err
}
}
if isOffsetBased {
lastReadPosition = startPosition
if nextOffset > startOffset {
lastReadPosition = log_buffer.NewMessagePositionFromOffset(nextOffset)
}
return
}
lastReadPosition = log_buffer.NewMessagePosition(processedTsNs, -2)
return
}
+15 -1
View File
@@ -13,11 +13,12 @@ import (
)
// OffsetRange accumulates the offset ranges recorded on a partition's files,
// and the newest start second a log file is named by.
// the newest start second a log file is named by, and the newest message time.
type OffsetRange struct {
earliest, latest int64
hasEarliest, hasLatest bool
newestLogFileTime time.Time
newestTsNs int64
// data files that record no range, which may hold offsets below every recorded one
unrangedLog bool
unrangedParquet [][]string
@@ -49,6 +50,12 @@ func (r *OffsetRange) Add(entry *filer_pb.Entry) {
r.latest, r.hasLatest = v, true
}
}
if b := extended[ExtendedAttrTimestampMax]; len(b) == 8 {
r.newestTsNs = max(r.newestTsNs, int64(binary.BigEndian.Uint64(b)))
} else if mtime := entry.GetAttributes().GetMtime(); notDataErr == nil && mtime > 0 {
// an older file was written after its messages were stamped, within its mtime's second
r.newestTsNs = max(r.newestTsNs, time.Unix(mtime+1, 0).UnixNano())
}
// compacted files, the fence and other entries do not parse as log file names
if t, err := topic.ParseLogFileTime(entry.Name); err == nil && t.After(r.newestLogFileTime) {
r.newestLogFileTime = t
@@ -77,6 +84,13 @@ func (r *OffsetRange) NewestLogFileTime() time.Time {
return r.newestLogFileTime
}
// NewestTsNs bounds the stored messages' times: the latest a log or parquet file
// records, or for a file recording none, the end of the second it was written in.
// A message whose time a client set later than its file was written is not bounded.
func (r *OffsetRange) NewestTsNs() int64 {
return r.newestTsNs
}
func (r *OffsetRange) hasUnknownOffsets() bool {
if r.unrangedLog {
return true
+9 -6
View File
@@ -84,12 +84,14 @@ func (e *SQLEngine) getSystemColumnGlobalMin(columnName string, allFileStats map
switch lowerName {
case SW_COLUMN_NAME_TIMESTAMP:
// For timestamps, find the earliest timestamp across all files
// This should match what's in the Extended[mq.ExtendedAttrTimestampMin] metadata
var minTimestamp *int64
for _, fileStats := range allFileStats {
for _, fileStat := range fileStats {
// Extract timestamp from filename (format: YYYY-MM-DD-HH-MM-SS.parquet)
timestamp := e.extractTimestampFromFilename(fileStat.FileName)
// a name is only the start second of the file's first source log
timestamp := fileStat.MinTimestampNs
if timestamp == 0 {
timestamp = e.extractTimestampFromFilename(fileStat.FileName)
}
if timestamp != 0 {
if minTimestamp == nil || timestamp < *minTimestamp {
minTimestamp = &timestamp
@@ -121,12 +123,13 @@ func (e *SQLEngine) getSystemColumnGlobalMax(columnName string, allFileStats map
switch lowerName {
case SW_COLUMN_NAME_TIMESTAMP:
// For timestamps, find the latest timestamp across all files
// This should match what's in the Extended[mq.ExtendedAttrTimestampMax] metadata
var maxTimestamp *int64
for _, fileStats := range allFileStats {
for _, fileStat := range fileStats {
// Extract timestamp from filename (format: YYYY-MM-DD-HH-MM-SS.parquet)
timestamp := e.extractTimestampFromFilename(fileStat.FileName)
timestamp := fileStat.MaxTimestampNs
if timestamp == 0 {
timestamp = e.extractTimestampFromFilename(fileStat.FileName)
}
if timestamp != 0 {
if maxTimestamp == nil || timestamp > *maxTimestamp {
maxTimestamp = &timestamp
+32
View File
@@ -0,0 +1,32 @@
package engine
import (
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
)
// A file's name is the start second of its first source log; MIN and MAX of _ts
// come from the timestamp range the file records, and from names only without one.
func TestSystemColumnTimestampRangePrefersFileStats(t *testing.T) {
base := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
stats := map[string][]*ParquetFileStats{
"p0": {
{FileName: topic.LogFileName(base, 0) + ".parquet", MinTimestampNs: base.Add(500 * time.Millisecond).UnixNano(), MaxTimestampNs: base.Add(9 * time.Second).UnixNano()},
{FileName: topic.LogFileName(base.Add(5*time.Second), 4) + ".parquet"},
},
}
e := &SQLEngine{}
if got, want := e.getSystemColumnGlobalMin(SW_COLUMN_NAME_TIMESTAMP, stats), base.Add(500*time.Millisecond).UnixNano(); got != want {
t.Errorf("min %v, want %v", got, want)
}
if got, want := e.getSystemColumnGlobalMax(SW_COLUMN_NAME_TIMESTAMP, stats), base.Add(9*time.Second).UnixNano(); got != want {
t.Errorf("max %v, want %v", got, want)
}
stats["p0"] = stats["p0"][1:]
if got, want := e.getSystemColumnGlobalMax(SW_COLUMN_NAME_TIMESTAMP, stats), base.Add(5*time.Second).UnixNano(); got != want {
t.Errorf("max without stats %v, want the name's %v", got, want)
}
}