mq: enforce topic retention (#13210)

* log_buffer: find a fetched offset in a disk chunk by its offset

A stateless read caches disk reads in chunks aligned to 1000 offsets and
picked the requested message by its distance from the aligned start. A
chunk read from disk begins at the first offset stored at or above that
start, so once the partition's oldest files are gone the chunk begins
later and the read returned messages from further on, under the
requested offsets. The message is now found by its offset, and the next
offset follows the last message returned.

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

* mq broker: start a loaded partition's log at its earliest stored offset

A loaded partition reported its earliest offset as 0 and its log start as
the start of its memory, so neither said where the stored data begins. The
log buffer now keeps the earliest offset still stored: a leader seeds it
from the offset ranges on its files when it loads, it only moves up, and
the partition's offset info and log start report it. A stateless read
below it fails with ErrOffsetOutOfRange instead of being answered from a
later file under the requested offsets.

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

* mq broker: purge a partition's files past its topic's retention

A topic's retention was stored but never applied, so a topic that is not
re-partitioned kept every flushed file. Every five minutes the broker now
purges each partition it leads whose topic has retention enabled. It
deletes the oldest run of files whose newest message is older than the
retention, stopping at the first file still retained so the stored
offsets stay contiguous, and always keeps the file with the highest
offset, which a later load continues offsets from. A log file is judged
by when it was flushed and a parquet file by its newest row; a parquet
file is deleted together with its source log files. The partition's log
start is raised before the deletes, and each delete is a transaction
conditioned on the partition's fence token, so a leader that lost its
fence deletes nothing.

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

* mq/kafka: map an unknown broker error to UNKNOWN_SERVER_ERROR (-1)

The gateway's error table gave UNKNOWN_SERVER_ERROR the code 1, which
Kafka uses for OFFSET_OUT_OF_RANGE, and the broker's table carried the
same value for its unknown and publisher-not-found errors. Today the
mapped code only reaches error text, but a fetch path that answers
OFFSET_OUT_OF_RANGE by its Kafka code would make every unknown broker
failure reset a consumer. The code is now -1. The gateway only tests
these codes against 0 and against specific codes, and the cached
assignment is still dropped on the broker's own code 1, so nothing
treated 1 as success or depended on it.

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

* mq: answer a fetch below retention with OFFSET_OUT_OF_RANGE

A read below the earliest retained offset failed like any other read, so
FetchMessage reported a storage error and the gateway answered
KAFKA_STORAGE_ERROR, which a consumer retries at the same offset forever
once retention has purged it. FetchMessage now answers
ErrOffsetOutOfRange with its own broker code, the earliest retained
offset as LogStartOffset, and the requested offset as NextOffset. The
gateway carries it as ErrOffsetOutOfRange and answers the partition with
OFFSET_OUT_OF_RANGE, so the consumer applies auto.offset.reset; a reset
to earliest asks ListOffsets, which reports the retained start through
the leader's range info.

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

* log_buffer: keep a disk chunk's entries in offset order

A disk read filled its 1000-offset chunk with the first 1000 entries
in the order the files listed, and the lookup searches the chunk by
offset. Files whose names sort out of offset order deliver entries out
of order, so the chunk held the wrong offsets and was cached that way.
It now keeps only the chunk's offsets, wherever they come, and sorts
them before caching.

* mq broker: purge a partition's files in offset order

The purge walked a partition's files in name order and stopped at the
first one still retained. Names sort by the start of a window, which can
be earlier than older files' after a reload, so a file holding higher
offsets could be purged ahead of a retained one below it, leaving a hole.
The walk now goes by each file's first offset, taking a parquet file that
records none from its first source, and by name among equals.

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

* mq broker: round a log file's flush time up to bound its messages

A log file without a recorded newest timestamp is judged by its Mtime,
which the filer keeps in whole seconds, so a file flushed later in the
cutoff's second looked older than messages it may hold. The purge now
takes the end of that second as the bound. A recorded newest timestamp
is still used as is.

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

* log_buffer: keep one entry per offset in a disk chunk

A disk read goes through a partition's log files and then its parquet
files, and a parquet file holds the same offsets as the log files it was
compacted from, so a chunk could take an offset twice and a fetch
returned the duplicate as the next message. The chunk now keeps the
first entry for each offset.

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

* log_buffer: reread a cached disk chunk that lacks the fetched offset

A disk chunk can be cached while its later offsets are still in memory.
Once those are flushed and memory moves on, a fetch past the cached part
hit the cache, found nothing, and returned no messages until the chunk
was evicted. A cached chunk that does not hold the fetched offset is now
dropped and read from disk again.

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

* mq/logstore: record a parquet file's offset range from its sources

The compactor took a parquet file's offset range from its entries'
offsets above 0 and recorded it only when the lowest was above 0, so a
file compacted from a partition's first window recorded no range, and one
whose entries started at 0 would have claimed to start at 1. The range
now comes from the source log files' recorded ranges, including one that
starts at offset 0, and is left out unless every source records one.

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

* mq: keep the earliest offset at or below files that record no range

The earliest stored offset was the lowest offset any file records, so a
file that records none, such as a parquet file compacted from a
partition's first window or a log file flushed without a range, was left
out. A reload or a purge could then start the log above offsets a read
can still return, and ListOffsets for the earliest offset left them out.
OffsetRange now takes the whole entry and keeps the earliest offset at 0
while a log or parquet file records no range, except a parquet file whose
listed sources are all present, as their ranges cover it.

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

* mq broker: keep a partition whose files cannot all be placed by offset

The purge ordered a data file that records no offsets, and whose
sources give none, as if it held the lowest, so an expired one could
be deleted while a retained file below its offsets stayed, leaving a
hole. A partition holding such a file is now left alone; only files
written before offsets were recorded lack them.

* mq broker: purge a parquet file only when each of its sources has expired

The purge deleted every source of an expired parquet file along with it,
judging the whole group by the parquet file's newest timestamp. Message
timestamps are not ordered across reloads, so a parquet file can hold an
expired source next to one still retained, and the retained one went
early. A parquet group is now purged only when the parquet file and each
source in it are past the cutoff on their own; otherwise the walk stops
there.

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

* mq/logstore: record a parquet file's lowest and highest timestamps

The compactor recorded a parquet file's timestamp range from its first
and last rows. Message timestamps are not ordered across reloads, so the
last row need not be the newest, and the recorded ts_max could sit below
messages the file holds, making it look older to the retention purge and
to readers that skip files by time. It now records the lowest and
highest timestamps over all rows.

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

* mq/logstore: keep each compacted row's offset in the _offset column

The compaction schema had no _offset column, so a schematized row's
offset was dropped and a schemaless row never carried one, while the
parquet reader expects the column and a fetch places rows by offset. The
compactor now adds the column when the schema lacks it and fills it for
every row, schemaless ones included, when the source files record their
offsets; otherwise it is left null.

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

* mq/logstore: read a parquet file by its own columns and mark unknown offsets

The parquet reader always expected an _offset column and read rows by
column position, so a file compacted before the column existed was read
out of alignment and panicked with an index out of range. A row with no
real offset also read back as offset 0, so a disk chunk, which keeps one
entry per offset, collapsed such rows into one. The reader now uses the
_offset column only when the file has it, trusts it only when the file
records its offset range, and reports any other row with offset -1,
which keeps it out of reads by offset.

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

* mq broker: keep a purge group that reaches past the first retained offset

A parquet file is purged with its sources as one group, and the sources
need not be contiguous: an expired parquet file could list expired files
on both sides of a retained one, so purging the group left a hole above
the retained file. A group now goes only when every offset it and its
sources cover lies below the first offset left behind; the walk keeps the
first group that does not, and the ones after it. A log file whose
offsets a retained parquet file also starts at now stays until that
parquet file goes.

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

* mq/logstore: give compaction test fixtures file ids no other fixture uses

The parquet reader caches chunks in a package-wide cache keyed by file
id, and each compaction fixture numbered its file ids from 1, so one
fixture could read another's cached bytes; with -count=3 a test read a
parquet file from an earlier run and failed. File ids are now numbered
across all fixtures.

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

* mq/logstore: compact legacy log files apart from ones that record offsets

A compaction group could hold a legacy log file without an offset range
next to files that record one, and a parquet file keeps its rows'
offsets only when every source records them, so the ranged rows lost
their offsets and could no longer be fetched by offset. Groups now split
where a file's having an offset range differs from the group's.

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

* mq broker: treat a parquet file's end as unknown when a source is gone

A parquet file that records no offset range took its last offset from
the sources still present, so one whose later source was already gone
looked as if it ended below a retained file and was purged, though it
may hold that source's offsets above the retained one. A gone or
unranged source now leaves the end unknown, and the group stays.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Chris LuandClaude Opus 5.5 authored and GitHub committed 2026-12-01 10:18:45 -08:00
1 parent d63c225d78
commit 746cae3895
28 files changed
+1592 -137

No files matched your search

+9 -3
View File
@@ -21,6 +21,8 @@ const (
BrokerErrorInvalidPartitions int32 = 37
BrokerErrorInvalidConfig int32 = 40
BrokerErrorStorageError int32 = 56
// Kafka's code 1, which here is BrokerErrorUnknownServerError
BrokerErrorOffsetOutOfRange int32 = 104
// Publisher/connection errors
BrokerErrorPublisherNotFound int32 = 100
@@ -46,7 +48,7 @@ var BrokerErrors = map[int32]BrokerErrorInfo{
},
BrokerErrorUnknownServerError: {
Code: BrokerErrorUnknownServerError, Name: "UNKNOWN_SERVER_ERROR",
Description: "Unknown server error", KafkaCode: 1,
Description: "Unknown server error", KafkaCode: -1,
},
BrokerErrorTopicNotFound: {
Code: BrokerErrorTopicNotFound, Name: "TOPIC_NOT_FOUND",
@@ -100,9 +102,13 @@ var BrokerErrors = map[int32]BrokerErrorInfo{
Code: BrokerErrorStorageError, Name: "KAFKA_STORAGE_ERROR",
Description: "Stored messages could not be read", KafkaCode: 56,
},
BrokerErrorOffsetOutOfRange: {
Code: BrokerErrorOffsetOutOfRange, Name: "OFFSET_OUT_OF_RANGE",
Description: "Offset is below the earliest retained offset", KafkaCode: 1,
},
BrokerErrorPublisherNotFound: {
Code: BrokerErrorPublisherNotFound, Name: "PUBLISHER_NOT_FOUND",
Description: "Publisher not found", KafkaCode: 1, // UNKNOWN_SERVER_ERROR
Description: "Publisher not found", KafkaCode: -1, // UNKNOWN_SERVER_ERROR
},
BrokerErrorConnectionFailed: {
Code: BrokerErrorConnectionFailed, Name: "CONNECTION_FAILED",
@@ -124,7 +130,7 @@ func GetBrokerErrorInfo(code int32) BrokerErrorInfo {
return info
}
return BrokerErrorInfo{
Code: code, Name: "UNKNOWN", Description: "Unknown broker error code", KafkaCode: 1,
Code: code, Name: "UNKNOWN", Description: "Unknown broker error code", KafkaCode: -1,
}
}
+13 -1
View File
@@ -2,11 +2,13 @@ package broker
import (
"context"
"errors"
"fmt"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
)
// FetchMessage implements Kafka-style stateless message fetching
@@ -121,8 +123,18 @@ func (b *MessageQueueBroker) FetchMessage(ctx context.Context, req *mq_pb.FetchM
nextOffset, endOfPartition, localPartition.LogBuffer.GetLogStartOffset())
}
if errors.Is(err, log_buffer.ErrOffsetOutOfRange) {
glog.V(1).Infof("[FetchMessage] %s/%s partition=%v: %v", t.Namespace, t.Name, partition, err)
return &mq_pb.FetchMessageResponse{
HighWaterMark: highWaterMark,
LogStartOffset: localPartition.LogBuffer.GetLogStartOffset(),
NextOffset: requestedOffset,
Error: err.Error(),
ErrorCode: BrokerErrorOffsetOutOfRange,
}, nil
}
if err != nil {
// Offsets below the buffer are on disk, so a failed read is never out of range; retry at the same offset.
// Any other failed read is retried at the same offset.
glog.Errorf("[FetchMessage] %s/%s partition=%v read at offset %d: %v", t.Namespace, t.Name, partition, requestedOffset, err)
return &mq_pb.FetchMessageResponse{
HighWaterMark: highWaterMark,
+38
View File
@@ -75,3 +75,41 @@ func TestFetchMessageMissingPartitionKeepsRequestedOffset(t *testing.T) {
t.Errorf("next offset %d after a failed fetch at 10", resp.NextOffset)
}
}
// A fetch below the earliest retained offset is out of range, not a storage
// error to retry, and the range info reports where the retained log starts.
func TestFetchBelowRetentionIsOutOfRange(t *testing.T) {
b := newUnelectedBroker()
b.localTopicManager = topic.NewLocalTopicManager()
tp := topic.NewTopic("test", "t")
partition := topic.Partition{RingSize: 2520, RangeStart: 0, RangeStop: 2520, UnixTimeNs: time.Now().UnixNano()}
b.topicCache = map[string]*topicCacheEntry{tp.String(): {conf: &mq_pb.ConfigureTopicResponse{}, expiresAt: time.Now().Add(time.Hour)}}
lp := topic.NewLocalPartition(partition, 3600, nil, nil)
defer lp.Shutdown()
if err := lp.LogBuffer.InitializeOffsetFromExistingData(func() (int64, error) { return 41, nil }); err != nil {
t.Fatal(err)
}
// a purge left offsets 30..41 on disk
lp.LogBuffer.SetLogStartOffset(30)
b.localTopicManager.AddLocalPartition(tp, lp)
pbTopic := &schema_pb.Topic{Namespace: tp.Namespace, Name: tp.Name}
pbPartition := &schema_pb.Partition{RingSize: partition.RingSize, RangeStart: partition.RangeStart, RangeStop: partition.RangeStop, UnixTimeNs: partition.UnixTimeNs}
resp, err := b.FetchMessage(context.Background(), &mq_pb.FetchMessageRequest{Topic: pbTopic, Partition: pbPartition, StartOffset: 10})
if err != nil {
t.Fatal(err)
}
if resp.ErrorCode != BrokerErrorOffsetOutOfRange || resp.LogStartOffset != 30 || resp.NextOffset != 10 || len(resp.Messages) != 0 {
t.Errorf("fetch at 10: code %d (%q), log start %d, next %d, %d messages; want out of range, log start 30, next 10",
resp.ErrorCode, resp.Error, resp.LogStartOffset, resp.NextOffset, len(resp.Messages))
}
info, err := b.GetPartitionRangeInfo(context.Background(), &mq_pb.GetPartitionRangeInfoRequest{Topic: pbTopic, Partition: pbPartition})
if err != nil {
t.Fatal(err)
}
if info.Error != "" || info.OffsetRange.GetEarliestOffset() != 30 || info.OffsetRange.GetHighWaterMark() != 42 {
t.Errorf("range info %v, want earliest 30, high water mark 42", info)
}
}
+3 -1
View File
@@ -5,10 +5,12 @@ import (
)
// GetPartitionOffsetInfoInternal reports offsets from the loaded partition's buffer, which
// assigns them, or from the ranges stored on disk when this broker has not loaded it.
// assigns them and tracks the earliest one retained, or from the ranges stored on disk
// when this broker has not loaded it.
func (b *MessageQueueBroker) GetPartitionOffsetInfoInternal(t topic.Topic, p topic.Partition) (*PartitionOffsetInfo, error) {
var earliestOffset, highWaterMark, activeSubscriptions int64
if localPartition := b.localTopicManager.GetLocalPartition(t, p); localPartition != nil {
earliestOffset = localPartition.LogBuffer.GetLogStartOffset()
highWaterMark = localPartition.LogBuffer.GetOffset()
activeSubscriptions = int64(localPartition.Subscribers.Size())
} else {
@@ -2,6 +2,7 @@ package broker
import (
"encoding/binary"
"errors"
"testing"
"time"
@@ -10,8 +11,37 @@ import (
"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/log_buffer"
)
// A loaded partition starts its log at the earliest offset still stored, so a
// read below it is out of range rather than answered from a later file.
func TestLoadedPartitionStartsAtTheEarliestStoredOffset(t *testing.T) {
f, b := newFencingFiler(t)
b.localTopicManager = topic.NewLocalTopicManager()
start := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
f.putLogFile(start, 100, 199, start)
f.putLogFile(start.Add(time.Minute), 200, 299, start.Add(time.Minute))
lp, err := b.newLeaderPartition(fenceTestTopic, fenceTestPartition, &mq_pb.BrokerPartitionAssignment{Partition: fenceTestPartition.ToPbPartition(), Epoch: 1})
if err != nil {
t.Fatal(err)
}
defer lp.LogBuffer.ShutdownLogBuffer()
b.localTopicManager.AddLocalPartition(fenceTestTopic, lp)
info, err := b.GetPartitionOffsetInfoInternal(fenceTestTopic, fenceTestPartition)
if err != nil {
t.Fatal(err)
}
if info.EarliestOffset != 100 || info.HighWaterMark != 300 || info.RecordCount != 200 {
t.Fatalf("info = %+v, want earliest 100, hwm 300, count 200", info)
}
if _, _, _, _, err := lp.LogBuffer.ReadMessagesAtOffset(50, 10, 1<<20); !errors.Is(err, log_buffer.ErrOffsetOutOfRange) {
t.Fatalf("read below the earliest stored offset: %v", err)
}
}
// A loaded partition's buffer assigns offsets, so it is the high water mark.
func TestPartitionOffsetInfoFromLoadedBuffer(t *testing.T) {
b := newUnelectedBroker()
+3 -3
View File
@@ -272,9 +272,9 @@ func fenceTokenCondition(token string) *filer_pb.WriteCondition_Clause {
return &filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_ETAG_MATCH, Etags: []string{token}}
}
// fencedTransaction applies mutation on the filer owning the fence while condition
// fencedTransaction applies mutations on the filer owning the fence while condition
// holds on the fence entry; a failed condition is errFenceLost.
func (b *MessageQueueBroker) fencedTransaction(ctx context.Context, fencePath string, condition *filer_pb.WriteCondition_Clause, requestId string, mutation *filer_pb.ObjectMutation) error {
func (b *MessageQueueBroker) fencedTransaction(ctx context.Context, fencePath string, condition *filer_pb.WriteCondition_Clause, requestId string, mutations ...*filer_pb.ObjectMutation) error {
var resp *filer_pb.ObjectTransactionResponse
err := b.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) (err error) {
resp, err = client.ObjectTransaction(ctx, &filer_pb.ObjectTransactionRequest{
@@ -282,7 +282,7 @@ func (b *MessageQueueBroker) fencedTransaction(ctx context.Context, fencePath st
RouteKey: s3_constants.ObjectWriteRouteKeyPrefix + fencePath,
ConditionKey: fencePath,
Condition: &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{condition}},
Mutations: []*filer_pb.ObjectMutation{mutation},
Mutations: mutations,
RequestId: requestId,
})
return err
@@ -2,6 +2,7 @@ package broker
import (
"context"
"encoding/binary"
"errors"
"io"
"net"
@@ -149,6 +150,10 @@ func (f *fencingFiler) apply(req *filer_pb.ObjectTransactionRequest) *filer_pb.O
}
}
for _, m := range req.Mutations {
if m.Type == filer_pb.ObjectMutation_DELETE {
delete(f.entries, string(util.NewFullPath(m.Directory, m.Name)))
continue
}
stored := proto.Clone(m.Entry).(*filer_pb.Entry)
// the filer fills in attributes the writer did not send
stored.Attributes.Inode = 4242
@@ -179,6 +184,21 @@ func (f *fencingFiler) put(path string, entry *filer_pb.Entry) {
f.entries[path] = entry
}
// putLogFile stores a flushed window of the test partition holding offsets minOffset..maxOffset.
func (f *fencingFiler) putLogFile(start time.Time, minOffset, maxOffset int64, flushedAt time.Time) string {
name := topic.LogFileName(start, minOffset)
f.put(topic.PartitionDir(fenceTestTopic, fenceTestPartition)+"/"+name, &filer_pb.Entry{
Name: name,
Chunks: []*filer_pb.FileChunk{{FileId: "3,01637037d6", Size: 4}},
Attributes: &filer_pb.FuseAttributes{FileSize: 4, Crtime: flushedAt.Unix(), Mtime: flushedAt.Unix()},
Extended: map[string][]byte{
mq.ExtendedAttrOffsetMin: binary.BigEndian.AppendUint64(nil, uint64(minOffset)),
mq.ExtendedAttrOffsetMax: binary.BigEndian.AppendUint64(nil, uint64(maxOffset)),
},
})
return name
}
func newFencingFiler(t *testing.T) (*fencingFiler, *MessageQueueBroker) {
f := &fencingFiler{entries: map[string]*filer_pb.Entry{}, outcome: map[string]*filer_pb.ObjectTransactionResponse{}}
f.volume = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -0,0 +1,272 @@
package broker
import (
"context"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"math"
"slices"
"sort"
"strings"
"time"
"github.com/google/uuid"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/mq"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
)
// retentionPurgeInterval is how often a leader purges its partitions' files past retention.
const retentionPurgeInterval = 5 * time.Minute
// loopPurgeRetention purges the partitions this broker leads past their topic's retention.
func (b *MessageQueueBroker) loopPurgeRetention() {
ticker := time.NewTicker(retentionPurgeInterval)
defer ticker.Stop()
for {
select {
case <-b.ctx.Done():
return
case <-ticker.C:
b.purgeTopicsPastRetention(b.ctx)
}
}
}
func (b *MessageQueueBroker) purgeTopicsPastRetention(ctx context.Context) {
for _, t := range b.localTopicManager.ListTopicsInMemory() {
conf, err := b.getTopicConfFromCache(t)
if err != nil {
continue
}
retention := topicRetention(conf)
if retention <= 0 {
continue
}
for _, assignment := range conf.BrokerPartitionAssignments {
p := b.localTopicManager.GetLocalPartition(t, topic.FromPbPartition(assignment.Partition))
if p == nil || p.Fence == nil {
continue
}
if err := b.purgeExpiredLogFiles(ctx, t, p, time.Now().Add(-retention)); err != nil {
glog.Warningf("purge %s %s past retention %v: %v", t, p.Partition, retention, err)
}
}
}
}
// topicRetention is how long the topic keeps its messages; 0 keeps them forever.
func topicRetention(conf *mq_pb.ConfigureTopicResponse) time.Duration {
if r := conf.GetRetention(); r.GetEnabled() && r.GetRetentionSeconds() > 0 {
return time.Duration(r.GetRetentionSeconds()) * time.Second
}
return 0
}
// purgeExpiredLogFiles deletes the oldest run of files whose newest message is older
// than cutoff, keeping the file with the highest offset, which later loads continue
// from. Each delete requires the fence, so a deposed leader deletes nothing.
func (b *MessageQueueBroker) purgeExpiredLogFiles(ctx context.Context, t topic.Topic, p *topic.LocalPartition, cutoff time.Time) error {
fence := p.Fence
if fence == nil || fence.IsLost() {
return fmt.Errorf("%s %s: %w", t, p.Partition, errFenceLost)
}
partitionDir := topic.PartitionDir(t, p.Partition)
var files []*filer_pb.Entry
err := b.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
return filer_pb.SeaweedList(ctx, client, partitionDir, "", func(entry *filer_pb.Entry, isLast bool) error {
if !entry.IsDirectory {
files = append(files, entry)
}
return nil
}, "", false, math.MaxInt32)
})
if err != nil {
return err
}
sort.Slice(files, func(i, j int) bool { return files[i].Name < files[j].Name })
newest := ""
newestOffset := int64(-1)
present := make(map[string]bool, len(files))
var data []*filer_pb.Entry
for _, entry := range files {
if !isPartitionDataFile(entry.Name) {
continue
}
present[entry.Name] = true
data = append(data, entry)
if offset := extendedInt64(entry.Extended, mq.ExtendedAttrOffsetMax, -1); offset >= newestOffset {
newest, newestOffset = entry.Name, offset
}
}
// names need not sort in offset order, so walk the files by their first offset
firstOffset := make(map[string]int64, len(data))
for _, entry := range data {
firstOffset[entry.Name] = extendedInt64(entry.Extended, mq.ExtendedAttrOffsetMin, -1)
}
for _, entry := range data {
if firstOffset[entry.Name] >= 0 {
continue
}
// a parquet file that records no range starts where its first source does
for _, source := range parquetSources(entry) {
if offset, found := firstOffset[source]; found && offset >= 0 && (firstOffset[entry.Name] < 0 || offset < firstOffset[entry.Name]) {
firstOffset[entry.Name] = offset
}
}
}
for _, entry := range data {
if firstOffset[entry.Name] < 0 {
// without its offsets the oldest run cannot be told apart, so keep everything
glog.V(1).Infof("not purging %s: %s records no offsets", partitionDir, entry.Name)
return nil
}
}
sort.SliceStable(data, func(i, j int) bool { return firstOffset[data[i].Name] < firstOffset[data[j].Name] })
byName := make(map[string]*filer_pb.Entry, len(data))
for _, entry := range data {
byName[entry.Name] = entry
}
expired := func(name string) bool { return newestMessageTime(byName[name]).Before(cutoff) }
var groups [][]string
purged := make(map[string]bool)
for _, entry := range data {
if purged[entry.Name] {
continue
}
if entry.Name == newest || !expired(entry.Name) {
break
}
group := []string{entry.Name}
for _, source := range parquetSources(entry) {
if present[source] && !purged[source] && source != newest && !slices.Contains(group, source) {
group = append(group, source)
}
}
// timestamps are not ordered across reloads, so each source must be past retention too
if slices.ContainsFunc(group, func(name string) bool { return !expired(name) }) {
break
}
for _, name := range group {
purged[name] = true
}
groups = append(groups, group)
}
// a parquet file's sources can straddle a retained file, so a group goes only
// when all it covers lies below the first offset left behind
lastOffset := func(name string) int64 {
if offset := extendedInt64(byName[name].Extended, mq.ExtendedAttrOffsetMax, -1); offset >= 0 {
return offset
}
// a gone or unranged source leaves the parquet file's end unknown
last := int64(-1)
for _, source := range parquetSources(byName[name]) {
sourceLast := int64(-1)
if present[source] {
sourceLast = extendedInt64(byName[source].Extended, mq.ExtendedAttrOffsetMax, -1)
}
if sourceLast < 0 {
return math.MaxInt64
}
last = max(last, sourceLast)
}
if last < 0 {
return math.MaxInt64
}
return last
}
for {
firstRetained := int64(math.MaxInt64)
for _, entry := range data {
if !purged[entry.Name] {
firstRetained = min(firstRetained, firstOffset[entry.Name])
}
}
kept := slices.IndexFunc(groups, func(group []string) bool {
return slices.ContainsFunc(group, func(name string) bool { return lastOffset(name) >= firstRetained })
})
if kept < 0 {
break
}
for _, group := range groups[kept:] {
for _, name := range group {
delete(purged, name)
}
}
groups = groups[:kept]
}
if len(groups) == 0 {
return nil
}
// raised first, so no read is answered from a file purged under it
var retained mq.OffsetRange
for _, entry := range files {
if !purged[entry.Name] {
retained.Add(entry)
}
}
earliestOffset, _ := retained.Bounds()
p.LogBuffer.SetLogStartOffset(earliestOffset)
for _, group := range groups {
mutations := make([]*filer_pb.ObjectMutation, 0, len(group))
for _, name := range group {
mutations = append(mutations, &filer_pb.ObjectMutation{
Type: filer_pb.ObjectMutation_DELETE,
Directory: partitionDir,
Name: name,
IsDeleteData: true,
})
}
if err := b.fencedTransaction(ctx, fence.Path, fenceTokenCondition(fence.Token()), uuid.NewString(), mutations...); err != nil {
if errors.Is(err, errFenceLost) {
fence.MarkLost()
}
return fmt.Errorf("delete %s/%v: %w", partitionDir, group, err)
}
glog.V(1).Infof("purged %s/%v past retention", partitionDir, group)
}
return nil
}
// isPartitionDataFile reports a flushed log file or a parquet file compacted from them.
func isPartitionDataFile(name string) bool {
_, err := topic.ParseLogFileTime(strings.TrimSuffix(name, ".parquet"))
return err == nil
}
// parquetSources lists the log files a compacted parquet file was made from.
func parquetSources(entry *filer_pb.Entry) (sources []string) {
if json.Unmarshal(entry.Extended[mq.ExtendedAttrSources], &sources) != nil {
return nil
}
return sources
}
// newestMessageTime bounds a file's newest message from above: a parquet file
// records it, and a log file is written after its last message arrives.
func newestMessageTime(entry *filer_pb.Entry) time.Time {
if tsNs := extendedInt64(entry.Extended, mq.ExtendedAttrTimestampMax, 0); tsNs > 0 {
return time.Unix(0, tsNs)
}
// Mtime is truncated to the second the write landed in
return time.Unix(entry.GetAttributes().GetMtime()+1, 0)
}
func extendedInt64(extended map[string][]byte, key string, missing int64) int64 {
if v := extended[key]; len(v) == 8 {
return int64(binary.BigEndian.Uint64(v))
}
return missing
}
@@ -0,0 +1,373 @@
package broker
import (
"context"
"encoding/binary"
"encoding/json"
"errors"
"slices"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/mq"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"google.golang.org/protobuf/proto"
)
func (f *fencingFiler) putParquetFile(sourceName string, sources []string, newestMessage, compactedAt time.Time) string {
name := sourceName + ".parquet"
sourcesJson, _ := json.Marshal(sources)
f.put(topic.PartitionDir(fenceTestTopic, fenceTestPartition)+"/"+name, &filer_pb.Entry{
Name: name,
Chunks: []*filer_pb.FileChunk{{FileId: "3,01637037d6", Size: 4}},
Attributes: &filer_pb.FuseAttributes{FileSize: 4, Crtime: compactedAt.Unix(), Mtime: compactedAt.Unix()},
Extended: map[string][]byte{
mq.ExtendedAttrSources: sourcesJson,
mq.ExtendedAttrTimestampMax: binary.BigEndian.AppendUint64(nil, uint64(newestMessage.UnixNano())),
},
})
return name
}
// partitionFiles lists the test partition's file names other than its fence.
func (f *fencingFiler) partitionFiles() (names []string) {
f.mu.Lock()
defer f.mu.Unlock()
dir := topic.PartitionDir(fenceTestTopic, fenceTestPartition) + "/"
for path := range f.entries {
if name, found := strings.CutPrefix(path, dir); found && name != topic.PartitionFenceName {
names = append(names, name)
}
}
slices.Sort(names)
return names
}
func TestPurgeDeletesFilesPastRetentionAndKeepsTheNewest(t *testing.T) {
f, b := newFencingFiler(t)
p, _ := newFencedPartition(t, b)
now := time.Now()
start := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
f.putLogFile(start, 0, 99, now.Add(-3*time.Hour))
f.putLogFile(start.Add(time.Minute), 100, 199, now.Add(-2*time.Hour))
f.putLogFile(start.Add(2*time.Minute), 200, 299, now.Add(-2*time.Hour))
// past retention too, but it holds the highest offset
newest := f.putLogFile(start.Add(3*time.Minute), 300, 399, now.Add(-2*time.Hour))
before := len(f.transactions())
if err := b.purgeExpiredLogFiles(context.Background(), fenceTestTopic, p, now.Add(-time.Hour)); err != nil {
t.Fatal(err)
}
if files := f.partitionFiles(); !slices.Equal(files, []string{newest}) {
t.Fatalf("files left %v, want only %s", files, newest)
}
if lso := p.LogBuffer.GetLogStartOffset(); lso != 300 {
t.Errorf("log start %d, want 300", lso)
}
txns := f.transactions()[before:]
if len(txns) != 3 {
t.Fatalf("%d transactions, want one per file", len(txns))
}
for _, txn := range txns {
clauses := txn.Condition.GetClauses()
if len(clauses) != 1 || clauses[0].Kind != filer_pb.WriteCondition_IF_ETAG_MATCH || !slices.Equal(clauses[0].Etags, []string{p.Fence.Token()}) {
t.Errorf("delete condition %v, want the fence token", clauses)
}
if m := txn.Mutations[0]; m.Type != filer_pb.ObjectMutation_DELETE || !m.IsDeleteData {
t.Errorf("mutation %v, want a delete of the data", m)
}
}
if f.entry(p.Fence.Path) == nil {
t.Error("purged the fence")
}
}
// Only the oldest run of expired files goes, so the retained offsets stay contiguous.
func TestPurgeStopsAtTheFirstRetainedFile(t *testing.T) {
f, b := newFencingFiler(t)
p, _ := newFencedPartition(t, b)
now := time.Now()
start := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
f.putLogFile(start, 0, 99, now.Add(-3*time.Hour))
second := f.putLogFile(start.Add(time.Minute), 100, 199, now.Add(-time.Minute))
third := f.putLogFile(start.Add(2*time.Minute), 200, 299, now.Add(-3*time.Hour))
fourth := f.putLogFile(start.Add(3*time.Minute), 300, 399, now)
if err := b.purgeExpiredLogFiles(context.Background(), fenceTestTopic, p, now.Add(-time.Hour)); err != nil {
t.Fatal(err)
}
if files := f.partitionFiles(); !slices.Equal(files, []string{second, third, fourth}) {
t.Fatalf("files left %v", files)
}
if lso := p.LogBuffer.GetLogStartOffset(); lso != 100 {
t.Errorf("log start %d, want 100", lso)
}
}
// A parquet file that records no range can still serve its purged source's offsets,
// so neither a purge nor a reload starts the log above them.
func TestLogStartStaysBelowAnUnrangedParquetFile(t *testing.T) {
f, b := newFencingFiler(t)
p, _ := newFencedPartition(t, b)
now := time.Now()
start := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
f.putLogFile(start.Add(-time.Minute), 0, 49, now.Add(-3*time.Hour))
// the parquet file's first source, 50..99, is already gone
first := topic.LogFileName(start, 50)
second := f.putLogFile(start.Add(time.Minute), 100, 199, now.Add(-time.Minute))
parquet := f.putParquetFile(first, []string{first, second}, now.Add(-time.Minute), now)
newest := f.putLogFile(start.Add(2*time.Minute), 200, 299, now)
if err := b.purgeExpiredLogFiles(context.Background(), fenceTestTopic, p, now.Add(-time.Hour)); err != nil {
t.Fatal(err)
}
if files := f.partitionFiles(); !slices.Equal(files, []string{parquet, second, newest}) {
t.Fatalf("files left %v", files)
}
if lso := p.LogBuffer.GetLogStartOffset(); lso != 0 {
t.Errorf("log start %d after the purge, want 0: the parquet file still holds 50..99", lso)
}
earliest, _, err := b.getOffsetRangeFromChunkMetadata(fenceTestTopic, fenceTestPartition)
if err != nil || earliest != 0 {
t.Errorf("stored earliest offset %d, %v; want 0", earliest, err)
}
}
// A log file's Mtime is in whole seconds, so a file flushed in the cutoff's
// second may hold messages after the cutoff and is kept.
func TestPurgeKeepsAFileFlushedInTheCutoffSecond(t *testing.T) {
f, b := newFencingFiler(t)
p, _ := newFencedPartition(t, b)
flushed := time.Unix(time.Now().Add(-2*time.Hour).Unix(), 0)
start := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
f.putLogFile(start, 0, 99, flushed.Add(-time.Minute))
kept := f.putLogFile(start.Add(time.Minute), 100, 199, flushed)
newest := f.putLogFile(start.Add(2*time.Minute), 200, 299, time.Now())
if err := b.purgeExpiredLogFiles(context.Background(), fenceTestTopic, p, flushed.Add(500*time.Millisecond)); err != nil {
t.Fatal(err)
}
if files := f.partitionFiles(); !slices.Equal(files, []string{kept, newest}) {
t.Fatalf("files left %v, want %s kept", files, kept)
}
}
// File names need not sort in offset order, as after a reload whose first window
// carries an earlier timestamp; the purge still takes the lowest offsets first.
func TestPurgeWalksFilesInOffsetOrder(t *testing.T) {
now := time.Now()
start := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
f, b := newFencingFiler(t)
p, _ := newFencedPartition(t, b)
retained := f.putLogFile(start.Add(5*time.Minute), 0, 99, now.Add(-time.Minute))
expired := f.putLogFile(start, 100, 199, now.Add(-3*time.Hour))
newest := f.putLogFile(start.Add(10*time.Minute), 200, 299, now)
if err := b.purgeExpiredLogFiles(context.Background(), fenceTestTopic, p, now.Add(-time.Hour)); err != nil {
t.Fatal(err)
}
if files := f.partitionFiles(); !slices.Equal(files, []string{expired, retained, newest}) {
t.Fatalf("files left %v; a later file went before a retained earlier one", files)
}
f, b = newFencingFiler(t)
p, _ = newFencedPartition(t, b)
f.putLogFile(start.Add(5*time.Minute), 0, 99, now.Add(-3*time.Hour))
f.putLogFile(start, 100, 199, now.Add(-2*time.Hour))
newest = f.putLogFile(start.Add(time.Minute), 200, 299, now.Add(-2*time.Hour))
if err := b.purgeExpiredLogFiles(context.Background(), fenceTestTopic, p, now.Add(-time.Hour)); err != nil {
t.Fatal(err)
}
if files := f.partitionFiles(); !slices.Equal(files, []string{newest}) {
t.Fatalf("files left %v, want only %s", files, newest)
}
if lso := p.LogBuffer.GetLogStartOffset(); lso != 200 {
t.Errorf("log start %d, want 200", lso)
}
}
// A compacted parquet file goes with its sources, and is judged by its newest row.
func TestPurgeDeletesAParquetFileWithItsSources(t *testing.T) {
f, b := newFencingFiler(t)
p, _ := newFencedPartition(t, b)
now := time.Now()
start := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
first := f.putLogFile(start, 0, 99, now.Add(-3*time.Hour))
second := f.putLogFile(start.Add(time.Minute), 100, 199, now.Add(-2*time.Hour))
f.putParquetFile(first, []string{first, second}, now.Add(-2*time.Hour), now.Add(-10*time.Minute))
newest := f.putLogFile(start.Add(2*time.Minute), 200, 299, now)
if err := b.purgeExpiredLogFiles(context.Background(), fenceTestTopic, p, now.Add(-time.Hour)); err != nil {
t.Fatal(err)
}
if files := f.partitionFiles(); !slices.Equal(files, []string{newest}) {
t.Fatalf("files left %v, want only %s", files, newest)
}
// a source still retained keeps its expired parquet file, as timestamps are not ordered across reloads
f3, b3 := newFencingFiler(t)
p3, _ := newFencedPartition(t, b3)
first = f3.putLogFile(start, 0, 99, now.Add(-3*time.Hour))
second = f3.putLogFile(start.Add(time.Minute), 100, 199, now.Add(-time.Minute))
third := f3.putLogFile(start.Add(2*time.Minute), 200, 299, now.Add(-3*time.Hour))
parquet := f3.putParquetFile(first, []string{first, second, third}, now.Add(-2*time.Hour), now.Add(-10*time.Minute))
newest = f3.putLogFile(start.Add(3*time.Minute), 300, 399, now)
if err := b3.purgeExpiredLogFiles(context.Background(), fenceTestTopic, p3, now.Add(-time.Hour)); err != nil {
t.Fatal(err)
}
// the first source stays too, as the retained parquet file starts at its offsets
if files := f3.partitionFiles(); !slices.Equal(files, []string{first, parquet, second, third, newest}) {
t.Fatalf("files left %v; the retained source %s must stay", files, second)
}
// a parquet file whose newest row is retained keeps it and what follows
f2, b2 := newFencingFiler(t)
p2, _ := newFencedPartition(t, b2)
first = f2.putLogFile(start, 0, 99, now.Add(-3*time.Hour))
second = f2.putLogFile(start.Add(time.Minute), 100, 199, now.Add(-3*time.Hour))
parquet = f2.putParquetFile(first, []string{first, second}, now.Add(-time.Minute), now)
newest = f2.putLogFile(start.Add(2*time.Minute), 200, 299, now)
if err := b2.purgeExpiredLogFiles(context.Background(), fenceTestTopic, p2, now.Add(-time.Hour)); err != nil {
t.Fatal(err)
}
if files := f2.partitionFiles(); !slices.Equal(files, []string{first, parquet, second, newest}) {
t.Fatalf("files left %v", files)
}
}
// An expired parquet file whose sources straddle a retained file stays, or its
// upper source would go and leave a hole above the retained one.
func TestPurgeKeepsAParquetGroupStraddlingARetainedFile(t *testing.T) {
f, b := newFencingFiler(t)
p, _ := newFencedPartition(t, b)
now := time.Now()
start := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
first := f.putLogFile(start, 0, 99, now.Add(-3*time.Hour))
second := f.putLogFile(start.Add(time.Minute), 100, 199, now.Add(-time.Minute))
third := f.putLogFile(start.Add(2*time.Minute), 200, 299, now.Add(-3*time.Hour))
parquet := f.putParquetFile(first, []string{first, third}, now.Add(-2*time.Hour), now.Add(-2*time.Hour))
newest := f.putLogFile(start.Add(3*time.Minute), 300, 399, now)
if err := b.purgeExpiredLogFiles(context.Background(), fenceTestTopic, p, now.Add(-time.Hour)); err != nil {
t.Fatal(err)
}
if files := f.partitionFiles(); !slices.Equal(files, []string{first, parquet, second, third, newest}) {
t.Fatalf("files left %v; %s above the retained %s must stay", files, third, second)
}
}
func TestPurgeKeepsEverythingWithoutRetention(t *testing.T) {
for name, retention := range map[string]*mq_pb.TopicRetention{
"unset": nil,
"disabled": {RetentionSeconds: 60, Enabled: false},
"zero": {RetentionSeconds: 0, Enabled: true},
"one hour": {RetentionSeconds: 3600, Enabled: true},
} {
t.Run(name, func(t *testing.T) {
f, b := newFencingFiler(t)
newFencedPartition(t, b)
b.topicCache = map[string]*topicCacheEntry{fenceTestTopic.String(): {
conf: &mq_pb.ConfigureTopicResponse{
BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{{Partition: fenceTestPartition.ToPbPartition(), Epoch: 1}},
Retention: retention,
},
expiresAt: time.Now().Add(time.Hour),
}}
now := time.Now()
start := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
old := f.putLogFile(start, 0, 99, now.Add(-30*24*time.Hour))
newest := f.putLogFile(start.Add(time.Minute), 100, 199, now)
b.purgeTopicsPastRetention(context.Background())
want := []string{old, newest}
if retention.GetEnabled() && retention.GetRetentionSeconds() > 0 {
want = []string{newest}
}
if files := f.partitionFiles(); !slices.Equal(files, want) {
t.Fatalf("files left %v, want %v", files, want)
}
})
}
}
// A leader whose fence another broker took deletes nothing.
func TestDeposedLeaderPurgesNothing(t *testing.T) {
f, b := newFencingFiler(t)
p, _ := newFencedPartition(t, b)
now := time.Now()
start := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
f.putLogFile(start, 0, 99, now.Add(-3*time.Hour))
f.putLogFile(start.Add(time.Minute), 100, 199, now.Add(-3*time.Hour))
f.putLogFile(start.Add(2*time.Minute), 200, 299, now)
taken := proto.Clone(f.entry(p.Fence.Path)).(*filer_pb.Entry)
taken.Extended[s3_constants.ExtETagKey] = []byte("another broker's token")
taken.Extended[mq.ExtendedAttrFenceEpoch] = []byte("2")
f.put(p.Fence.Path, taken)
files := f.partitionFiles()
if err := b.purgeExpiredLogFiles(context.Background(), fenceTestTopic, p, now.Add(-time.Hour)); !errors.Is(err, errFenceLost) {
t.Fatalf("purge under a taken fence: %v", err)
}
if left := f.partitionFiles(); !slices.Equal(left, files) {
t.Fatalf("files left %v, want %v", left, files)
}
if !p.IsFenced() {
t.Error("the refused purge did not mark the fence lost")
}
// once known lost, it does not try again
before := len(f.transactions())
if err := b.purgeExpiredLogFiles(context.Background(), fenceTestTopic, p, now.Add(-time.Hour)); !errors.Is(err, errFenceLost) {
t.Fatalf("purge under a lost fence: %v", err)
}
if len(f.transactions()) != before {
t.Error("sent a delete under a fence known lost")
}
}
// A data file that records no offsets cannot be placed in offset order, so the
// purge keeps everything rather than risk deleting past a retained offset.
func TestPurgeKeepsAPartitionWithAFileOfUnknownOffsets(t *testing.T) {
now := time.Now()
start := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
f, b := newFencingFiler(t)
p, _ := newFencedPartition(t, b)
// an expired file of unknown offsets, which may hold offsets above the retained one
legacy := start.Add(5 * time.Minute).Format(topic.TIME_FORMAT)
f.put(topic.PartitionDir(fenceTestTopic, fenceTestPartition)+"/"+legacy, &filer_pb.Entry{Name: legacy, Attributes: &filer_pb.FuseAttributes{Mtime: now.Add(-3 * time.Hour).Unix()}})
retained := f.putLogFile(start, 0, 99, now.Add(-time.Minute))
newest := f.putLogFile(start.Add(10*time.Minute), 200, 299, now)
if err := b.purgeExpiredLogFiles(context.Background(), fenceTestTopic, p, now.Add(-time.Hour)); err != nil {
t.Fatal(err)
}
if files := f.partitionFiles(); !slices.Equal(files, []string{retained, legacy, newest}) {
t.Fatalf("files left %v, want all three kept", files)
}
}
// An unranged parquet file whose source is gone may still hold that source's
// offsets past a retained file, so its group stays.
func TestPurgeKeepsAParquetGroupWhoseEndIsUnknown(t *testing.T) {
f, b := newFencingFiler(t)
p, _ := newFencedPartition(t, b)
now := time.Now()
start := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
first := f.putLogFile(start, 0, 99, now.Add(-3*time.Hour))
second := f.putLogFile(start.Add(time.Minute), 100, 199, now.Add(-time.Minute))
gone := topic.LogFileName(start.Add(2*time.Minute), 200)
parquet := f.putParquetFile(first, []string{first, gone}, now.Add(-2*time.Hour), now.Add(-2*time.Hour))
newest := f.putLogFile(start.Add(3*time.Minute), 300, 399, now)
if err := b.purgeExpiredLogFiles(context.Background(), fenceTestTopic, p, now.Add(-time.Hour)); err != nil {
t.Fatal(err)
}
if files := f.partitionFiles(); !slices.Equal(files, []string{first, parquet, second, newest}) {
t.Fatalf("files left %v; %s may hold offsets above the retained %s", files, parquet, second)
}
}
+2 -2
View File
@@ -191,7 +191,7 @@ func TestLeaderStoresAndSealsWhenItLosesItsFollower(t *testing.T) {
f.mu.Lock()
for path, entry := range f.entries {
if d, name := util.FullPath(path).DirAndName(); d == dir && name != topic.PartitionFenceName {
stored.Add(entry.Extended)
stored.Add(entry)
}
}
f.mu.Unlock()
@@ -263,7 +263,7 @@ func storedRanges(f *fencingFiler, dir string) (stored []string) {
for path, entry := range f.entries {
if d, name := util.FullPath(path).DirAndName(); d == dir && name != topic.PartitionFenceName {
var r mq.OffsetRange
r.Add(entry.Extended)
r.Add(entry)
earliest, hwm := r.Bounds()
stored = append(stored, fmt.Sprintf("%d-%d", earliest, hwm-1))
}
+1
View File
@@ -158,6 +158,7 @@ func NewMessageBroker(option *MessageQueueBrokerOption, grpcDialOption grpc.Dial
glog.V(0).Info("Started idle partition cleanup task (check: 1m, timeout: 5m)")
go mqBroker.joinBalancer()
go mqBroker.loopPurgeRetention()
return mqBroker, nil
}
@@ -233,15 +233,20 @@ func (b *MessageQueueBroker) ensureTopicActiveAssignments(t topic.Topic, conf *m
}
// initializePartitionOffsetFromExistingData continues the partition's offsets above
// what is already stored. A partition whose stored offsets cannot be read is not served.
// what is already stored, and starts its log at the earliest stored offset. 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) {
_, highWaterMark, err := b.getOffsetRangeFromChunkMetadata(t, partition)
var highWaterMark int64
var err error
earliestOffset, highWaterMark, err = b.getOffsetRangeFromChunkMetadata(t, partition)
return highWaterMark - 1, err
})
if err != nil {
return fmt.Errorf("topic %s partition %s: %w", t, partition, err)
}
localPartition.LogBuffer.SetLogStartOffset(earliestOffset)
return nil
}
@@ -56,10 +56,13 @@ func (bc *BrokerClient) FetchMessagesStateless(ctx context.Context, topic string
return nil, fmt.Errorf("FetchMessage RPC failed: %v", err)
}
// The caller retries at startOffset; LogStartOffset is only the start of the broker's memory, not of the partition.
// The caller retries at startOffset, or resets the consumer when the offset is out of range.
if resp.Error != "" {
if MapBrokerErrorToKafka(resp.ErrorCode) == kafkaErrorCodeKafkaStorageError {
switch MapBrokerErrorToKafka(resp.ErrorCode) {
case kafkaErrorCodeKafkaStorageError:
return nil, fmt.Errorf("%w: broker error: %s (code=%d)", ErrKafkaStorageError, resp.Error, resp.ErrorCode)
case kafkaErrorCodeOffsetOutOfRange:
return nil, fmt.Errorf("%w: broker error: %s (code=%d, log start %d)", ErrOffsetOutOfRange, resp.Error, resp.ErrorCode, resp.LogStartOffset)
}
return nil, fmt.Errorf("broker error: %s (code=%d)", resp.Error, resp.ErrorCode)
}
@@ -62,3 +62,36 @@ func TestGetStoredRecordsKeepsBrokerStorageError(t *testing.T) {
t.Errorf("got %v, want a storage error", err)
}
}
// A fetch below retention reaches the fetch path as out of range, and the
// earliest offset a reset lands on is the retained start.
func TestFetchBelowRetentionIsOutOfRange(t *testing.T) {
var mu sync.Mutex
var asked []int64
broker := startPublishBroker(t, &publishBroker{earliest: 30, fetch: func(req *mq_pb.FetchMessageRequest) *mq_pb.FetchMessageResponse {
mu.Lock()
asked = append(asked, req.StartOffset)
mu.Unlock()
return &mq_pb.FetchMessageResponse{Error: "offset 10 is before the log start offset 30", ErrorCode: 104, HighWaterMark: 43, LogStartOffset: 30, NextOffset: req.StartOffset}
}})
h := &SeaweedMQHandler{
brokerClient: newPublishTestClient(t, broker.addr),
topicExistsCache: map[string]*topicExistsCacheEntry{"events": {exists: true, expiresAt: time.Now().Add(time.Hour)}},
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err := h.GetStoredRecords(ctx, "events", 0, 10, 10)
if !errors.Is(err, ErrOffsetOutOfRange) || errors.Is(err, ErrKafkaStorageError) {
t.Errorf("got %v, want out of range", err)
}
mu.Lock()
if len(asked) != 1 || asked[0] != 10 {
t.Errorf("broker was asked for %v, want one fetch at 10", asked)
}
mu.Unlock()
if earliest, err := h.GetEarliestOffset("events", 0); err != nil || earliest != 30 {
t.Errorf("earliest offset %d, %v; want the retained start 30", earliest, err)
}
}
@@ -31,6 +31,8 @@ type publishBroker struct {
holdLookup chan struct{}
// fetch, when set, answers FetchMessage on the leader
fetch func(req *mq_pb.FetchMessageRequest) *mq_pb.FetchMessageResponse
// earliest is the earliest retained offset the range info reports
earliest int64
mu sync.Mutex
streams int
@@ -143,7 +145,7 @@ func (b *publishBroker) GetPartitionRangeInfo(ctx context.Context, req *mq_pb.Ge
if b.notLeader || (leader != "" && leader != b.addr) {
return &mq_pb.GetPartitionRangeInfoResponse{Error: "partition not found"}, nil
}
return &mq_pb.GetPartitionRangeInfoResponse{OffsetRange: &mq_pb.OffsetRangeInfo{HighWaterMark: 7}}, nil
return &mq_pb.GetPartitionRangeInfoResponse{OffsetRange: &mq_pb.OffsetRangeInfo{EarliestOffset: b.earliest, HighWaterMark: 7}}, nil
}
func (b *publishBroker) streamCount() int {
@@ -10,7 +10,8 @@ import (
// Kafka Protocol Error Codes (copied from protocol package to avoid import cycle)
const (
kafkaErrorCodeNone int16 = 0
kafkaErrorCodeUnknownServerError int16 = 1
kafkaErrorCodeOffsetOutOfRange int16 = 1
kafkaErrorCodeUnknownServerError int16 = -1
kafkaErrorCodeUnknownTopicOrPartition int16 = 3
kafkaErrorCodeNotLeaderOrFollower int16 = 6
kafkaErrorCodeRequestTimedOut int16 = 7
@@ -29,6 +30,10 @@ const (
// The Kafka client should refresh its metadata and retry.
var ErrNotLeaderOrFollower = errors.New("not leader or follower")
// ErrOffsetOutOfRange marks a fetch below the earliest offset the partition retains.
// The Kafka client should reset its position by its auto.offset.reset policy.
var ErrOffsetOutOfRange = errors.New("offset out of range")
// ErrKafkaStorageError marks a fetch whose stored records the broker could not read.
// The Kafka client should retry at the same offset.
var ErrKafkaStorageError = errors.New("kafka storage error")
@@ -66,6 +71,8 @@ func MapBrokerErrorToKafka(brokerErrorCode int32) int16 {
return kafkaErrorCodeInvalidConfig
case 56: // BrokerErrorStorageError
return kafkaErrorCodeKafkaStorageError
case 104: // BrokerErrorOffsetOutOfRange
return kafkaErrorCodeOffsetOutOfRange
case 100: // BrokerErrorPublisherNotFound
return kafkaErrorCodeUnknownServerError
case 101: // BrokerErrorConnectionFailed
@@ -13,7 +13,7 @@ func TestMapBrokerErrorToKafka(t *testing.T) {
expectedKafka int16
}{
{"No error", 0, kafkaErrorCodeNone},
{"Unknown server error", 1, kafkaErrorCodeUnknownServerError},
{"Unknown server error", 1, -1},
{"Topic not found", 2, kafkaErrorCodeUnknownTopicOrPartition},
{"Partition not found", 3, kafkaErrorCodeUnknownTopicOrPartition},
{"Not leader or follower", 6, kafkaErrorCodeNotLeaderOrFollower},
@@ -27,11 +27,12 @@ func TestMapBrokerErrorToKafka(t *testing.T) {
{"Invalid partitions", 37, kafkaErrorCodeInvalidPartitions},
{"Invalid config", 40, kafkaErrorCodeInvalidConfig},
{"Storage error", 56, kafkaErrorCodeKafkaStorageError},
{"Publisher not found", 100, kafkaErrorCodeUnknownServerError},
{"Offset out of range", 104, 1},
{"Publisher not found", 100, -1},
{"Connection failed", 101, kafkaErrorCodeNetworkException},
{"Follower connection failed", 102, kafkaErrorCodeNetworkException},
{"Generation ended", 103, kafkaErrorCodeNotLeaderOrFollower},
{"Unknown error code", 999, kafkaErrorCodeUnknownServerError},
{"Unknown error code", 999, -1},
}
for _, tt := range tests {
@@ -157,7 +158,7 @@ func TestParseStringErrorToKafkaCode(t *testing.T) {
{"Connection error", "connection failed", kafkaErrorCodeNetworkException},
{"Message too large", "message too large", kafkaErrorCodeMessageTooLarge},
{"Size error", "size exceeds limit", kafkaErrorCodeMessageTooLarge},
{"Unknown error", "some random error", kafkaErrorCodeUnknownServerError},
{"Unknown error", "some random error", -1},
}
for _, tt := range tests {
@@ -315,9 +315,13 @@ func (pr *partitionReader) readRecords(ctx context.Context, fromOffset int64, ma
}
// fetchErrorCode answers records the broker could not read with KAFKA_STORAGE_ERROR, so the client
// retries at the same offset instead of taking an empty fetch for the end of the partition.
// retries at the same offset instead of taking an empty fetch for the end of the partition, and an
// offset below retention with OFFSET_OUT_OF_RANGE, so the client resets its position.
func fetchErrorCode(err error) int16 {
if errors.Is(err, integration.ErrKafkaStorageError) {
switch {
case errors.Is(err, integration.ErrOffsetOutOfRange):
return ErrorCodeOffsetOutOfRange
case errors.Is(err, integration.ErrKafkaStorageError):
return ErrorCodeKafkaStorageError
}
return ErrorCodeNone
@@ -17,6 +17,8 @@ type storageErrorMQHandler struct {
asked []int64
// answers reads after the first, as a fallback read that fails another way
laterErr error
// answers every read in place of a storage error when set
readErr error
}
func (h *storageErrorMQHandler) GetLatestOffset(topic string, partition int32) (int64, error) {
@@ -31,6 +33,9 @@ func (h *storageErrorMQHandler) GetStoredRecords(ctx context.Context, topic stri
if later && h.laterErr != nil {
return nil, h.laterErr
}
if h.readErr != nil {
return nil, h.readErr
}
return nil, fmt.Errorf("failed to fetch records: %w: disk read failed", integration.ErrKafkaStorageError)
}
@@ -41,8 +46,21 @@ func TestFetchReportsBrokerStorageError(t *testing.T) {
})
}
// A fetch below the earliest retained offset is answered with OFFSET_OUT_OF_RANGE, so the
// consumer applies auto.offset.reset instead of retrying the same offset forever.
func TestFetchReportsOffsetOutOfRange(t *testing.T) {
mq := &storageErrorMQHandler{FastMockHandler: FastMockHandler{topics: []string{"events"}},
readErr: fmt.Errorf("failed to fetch records: %w: offset 10 is before the log start offset 30", integration.ErrOffsetOutOfRange)}
checkFetchPartitionError(t, mq, ErrorCodeOffsetOutOfRange)
}
func checkFetchReportsStorageError(t *testing.T, laterErr error) {
mq := &storageErrorMQHandler{FastMockHandler: FastMockHandler{topics: []string{"events"}}, laterErr: laterErr}
checkFetchPartitionError(t, mq, ErrorCodeKafkaStorageError)
}
// checkFetchPartitionError fetches partition 0 at offset 10 and wants the partition answered with want.
func checkFetchPartitionError(t *testing.T, mq *storageErrorMQHandler, want int16) {
h := &Handler{seaweedMQHandler: mq}
connCtx := &ConnectionContext{ConnectionID: "test"}
ctx, cancel := context.WithCancel(context.WithValue(context.Background(), connContextKey, connCtx))
@@ -71,8 +89,8 @@ func checkFetchReportsStorageError(t *testing.T, laterErr error) {
if len(resp) < pos+2 {
t.Fatalf("short fetch response: %d bytes", len(resp))
}
if code := int16(binary.BigEndian.Uint16(resp[pos:])); code != ErrorCodeKafkaStorageError {
t.Errorf("partition error code %d, want KAFKA_STORAGE_ERROR %d", code, ErrorCodeKafkaStorageError)
if code := int16(binary.BigEndian.Uint16(resp[pos:])); code != want {
t.Errorf("partition error code %d, want %d", code, want)
}
mq.mu.Lock()
@@ -82,7 +100,7 @@ func checkFetchReportsStorageError(t *testing.T, laterErr error) {
}
for _, offset := range mq.asked {
if offset != 10 {
t.Errorf("read at %d after a storage error at 10", offset)
t.Errorf("read at %d after an error at 10", offset)
}
}
}
+378
View File
@@ -0,0 +1,378 @@
package logstore
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"sort"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/mq"
"github.com/seaweedfs/seaweedfs/weed/mq/schema"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/operation"
"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/util"
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
"google.golang.org/grpc"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
// compactionFiler keeps a filer's entries and a volume server's blobs in memory,
// enough to compact a partition and read the result back.
type compactionFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
mu sync.Mutex
entries map[string]*filer_pb.Entry
blobs map[string][]byte
volume *httptest.Server
}
// compactionFileKeys numbers file ids across fixtures, as the parquet reader's
// chunk cache is package-wide and keyed by file id.
var compactionFileKeys atomic.Int64
func newCompactionFileId() string {
return fmt.Sprintf("3,%x12345678", compactionFileKeys.Add(1))
}
func (f *compactionFiler) volumeUrl() string { return strings.TrimPrefix(f.volume.URL, "http://") }
func (f *compactionFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream grpc.ServerStreamingServer[filer_pb.ListEntriesResponse]) error {
f.mu.Lock()
var children []*filer_pb.Entry
for path, entry := range f.entries {
if dir, _ := util.FullPath(path).DirAndName(); dir == req.Directory {
children = append(children, proto.Clone(entry).(*filer_pb.Entry))
}
}
f.mu.Unlock()
sort.Slice(children, func(i, j int) bool { return children[i].Name < children[j].Name })
for _, entry := range children {
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 *compactionFiler) LookupDirectoryEntry(_ context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
f.mu.Lock()
defer f.mu.Unlock()
entry, found := f.entries[string(util.NewFullPath(req.Directory, req.Name))]
if !found {
return nil, fmt.Errorf("%s/%s: %w", req.Directory, req.Name, filer_pb.ErrNotFound)
}
return &filer_pb.LookupDirectoryEntryResponse{Entry: proto.Clone(entry).(*filer_pb.Entry)}, nil
}
func (f *compactionFiler) CreateEntry(_ context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.entries[string(util.NewFullPath(req.Directory, req.Entry.Name))] = proto.Clone(req.Entry).(*filer_pb.Entry)
return &filer_pb.CreateEntryResponse{}, nil
}
func (f *compactionFiler) AssignVolume(context.Context, *filer_pb.AssignVolumeRequest) (*filer_pb.AssignVolumeResponse, error) {
return &filer_pb.AssignVolumeResponse{FileId: newCompactionFileId(), Location: &filer_pb.Location{Url: f.volumeUrl()}}, nil
}
func (f *compactionFiler) 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
}
func (f *compactionFiler) serveVolume(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
f.mu.Lock()
blob, found := f.blobs[r.URL.Path]
f.mu.Unlock()
if !found {
http.NotFound(w, r)
return
}
http.ServeContent(w, r, "", time.Time{}, bytes.NewReader(blob))
return
}
file, _, err := r.FormFile("file")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer file.Close()
blob, _ := io.ReadAll(file)
f.mu.Lock()
f.blobs[r.URL.Path] = blob
f.mu.Unlock()
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, `{"size":%d}`, len(blob))
}
func newCompactionFiler(t *testing.T) (*compactionFiler, listingFilerClient) {
f := &compactionFiler{entries: map[string]*filer_pb.Entry{}, blobs: map[string][]byte{}}
f.volume = httptest.NewServer(http.HandlerFunc(f.serveVolume))
t.Cleanup(f.volume.Close)
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
server := grpc.NewServer()
filer_pb.RegisterSeaweedFilerServer(server, f)
go server.Serve(listener)
t.Cleanup(server.Stop)
return f, listingFilerClient{address: pb.NewServerAddressWithGrpcPort(listener.Addr().String(), listener.Addr().(*net.TCPAddr).Port)}
}
var (
compactionTopic = topic.NewTopic("test", "events")
compactionPartition = topic.Partition{RingSize: 2520, RangeStop: 2520, UnixTimeNs: 1}
)
// putTopicConf stores a schemaless topic's configuration.
func (f *compactionFiler) putTopicConf(t *testing.T) {
conf, err := protojson.Marshal(&mq_pb.ConfigureTopicResponse{
MessageRecordType: schema.RecordTypeBegin().WithField(SW_COLUMN_NAME_VALUE, schema.TypeBytes).RecordTypeEnd(),
})
if err != nil {
t.Fatal(err)
}
f.entries[compactionTopic.Dir()+"/topic.conf"] = &filer_pb.Entry{Name: "topic.conf", Content: conf, Attributes: &filer_pb.FuseAttributes{}}
}
// 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
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})
if err != nil {
t.Fatal(err)
}
buf = binary.BigEndian.AppendUint32(buf, uint32(len(data)))
buf = append(buf, data...)
}
fileId := newCompactionFileId()
f.mu.Lock()
defer f.mu.Unlock()
f.blobs["/"+fileId] = buf
name := topic.LogFileName(start, minOffset)
f.entries[topic.PartitionDir(compactionTopic, compactionPartition)+"/"+name] = &filer_pb.Entry{
Name: name,
Chunks: []*filer_pb.FileChunk{{FileId: fileId, Size: uint64(len(buf))}},
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)),
},
}
}
// putLegacyLogFile stores a window flushed before files recorded offsets: named by
// its start second alone, with no offset range.
func (f *compactionFiler) putLegacyLogFile(t *testing.T, start time.Time, firstKey int64, tsNs ...int64) {
f.putLogFile(t, start, firstKey, tsNs...)
f.mu.Lock()
defer f.mu.Unlock()
dir := topic.PartitionDir(compactionTopic, compactionPartition) + "/"
entry := f.entries[dir+topic.LogFileName(start, firstKey)]
delete(f.entries, dir+entry.Name)
entry.Name = start.UTC().Format(topic.TIME_FORMAT)
entry.Extended = nil
f.entries[dir+entry.Name] = entry
}
// removeLogFiles leaves only the partition's parquet files, so reads come from them.
func (f *compactionFiler) removeLogFiles() {
f.mu.Lock()
defer f.mu.Unlock()
dir := topic.PartitionDir(compactionTopic, compactionPartition) + "/"
for path, entry := range f.entries {
if strings.HasPrefix(path, dir) && !strings.HasSuffix(entry.Name, ".parquet") {
delete(f.entries, path)
}
}
}
func (f *compactionFiler) parquetFiles() (files []*filer_pb.Entry) {
f.mu.Lock()
defer f.mu.Unlock()
for _, entry := range f.entries {
if strings.HasSuffix(entry.Name, ".parquet") {
files = append(files, entry)
}
}
return files
}
// compactSchemaless compacts the test partition the way mq.topic.compact does for a schemaless topic.
func compactSchemaless(t *testing.T, client listingFilerClient) {
recordType := schema.RecordTypeBegin().WithField(SW_COLUMN_NAME_VALUE, schema.TypeBytes).RecordTypeEnd()
recordType = schema.NewRecordTypeBuilder(recordType).
WithField(SW_COLUMN_NAME_TS, schema.TypeInt64).
WithField(SW_COLUMN_NAME_KEY, schema.TypeBytes).
RecordTypeEnd()
if err := compactTopicPartitionDir(client, compactionTopic.Name, topic.PartitionDir(compactionTopic, compactionPartition), 0, recordType, &operation.StoragePreference{}); err != nil {
t.Fatal(err)
}
}
// Timestamps are not ordered across reloads, so a parquet file records the
// lowest and highest of its rows, not its first and last.
func TestCompactionRecordsTheTimestampRangeOfAllRows(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, 0, base.Add(5*time.Second).UnixNano(), base.Add(9*time.Second).UnixNano())
f.putLogFile(t, base.Add(time.Second), 2, base.Add(time.Second).UnixNano(), base.Add(7*time.Second).UnixNano())
compactSchemaless(t, client)
files := f.parquetFiles()
if len(files) != 1 {
t.Fatalf("%d parquet files, want 1", len(files))
}
tsMin := int64(binary.BigEndian.Uint64(files[0].Extended[mq.ExtendedAttrTimestampMin]))
tsMax := int64(binary.BigEndian.Uint64(files[0].Extended[mq.ExtendedAttrTimestampMax]))
if tsMin != base.Add(time.Second).UnixNano() || tsMax != base.Add(9*time.Second).UnixNano() {
t.Errorf("timestamp range %v..%v, want %v..%v", time.Unix(0, tsMin).UTC(), time.Unix(0, tsMax).UTC(), base.Add(time.Second), base.Add(9*time.Second))
}
}
// readParquetAtOffsets fetches from offset 0 on through a partition whose older
// offsets are only in its parquet files, as a Kafka fetch does.
func readParquetAtOffsets(t *testing.T, client listingFilerClient, end int64) (got []*filer_pb.LogEntry) {
lb := log_buffer.NewLogBuffer("test", time.Hour, nil, GenParquetReadFunc(client, compactionTopic, compactionPartition), func() {})
t.Cleanup(lb.ShutdownLogBuffer)
if err := lb.InitializeOffsetFromExistingData(func() (int64, error) { return end - 1, nil }); err != nil {
t.Fatal(err)
}
for next := int64(0); next < end; {
messages, nextOffset, _, _, err := lb.ReadMessagesAtOffset(next, 3, 1<<20)
if err != nil {
t.Fatal(err)
}
if len(messages) == 0 {
break
}
got = append(got, messages...)
next = nextOffset
}
return got
}
// putTenMessages stores offsets 0..9 in two flushed windows.
func (f *compactionFiler) putTenMessages(t *testing.T) {
base := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC).UnixNano()
f.putLogFile(t, time.Unix(0, base), 0, base+1, base+2, base+3, base+4, base+5)
f.putLogFile(t, time.Unix(0, base).Add(time.Second), 5, base+6, base+7, base+8, base+9, base+10)
}
// A parquet file compacted before the _offset column existed is read by its own
// columns, and its rows, which carry no offset, are not placed at any offset.
func TestParquetRowsWithoutOffsetsAreNotPlacedByOffset(t *testing.T) {
f, client := newCompactionFiler(t)
f.putTopicConf(t)
f.putTenMessages(t)
recordType := schema.RecordTypeBegin().
WithField(SW_COLUMN_NAME_VALUE, schema.TypeBytes).
WithField(SW_COLUMN_NAME_TS, schema.TypeInt64).
WithField(SW_COLUMN_NAME_KEY, schema.TypeBytes).
RecordTypeEnd()
parquetSchema, err := schema.ToParquetSchema(compactionTopic.Name, recordType)
if err != nil {
t.Fatal(err)
}
parquetLevels, err := schema.ToParquetLevels(recordType)
if err != nil {
t.Fatal(err)
}
partitionDir := topic.PartitionDir(compactionTopic, compactionPartition)
var logFiles []*filer_pb.Entry
if err := filer_pb.ReadDirAllEntries(context.Background(), client, util.FullPath(partitionDir), "", func(entry *filer_pb.Entry, isLast bool) error {
logFiles = append(logFiles, entry)
return nil
}); err != nil {
t.Fatal(err)
}
if err := writeLogFilesToParquet(client, partitionDir, recordType, logFiles, parquetSchema, parquetLevels, &operation.StoragePreference{}); err != nil {
t.Fatal(err)
}
f.removeLogFiles()
if got := readParquetAtOffsets(t, client, 10); len(got) != 0 {
t.Errorf("placed %d rows that record no offset: %v", len(got), got)
}
var keys []string
read := GenParquetReadFunc(client, compactionTopic, compactionPartition)
if _, _, err := read(log_buffer.NewMessagePosition(1, -2), 0, func(entry *filer_pb.LogEntry) (bool, error) {
if entry.Offset != -1 {
t.Errorf("row %q read with offset %d", entry.Key, entry.Offset)
}
keys = append(keys, string(entry.Key))
return false, nil
}); err != nil {
t.Fatal(err)
}
if len(keys) != 10 || keys[0] != "k0" || keys[9] != "k9" {
t.Errorf("read rows %v, want k0..k9", keys)
}
}
// A legacy log file without offsets is compacted apart from files that record
// them, so their rows keep their offsets.
func TestCompactionKeepsOffsetsBesideALegacyLogFile(t *testing.T) {
f, client := newCompactionFiler(t)
f.putTopicConf(t)
base := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
f.putLegacyLogFile(t, base, 100, base.UnixNano()+1, base.UnixNano()+2)
f.putLogFile(t, base.Add(time.Second), 0, base.UnixNano()+3, base.UnixNano()+4, base.UnixNano()+5, base.UnixNano()+6, base.UnixNano()+7)
compactSchemaless(t, client)
f.removeLogFiles()
got := readParquetAtOffsets(t, client, 5)
if len(got) != 5 {
t.Fatalf("read %d records by offset, want 5: %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)
}
}
}
// A schemaless topic's parquet rows keep their offsets, so a fetch by offset
// returns every record at its own offset.
func TestCompactedSchemalessRowsKeepTheirOffsets(t *testing.T) {
f, client := newCompactionFiler(t)
f.putTopicConf(t)
f.putTenMessages(t)
compactSchemaless(t, client)
f.removeLogFiles()
got := readParquetAtOffsets(t, client, 10)
if len(got) != 10 {
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)
}
}
}
+37 -24
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"io"
"os"
"slices"
"strings"
"time"
@@ -116,6 +117,13 @@ func compactTopicPartitionDir(filerClient filer_pb.FilerClient, topicName, parti
// divide log files into groups of 128MB
logFileGroups := groupFilesBySize(logFiles, 128*1024*1024)
// readers place each row by its offset, so every file keeps the column
if !slices.ContainsFunc(recordType.Fields, func(field *schema_pb.Field) bool { return field.Name == SW_COLUMN_NAME_OFFSET }) {
recordType = schema.NewRecordTypeBuilder(proto.Clone(recordType).(*schema_pb.RecordType)).
WithField(SW_COLUMN_NAME_OFFSET, schema.TypeInt64).
RecordTypeEnd()
}
// write to parquet file
parquetLevels, err := schema.ToParquetLevels(recordType)
if err != nil {
@@ -138,11 +146,13 @@ func compactTopicPartitionDir(filerClient filer_pb.FilerClient, topicName, parti
return nil
}
// groupFilesBySize also keeps files that record no offsets apart from those that do,
// as a parquet file keeps its rows' offsets only when every source records them.
func groupFilesBySize(logFiles []*filer_pb.Entry, maxGroupSize int64) (logFileGroups [][]*filer_pb.Entry) {
var logFileGroup []*filer_pb.Entry
var groupSize int64
for _, logFile := range logFiles {
if len(logFileGroup) > 0 && groupSize+int64(logFile.Attributes.FileSize) > maxGroupSize {
if len(logFileGroup) > 0 && (groupSize+int64(logFile.Attributes.FileSize) > maxGroupSize || recordsOffsetRange(logFile) != recordsOffsetRange(logFileGroup[0])) {
logFileGroups = append(logFileGroups, logFileGroup)
logFileGroup = nil
groupSize = 0
@@ -265,8 +275,7 @@ func writeLogFilesToParquet(filerClient filer_pb.FilerClient, partitionDir strin
rowBuilder := parquet.NewRowBuilder(parquetSchema)
var startTsNs, stopTsNs int64
var minOffset, maxOffset int64
var hasOffsets bool
minOffset, maxOffset, hasOffsets := sourcesOffsetRange(logFileGroups)
isSchemaless := isSchemalessRecordType(recordType)
for _, logFile := range logFileGroups {
@@ -278,26 +287,11 @@ func writeLogFilesToParquet(filerClient filer_pb.FilerClient, partitionDir strin
return nil
}
if startTsNs == 0 {
// timestamps are not ordered across reloads, so take the extremes, not the ends
if startTsNs == 0 || entry.TsNs < startTsNs {
startTsNs = entry.TsNs
}
stopTsNs = entry.TsNs
// Track offset ranges for Kafka integration
if entry.Offset > 0 {
if !hasOffsets {
minOffset = entry.Offset
maxOffset = entry.Offset
hasOffsets = true
} else {
if entry.Offset < minOffset {
minOffset = entry.Offset
}
if entry.Offset > maxOffset {
maxOffset = entry.Offset
}
}
}
stopTsNs = max(stopTsNs, entry.TsNs)
// write to parquet file
rowBuilder.Reset()
@@ -322,9 +316,10 @@ func writeLogFilesToParquet(filerClient filer_pb.FilerClient, partitionDir strin
if record.Fields == nil {
record.Fields = make(map[string]*schema_pb.Value)
}
}
// Add offset field to parquet records for native offset support
// ASSUMPTION: LogEntry.Offset field is populated by broker during message publishing
// an entry's offset is only real when its file records a range; otherwise the column stays null
if hasOffsets {
record.Fields[SW_COLUMN_NAME_OFFSET] = &schema_pb.Value{
Kind: &schema_pb.Value_Int64Value{
Int64Value: entry.Offset,
@@ -410,6 +405,24 @@ func writeLogFilesToParquet(filerClient filer_pb.FilerClient, partitionDir strin
}
// sourcesOffsetRange is the offset range the source log files record, which may
// start at offset 0; ok is false unless every source records its range.
func sourcesOffsetRange(logFiles []*filer_pb.Entry) (minOffset, maxOffset int64, ok bool) {
var r mq.OffsetRange
for _, logFile := range logFiles {
if !recordsOffsetRange(logFile) {
return 0, 0, false
}
r.Add(logFile)
}
minOffset, highWaterMark := r.Bounds()
return minOffset, highWaterMark - 1, len(logFiles) > 0
}
func recordsOffsetRange(logFile *filer_pb.Entry) bool {
return len(logFile.Extended[mq.ExtendedAttrOffsetMin]) == 8 && len(logFile.Extended[mq.ExtendedAttrOffsetMax]) == 8
}
func saveParquetFileToPartitionDir(filerClient filer_pb.FilerClient, sourceFile *os.File, partitionDir, parquetFileName string, preference *operation.StoragePreference, startTsNs, stopTsNs int64, sourceLogFiles []string, earliestBufferStart int64, minOffset, maxOffset int64, hasOffsets bool) error {
uploader, err := operation.NewUploader()
if err != nil {
@@ -444,7 +457,7 @@ func saveParquetFileToPartitionDir(filerClient filer_pb.FilerClient, sourceFile
entry.Extended[mq.ExtendedAttrTimestampMax] = maxTsBytes
// Add offset range metadata for Kafka integration (same as regular log files)
if hasOffsets && minOffset > 0 && maxOffset >= minOffset {
if hasOffsets && maxOffset >= minOffset {
minOffsetBytes := make([]byte, 8)
binary.BigEndian.PutUint64(minOffsetBytes, uint64(minOffset))
entry.Extended[mq.ExtendedAttrOffsetMin] = minOffsetBytes
@@ -0,0 +1,30 @@
package logstore
import (
"encoding/binary"
"testing"
"github.com/seaweedfs/seaweedfs/weed/mq"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
func rangedLogFile(minOffset, maxOffset int64) *filer_pb.Entry {
return &filer_pb.Entry{Extended: map[string][]byte{
mq.ExtendedAttrOffsetMin: binary.BigEndian.AppendUint64(nil, uint64(minOffset)),
mq.ExtendedAttrOffsetMax: binary.BigEndian.AppendUint64(nil, uint64(maxOffset)),
}}
}
// A parquet file records its sources' offset range, also one starting at offset 0,
// and none when a source records no range.
func TestParquetOffsetRangeFromSources(t *testing.T) {
if minOffset, maxOffset, ok := sourcesOffsetRange([]*filer_pb.Entry{rangedLogFile(0, 99), rangedLogFile(100, 199)}); !ok || minOffset != 0 || maxOffset != 199 {
t.Errorf("range %d..%d ok=%v, want 0..199", minOffset, maxOffset, ok)
}
if minOffset, maxOffset, ok := sourcesOffsetRange([]*filer_pb.Entry{rangedLogFile(300, 399), rangedLogFile(200, 299)}); !ok || minOffset != 200 || maxOffset != 399 {
t.Errorf("range %d..%d ok=%v, want 200..399", minOffset, maxOffset, ok)
}
if _, _, ok := sourcesOffsetRange([]*filer_pb.Entry{rangedLogFile(0, 99), {Name: "legacy"}}); ok {
t.Error("recorded a range for sources one of which records none")
}
}
+18 -5
View File
@@ -83,9 +83,12 @@ func GenParquetReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p topic
return startPosition, true, nil
}
}
recordType = schema.NewRecordTypeBuilder(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).
WithField(SW_COLUMN_NAME_KEY, schema.TypeBytes).
RecordTypeEnd()
recordType = schema.NewRecordTypeBuilder(proto.Clone(recordTypeWithoutOffset).(*schema_pb.RecordType)).
WithField(SW_COLUMN_NAME_OFFSET, schema.TypeInt64).
RecordTypeEnd()
@@ -93,6 +96,10 @@ func GenParquetReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p topic
if err != nil {
return nil
}
parquetLevelsWithoutOffset, err := schema.ToParquetLevels(recordTypeWithoutOffset)
if err != nil {
return nil
}
// 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) {
@@ -108,6 +115,13 @@ func GenParquetReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p topic
// create parquet reader
parquetReader := parquet.NewReader(readerAt)
fileRecordType, fileLevels := recordTypeWithoutOffset, parquetLevelsWithoutOffset
_, hasOffsetColumn := parquetReader.Schema().Lookup(SW_COLUMN_NAME_OFFSET)
if hasOffsetColumn {
fileRecordType, fileLevels = recordType, parquetLevels
}
// 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
rows := make([]parquet.Row, 128)
for {
rowCount, readErr := parquetReader.ReadRows(rows)
@@ -116,7 +130,7 @@ func GenParquetReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p topic
for i := 0; i < rowCount; i++ {
row := rows[i]
// convert parquet row to schema_pb.RecordValue
recordValue, err := schema.ToRecordValue(recordType, parquetLevels, row)
recordValue, err := schema.ToRecordValue(fileRecordType, fileLevels, row)
if err != nil {
return processedTsNs, fmt.Errorf("ToRecordValue failed: %w", err)
}
@@ -133,9 +147,8 @@ func GenParquetReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p topic
return processedTsNs, fmt.Errorf("marshal record value: %w", marshalErr)
}
// Get offset from parquet, default to 0 if not present (backward compatibility)
var offset int64 = 0
if offsetValue, exists := recordValue.Fields[SW_COLUMN_NAME_OFFSET]; exists {
offset := int64(-1)
if offsetValue := recordValue.Fields[SW_COLUMN_NAME_OFFSET]; hasOffsets && offsetValue != nil {
offset = offsetValue.GetInt64Value()
}
+47 -6
View File
@@ -3,8 +3,11 @@ package mq
import (
"context"
"encoding/binary"
"encoding/json"
"math"
"strings"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
@@ -12,25 +15,48 @@ import (
type OffsetRange struct {
earliest, latest int64
hasEarliest, hasLatest bool
// data files that record no range, which may hold offsets below every recorded one
unrangedLog bool
unrangedParquet [][]string
names map[string]bool
}
func (r *OffsetRange) Add(extended map[string][]byte) {
func (r *OffsetRange) Add(entry *filer_pb.Entry) {
if entry.IsDirectory {
return
}
extended := entry.Extended
base, isParquet := strings.CutSuffix(entry.Name, ".parquet")
_, notDataErr := topic.ParseLogFileTime(base)
if b, ok := extended[ExtendedAttrOffsetMin]; ok && len(b) == 8 {
if v := int64(binary.BigEndian.Uint64(b)); !r.hasEarliest || v < r.earliest {
r.earliest, r.hasEarliest = v, true
}
} else if notDataErr == nil {
if isParquet {
var sources []string
_ = json.Unmarshal(extended[ExtendedAttrSources], &sources)
r.unrangedParquet = append(r.unrangedParquet, sources)
} else {
r.unrangedLog = true
}
}
if b, ok := extended[ExtendedAttrOffsetMax]; ok && len(b) == 8 {
if v := int64(binary.BigEndian.Uint64(b)); !r.hasLatest || v > r.latest {
r.latest, r.hasLatest = v, true
}
}
if r.names == nil {
r.names = make(map[string]bool)
}
r.names[entry.Name] = true
}
// Bounds is the earliest recorded offset and the offset after the latest,
// both 0 when no file records a range.
// both 0 when no file records a range. The earliest is 0 while a data file
// records no range, unless it is a parquet file whose sources are all present.
func (r *OffsetRange) Bounds() (earliestOffset, highWaterMark int64) {
if r.hasEarliest {
if r.hasEarliest && !r.hasUnknownOffsets() {
earliestOffset = r.earliest
}
if r.hasLatest {
@@ -39,14 +65,29 @@ func (r *OffsetRange) Bounds() (earliestOffset, highWaterMark int64) {
return
}
func (r *OffsetRange) hasUnknownOffsets() bool {
if r.unrangedLog {
return true
}
for _, sources := range r.unrangedParquet {
if len(sources) == 0 {
return true
}
for _, source := range sources {
if !r.names[source] {
return true
}
}
}
return false
}
// ReadOffsetRange scans every file of a partition directory, not just the
// filer's default listing page, for the offset ranges they record.
func ReadOffsetRange(ctx context.Context, client filer_pb.SeaweedFilerClient, partitionDir string) (earliestOffset, highWaterMark int64, err error) {
var r OffsetRange
err = filer_pb.SeaweedList(ctx, client, partitionDir, "", func(entry *filer_pb.Entry, isLast bool) error {
if !entry.IsDirectory {
r.Add(entry.Extended)
}
r.Add(entry)
return nil
}, "", false, math.MaxInt32)
if err != nil {
+34
View File
@@ -3,6 +3,7 @@ package mq
import (
"context"
"encoding/binary"
"encoding/json"
"fmt"
"net"
"testing"
@@ -31,6 +32,39 @@ func TestOffsetRangeBounds(t *testing.T) {
{"first window", []map[string][]byte{rangeAttrs(0, 199)}, 0, 200},
{"two windows", []map[string][]byte{rangeAttrs(200, 399), rangeAttrs(0, 199)}, 0, 400},
{"trimmed head", []map[string][]byte{rangeAttrs(500, 599)}, 500, 600},
} {
var r OffsetRange
for _, f := range tc.files {
r.Add(&filer_pb.Entry{Extended: f})
}
if earliest, hwm := r.Bounds(); earliest != tc.earliest || hwm != tc.hwm {
t.Errorf("%s: Bounds() = %d, %d; want %d, %d", tc.name, earliest, hwm, tc.earliest, tc.hwm)
}
}
}
// A data file that records no range may hold offsets below every recorded one,
// so the earliest offset is not raised past it; a parquet file is covered by its
// sources while they are all present.
func TestOffsetRangeWithUnrangedFiles(t *testing.T) {
logFile := func(name string, min, max int64) *filer_pb.Entry {
return &filer_pb.Entry{Name: name, Extended: rangeAttrs(min, max)}
}
parquet := func(name string, sources ...string) *filer_pb.Entry {
listed, _ := json.Marshal(sources)
return &filer_pb.Entry{Name: name + ".parquet", Extended: map[string][]byte{ExtendedAttrSources: listed}}
}
first, second, third := "2026-11-30-10-00-00.00000000000000000000", "2026-11-30-10-01-00.00000000000000000100", "2026-11-30-10-02-00.00000000000000000200"
for _, tc := range []struct {
name string
files []*filer_pb.Entry
earliest, hwm int64
}{
{"parquet with its sources", []*filer_pb.Entry{logFile(second, 100, 199), logFile(third, 200, 299), parquet(second, second, third)}, 100, 300},
{"parquet past its purged source", []*filer_pb.Entry{logFile(second, 100, 199), parquet(first, first, second)}, 0, 200},
{"parquet listing no sources", []*filer_pb.Entry{logFile(second, 100, 199), parquet(first)}, 0, 200},
{"legacy log file", []*filer_pb.Entry{{Name: "2026-11-30-09-59-00"}, logFile(second, 100, 199)}, 0, 200},
{"other entries", []*filer_pb.Entry{{Name: ".fence"}, {Name: "group.offset"}, logFile(second, 100, 199)}, 100, 200},
} {
var r OffsetRange
for _, f := range tc.files {
+3
View File
@@ -50,6 +50,8 @@ var (
ErrBufferCorrupted = fmt.Errorf("log buffer is corrupted")
// ErrBufferStopped indicates that shutdown has closed write admission.
ErrBufferStopped = fmt.Errorf("log buffer is stopping")
// ErrOffsetOutOfRange is a read below the earliest offset still stored.
ErrOffsetOutOfRange = fmt.Errorf("offset out of range")
)
type dataToFlush struct {
@@ -173,6 +175,7 @@ type LogBuffer struct {
curWindowMaxOriginalTsNs int64 // max pre-bump ts in the open window, under the write lock
offset int64
bufferStartOffset int64
logStartOffset int64 // earliest offset still stored, raised as old files are purged
minOffset int64
maxOffset int64
flushInterval time.Duration
+52 -74
View File
@@ -2,6 +2,7 @@ package log_buffer
import (
"fmt"
"sort"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
@@ -51,6 +52,11 @@ func (logBuffer *LogBuffer) ReadMessagesAtOffset(startOffset int64, maxMessages
bufferStartOffset := logBuffer.bufferStartOffset
highWaterMark = currentBufferEnd
if logStartOffset := logBuffer.logStartOffset; startOffset < logStartOffset {
logBuffer.RUnlock()
return messages, startOffset, highWaterMark, false, fmt.Errorf("offset %d is before the log start offset %d: %w", startOffset, logStartOffset, ErrOffsetOutOfRange)
}
// Special case: empty buffer (no data written yet)
if currentBufferEnd == 0 && bufferStartOffset == 0 && logBuffer.pos == 0 {
logBuffer.RUnlock()
@@ -230,31 +236,19 @@ func readHistoricalDataFromDisk(
cachedMessages, cacheHit := getCachedDiskChunk(logBuffer, chunkStartOffset)
if cacheHit {
// Found in cache - extract requested messages
result, nextOff, err := extractMessagesFromCache(cachedMessages, startOffset, maxMessages, maxBytes)
if err != nil {
// CRITICAL: Cache extraction failed because requested offset is BEYOND cached chunk
// This means disk files only contain partial data (e.g., 1000-1763) and the
// requested offset (e.g., 1764) is in a gap between disk and memory.
//
// SOLUTION: Return empty result with NO ERROR to let ReadMessagesAtOffset
// continue to check memory buffers. The data might be in memory even though
// it's not on disk.
glog.Errorf("[DiskCache] Offset %d is beyond cached chunk (start=%d, size=%d)",
startOffset, chunkStartOffset, len(cachedMessages))
// Return empty but NO ERROR - this signals "not on disk, try memory"
return nil, startOffset, nil
result, nextOff := extractMessagesFromCache(cachedMessages, startOffset, maxMessages, maxBytes)
if len(result) > 0 && result[0].Offset == startOffset {
return result, nextOff, nil
}
// Success - return cached data
return result, nextOff, nil
// cached while later offsets were still in memory; they may be on disk by now
logBuffer.diskChunkCache.mu.Lock()
delete(logBuffer.diskChunkCache.chunks, chunkStartOffset)
logBuffer.diskChunkCache.mu.Unlock()
}
// Not in cache - read entire chunk from disk for caching
chunkMessages := make([]*filer_pb.LogEntry, 0, chunkSize)
chunkNextOffset := chunkStartOffset
chunkEndOffset := chunkStartOffset + chunkSize
// Create a position for the chunk start
chunkPosition := MessagePosition{
@@ -262,18 +256,22 @@ func readHistoricalDataFromDisk(
Offset: chunkStartOffset,
}
// Define callback to collect the entire chunk
// Files whose names sort out of offset order deliver entries out of order, so
// keep the chunk's offsets wherever they come and stop a bounded way past it.
outside := 0
// log files and the parquet files compacted from them can both deliver an offset
seen := make(map[int64]bool, chunkSize)
eachMessageFn := func(logEntry *filer_pb.LogEntry) (isDone bool, err error) {
// Read up to chunkSize messages for caching
if len(chunkMessages) >= chunkSize {
return true, nil
if logEntry.Offset < chunkStartOffset || logEntry.Offset >= chunkEndOffset {
outside++
return outside >= chunkSize, nil
}
if seen[logEntry.Offset] {
return false, nil
}
seen[logEntry.Offset] = true
chunkMessages = append(chunkMessages, logEntry)
chunkNextOffset++
// Continue reading the chunk
return false, nil
return len(chunkMessages) >= chunkSize, nil
}
// Read chunk from disk
@@ -285,15 +283,16 @@ func readHistoricalDataFromDisk(
}
// Cache the chunk for future reads
sort.Slice(chunkMessages, func(i, j int) bool { return chunkMessages[i].Offset < chunkMessages[j].Offset })
if len(chunkMessages) > 0 {
cacheDiskChunk(logBuffer, chunkStartOffset, chunkNextOffset-1, chunkMessages)
cacheDiskChunk(logBuffer, chunkStartOffset, chunkMessages[len(chunkMessages)-1].Offset, chunkMessages)
} else {
glog.Errorf("[DiskRead] WARNING: ReadFromDiskFn returned 0 messages for chunkStart=%d", chunkStartOffset)
}
// Extract requested messages from the chunk
result, resNextOffset, resErr := extractMessagesFromCache(chunkMessages, startOffset, maxMessages, maxBytes)
return result, resNextOffset, resErr
result, resNextOffset := extractMessagesFromCache(chunkMessages, startOffset, maxMessages, maxBytes)
return result, resNextOffset, nil
}
// getCachedDiskChunk retrieves a cached disk chunk if available
@@ -344,55 +343,37 @@ func cacheDiskChunk(logBuffer *LogBuffer, startOffset, endOffset int64, messages
}
}
// extractMessagesFromCache extracts requested messages from a cached chunk
// chunkMessages contains messages starting from the chunk's aligned start offset
// We need to skip to the requested startOffset within the chunk
func extractMessagesFromCache(chunkMessages []*filer_pb.LogEntry, startOffset int64, maxMessages, maxBytes int) ([]*filer_pb.LogEntry, int64, error) {
const chunkSize = 1000
chunkStartOffset := (startOffset / chunkSize) * chunkSize
// Calculate position within chunk
positionInChunk := int(startOffset - chunkStartOffset)
// Check if requested offset is within the chunk
if positionInChunk < 0 {
glog.Errorf("[DiskCache] CRITICAL: Requested offset %d is BEFORE chunk start %d (positionInChunk=%d < 0)",
startOffset, chunkStartOffset, positionInChunk)
return nil, startOffset, fmt.Errorf("offset %d before chunk start %d", startOffset, chunkStartOffset)
// extractMessagesFromCache returns the chunk's messages from startOffset on. They are
// found by offset, because a chunk starts at its first stored offset, not at its aligned start.
func extractMessagesFromCache(chunkMessages []*filer_pb.LogEntry, startOffset int64, maxMessages, maxBytes int) ([]*filer_pb.LogEntry, int64) {
first := sort.Search(len(chunkMessages), func(i int) bool { return chunkMessages[i].Offset >= startOffset })
if first == len(chunkMessages) {
// not on disk; the caller checks the memory buffers
return nil, startOffset
}
if positionInChunk >= len(chunkMessages) {
// Requested offset is beyond the cached chunk
// This happens when disk files only contain partial data
// The requested offset might be in the gap between disk and memory
// Return empty (data not on disk) - caller will check memory buffers
return nil, startOffset, nil
}
// Extract messages starting from the requested position
messages := make([]*filer_pb.LogEntry, 0, maxMessages)
nextOffset := startOffset
totalBytes := 0
for i := positionInChunk; i < len(chunkMessages) && len(messages) < maxMessages; i++ {
entry := chunkMessages[i]
for _, entry := range chunkMessages[first:] {
if len(messages) >= maxMessages {
break
}
entrySize := proto.Size(entry)
// Check byte limit
if totalBytes > 0 && totalBytes+entrySize > maxBytes {
break
}
messages = append(messages, entry)
totalBytes += entrySize
nextOffset++
nextOffset = entry.Offset + 1
}
glog.V(4).Infof("[DiskCache] Extracted %d messages from cache (offset %d-%d, bytes=%d)",
len(messages), startOffset, nextOffset-1, totalBytes)
return messages, nextOffset, nil
return messages, nextOffset
}
// parseMessagesFromBuffer parses messages from a buffer byte slice
@@ -469,21 +450,18 @@ func (logBuffer *LogBuffer) GetHighWaterMark() int64 {
return logBuffer.offset
}
// GetLogStartOffset returns the earliest offset available (either in memory or on disk)
// This is useful for clients to know the valid offset range
// GetLogStartOffset returns the earliest offset still stored, in memory or on disk.
func (logBuffer *LogBuffer) GetLogStartOffset() int64 {
logBuffer.RLock()
defer logBuffer.RUnlock()
return logBuffer.logStartOffset
}
// Check if we have offset information
if !logBuffer.hasOffsets {
return 0
}
// Return the current buffer start offset - this is the earliest offset in memory RIGHT NOW
// For stateless fetch, we only return what's currently available in memory
// We don't check prevBuffers because they may be stale or getting flushed
return logBuffer.bufferStartOffset
// SetLogStartOffset raises the earliest offset still stored; reads below it are out of range.
func (logBuffer *LogBuffer) SetLogStartOffset(offset int64) {
logBuffer.Lock()
defer logBuffer.Unlock()
logBuffer.logStartOffset = max(logBuffer.logStartOffset, offset)
}
// WaitForDataWithTimeout waits up to maxWaitMs for data to be available at startOffset
+141 -3
View File
@@ -1,6 +1,7 @@
package log_buffer
import (
"errors"
"testing"
"time"
@@ -382,9 +383,146 @@ func TestGetLogStartOffset(t *testing.T) {
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
lb.hasOffsets = true
lb.bufferStartOffset = 10
lb.offset = 20
lso := lb.GetLogStartOffset()
if lso != 10 {
t.Errorf("Expected LSO=10, got %d", lso)
// offsets below the in-memory window are still on disk
if lso := lb.GetLogStartOffset(); lso != 0 {
t.Errorf("Expected LSO=0, got %d", lso)
}
lb.SetLogStartOffset(7)
lb.SetLogStartOffset(3)
if lso := lb.GetLogStartOffset(); lso != 7 {
t.Errorf("Expected LSO=7 after it was raised to 7, got %d", lso)
}
if _, _, _, _, err := lb.ReadMessagesAtOffset(6, 10, 1024); !errors.Is(err, ErrOffsetOutOfRange) {
t.Errorf("read below the log start: %v, want ErrOffsetOutOfRange", err)
}
}
// Once older files are purged, a disk chunk starts above its aligned start, so
// a read must find its offset by value rather than by position in the chunk.
func TestReadMessagesAtOffset_DiskChunkStartingAboveItsAlignedStart(t *testing.T) {
const earliest, end = 1500, 3000
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
lb.hasOffsets = true
lb.bufferStartOffset = end
lb.offset = end
lb.ReadFromDiskFn = func(start MessagePosition, stopTsNs int64, eachLogEntryFn EachLogEntryFuncType) (MessagePosition, bool, error) {
for offset := max(start.Offset, earliest); offset < end; offset++ {
if done, err := eachLogEntryFn(&filer_pb.LogEntry{Offset: offset, Data: []byte("v")}); done || err != nil {
return start, false, err
}
}
return start, false, nil
}
for _, startOffset := range []int64{1600, 1501, 2400} {
messages, nextOffset, _, _, err := lb.ReadMessagesAtOffset(startOffset, 5, 1<<20)
if err != nil {
t.Fatal(err)
}
if len(messages) != 5 || messages[0].Offset != startOffset || messages[4].Offset != startOffset+4 || nextOffset != startOffset+5 {
t.Fatalf("read at %d: %d messages from %v, next %d", startOffset, len(messages), messages, nextOffset)
}
}
}
// Files whose names sort out of offset order hand a disk read its entries out of
// order; each read must still return the messages at the offsets it asked for.
func TestReadMessagesAtOffset_DiskEntriesOutOfOrder(t *testing.T) {
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
lb.hasOffsets = true
lb.bufferStartOffset = 300
lb.offset = 300
order := append([]int64{256, 257}, make([]int64, 0, 256)...)
for offset := int64(0); offset < 256; offset++ {
order = append(order, offset)
}
for offset := int64(258); offset < 300; offset++ {
order = append(order, offset)
}
lb.ReadFromDiskFn = func(start MessagePosition, stopTsNs int64, eachLogEntryFn EachLogEntryFuncType) (MessagePosition, bool, error) {
for _, offset := range order {
if offset < start.Offset {
continue
}
if done, err := eachLogEntryFn(&filer_pb.LogEntry{Offset: offset, Data: []byte("v")}); done || err != nil {
return start, false, err
}
}
return start, false, nil
}
for _, startOffset := range []int64{0, 255, 256, 3} {
messages, nextOffset, _, _, err := lb.ReadMessagesAtOffset(startOffset, 3, 1<<20)
if err != nil {
t.Fatal(err)
}
if len(messages) != 3 || messages[0].Offset != startOffset || messages[2].Offset != startOffset+2 || nextOffset != startOffset+3 {
t.Fatalf("read at %d: %v, next %d", startOffset, messages, nextOffset)
}
}
}
// diskReadFrom serves offset-based disk reads from runs of offsets delivered in turn,
// as a reader that goes through the log files and then the parquet files does.
func diskReadFrom(runs ...[2]int64) LogReadFromDiskFuncType {
return func(start MessagePosition, stopTsNs int64, eachLogEntryFn EachLogEntryFuncType) (MessagePosition, bool, error) {
for _, run := range runs {
for offset := max(run[0], start.Offset); offset <= run[1]; offset++ {
if done, err := eachLogEntryFn(&filer_pb.LogEntry{Offset: offset, Data: []byte("v")}); done || err != nil {
return start, false, err
}
}
}
return start, false, nil
}
}
// A chunk cached while its later offsets were still in memory must not hide
// them once they are flushed and the memory has moved on.
func TestReadMessagesAtOffset_CachedChunkPrefix(t *testing.T) {
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
lb.hasOffsets = true
lb.bufferStartOffset = 300
lb.offset = 300
lb.ReadFromDiskFn = diskReadFrom([2]int64{0, 99})
if messages, _, _, _, err := lb.ReadMessagesAtOffset(50, 5, 1<<20); err != nil || len(messages) != 5 {
t.Fatalf("read at 50: %d messages, %v", len(messages), err)
}
lb.ReadFromDiskFn = diskReadFrom([2]int64{0, 299})
messages, nextOffset, _, _, err := lb.ReadMessagesAtOffset(150, 5, 1<<20)
if err != nil {
t.Fatal(err)
}
if len(messages) != 5 || messages[0].Offset != 150 || nextOffset != 155 {
t.Fatalf("read at 150 past the cached prefix: %v, next %d", messages, nextOffset)
}
}
// Log files and a parquet file compacted from them both hold offsets 1000-1499;
// each offset is returned once.
func TestReadMessagesAtOffset_DiskOffsetsInLogsAndParquet(t *testing.T) {
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
lb.hasOffsets = true
lb.bufferStartOffset = 1500
lb.offset = 1500
lb.ReadFromDiskFn = diskReadFrom([2]int64{1000, 1499}, [2]int64{0, 1499})
for _, startOffset := range []int64{1100, 0} {
messages, nextOffset, _, _, err := lb.ReadMessagesAtOffset(startOffset, 5, 1<<20)
if err != nil {
t.Fatal(err)
}
for i, m := range messages {
if m.Offset != startOffset+int64(i) {
t.Fatalf("read at %d: message %d has offset %d", startOffset, i, m.Offset)
}
}
if len(messages) != 5 || nextOffset != startOffset+5 {
t.Fatalf("read at %d: %d messages, next %d", startOffset, len(messages), nextOffset)
}
}
}