Skip to content

SeaweedFS is a distributed storage system for object storage (S3), file systems, Iceberg table buckets, and Lance vector buckets, designed to handle billions of files with O(1) disk access and effortless horizontal scaling.

Share metadata-log replays per chunk instead of per file (#9906)

Chris Lubf7604004634
diff --git a/weed/filer/filer_notify_read.go b/weed/filer/filer_notify_read.go
index 695e38af5f..1f0dd0507b 100644
--- a/weed/filer/filer_notify_read.go
+++ b/weed/filer/filer_notify_read.go
@@ -3,9 +3,11 @@ package filer
import (
"container/heap"
"context"
+ "errors"
"fmt"
"io"
"math"
+ "sort"
"strings"
"time"
@@ -366,9 +368,10 @@ func (iter *LogFileQueueIterator) Close() {
}
}
-// getNext streams one log entry at a time from the current file, advancing to
+// getNext yields one log entry at a time from the current file, advancing to
// the next file as each is exhausted. It returns io.EOF when done. Entries are
-// not buffered per file, so memory stays O(1) regardless of log file size.
+// decoded one chunk at a time and shared across subscribers, so per-subscriber
+// memory stays bounded regardless of log file size.
func (iter *LogFileQueueIterator) getNext(v *OrderedLogVisitor) (logEntry *filer_pb.LogEntry, err error) {
for {
if iter.currentFileIterator != nil {
@@ -420,49 +423,65 @@ func (iter *LogFileQueueIterator) getNext(v *OrderedLogVisitor) (logEntry *filer
if next != nil && next.TsNs <= iter.startTsNs {
continue
}
- iter.currentFileIterator = newLogFileIterator(iter.masterClient, iter.cache, t.FileEntry, t.TsNs, iter.startTsNs, iter.stopTsNs)
+ iter.currentFileIterator = newLogFileIterator(iter.masterClient, iter.cache, t.FileEntry, iter.startTsNs, iter.stopTsNs)
}
}
// ----------
type LogFileIterator struct {
- // streaming mode (current/incomplete file): one entry read at a time.
- r io.Reader
- sizeBuf []byte
- // cached mode (completed file): iterate the shared decoded slice. Entries are
- // read-only and shared across subscribers, so they are never mutated here.
- cached []*filer_pb.LogEntry
- cachedPos int
- loadErr error
+ // cached mode: each immutable chunk is decoded once and shared read-only
+ // across subscribers via the persisted-log cache.
+ masterClient *wdclient.MasterClient
+ cache *persistedLogCache
+ chunks []*filer_pb.FileChunk
+ chunkIdx int
+ cur []*filer_pb.LogEntry
+ curPos int
+ lastTsNs int64
+ // streaming mode: the whole file as one byte stream, the fallback when a
+ // chunk does not decode standalone (records spanning chunk boundaries).
+ r io.Reader
+ sizeBuf []byte
startTsNs int64
stopTsNs int64
filePath string
}
-func newLogFileIterator(masterClient *wdclient.MasterClient, cache *persistedLogCache, fileEntry *Entry, fileTsNs, startTsNs, stopTsNs int64) *LogFileIterator {
- filePath := string(fileEntry.FullPath)
- if cache != nil && logFileIsCacheable(fileTsNs) {
- chunks := fileEntry.GetChunks()
- fingerprint := chunksFingerprint(chunks)
- entries, err := cache.getOrLoad(filePath, fingerprint, func() ([]*filer_pb.LogEntry, bool, error) {
- return loadLogFileEntries(masterClient, filePath, chunks)
- })
- return &LogFileIterator{
- cached: entries,
- loadErr: err,
- startTsNs: startTsNs,
- stopTsNs: stopTsNs,
- filePath: filePath,
- }
- }
- return &LogFileIterator{
- r: NewChunkStreamReaderFromFiler(context.Background(), masterClient, fileEntry.Chunks),
- sizeBuf: make([]byte, 4),
+// swapped in tests
+var loadLogFileEntriesFn = loadLogFileEntries
+var newLogFileStreamReader = func(masterClient *wdclient.MasterClient, chunks []*filer_pb.FileChunk) io.Reader {
+ return NewChunkStreamReaderFromFiler(context.Background(), masterClient, chunks)
+}
+
+func newLogFileIterator(masterClient *wdclient.MasterClient, cache *persistedLogCache, fileEntry *Entry, startTsNs, stopTsNs int64) *LogFileIterator {
+ iter := &LogFileIterator{
+ masterClient: masterClient,
+ cache: cache,
+ // sort a copy, leaving the listed entry's chunk order alone
+ chunks: append([]*filer_pb.FileChunk(nil), fileEntry.GetChunks()...),
startTsNs: startTsNs,
stopTsNs: stopTsNs,
- filePath: filePath,
+ filePath: string(fileEntry.FullPath),
}
+ sort.SliceStable(iter.chunks, func(i, j int) bool {
+ return iter.chunks[i].Offset < iter.chunks[j].Offset
+ })
+ if cache == nil {
+ iter.startStreaming()
+ }
+ return iter
+}
+
+// startStreaming switches to the byte-stream fallback, resuming after the last
+// yielded entry.
+func (iter *LogFileIterator) startStreaming() {
+ if iter.lastTsNs > iter.startTsNs {
+ iter.startTsNs = iter.lastTsNs
+ }
+ iter.r = newLogFileStreamReader(iter.masterClient, iter.chunks)
+ iter.sizeBuf = make([]byte, 4)
+ iter.cur, iter.curPos = nil, 0
}
func (iter *LogFileIterator) Close() error {
@@ -512,26 +531,44 @@ func (iter *LogFileIterator) getNext() (logEntry *filer_pb.LogEntry, err error)
}
}
-// getNextCached yields entries from the shared cached slice, applying the same
-// per-subscriber timestamp filtering as the streaming path. Any load error is
-// surfaced only after the read entries are yielded, so a partial read delivers
-// its prefix before failing, just like the streaming path.
+// getNextCached yields from shared per-chunk decoded slices, loading chunks
+// lazily and in order.
func (iter *LogFileIterator) getNextCached() (logEntry *filer_pb.LogEntry, err error) {
- for iter.cachedPos < len(iter.cached) {
- logEntry = iter.cached[iter.cachedPos]
- iter.cachedPos++
- if logEntry.TsNs <= iter.startTsNs {
- continue
+ for {
+ for iter.curPos < len(iter.cur) {
+ logEntry = iter.cur[iter.curPos]
+ iter.curPos++
+ if logEntry.TsNs <= iter.startTsNs {
+ continue
+ }
+ if iter.stopTsNs != 0 && logEntry.TsNs > iter.stopTsNs {
+ return nil, io.EOF
+ }
+ iter.lastTsNs = logEntry.TsNs
+ return logEntry, nil
}
- if iter.stopTsNs != 0 && logEntry.TsNs > iter.stopTsNs {
+ if iter.chunkIdx >= len(iter.chunks) {
return nil, io.EOF
}
- return logEntry, nil
- }
- if iter.loadErr != nil {
- err = iter.loadErr
- iter.loadErr = nil
- return nil, err
+ chunk := iter.chunks[iter.chunkIdx]
+ iter.chunkIdx++
+ // the flush upload time upper-bounds every record ts in the chunk; the
+ // margin tolerates a wall-clock retreat between stamping and upload
+ if chunk.ModifiedTsNs > 0 && chunk.ModifiedTsNs+int64(LogFlushInterval) <= iter.startTsNs {
+ continue
+ }
+ entries, loadErr := iter.cache.getOrLoad(chunk.GetFileIdString(), func() ([]*filer_pb.LogEntry, bool, error) {
+ return loadLogFileEntriesFn(iter.masterClient, chunk)
+ })
+ if loadErr != nil {
+ if errors.Is(loadErr, errLogChunkIncomplete) {
+ glog.V(1).Infof("log file %s chunk %s does not decode standalone, streaming the file", iter.filePath, chunk.GetFileIdString())
+ iter.startStreaming()
+ return iter.getNext()
+ }
+ return nil, loadErr
+ }
+ iter.cur = entries
+ iter.curPos = sort.Search(len(entries), func(i int) bool { return entries[i].TsNs > iter.startTsNs })
}
- return nil, io.EOF
}
diff --git a/weed/filer/persisted_log_cache.go b/weed/filer/persisted_log_cache.go
index c24777cb7a..762e17d745 100644
--- a/weed/filer/persisted_log_cache.go
+++ b/weed/filer/persisted_log_cache.go
@@ -1,44 +1,41 @@
package filer
import (
+ "bytes"
"container/list"
"context"
- "fmt"
- "io"
+ "errors"
"sync"
"time"
"golang.org/x/sync/singleflight"
"google.golang.org/protobuf/proto"
- "github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
)
const (
- // persistedLogCacheMaxBytes bounds retained entries regardless of subscriber
- // count.
+ // persistedLogCacheMaxBytes bounds retained entries regardless of subscriber count.
persistedLogCacheMaxBytes = 256 << 20
- // persistedLogCacheMinAge keeps the actively-written current file out of the
- // cache to avoid reload churn. It is a heuristic, not a correctness gate:
- // every hit is validated against the file's current chunk set (a fingerprint),
- // so a file that turns out to have grown is reloaded rather than served stale.
- persistedLogCacheMinAge = 2 * LogFlushInterval
- // persistedLogCacheMaxLoads bounds how many distinct files decode at once, so
- // the transient peak (an 8MB chunk reader plus the decoded slice per load)
- // stays bounded no matter how many positions the subscriber fleet spans.
+ // persistedLogCacheMaxLoads bounds how many chunks fetch and decode at once.
persistedLogCacheMaxLoads = 8
- // maxLogEntrySize guards the per-entry allocation against a corrupt size
- // prefix. The write path caps a single entry well under this, so it never
- // rejects a legitimate event.
+ // persistedLogCacheIdleTTL frees entries no replay has touched recently, so
+ // the cache holds memory only while subscribers actually replay.
+ persistedLogCacheIdleTTL = 5 * time.Minute
+ // maxLogEntrySize guards the per-entry allocation against a corrupt size prefix.
maxLogEntrySize = 1 << 30
)
-// persistedLogCache shares the decoded entries of completed metadata log files
-// across concurrent SubscribeMetadata replays, so N replays of the same history
-// read and decode each file once instead of N times. Cached entries are shared
+// errLogChunkIncomplete reports a chunk that does not start and end on record
+// boundaries; the file is then only readable as a whole byte stream.
+var errLogChunkIncomplete = errors.New("log chunk does not hold whole records")
+
+// persistedLogCache shares decoded metadata-log chunks across concurrent
+// SubscribeMetadata replays. Chunks are immutable (each log flush uploads one
+// whole buffer of complete records as a new chunk), so even the actively
+// written current file shares its flushed chunks. Cached entries are shared
// read-only; callers must not mutate them.
type persistedLogCache struct {
mu sync.Mutex
@@ -51,72 +48,66 @@ type persistedLogCache struct {
}
type logCacheItem struct {
- key string
- // fingerprint identifies the file's chunk set when it was decoded. A cached
- // item is only served when the caller's fingerprint still matches; an
- // appended-to file (e.g. a delayed flush landed after the file was first read)
- // produces a new fingerprint and is reloaded.
- fingerprint string
- entries []*filer_pb.LogEntry
- bytes int64
+ key string // chunk file id
+ entries []*filer_pb.LogEntry
+ bytes int64
+ lastUsed time.Time
}
func newPersistedLogCache(maxBytes int64) *persistedLogCache {
- return &persistedLogCache{
+ c := &persistedLogCache{
ll: list.New(),
index: make(map[string]*list.Element),
maxBytes: maxBytes,
loadSem: make(chan struct{}, persistedLogCacheMaxLoads),
}
+ // the filer's cache lives for the process lifetime
+ go c.loopEvictIdle()
+ return c
}
-// logFileIsCacheable reports whether a log file identified by its minute
-// timestamp is old enough that caching it is worthwhile (it is unlikely to still
-// be receiving appends). Correctness does not depend on this being exact.
-func logFileIsCacheable(fileTsNs int64) bool {
- return time.Since(time.Unix(0, fileTsNs)) > persistedLogCacheMinAge
+func (c *persistedLogCache) loopEvictIdle() {
+ ticker := time.NewTicker(time.Minute)
+ defer ticker.Stop()
+ for range ticker.C {
+ c.evictIdle(time.Now().Add(-persistedLogCacheIdleTTL))
+ }
}
-// chunksFingerprint summarizes a log file's append-only chunk set; it changes
-// whenever the file grows.
-func chunksFingerprint(chunks []*filer_pb.FileChunk) string {
- if len(chunks) == 0 {
- return "empty"
- }
- var total uint64
- for _, c := range chunks {
- total += c.Size
+// evictIdle drops every entry last used at or before cutoff. Recency order
+// makes the idle entries exactly the tail of the LRU list.
+func (c *persistedLogCache) evictIdle(cutoff time.Time) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ for c.ll.Len() > 0 {
+ el := c.ll.Back()
+ if el.Value.(*logCacheItem).lastUsed.After(cutoff) {
+ break
+ }
+ c.removeElement(el)
}
- return fmt.Sprintf("%d/%d/%s", len(chunks), total, chunks[len(chunks)-1].GetFileIdString())
}
-// getOrLoad returns the decoded entries for key, loading them once on miss and
-// coalescing concurrent misses for the same (key, fingerprint). A cached item
-// whose fingerprint no longer matches is treated as a miss and replaced. The
-// returned slice is shared and must be treated as read-only.
type logLoadResult struct {
entries []*filer_pb.LogEntry
err error
}
-// load returns the decoded entries, whether the result is stable enough to
-// cache, and any error. A read that stopped on a missing chunk is delivered to
-// this caller but not cached: the truncation point depends on transient volume
-// availability, not on the (cached) fingerprint, so it must be re-probed on
-// later replays. On a genuine error the partially-read entries are still
-// returned alongside the error so the caller can deliver them before failing,
-// matching the streaming path; only a clean, complete read is cached.
-func (c *persistedLogCache) getOrLoad(key, fingerprint string, load func() ([]*filer_pb.LogEntry, bool, error)) ([]*filer_pb.LogEntry, error) {
- if entries, ok := c.lookup(key, fingerprint); ok {
+// getOrLoad returns the decoded entries for a chunk, loading once on miss and
+// coalescing concurrent misses. Only a clean, complete decode is cached: a
+// chunk-not-found read must be re-probed on later replays, and an incomplete
+// chunk stays with the streaming fallback.
+func (c *persistedLogCache) getOrLoad(fileId string, load func() ([]*filer_pb.LogEntry, bool, error)) ([]*filer_pb.LogEntry, error) {
+ if entries, ok := c.lookup(fileId); ok {
return entries, nil
}
- v, _, _ := c.sf.Do(key+"\x00"+fingerprint, func() (interface{}, error) {
- if entries, ok := c.lookup(key, fingerprint); ok {
+ v, _, _ := c.sf.Do(fileId, func() (interface{}, error) {
+ if entries, ok := c.lookup(fileId); ok {
return logLoadResult{entries: entries}, nil
}
entries, cacheable, loadErr := c.loadGuarded(load)
if loadErr == nil && cacheable {
- c.store(key, fingerprint, entries)
+ c.store(fileId, entries)
}
return logLoadResult{entries: entries, err: loadErr}, nil
})
@@ -124,49 +115,39 @@ func (c *persistedLogCache) getOrLoad(key, fingerprint string, load func() ([]*f
return res.entries, res.err
}
-// loadGuarded runs load under the concurrent-load semaphore, releasing the slot
-// via defer so an abnormal exit cannot leak slots and wedge future loads.
func (c *persistedLogCache) loadGuarded(load func() ([]*filer_pb.LogEntry, bool, error)) ([]*filer_pb.LogEntry, bool, error) {
c.loadSem <- struct{}{}
defer func() { <-c.loadSem }()
return load()
}
-func (c *persistedLogCache) lookup(key, fingerprint string) ([]*filer_pb.LogEntry, bool) {
+func (c *persistedLogCache) lookup(fileId string) ([]*filer_pb.LogEntry, bool) {
c.mu.Lock()
defer c.mu.Unlock()
- el, ok := c.index[key]
+ el, ok := c.index[fileId]
if !ok {
return nil, false
}
- item := el.Value.(*logCacheItem)
- if item.fingerprint != fingerprint {
- // The file changed (grew) since it was cached; drop the stale snapshot so
- // the caller reloads and stores the current version.
- c.removeElement(el)
- return nil, false
- }
c.ll.MoveToFront(el)
+ item := el.Value.(*logCacheItem)
+ item.lastUsed = time.Now()
return item.entries, true
}
-func (c *persistedLogCache) store(key, fingerprint string, entries []*filer_pb.LogEntry) {
+func (c *persistedLogCache) store(fileId string, entries []*filer_pb.LogEntry) {
bytes := estimateEntriesBytes(entries)
if bytes > c.maxBytes {
- // A single file larger than the whole budget would evict everything else
- // and still not fit; serve it this round but do not retain it.
+ // would evict everything else and still not fit; serve unretained
return
}
c.mu.Lock()
defer c.mu.Unlock()
- if el, ok := c.index[key]; ok {
- c.removeElement(el) // replace any older version of this file
+ if el, ok := c.index[fileId]; ok {
+ c.removeElement(el)
}
- el := c.ll.PushFront(&logCacheItem{key: key, fingerprint: fingerprint, entries: entries, bytes: bytes})
- c.index[key] = el
+ el := c.ll.PushFront(&logCacheItem{key: fileId, entries: entries, bytes: bytes, lastUsed: time.Now()})
+ c.index[fileId] = el
c.curBytes += bytes
- // Evict least-recently-used until under budget, but always keep what we just
- // inserted (a single file larger than the budget still serves this round).
for c.curBytes > c.maxBytes && c.ll.Len() > 1 {
c.removeElement(c.ll.Back())
}
@@ -180,10 +161,9 @@ func (c *persistedLogCache) removeElement(el *list.Element) {
c.curBytes -= item.bytes
}
+// estimateEntriesBytes is deliberately generous so curBytes does not run under
+// the real retained heap.
func estimateEntriesBytes(entries []*filer_pb.LogEntry) int64 {
- // LogEntry struct (~112B) + slice slot (8B) + a little slack, plus the
- // payload backing arrays. Deliberately generous so curBytes does not run
- // under the real retained heap.
total := int64(len(entries)) * 128
for _, e := range entries {
total += int64(len(e.Data)+len(e.Key)) + 16
@@ -191,52 +171,52 @@ func estimateEntriesBytes(entries []*filer_pb.LogEntry) int64 {
return total
}
-// loadLogFileEntries reads a whole persisted log file from volume servers and
-// decodes every LogEntry. The second result reports whether the read reached a
-// clean end (cacheable). A chunk-not-found stop returns the readable prefix with
-// cacheable=false: the file's chunk list (the cache fingerprint) is unchanged by
-// a momentarily-unreachable volume, so caching the prefix would pin a truncation
-// that a transient outage should self-heal. Such reads mirror the streaming
-// path for this round but are re-probed on the next replay instead.
-func loadLogFileEntries(masterClient *wdclient.MasterClient, filePath string, chunks []*filer_pb.FileChunk) (entries []*filer_pb.LogEntry, cacheable bool, err error) {
- r := NewChunkStreamReaderFromFiler(context.Background(), masterClient, chunks)
- defer r.Close()
-
- sizeBuf := make([]byte, 4)
- for {
- if _, readErr := io.ReadFull(r, sizeBuf); readErr != nil {
- if readErr == io.EOF {
- // clean end exactly at a record boundary: every record was read
- return entries, true, nil
- }
- if readErr == io.ErrUnexpectedEOF {
- // stopped mid-frame (a partial size prefix): ambiguous, possibly a
- // transient short read, so deliver the prefix but do not cache it
- glog.V(1).Infof("log file %s ends mid-record, not caching", filePath)
- return entries, false, nil
- }
- if isChunkNotFoundError(readErr) {
- glog.V(1).Infof("log file %s has an unreadable chunk, not caching: %v", filePath, readErr)
- return entries, false, nil
- }
- return entries, false, readErr
+// loadLogFileEntries reads one log file chunk from volume servers and decodes
+// its records. fetchWholeChunk handles lookup, retries, cipher and gzip.
+func loadLogFileEntries(masterClient *wdclient.MasterClient, chunk *filer_pb.FileChunk) (entries []*filer_pb.LogEntry, cacheable bool, err error) {
+ bytesBuffer := bytesBufferPool.Get().(*bytes.Buffer)
+ bytesBuffer.Reset()
+ defer bytesBufferPool.Put(bytesBuffer)
+ lookupFileIdFn := func(ctx context.Context, fileId string) (targetUrls []string, err error) {
+ return masterClient.LookupFileId(ctx, fileId)
+ }
+ if fetchErr := fetchWholeChunk(context.Background(), bytesBuffer, lookupFileIdFn, chunk.GetFileIdString(), chunk.CipherKey, chunk.IsCompressed); fetchErr != nil {
+ return nil, false, fetchErr
+ }
+ return decodeLogRecords(bytesBuffer.Bytes())
+}
+
+// decodeLogRecords parses size-prefixed LogEntry records. A buffer that stops
+// mid-record, or whose size prefix is garbage (also the symptom of starting
+// mid-record), reports errLogChunkIncomplete with the cleanly decoded prefix.
+// Since proto.Unmarshal is permissive enough to accept misaligned bytes,
+// records must also satisfy the writer's invariants: never empty, a positive
+// timestamp, and strictly increasing within one flushed buffer.
+// proto.Unmarshal copies all bytes, so the entries do not alias data.
+func decodeLogRecords(data []byte) (entries []*filer_pb.LogEntry, cacheable bool, err error) {
+ var lastTsNs int64
+ for pos := 0; pos < len(data); {
+ if pos+4 > len(data) {
+ return entries, false, errLogChunkIncomplete
}
- size := util.BytesToUint32(sizeBuf)
- if size > maxLogEntrySize {
- return entries, false, fmt.Errorf("log file %s entry size %d exceeds %d", filePath, size, maxLogEntrySize)
+ size32 := util.BytesToUint32(data[pos : pos+4])
+ if size32 == 0 || size32 > maxLogEntrySize {
+ return entries, false, errLogChunkIncomplete
}
- entryData := make([]byte, size)
- if _, readErr := io.ReadFull(r, entryData); readErr != nil {
- if isChunkNotFoundError(readErr) {
- glog.V(1).Infof("log file %s has an unreadable chunk, not caching: %v", filePath, readErr)
- return entries, false, nil
- }
- return entries, false, readErr
+ size := int(size32)
+ if pos+4+size > len(data) {
+ return entries, false, errLogChunkIncomplete
}
logEntry := &filer_pb.LogEntry{}
- if unmarshalErr := proto.Unmarshal(entryData, logEntry); unmarshalErr != nil {
- return entries, false, unmarshalErr
+ if unmarshalErr := proto.Unmarshal(data[pos+4:pos+4+size], logEntry); unmarshalErr != nil {
+ return entries, false, errLogChunkIncomplete
+ }
+ if logEntry.TsNs <= lastTsNs {
+ return entries, false, errLogChunkIncomplete
}
+ lastTsNs = logEntry.TsNs
entries = append(entries, logEntry)
+ pos += 4 + size
}
+ return entries, true, nil
}
diff --git a/weed/filer/persisted_log_cache_test.go b/weed/filer/persisted_log_cache_test.go
index e3db7fbb48..3ab5b9ba2c 100644
--- a/weed/filer/persisted_log_cache_test.go
+++ b/weed/filer/persisted_log_cache_test.go
@@ -1,6 +1,7 @@
package filer
import (
+ "bytes"
"fmt"
"io"
"sync"
@@ -8,7 +9,11 @@ import (
"testing"
"time"
+ "google.golang.org/protobuf/proto"
+
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
+ "github.com/seaweedfs/seaweedfs/weed/util"
+ "github.com/seaweedfs/seaweedfs/weed/wdclient"
)
func logEntriesAt(tsNs ...int64) []*filer_pb.LogEntry {
@@ -19,6 +24,22 @@ func logEntriesAt(tsNs ...int64) []*filer_pb.LogEntry {
return out
}
+func encodeLogRecords(t *testing.T, entries []*filer_pb.LogEntry) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ sizeBuf := make([]byte, 4)
+ for _, e := range entries {
+ data, err := proto.Marshal(e)
+ if err != nil {
+ t.Fatal(err)
+ }
+ util.Uint32toBytes(sizeBuf, uint32(len(data)))
+ buf.Write(sizeBuf)
+ buf.Write(data)
+ }
+ return buf.Bytes()
+}
+
func TestPersistedLogCacheHitMiss(t *testing.T) {
c := newPersistedLogCache(persistedLogCacheMaxBytes)
var loads int32
@@ -27,11 +48,11 @@ func TestPersistedLogCacheHitMiss(t *testing.T) {
return logEntriesAt(1, 2, 3), true, nil
}
- e1, err := c.getOrLoad("k", "fp", load)
+ e1, err := c.getOrLoad("3,01", load)
if err != nil || len(e1) != 3 {
t.Fatalf("first getOrLoad: err=%v len=%d", err, len(e1))
}
- e2, err := c.getOrLoad("k", "fp", load)
+ e2, err := c.getOrLoad("3,01", load)
if err != nil {
t.Fatal(err)
}
@@ -43,42 +64,6 @@ func TestPersistedLogCacheHitMiss(t *testing.T) {
}
}
-func TestPersistedLogCacheFingerprintReload(t *testing.T) {
- c := newPersistedLogCache(persistedLogCacheMaxBytes)
- var loads int32
- loadV1 := func() ([]*filer_pb.LogEntry, bool, error) {
- atomic.AddInt32(&loads, 1)
- return logEntriesAt(1, 2), true, nil
- }
- loadV2 := func() ([]*filer_pb.LogEntry, bool, error) {
- atomic.AddInt32(&loads, 1)
- return logEntriesAt(1, 2, 3), true, nil // a delayed append grew the file
- }
-
- if e, _ := c.getOrLoad("k", "fp1", loadV1); len(e) != 2 {
- t.Fatalf("v1 len=%d", len(e))
- }
- // a later replay observes the grown file (new fingerprint): it must reload,
- // not serve the stale truncated snapshot.
- e, err := c.getOrLoad("k", "fp2", loadV2)
- if err != nil {
- t.Fatal(err)
- }
- if len(e) != 3 {
- t.Fatalf("expected reload to 3 entries, got %d", len(e))
- }
- if n := atomic.LoadInt32(&loads); n != 2 {
- t.Fatalf("expected one reload (2 loads), got %d", n)
- }
- // the cache now holds the new version; the matching fingerprint hits
- if _, err := c.getOrLoad("k", "fp2", loadV2); err != nil {
- t.Fatal(err)
- }
- if n := atomic.LoadInt32(&loads); n != 2 {
- t.Fatalf("expected fp2 to hit (still 2 loads), got %d", n)
- }
-}
-
func TestPersistedLogCacheNotCachedWhenUncacheable(t *testing.T) {
c := newPersistedLogCache(persistedLogCacheMaxBytes)
var loads int32
@@ -89,10 +74,10 @@ func TestPersistedLogCacheNotCachedWhenUncacheable(t *testing.T) {
return logEntriesAt(1, 2), false, nil
}
- if e, err := c.getOrLoad("k", "fp", load); err != nil || len(e) != 2 {
+ if e, err := c.getOrLoad("3,01", load); err != nil || len(e) != 2 {
t.Fatalf("first: err=%v len=%d", err, len(e))
}
- if e, err := c.getOrLoad("k", "fp", load); err != nil || len(e) != 2 {
+ if e, err := c.getOrLoad("3,01", load); err != nil || len(e) != 2 {
t.Fatalf("second: err=%v len=%d", err, len(e))
}
if n := atomic.LoadInt32(&loads); n != 2 {
@@ -100,20 +85,15 @@ func TestPersistedLogCacheNotCachedWhenUncacheable(t *testing.T) {
}
}
-func TestChunksFingerprintChangesOnGrowth(t *testing.T) {
- c1 := []*filer_pb.FileChunk{{FileId: "3,01", Size: 100}}
- c2 := []*filer_pb.FileChunk{{FileId: "3,01", Size: 100}, {FileId: "3,02", Size: 50}}
- if chunksFingerprint(c1) == chunksFingerprint(c2) {
- t.Fatal("fingerprint must change when a chunk is appended")
- }
-}
-
func TestPersistedLogCacheSingleFlight(t *testing.T) {
c := newPersistedLogCache(persistedLogCacheMaxBytes)
var loads int32
release := make(chan struct{})
+ started := make(chan struct{})
load := func() ([]*filer_pb.LogEntry, bool, error) {
- atomic.AddInt32(&loads, 1)
+ if atomic.AddInt32(&loads, 1) == 1 {
+ close(started)
+ }
<-release // hold the flight open so concurrent callers coalesce
return logEntriesAt(1), true, nil
}
@@ -124,12 +104,13 @@ func TestPersistedLogCacheSingleFlight(t *testing.T) {
wg.Add(1)
go func() {
defer wg.Done()
- if _, err := c.getOrLoad("k", "fp", load); err != nil {
+ if _, err := c.getOrLoad("3,01", load); err != nil {
t.Error(err)
}
}()
}
- time.Sleep(50 * time.Millisecond)
+ <-started // the flight is provably open before anyone is released
+ time.Sleep(10 * time.Millisecond)
close(release)
wg.Wait()
@@ -147,10 +128,10 @@ func TestPersistedLogCacheEviction(t *testing.T) {
}
}
- if _, err := c.getOrLoad("a", "fp", mk(1)); err != nil {
+ if _, err := c.getOrLoad("a", mk(1)); err != nil {
t.Fatal(err)
}
- if _, err := c.getOrLoad("b", "fp", mk(2)); err != nil { // pushes over budget, evicts LRU "a"
+ if _, err := c.getOrLoad("b", mk(2)); err != nil { // pushes over budget, evicts LRU "a"
t.Fatal(err)
}
@@ -166,61 +147,269 @@ func TestPersistedLogCacheEviction(t *testing.T) {
}
}
-func TestLogFileIsCacheable(t *testing.T) {
- now := time.Now()
- if logFileIsCacheable(now.UnixNano()) {
- t.Error("a current-minute file must not be cacheable")
+func TestDecodeLogRecords(t *testing.T) {
+ want := logEntriesAt(10, 20, 30)
+ entries, cacheable, err := decodeLogRecords(encodeLogRecords(t, want))
+ if err != nil || !cacheable {
+ t.Fatalf("clean chunk: err=%v cacheable=%v", err, cacheable)
+ }
+ if len(entries) != 3 || entries[0].TsNs != 10 || entries[2].TsNs != 30 {
+ t.Fatalf("decoded %v", entries)
}
- old := now.Add(-persistedLogCacheMinAge - time.Minute).UnixNano()
- if !logFileIsCacheable(old) {
- t.Error("a file older than the min age should be cacheable")
+
+ if entries, cacheable, err := decodeLogRecords(nil); err != nil || !cacheable || len(entries) != 0 {
+ t.Fatalf("empty chunk: entries=%v cacheable=%v err=%v", entries, cacheable, err)
}
}
-func TestLogFileIteratorCachedFiltering(t *testing.T) {
- iter := &LogFileIterator{
- cached: logEntriesAt(10, 20, 30, 40),
- startTsNs: 15,
- stopTsNs: 35,
+func TestDecodeLogRecordsIncomplete(t *testing.T) {
+ full := encodeLogRecords(t, logEntriesAt(10, 20))
+ rec1 := len(encodeLogRecords(t, logEntriesAt(10)))
+
+ // stops mid-record: the second record's bytes are cut short
+ entries, cacheable, err := decodeLogRecords(full[:len(full)-2])
+ if err != errLogChunkIncomplete || cacheable {
+ t.Fatalf("mid-record: err=%v cacheable=%v", err, cacheable)
+ }
+ if len(entries) != 1 || entries[0].TsNs != 10 {
+ t.Fatalf("mid-record prefix: %v", entries)
+ }
+
+ // stops mid-size-prefix
+ if _, _, err := decodeLogRecords(full[:rec1+2]); err != errLogChunkIncomplete {
+ t.Fatalf("mid-prefix: err=%v", err)
}
- var got []int64
+
+ // garbage size prefix, e.g. a chunk that starts mid-record
+ garbage := make([]byte, 8)
+ util.Uint32toBytes(garbage, uint32(maxLogEntrySize)+1)
+ if _, _, err := decodeLogRecords(garbage); err != errLogChunkIncomplete {
+ t.Fatalf("garbage size: err=%v", err)
+ }
+}
+
+func logFileEntry(chunks ...*filer_pb.FileChunk) *Entry {
+ return &Entry{
+ FullPath: "/topics/.system/log/2026-06-10/00-01.f1",
+ Attr: Attr{Mode: 0644},
+ Chunks: chunks,
+ }
+}
+
+func stubChunkLoader(t *testing.T, chunkData map[string][]byte) *int32 {
+ t.Helper()
+ var loads int32
+ prev := loadLogFileEntriesFn
+ loadLogFileEntriesFn = func(_ *wdclient.MasterClient, chunk *filer_pb.FileChunk) ([]*filer_pb.LogEntry, bool, error) {
+ atomic.AddInt32(&loads, 1)
+ data, ok := chunkData[chunk.GetFileIdString()]
+ if !ok {
+ t.Errorf("unexpected load of chunk %s", chunk.GetFileIdString())
+ return nil, false, fmt.Errorf("unexpected chunk %s", chunk.GetFileIdString())
+ }
+ return decodeLogRecords(data)
+ }
+ t.Cleanup(func() { loadLogFileEntriesFn = prev })
+ return &loads
+}
+
+func collectTs(t *testing.T, iter *LogFileIterator) (got []int64) {
+ t.Helper()
for {
e, err := iter.getNext()
if err == io.EOF {
- break
+ return
}
if err != nil {
t.Fatal(err)
}
got = append(got, e.TsNs)
}
+}
+
+func TestLogFileIteratorChunkedFiltering(t *testing.T) {
+ stubChunkLoader(t, map[string][]byte{
+ "3,01": encodeLogRecords(t, logEntriesAt(10, 20)),
+ "3,02": encodeLogRecords(t, logEntriesAt(30, 40)),
+ })
+ entry := logFileEntry(
+ &filer_pb.FileChunk{FileId: "3,01", Offset: 0, Size: 100, ModifiedTsNs: 25},
+ &filer_pb.FileChunk{FileId: "3,02", Offset: 100, Size: 100, ModifiedTsNs: 45},
+ )
+
+ iter := newLogFileIterator(nil, newPersistedLogCache(persistedLogCacheMaxBytes), entry, 15, 35)
+ got := collectTs(t, iter)
want := []int64{20, 30} // 10 filtered by startTsNs, 40 cut off by stopTsNs
if fmt.Sprint(got) != fmt.Sprint(want) {
- t.Fatalf("cached filtering: got %v, want %v", got, want)
+ t.Fatalf("chunked filtering: got %v, want %v", got, want)
}
}
-func TestLogFileIteratorCachedLoadError(t *testing.T) {
- iter := &LogFileIterator{loadErr: fmt.Errorf("boom")}
- if _, err := iter.getNext(); err == nil || err.Error() != "boom" {
- t.Fatalf("expected load error surfaced on first getNext, got %v", err)
+func TestLogFileIteratorSkipsColdChunks(t *testing.T) {
+ // chunk "3,01" is not in the stub map: loading it would fail the test. Its
+ // flush time (ModifiedTsNs) is a full flush interval before startTsNs, so it
+ // must be skipped without being read.
+ start := int64(20) + int64(LogFlushInterval)
+ stubChunkLoader(t, map[string][]byte{
+ "3,02": encodeLogRecords(t, logEntriesAt(start+10, start+20)),
+ })
+ entry := logFileEntry(
+ &filer_pb.FileChunk{FileId: "3,01", Offset: 0, Size: 100, ModifiedTsNs: 20},
+ &filer_pb.FileChunk{FileId: "3,02", Offset: 100, Size: 100, ModifiedTsNs: start + 25},
+ )
+
+ iter := newLogFileIterator(nil, newPersistedLogCache(persistedLogCacheMaxBytes), entry, start, 0)
+ got := collectTs(t, iter)
+ if fmt.Sprint(got) != fmt.Sprint([]int64{start + 10, start + 20}) {
+ t.Fatalf("cold-chunk skip: got %v", got)
}
}
-func TestLogFileIteratorCachedYieldsBeforeError(t *testing.T) {
- iter := &LogFileIterator{cached: logEntriesAt(10, 20), loadErr: fmt.Errorf("boom")}
- var got []int64
- for {
- e, err := iter.getNext()
- if err != nil {
- if err.Error() != "boom" {
- t.Fatalf("expected boom after entries, got %v", err)
- }
- break
+func TestLogFileIteratorSharesDecodedChunks(t *testing.T) {
+ loads := stubChunkLoader(t, map[string][]byte{
+ "3,01": encodeLogRecords(t, logEntriesAt(10, 20)),
+ })
+ entry := logFileEntry(&filer_pb.FileChunk{FileId: "3,01", Offset: 0, Size: 100, ModifiedTsNs: 25})
+ cache := newPersistedLogCache(persistedLogCacheMaxBytes)
+
+ for i := 0; i < 3; i++ { // three replays of the same chunk
+ iter := newLogFileIterator(nil, cache, entry, 0, 0)
+ if got := collectTs(t, iter); fmt.Sprint(got) != fmt.Sprint([]int64{10, 20}) {
+ t.Fatalf("replay %d: got %v", i, got)
}
- got = append(got, e.TsNs)
}
- if fmt.Sprint(got) != fmt.Sprint([]int64{10, 20}) {
- t.Fatalf("partial read must yield entries before the error, got %v", got)
+ if n := atomic.LoadInt32(loads); n != 1 {
+ t.Fatalf("expected one shared decode across replays, got %d", n)
+ }
+}
+
+func TestLogFileIteratorStreamsWhenRecordsSpanChunks(t *testing.T) {
+ // One file of four records, flushed in a way that splits the third record
+ // across two chunks. The first chunk decodes records 10 and 20 cleanly; the
+ // second starts mid-record. The iterator must yield every record exactly
+ // once by falling back to a whole-file byte stream.
+ all := logEntriesAt(10, 20, 30, 40)
+ full := encodeLogRecords(t, all)
+ cut := len(encodeLogRecords(t, all[:2])) + 3 // 3 bytes into record 30
+
+ stubChunkLoader(t, map[string][]byte{
+ "3,01": full[:cut],
+ "3,02": full[cut:],
+ })
+ prev := newLogFileStreamReader
+ newLogFileStreamReader = func(_ *wdclient.MasterClient, _ []*filer_pb.FileChunk) io.Reader {
+ return bytes.NewReader(full)
+ }
+ t.Cleanup(func() { newLogFileStreamReader = prev })
+
+ entry := logFileEntry(
+ &filer_pb.FileChunk{FileId: "3,01", Offset: 0, Size: uint64(cut), ModifiedTsNs: 45},
+ &filer_pb.FileChunk{FileId: "3,02", Offset: int64(cut), Size: uint64(len(full) - cut), ModifiedTsNs: 45},
+ )
+
+ iter := newLogFileIterator(nil, newPersistedLogCache(persistedLogCacheMaxBytes), entry, 0, 0)
+ got := collectTs(t, iter)
+ if fmt.Sprint(got) != fmt.Sprint([]int64{10, 20, 30, 40}) {
+ t.Fatalf("spanning fallback: got %v", got)
+ }
+}
+
+func TestLogFileIteratorStreamFallbackResumesAfterYielded(t *testing.T) {
+ // The first chunk decodes standalone and its records are yielded before the
+ // second chunk turns out to be incomplete. The stream fallback re-reads the
+ // file from the start, so the already-yielded records must be skipped.
+ all := logEntriesAt(10, 20, 30, 40)
+ full := encodeLogRecords(t, all)
+ chunk1 := len(encodeLogRecords(t, all[:2]))
+
+ stubChunkLoader(t, map[string][]byte{
+ "3,01": full[:chunk1],
+ "3,02": full[chunk1 : len(full)-2], // truncated mid-record
+ })
+ prev := newLogFileStreamReader
+ newLogFileStreamReader = func(_ *wdclient.MasterClient, _ []*filer_pb.FileChunk) io.Reader {
+ return bytes.NewReader(full)
+ }
+ t.Cleanup(func() { newLogFileStreamReader = prev })
+
+ entry := logFileEntry(
+ &filer_pb.FileChunk{FileId: "3,01", Offset: 0, Size: uint64(chunk1), ModifiedTsNs: 45},
+ &filer_pb.FileChunk{FileId: "3,02", Offset: int64(chunk1), Size: uint64(len(full) - chunk1), ModifiedTsNs: 45},
+ )
+
+ iter := newLogFileIterator(nil, newPersistedLogCache(persistedLogCacheMaxBytes), entry, 0, 0)
+ got := collectTs(t, iter)
+ if fmt.Sprint(got) != fmt.Sprint([]int64{10, 20, 30, 40}) {
+ t.Fatalf("fallback resume: got %v", got)
+ }
+}
+
+func TestLogFileIteratorLoadErrorPropagates(t *testing.T) {
+ boom := fmt.Errorf("boom")
+ prev := loadLogFileEntriesFn
+ loadLogFileEntriesFn = func(_ *wdclient.MasterClient, _ *filer_pb.FileChunk) ([]*filer_pb.LogEntry, bool, error) {
+ return nil, false, boom
+ }
+ t.Cleanup(func() { loadLogFileEntriesFn = prev })
+
+ entry := logFileEntry(&filer_pb.FileChunk{FileId: "3,01", Offset: 0, Size: 100, ModifiedTsNs: 45})
+ iter := newLogFileIterator(nil, newPersistedLogCache(persistedLogCacheMaxBytes), entry, 0, 0)
+ if _, err := iter.getNext(); err == nil || err.Error() != "boom" {
+ t.Fatalf("expected load error surfaced, got %v", err)
+ }
+}
+
+func TestPersistedLogCacheIdleEviction(t *testing.T) {
+ c := newPersistedLogCache(persistedLogCacheMaxBytes)
+ load := func() ([]*filer_pb.LogEntry, bool, error) {
+ return logEntriesAt(1), true, nil
+ }
+ if _, err := c.getOrLoad("idle", load); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := c.getOrLoad("hot", load); err != nil {
+ t.Fatal(err)
+ }
+
+ c.mu.Lock()
+ c.index["idle"].Value.(*logCacheItem).lastUsed = time.Now().Add(-2 * persistedLogCacheIdleTTL)
+ c.mu.Unlock()
+
+ c.evictIdle(time.Now().Add(-persistedLogCacheIdleTTL))
+
+ c.mu.Lock()
+ _, hasIdle := c.index["idle"]
+ _, hasHot := c.index["hot"]
+ bytesLeft := c.curBytes
+ c.mu.Unlock()
+ if hasIdle {
+ t.Error("idle entry should have been evicted")
+ }
+ if !hasHot {
+ t.Error("recently used entry should remain")
+ }
+ if want := estimateEntriesBytes(logEntriesAt(1)); bytesLeft != want {
+ t.Errorf("curBytes=%d, want %d", bytesLeft, want)
+ }
+}
+
+func TestDecodeLogRecordsRejectsImplausibleRecords(t *testing.T) {
+ // zeroed region: parses as endless empty records without the size guard
+ if _, _, err := decodeLogRecords(make([]byte, 16)); err != errLogChunkIncomplete {
+ t.Fatalf("zeroed data: err=%v", err)
+ }
+
+ // the writer never produces a zero timestamp
+ if _, _, err := decodeLogRecords(encodeLogRecords(t, logEntriesAt(0))); err != errLogChunkIncomplete {
+ t.Fatalf("zero ts: err=%v", err)
+ }
+
+ // timestamps are strictly increasing within one flushed buffer
+ entries, cacheable, err := decodeLogRecords(encodeLogRecords(t, logEntriesAt(10, 10)))
+ if err != errLogChunkIncomplete || cacheable {
+ t.Fatalf("non-increasing ts: err=%v cacheable=%v", err, cacheable)
+ }
+ if len(entries) != 1 || entries[0].TsNs != 10 {
+ t.Fatalf("non-increasing prefix: %v", entries)
}
}