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.

fix(mount): run entry invalidations off the meta-cache apply loop (#10002)

Jaehoon Kim18868e5204d2
diff --git a/weed/mount/meta_cache/meta_cache.go b/weed/mount/meta_cache/meta_cache.go
index 68f153a9e6..be586343b4 100644
--- a/weed/mount/meta_cache/meta_cache.go
+++ b/weed/mount/meta_cache/meta_cache.go
@@ -42,6 +42,12 @@ type MetaCache struct {
buildingDirs map[util.FullPath]*directoryBuildState
dedupRing dedupRingBuffer
includeSystemEntries bool
+
+ // Entry invalidations run on a worker, not inline on the apply loop:
+ // invalidateFunc takes the fh lock, which a flush can hold while waiting on
+ // the apply loop (flushMetadataToFiler -> applyLocalMetadataEvent), so inline
+ // invalidation deadlocks the mount.
+ invalidateWorker *util.AsyncBatchWorker[metadataInvalidation]
}
var errMetaCacheClosed = errors.New("metadata cache is shut down")
@@ -109,6 +115,11 @@ func NewMetaCache(dbFolder string, uidGidMapper *UidGidMapper, root util.FullPat
buildingDirs: make(map[util.FullPath]*directoryBuildState),
dedupRing: newDedupRingBuffer(),
}
+ mc.invalidateWorker = util.NewAsyncBatchWorker(func(batch []metadataInvalidation) {
+ for _, invalidation := range batch {
+ mc.invalidateFunc(invalidation.path, invalidation.entry)
+ }
+ })
go mc.runApplyLoop()
return mc
}
@@ -437,6 +448,10 @@ func (mc *MetaCache) Shutdown() {
<-mc.applyDone
+ // The apply loop is the only dispatcher of entry invalidations; with it
+ // stopped, drain and stop the invalidate worker before closing the store.
+ mc.invalidateWorker.Shutdown()
+
mc.Lock()
defer mc.Unlock()
mc.localStore.Shutdown()
@@ -606,9 +621,7 @@ func (mc *MetaCache) applyMetadataSideEffects(resp *filer_pb.SubscribeMetadataRe
for _, dirPath := range sideEffects.dirsToNotify {
mc.noteDirectoryUpdate(dirPath)
}
- for _, invalidation := range sideEffects.invalidations {
- mc.invalidateFunc(invalidation.path, invalidation.entry)
- }
+ mc.invalidateWorker.Enqueue(sideEffects.invalidations...)
}
// applyMetadataSideEffectsSkippingBuildingDirs is like applyMetadataSideEffects
@@ -627,9 +640,14 @@ func (mc *MetaCache) applyMetadataSideEffectsSkippingBuildingDirs(resp *filer_pb
mc.noteDirectoryUpdate(dirPath)
}
}
- for _, invalidation := range sideEffects.invalidations {
- mc.invalidateFunc(invalidation.path, invalidation.entry)
- }
+ mc.invalidateWorker.Enqueue(sideEffects.invalidations...)
+}
+
+// WaitForEntryInvalidations blocks until every invalidation enqueued so far
+// has been processed by the invalidate worker. Intended for tests and
+// shutdown paths that need the previously-synchronous behavior.
+func (mc *MetaCache) WaitForEntryInvalidations() {
+ mc.invalidateWorker.Drain()
}
func (mc *MetaCache) applyMetadataResponseLocked(ctx context.Context, resp *filer_pb.SubscribeMetadataResponse, _ MetadataResponseApplyOptions, allowUncachedInsert bool) (metadataResponseSideEffects, error) {
diff --git a/weed/mount/meta_cache/meta_cache_apply_test.go b/weed/mount/meta_cache/meta_cache_apply_test.go
index 214403f2c5..aa97675f9f 100644
--- a/weed/mount/meta_cache/meta_cache_apply_test.go
+++ b/weed/mount/meta_cache/meta_cache_apply_test.go
@@ -100,6 +100,7 @@ func TestApplyMetadataResponseAppliesEventsInOrder(t *testing.T) {
if got := countPath(notifications.paths(), util.FullPath("/dir")); got != 3 {
t.Fatalf("directory notifications for /dir = %d, want 3", got)
}
+ mc.WaitForEntryInvalidations()
if got := countPath(invalidations.paths(), util.FullPath("/dir/file.txt")); got != 3 {
t.Fatalf("invalidations for /dir/file.txt = %d, want 3 (create + update + delete)", got)
}
@@ -170,6 +171,7 @@ func TestApplyMetadataResponseRenamesAcrossCachedDirectories(t *testing.T) {
if got := countPath(notifications.paths(), util.FullPath("/dst")); got != 1 {
t.Fatalf("directory notifications for /dst = %d, want 1", got)
}
+ mc.WaitForEntryInvalidations()
if got := countPath(invalidations.paths(), util.FullPath("/src/file.tmp")); got != 1 {
t.Fatalf("invalidations for /src/file.tmp = %d, want 1", got)
}
@@ -230,6 +232,7 @@ func TestApplyMetadataResponseLocalOptionsSkipInvalidations(t *testing.T) {
if got := countPath(notifications.paths(), util.FullPath("/dir")); got != 1 {
t.Fatalf("directory notifications for /dir = %d, want 1", got)
}
+ mc.WaitForEntryInvalidations()
if got := len(invalidations.paths()); got != 0 {
t.Fatalf("invalidations = %d, want 0", got)
}
@@ -292,6 +295,7 @@ func TestApplyMetadataResponseDeduplicatesRepeatedFilerEvent(t *testing.T) {
if got := countPath(notifications.paths(), util.FullPath("/dir")); got != 1 {
t.Fatalf("directory notifications for /dir = %d, want 1", got)
}
+ mc.WaitForEntryInvalidations()
if got := countPath(invalidations.paths(), util.FullPath("/dir/file.txt")); got != 1 {
t.Fatalf("invalidations for /dir/file.txt = %d, want 1", got)
}
diff --git a/weed/mount/meta_cache/meta_cache_deadlock_test.go b/weed/mount/meta_cache/meta_cache_deadlock_test.go
new file mode 100644
index 0000000000..ce94bee852
--- /dev/null
+++ b/weed/mount/meta_cache/meta_cache_deadlock_test.go
@@ -0,0 +1,161 @@
+package meta_cache
+
+import (
+ "context"
+ "path/filepath"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
+ "github.com/seaweedfs/seaweedfs/weed/util"
+)
+
+// TestApplyLoopInvalidateDoesNotDeadlockWithLockHoldingEnqueuer reproduces the
+// mount hang seen in production (all readdirs stuck, FUSE waiting>0):
+//
+// - A FUSE flush handler (flushMetadataToFiler) holds the file handle's
+// exclusive lock in wfs.fhLockTable and then enqueues a local metadata
+// event, waiting for the apply loop to process it.
+// - Concurrently the apply loop processes a subscriber event whose
+// invalidateFunc (weedfs.go) acquires the same file handle lock.
+//
+// The single-goroutine apply loop blocks on the fh lock while the fh lock
+// holder blocks on the apply loop: a permanent ABBA deadlock. Every later
+// EnsureVisited/BeginDirectoryBuild then backs up behind the dead loop, FUSE
+// handler goroutines exhaust, and the kernel queue (waiting) grows.
+//
+// The contract under test: the apply loop must never block on locks that can
+// be held by goroutines waiting on the apply loop.
+func TestApplyLoopInvalidateDoesNotDeadlockWithLockHoldingEnqueuer(t *testing.T) {
+ mapper, err := NewUidGidMapper("", "")
+ if err != nil {
+ t.Fatalf("uid/gid mapper: %v", err)
+ }
+
+ // Stand-in for wfs.fhLockTable, keyed like FileHandleId.
+ fhLockTable := util.NewLockTable[uint64]()
+ const fhKey uint64 = 42
+
+ invalidateEntered := make(chan struct{})
+ var enteredOnce sync.Once
+
+ var cachedMu sync.Mutex
+ cached := map[util.FullPath]bool{"/": true, "/dir": true}
+
+ mc := NewMetaCache(
+ filepath.Join(t.TempDir(), "meta"),
+ mapper,
+ util.FullPath("/"),
+ false,
+ func(path util.FullPath) {
+ cachedMu.Lock()
+ defer cachedMu.Unlock()
+ cached[path] = true
+ },
+ func(path util.FullPath) bool {
+ cachedMu.Lock()
+ defer cachedMu.Unlock()
+ return cached[path]
+ },
+ func(path util.FullPath, entry *filer_pb.Entry) {
+ // Mirrors the wfs invalidateFunc: it takes the open file
+ // handle's exclusive lock before refreshing the handle entry.
+ enteredOnce.Do(func() { close(invalidateEntered) })
+ lock := fhLockTable.AcquireLock("invalidateFunc", fhKey, util.ExclusiveLock)
+ fhLockTable.ReleaseLock(fhKey, lock)
+ },
+ func(dir util.FullPath) {},
+ )
+ defer func() {
+ // Only safe to shut down once the apply loop is unwedged.
+ mc.Shutdown()
+ }()
+
+ subscriberEvent := &filer_pb.SubscribeMetadataResponse{
+ Directory: "/dir",
+ EventNotification: &filer_pb.EventNotification{
+ NewEntry: &filer_pb.Entry{
+ Name: "file.txt",
+ Attributes: &filer_pb.FuseAttributes{
+ Crtime: 1,
+ Mtime: 1,
+ FileMode: 0100644,
+ },
+ },
+ },
+ }
+ localEvent := &filer_pb.SubscribeMetadataResponse{
+ Directory: "/dir",
+ EventNotification: &filer_pb.EventNotification{
+ OldEntry: &filer_pb.Entry{Name: "file.txt"},
+ NewEntry: &filer_pb.Entry{
+ Name: "file.txt",
+ Attributes: &filer_pb.FuseAttributes{
+ Crtime: 1,
+ Mtime: 2,
+ FileMode: 0100644,
+ },
+ },
+ NewParentPath: "/dir",
+ },
+ }
+
+ // Step 1: the "flush handler" takes the fh exclusive lock
+ // (flushMetadataToFiler does this before talking to the filer).
+ flushLock := fhLockTable.AcquireLock("doFlush", fhKey, util.ExclusiveLock)
+ flushLockReleased := false
+ releaseFlushLock := func() {
+ if !flushLockReleased {
+ flushLockReleased = true
+ fhLockTable.ReleaseLock(fhKey, flushLock)
+ }
+ }
+ defer releaseFlushLock()
+
+ // Step 2: a subscriber event arrives; the apply loop will run
+ // invalidateFunc, which wants the fh lock held above.
+ subscriberDone := make(chan error, 1)
+ go func() {
+ subscriberDone <- mc.ApplyMetadataResponse(context.Background(), subscriberEvent, SubscriberMetadataResponseApplyOptions)
+ }()
+
+ select {
+ case <-invalidateEntered:
+ case <-time.After(5 * time.Second):
+ t.Fatal("invalidateFunc was never invoked for the subscriber event")
+ }
+ // Give the invalidate goroutine a moment to actually block on AcquireLock.
+ time.Sleep(50 * time.Millisecond)
+
+ // Step 3: still holding the fh lock, the flush handler applies its local
+ // metadata event and waits for the apply loop — exactly what
+ // flushMetadataToFiler does after streamCreateEntry succeeds.
+ flushApplyDone := make(chan error, 1)
+ go func() {
+ flushApplyDone <- mc.ApplyMetadataResponseOwned(context.Background(), localEvent, LocalMetadataResponseApplyOptions)
+ }()
+
+ select {
+ case err := <-flushApplyDone:
+ if err != nil {
+ t.Fatalf("local metadata apply: %v", err)
+ }
+ case <-time.After(3 * time.Second):
+ // Unwedge the apply loop so Shutdown in the deferred cleanup
+ // doesn't hang the whole test binary.
+ releaseFlushLock()
+ t.Fatal("deadlock: apply loop blocked on fh lock while fh lock holder waits on apply loop")
+ }
+
+ releaseFlushLock()
+
+ select {
+ case err := <-subscriberDone:
+ if err != nil {
+ t.Fatalf("subscriber apply: %v", err)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("subscriber apply never completed")
+ }
+}
diff --git a/weed/util/async_worker.go b/weed/util/async_worker.go
new file mode 100644
index 0000000000..a31616d27c
--- /dev/null
+++ b/weed/util/async_worker.go
@@ -0,0 +1,94 @@
+package util
+
+import "sync"
+
+// AsyncBatchWorker is an unbounded FIFO drained by one background goroutine,
+// handing it everything queued so far per process call. Unbounded on purpose:
+// a bound would let a stalled consumer block producers, which deadlocks when a
+// producer is itself a goroutine the consumer can end up waiting on.
+type AsyncBatchWorker[T any] struct {
+ mu sync.Mutex
+ cond *sync.Cond
+ queue []T
+ enqueued int64
+ processed int64
+ closed bool
+ done chan struct{}
+ process func([]T)
+}
+
+// NewAsyncBatchWorker starts the worker. process runs outside the internal
+// lock, so it may take locks held by goroutines that are themselves enqueueing.
+func NewAsyncBatchWorker[T any](process func([]T)) *AsyncBatchWorker[T] {
+ w := &AsyncBatchWorker[T]{
+ process: process,
+ done: make(chan struct{}),
+ }
+ w.cond = sync.NewCond(&w.mu)
+ go w.run()
+ return w
+}
+
+// Enqueue appends items for the worker without blocking. Items enqueued after
+// Shutdown are dropped.
+func (w *AsyncBatchWorker[T]) Enqueue(items ...T) {
+ if len(items) == 0 {
+ return
+ }
+ w.mu.Lock()
+ if w.closed {
+ w.mu.Unlock()
+ return
+ }
+ w.queue = append(w.queue, items...)
+ w.enqueued += int64(len(items))
+ w.mu.Unlock()
+ w.cond.Signal()
+}
+
+func (w *AsyncBatchWorker[T]) run() {
+ defer close(w.done)
+ for {
+ w.mu.Lock()
+ for len(w.queue) == 0 && !w.closed {
+ w.cond.Wait()
+ }
+ if len(w.queue) == 0 { // closed and drained
+ w.mu.Unlock()
+ return
+ }
+ batch := w.queue
+ w.queue = nil
+ w.mu.Unlock()
+
+ w.process(batch)
+
+ // Once per batch, not per item: Drain only needs the count to reach its target.
+ w.mu.Lock()
+ w.processed += int64(len(batch))
+ w.mu.Unlock()
+ w.cond.Broadcast()
+ }
+}
+
+// Drain blocks until every item enqueued so far has been processed, including
+// across a concurrent Shutdown — Shutdown drains all accepted items, so
+// processed always reaches the target and this cannot hang.
+func (w *AsyncBatchWorker[T]) Drain() {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ target := w.enqueued
+ for w.processed < target {
+ w.cond.Wait()
+ }
+}
+
+// Shutdown processes any outstanding items, then stops the worker and waits for
+// it to exit. Subsequent Enqueue calls are dropped.
+func (w *AsyncBatchWorker[T]) Shutdown() {
+ w.mu.Lock()
+ w.closed = true
+ w.mu.Unlock()
+ w.cond.Broadcast()
+ <-w.done
+}
diff --git a/weed/util/async_worker_test.go b/weed/util/async_worker_test.go
new file mode 100644
index 0000000000..b39594000b
--- /dev/null
+++ b/weed/util/async_worker_test.go
@@ -0,0 +1,123 @@
+package util
+
+import (
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func TestAsyncBatchWorkerProcessesInOrder(t *testing.T) {
+ var mu sync.Mutex
+ var got []int
+ w := NewAsyncBatchWorker(func(batch []int) {
+ mu.Lock()
+ got = append(got, batch...)
+ mu.Unlock()
+ })
+ for i := 0; i < 100; i++ {
+ w.Enqueue(i)
+ }
+ w.Drain()
+ mu.Lock()
+ defer mu.Unlock()
+ if len(got) != 100 {
+ t.Fatalf("processed %d items, want 100", len(got))
+ }
+ for i, v := range got {
+ if v != i {
+ t.Fatalf("item %d = %d, want %d (FIFO order broken)", i, v, i)
+ }
+ }
+}
+
+func TestAsyncBatchWorkerDrainWaitsForEnqueued(t *testing.T) {
+ var processed int64
+ w := NewAsyncBatchWorker(func(batch []int) {
+ time.Sleep(time.Millisecond)
+ atomic.AddInt64(&processed, int64(len(batch)))
+ })
+ w.Enqueue(1, 2, 3)
+ w.Enqueue(4, 5)
+ w.Drain()
+ if n := atomic.LoadInt64(&processed); n != 5 {
+ t.Fatalf("processed %d, want 5 after Drain", n)
+ }
+}
+
+// Enqueue must not block even while the worker is busy processing under a lock
+// the producer also holds — the unbounded queue is what guarantees this.
+func TestAsyncBatchWorkerEnqueueNeverBlocks(t *testing.T) {
+ release := make(chan struct{})
+ entered := make(chan struct{})
+ var once sync.Once
+ w := NewAsyncBatchWorker(func(batch []int) {
+ once.Do(func() { close(entered) })
+ <-release
+ })
+ w.Enqueue(0) // worker picks this up and blocks in process
+ <-entered
+
+ done := make(chan struct{})
+ go func() {
+ for i := 1; i < 1000; i++ {
+ w.Enqueue(i)
+ }
+ close(done)
+ }()
+ select {
+ case <-done:
+ case <-time.After(2 * time.Second):
+ t.Fatal("Enqueue blocked while worker was busy")
+ }
+ close(release)
+ w.Shutdown()
+}
+
+// Drain must honor its contract even when Shutdown runs concurrently: it may
+// not return until the in-flight batch has actually been processed.
+func TestAsyncBatchWorkerDrainCompletesDuringShutdown(t *testing.T) {
+ var processed int64
+ release := make(chan struct{})
+ entered := make(chan struct{})
+ var once sync.Once
+ w := NewAsyncBatchWorker(func(batch []int) {
+ once.Do(func() { close(entered) })
+ <-release
+ atomic.AddInt64(&processed, int64(len(batch)))
+ })
+ w.Enqueue(1, 2, 3)
+ <-entered // worker has picked up the batch and is blocked in process
+
+ drained := make(chan struct{})
+ go func() { w.Drain(); close(drained) }()
+ go w.Shutdown() // sets closed and broadcasts while the batch is still in flight
+
+ select {
+ case <-drained:
+ t.Fatal("Drain returned before the in-flight batch finished")
+ case <-time.After(100 * time.Millisecond):
+ }
+ close(release)
+ <-drained
+ if n := atomic.LoadInt64(&processed); n != 3 {
+ t.Fatalf("processed %d after Drain, want 3", n)
+ }
+}
+
+func TestAsyncBatchWorkerShutdownDrainsThenStops(t *testing.T) {
+ var processed int64
+ w := NewAsyncBatchWorker(func(batch []int) {
+ atomic.AddInt64(&processed, int64(len(batch)))
+ })
+ w.Enqueue(1, 2, 3, 4)
+ w.Shutdown()
+ if n := atomic.LoadInt64(&processed); n != 4 {
+ t.Fatalf("processed %d, want 4 (Shutdown should drain)", n)
+ }
+ // Enqueue after Shutdown is dropped, not processed.
+ w.Enqueue(5, 6)
+ if n := atomic.LoadInt64(&processed); n != 4 {
+ t.Fatalf("processed %d after post-shutdown Enqueue, want 4", n)
+ }
+}