From 0aeed517fdd20b5adea5a897304515e22cf33db3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 28 Nov 2026 06:13:15 -0800 Subject: [PATCH 01/13] test immediate retry after cut staging progress --- .../frontend/durable/cut_progress_test.go | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/cut_progress_test.go diff --git a/seaweed-block/core/frontend/durable/cut_progress_test.go b/seaweed-block/core/frontend/durable/cut_progress_test.go new file mode 100644 index 0000000000..b1ae5606a9 --- /dev/null +++ b/seaweed-block/core/frontend/durable/cut_progress_test.go @@ -0,0 +1,39 @@ +package durable + +import ( + "context" + "sync/atomic" + "testing" + "testing/synctest" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// The public layer counters report completed staging even when its cut times out. +type progressLoopLayer struct { + storage.ChunkLayer + staged atomic.Uint64 + calls atomic.Int32 +} +func (l *progressLoopLayer) Fenced() bool { return false } +func (l *progressLoopLayer) Stats() storage.ChunkLayerStats { return storage.ChunkLayerStats{StagedChunks:l.staged.Load()} } +func (l *progressLoopLayer) Cut(context.Context) (storage.ChunkCutResult,error) { + l.calls.Add(1) + l.staged.Add(1) + return storage.ChunkCutResult{},context.DeadlineExceeded +} + +func TestCutLoopProgressRetriesWithoutBackoff(t *testing.T) { + synctest.Test(t,func(t *testing.T){ + layer:=&progressLoopLayer{} + p:=&DurableProvider{cfg:ProviderConfig{ChunkCaptureInterval:time.Millisecond}} + ctx,cancel:=context.WithCancel(context.Background()) + done:=make(chan struct{}) + go p.chunkLoop(ctx,"progress",layer,done,nil) + defer func(){cancel(); <-done}() + time.Sleep(500*time.Millisecond) + synctest.Wait() + if n:=layer.calls.Load();n<3 {t.Fatalf("only %d attempts despite new staged chunks; progress must retry at the next poll, without backoff or minimum spacing",n)} + }) +} \ No newline at end of file From acfafb4aca60be04202061fb2cc7c8cdcb3bce50 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 28 Nov 2026 06:13:55 -0800 Subject: [PATCH 02/13] retry automatic cuts while staging makes progress --- .../frontend/durable/cut_progress_test.go | 57 ++++++++++--------- .../core/frontend/durable/provider_chunk.go | 15 ++++- 2 files changed, 45 insertions(+), 27 deletions(-) diff --git a/seaweed-block/core/frontend/durable/cut_progress_test.go b/seaweed-block/core/frontend/durable/cut_progress_test.go index b1ae5606a9..a0a8efa20c 100644 --- a/seaweed-block/core/frontend/durable/cut_progress_test.go +++ b/seaweed-block/core/frontend/durable/cut_progress_test.go @@ -1,39 +1,44 @@ package durable import ( - "context" - "sync/atomic" - "testing" - "testing/synctest" - "time" + "context" + "sync/atomic" + "testing" + "testing/synctest" + "time" - "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/storage" ) // The public layer counters report completed staging even when its cut times out. type progressLoopLayer struct { - storage.ChunkLayer - staged atomic.Uint64 - calls atomic.Int32 + storage.ChunkLayer + staged atomic.Uint64 + calls atomic.Int32 } + func (l *progressLoopLayer) Fenced() bool { return false } -func (l *progressLoopLayer) Stats() storage.ChunkLayerStats { return storage.ChunkLayerStats{StagedChunks:l.staged.Load()} } -func (l *progressLoopLayer) Cut(context.Context) (storage.ChunkCutResult,error) { - l.calls.Add(1) - l.staged.Add(1) - return storage.ChunkCutResult{},context.DeadlineExceeded +func (l *progressLoopLayer) Stats() storage.ChunkLayerStats { + return storage.ChunkLayerStats{StagedChunks: l.staged.Load()} +} +func (l *progressLoopLayer) Cut(context.Context) (storage.ChunkCutResult, error) { + l.calls.Add(1) + l.staged.Add(1) + return storage.ChunkCutResult{}, context.DeadlineExceeded } func TestCutLoopProgressRetriesWithoutBackoff(t *testing.T) { - synctest.Test(t,func(t *testing.T){ - layer:=&progressLoopLayer{} - p:=&DurableProvider{cfg:ProviderConfig{ChunkCaptureInterval:time.Millisecond}} - ctx,cancel:=context.WithCancel(context.Background()) - done:=make(chan struct{}) - go p.chunkLoop(ctx,"progress",layer,done,nil) - defer func(){cancel(); <-done}() - time.Sleep(500*time.Millisecond) - synctest.Wait() - if n:=layer.calls.Load();n<3 {t.Fatalf("only %d attempts despite new staged chunks; progress must retry at the next poll, without backoff or minimum spacing",n)} - }) -} \ No newline at end of file + synctest.Test(t, func(t *testing.T) { + layer := &progressLoopLayer{} + p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond}} + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go p.chunkLoop(ctx, "progress", layer, done, nil) + defer func() { cancel(); <-done }() + time.Sleep(500 * time.Millisecond) + synctest.Wait() + if n := layer.calls.Load(); n < 3 { + t.Fatalf("only %d attempts despite new staged chunks; progress must retry at the next poll, without backoff or minimum spacing", n) + } + }) +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index e275e2ac4e..7a67a2757a 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -837,6 +837,18 @@ func (pol cutPolicy) after(s cutSchedule, start, end time.Time, err error, seq u return s } +// afterStaging retries at the next poll when a failed attempt completed new +// staging. Minimum spacing and exponential backoff apply only without progress. +func (pol cutPolicy) afterStaging(s cutSchedule, start, end time.Time, err error, seq, staged uint64) cutSchedule { + s = pol.after(s, start, end, err, seq) + if err != nil && staged > 0 { + s.lastAuto = time.Time{} + s.backoff = 0 + s.retryAt = end + } + return s +} + // initialCutSchedule starts a fresh schedule at now; seq is the layer's // CutSeq at start, so a cut already made is not taken in as new. func initialCutSchedule(volumeID string, interval time.Duration, now time.Time, stagger bool, seq uint64) cutSchedule { @@ -910,7 +922,8 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer } } cancel() - s = pol.after(s, start, time.Now(), err, layer.Stats().CutSeq) + after := layer.Stats() + s = pol.afterStaging(s, start, time.Now(), err, after.CutSeq, after.StagedChunks-ls.StagedChunks) wait.record(s) if err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && ctx.Err() == nil { if note, stuck := capturePendingNote(err); stuck { From a46fd57756f2cae402bf98a4823b197211600f47 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 28 Nov 2026 06:20:15 -0800 Subject: [PATCH 03/13] bound stalled cut sessions and order startup cleaning --- .../chunkstore/layout_stalled_discard_test.go | 44 ++++++ .../durable/chunk_snapshot_schedule.go | 19 ++- .../frontend/durable/cut_loop_fence_test.go | 2 +- .../frontend/durable/cut_progress_test.go | 132 +++++++++++++++++- .../frontend/durable/maintenance_kick_test.go | 2 +- .../durable/maintenance_lineage_test.go | 4 +- .../core/frontend/durable/provider_chunk.go | 72 ++++++++-- .../core/storage/chunk_periodic_cut.go | 21 +++ .../storage/chunk_stalled_discard_test.go | 35 +++++ seaweed-block/docs/design/invariants.md | 1 + seaweed-block/docs/standalone-deployment.md | 15 ++ 11 files changed, 328 insertions(+), 19 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout_stalled_discard_test.go create mode 100644 seaweed-block/core/storage/chunk_stalled_discard_test.go diff --git a/seaweed-block/core/frontend/chunkstore/layout_stalled_discard_test.go b/seaweed-block/core/frontend/chunkstore/layout_stalled_discard_test.go new file mode 100644 index 0000000000..85cd4003bf --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_stalled_discard_test.go @@ -0,0 +1,44 @@ +package chunkstore + +import ( + "context" + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestLayoutStalledSessionYieldAllowsCleaning(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, layer, remote := lh.attach("stalled", true, true) + defer s.Close() + data := block(71) + key := remote.ChunkKey(0, layout.Sum(data)) + if err := remote.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + clean := func() (removed int, err error) { + err = remote.Clean(ctx, func(ctx context.Context, me layout.HolderID, session string) error { + st, reader, e := lh.cat.open(lh.v) + if e != nil { + return e + } + r, e := layout.RemoveUnreachable(ctx, st, reader, st, me, session, layout.Shard(0), []layout.ChunkName{layout.NameChunk(0, data)}) + removed = len(r) + return e + }) + return + } + if _, err := clean(); !errors.Is(err, layout.ErrBusy) { + t.Fatalf("cleaning an open session: %v", err) + } + stats := layer.Stats() + if !layer.(storage.ChunkStagedDiscarder).DiscardStagedIfUnchanged(stats.StagedChunks, stats.CutSeq) { + t.Fatal("idle stalled session was not discarded") + } + if n, err := clean(); err != nil || n != 1 { + t.Fatalf("after yield: removed=%d err=%v; want the unreachable chunk removed", n, err) + } +} diff --git a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go index 2d2534b472..5a9c324c6c 100644 --- a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go +++ b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go @@ -100,6 +100,7 @@ type snapshotSchedule struct { next time.Time failure *ScheduledSnapshotFailure attempts int + stalled int // consecutive failed attempts without new staging skipped map[string]int64 } @@ -130,15 +131,16 @@ func (s *snapshotSchedule) record(now time.Time, err error) { var skip *SnapshotSkip switch { case err == nil: - s.lastOK, s.failure, s.attempts = now, nil, 0 + s.lastOK, s.failure, s.attempts, s.stalled = now, nil, 0, 0 s.next = s.slotAfter(now) case errors.As(err, &skip): s.skipped[skip.Reason]++ s.next = earlier(now.Add(snapshotRetryMax), s.slotAfter(now)) default: s.attempts++ + s.stalled++ s.failure = &ScheduledSnapshotFailure{Code: snapshotFailureCode(err), AtNs: now.UnixNano()} - backoff := snapshotRetryMin << min(s.attempts-1, 30) + backoff := snapshotRetryMin << min(s.stalled-1, 30) if backoff > snapshotRetryMax || backoff <= 0 { backoff = snapshotRetryMax } @@ -218,7 +220,7 @@ func (sl *snapshotSlot) record(now time.Time, err error) { // the snapshot record. An attempt cut short by the loop's own end is not // recorded. chunkBackground joins it with its other workers // (INV-MAINT-JOIN). -func (p *DurableProvider) chunkSnapshotLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool, slot *snapshotSlot) { +func (p *DurableProvider) chunkSnapshotLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool, slot *snapshotSlot, attempted func(storage.ChunkLayerStats, storage.ChunkLayerStats, error)) { timer := time.NewTimer(time.Until(slot.due())) defer timer.Stop() timeout := 2 * p.cfg.ChunkCutTimeout @@ -239,6 +241,7 @@ func (p *DurableProvider) chunkSnapshotLoop(ctx context.Context, volumeID string return } at := time.Now() + before := layer.Stats() var err error if layer.Stats().AbsentChunks > 0 { // Restoring: HEAD names chunks this volume has not fetched yet. @@ -251,7 +254,17 @@ func (p *DurableProvider) chunkSnapshotLoop(ctx context.Context, volumeID string if ctx.Err() != nil { return } + after := layer.Stats() + if attempted != nil { + attempted(before, after, err) + } slot.record(time.Now(), err) + if err != nil && after.StagedChunks > before.StagedChunks { + slot.mu.Lock() + slot.s.next = time.Now() + slot.s.stalled = 0 // progress breaks the backoff, not the reported attempt count + slot.mu.Unlock() + } if err != nil { next := time.Until(slot.due()).Round(time.Second) if note, stuck := capturePendingNote(err); stuck { diff --git a/seaweed-block/core/frontend/durable/cut_loop_fence_test.go b/seaweed-block/core/frontend/durable/cut_loop_fence_test.go index febe7a702d..ba45a03693 100644 --- a/seaweed-block/core/frontend/durable/cut_loop_fence_test.go +++ b/seaweed-block/core/frontend/durable/cut_loop_fence_test.go @@ -31,7 +31,7 @@ func TestChunkLoop_EndsWhenTheLayerIsFenced(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() done := make(chan struct{}) - go p.chunkLoop(ctx, "v1", layer, done, nil) + go p.chunkLoop(ctx, "v1", layer, done, nil, nil) deadline := time.Now().Add(5 * time.Second) for layer.cuts.Load() == 0 { if time.Now().After(deadline) { diff --git a/seaweed-block/core/frontend/durable/cut_progress_test.go b/seaweed-block/core/frontend/durable/cut_progress_test.go index a0a8efa20c..e901cfb7e8 100644 --- a/seaweed-block/core/frontend/durable/cut_progress_test.go +++ b/seaweed-block/core/frontend/durable/cut_progress_test.go @@ -33,7 +33,7 @@ func TestCutLoopProgressRetriesWithoutBackoff(t *testing.T) { p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond}} ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) - go p.chunkLoop(ctx, "progress", layer, done, nil) + go p.chunkLoop(ctx, "progress", layer, done, nil, nil) defer func() { cancel(); <-done }() time.Sleep(500 * time.Millisecond) synctest.Wait() @@ -42,3 +42,133 @@ func TestCutLoopProgressRetriesWithoutBackoff(t *testing.T) { } }) } + +func TestScheduledSnapshotProgressRetriesWithoutBackoff(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + layer := &progressLoopLayer{} + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + calls := 0 + p := &DurableProvider{cfg: ProviderConfig{ChunkScheduledSnapshot: func(context.Context, string, time.Time, func(context.Context) (storage.ChunkHead, error)) error { + calls++ + if calls < 3 { + layer.staged.Add(1) + return context.DeadlineExceeded + } + return nil + }}} + slot := &snapshotSlot{s: newSnapshotSchedule("v1", 24*time.Hour, time.Now())} + slot.s.next = time.Now() + go func() { + defer close(done) + p.chunkSnapshotLoop(ctx, "v1", layer, func() bool { return true }, slot, nil) + }() + defer func() { cancel(); <-done }() + synctest.Wait() + if calls != 3 { + t.Fatalf("got %d attempts, want two progress retries then success without advancing the clock", calls) + } + }) +} + +type firstAttemptLayer struct { + progressLoopLayer + entered chan struct{} + release chan struct{} +} + +func (l *firstAttemptLayer) Stats() storage.ChunkLayerStats { + return storage.ChunkLayerStats{DirtyChunks: 1} +} +func (l *firstAttemptLayer) Cut(ctx context.Context) (storage.ChunkCutResult, error) { + select { + case l.entered <- struct{}{}: + default: + } + select { + case <-l.release: + case <-ctx.Done(): + } + return storage.ChunkCutResult{}, context.DeadlineExceeded +} +func TestDirtyStartCleaningWaitsForFirstCutAttempt(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + layer := &firstAttemptLayer{entered: make(chan struct{}, 1), release: make(chan struct{})} + var cleaned atomic.Int32 + p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond, ChunkMaintenanceInterval: time.Millisecond, ChunkMaintenance: func(context.Context, string) error { cleaned.Add(1); return nil }}} + go p.chunkBackground(ctx, cancel, "dirty", layer, done, func() bool { return true }, nil, nil, nil) + defer func() { cancel(); <-done }() + time.Sleep(500 * time.Millisecond) + synctest.Wait() + select { + case <-layer.entered: + default: + t.Fatal("first cut did not start") + } + if n := cleaned.Load(); n != 0 { + t.Fatalf("%d cleaning passes ran before the dirty start's first cut returned", n) + } + close(layer.release) + time.Sleep(time.Millisecond) + synctest.Wait() + if cleaned.Load() == 0 { + t.Fatal("cleaning never ran after the first cut attempt") + } + }) +} + +type yieldingLayer struct { + progressLoopLayer + progressAt int32 + discarded atomic.Int32 +} + +func (l *yieldingLayer) Stats() storage.ChunkLayerStats { + return storage.ChunkLayerStats{DirtyChunks: 1, StagedChunks: l.staged.Load()} +} +func (l *yieldingLayer) Cut(context.Context) (storage.ChunkCutResult, error) { + if l.calls.Add(1) == l.progressAt { + l.staged.Add(1) + } + return storage.ChunkCutResult{}, context.DeadlineExceeded +} +func (l *yieldingLayer) DiscardStagedIfUnchanged(staged, seq uint64) bool { + l.discarded.Add(1) + return true +} +func TestStalledCutYieldsSessionToCleaning(t *testing.T) { + for _, progress := range []bool{false, true} { + t.Run(map[bool]string{false: "K_zero_progress", true: "progress_resets_K"}[progress], func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + layer := &yieldingLayer{} + if progress { + layer.progressAt = chunkZeroProgressLimit + } + var cleaned atomic.Int32 + p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond, ChunkMaintenanceInterval: time.Hour, ChunkMaintenance: func(context.Context, string) error { + if layer.discarded.Load() == 0 { + t.Error("cleaning ran with the stalled session still open") + } + cleaned.Add(1) + return nil + }}} + kick := make(chan struct{}, 1) + go p.chunkBackground(ctx, cancel, "stalled", layer, done, func() bool { return true }, nil, nil, kick) + defer func() { cancel(); <-done }() + time.Sleep(3500 * time.Millisecond) + synctest.Wait() + if progress { + if layer.discarded.Load() != 0 || cleaned.Load() != 0 { + t.Fatal("K-1 stalls followed by progress discarded a live session") + } + } else if layer.discarded.Load() != 1 || cleaned.Load() != 1 { + t.Fatalf("discarded=%d cleaning=%d; K stalls must release the session and kick a pass", layer.discarded.Load(), cleaned.Load()) + } + }) + }) + } +} diff --git a/seaweed-block/core/frontend/durable/maintenance_kick_test.go b/seaweed-block/core/frontend/durable/maintenance_kick_test.go index 2e7106f8ac..60e9154c96 100644 --- a/seaweed-block/core/frontend/durable/maintenance_kick_test.go +++ b/seaweed-block/core/frontend/durable/maintenance_kick_test.go @@ -61,7 +61,7 @@ func runLoop(t *testing.T, p *DurableProvider, kick chan struct{}) { done := make(chan struct{}) go func() { defer close(done) - p.chunkMaintenanceLoop(ctx, "v1", maintenanceStubLayer{}, func() bool { return true }, kick) + p.chunkMaintenanceLoop(ctx, "v1", maintenanceStubLayer{}, func() bool { return true }, kick, nil) }() t.Cleanup(func() { cancel() diff --git a/seaweed-block/core/frontend/durable/maintenance_lineage_test.go b/seaweed-block/core/frontend/durable/maintenance_lineage_test.go index 7b433083b2..ca73eb8122 100644 --- a/seaweed-block/core/frontend/durable/maintenance_lineage_test.go +++ b/seaweed-block/core/frontend/durable/maintenance_lineage_test.go @@ -43,7 +43,7 @@ func TestMaintenanceRejectsForeignLineageBeforeAdmission(t *testing.T) { p.cfg.ChunkMaintenance = func(context.Context, string) error { calls++; return nil } ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() - p.chunkMaintenanceLoop(ctx, "v1", layer, func() bool { return p.maintenanceCurrent("v1", h, layer, lin) }, nil) + p.chunkMaintenanceLoop(ctx, "v1", layer, func() bool { return p.maintenanceCurrent("v1", h, layer, lin) }, nil, nil) if calls != 0 { t.Fatalf("foreign attachment admitted %d passes", calls) } @@ -117,7 +117,7 @@ func TestMaintenanceRefusalReachesTheLayer(t *testing.T) { }}} ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() - go p.chunkMaintenanceLoop(ctx, "v1", layer, func() bool { return true }, nil) + go p.chunkMaintenanceLoop(ctx, "v1", layer, func() bool { return true }, nil, nil) select { case err := <-layer.seen: if !errors.Is(err, storage.ErrChunkLayerFenced) { diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 7a67a2757a..40df112281 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -693,11 +693,12 @@ func (r *closeBoundRemote) Abort() { r.ChunkRemote.Abort() } // Cut scheduler constants (B9 W3 ruling). const ( - chunkSchedulePoll = 100 * time.Millisecond - chunkCutMinSpacing = time.Second - chunkCutBackoffMin = time.Second - chunkCutBackoffMax = 30 * time.Second - chunkSlotDelayMax = 200 * time.Millisecond + chunkSchedulePoll = 100 * time.Millisecond + chunkCutMinSpacing = time.Second + chunkCutBackoffMin = time.Second + chunkCutBackoffMax = 30 * time.Second + chunkSlotDelayMax = 200 * time.Millisecond + chunkZeroProgressLimit = 3 // yield an unfinished session to cleaning after this many stalled attempts ) // cutPolicy decides when an automatic cut is due. The remote holds @@ -865,7 +866,7 @@ func initialCutSchedule(volumeID string, interval time.Duration, now time.Time, // cut (not a healthy primary of this lineage, BASE install) is expected // and logged only when it is something else. A fenced layer can never // publish again: the loop ends. -func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, done chan struct{}, wait *cutWaitSlot) { +func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, done chan struct{}, wait *cutWaitSlot, attempted func(storage.ChunkLayerStats, storage.ChunkLayerStats, error)) { defer close(done) pol := cutPolicy{ interval: p.cfg.ChunkCaptureInterval, @@ -912,6 +913,9 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer trace("cut", ls.LastCutNs, skipped) } if skipped { + if attempted != nil { + attempted(ls, layer.Stats(), nil) + } cancel() continue } @@ -923,6 +927,9 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer } cancel() after := layer.Stats() + if attempted != nil { + attempted(ls, after, err) + } s = pol.afterStaging(s, start, time.Now(), err, after.CutSeq, after.StagedChunks-ls.StagedChunks) wait.record(s) if err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && ctx.Err() == nil { @@ -938,25 +945,60 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer // chunkBackground owns both workers and their cancellation. A fence is observed // even while either worker is waiting on a cooperative remote call. INV-MAINT-JOIN: // done closes only after every admitted worker has returned. -func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.CancelFunc, volumeID string, layer storage.ChunkLayer, done chan struct{}, current func() bool, snapshots *snapshotSlot, cutWait *cutWaitSlot, kick <-chan struct{}) { +func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.CancelFunc, volumeID string, layer storage.ChunkLayer, done chan struct{}, current func() bool, snapshots *snapshotSlot, cutWait *cutWaitSlot, kick chan struct{}) { defer close(done) defer cancel() var workers sync.WaitGroup + // Both background publishers share this in-process stall count. The layer + // rechecks its counters under its capture lock before discarding anything. + var attemptMu sync.Mutex + var first sync.Once + firstAttempt := make(chan struct{}) + zeroProgress := 0 + if p.cfg.ChunkCaptureInterval <= 0 || layer.Stats().DirtyChunks == 0 { + first.Do(func() { close(firstAttempt) }) + } + attempted := func(before, after storage.ChunkLayerStats, err error) { + attemptMu.Lock() + defer attemptMu.Unlock() + first.Do(func() { close(firstAttempt) }) + if err == nil || after.StagedChunks > before.StagedChunks || after.CutSeq != before.CutSeq { + zeroProgress = 0 + return + } + if errors.Is(err, hostlimit.ErrSlotsHeld) { + return + } // no attempt ran + zeroProgress++ + if zeroProgress < chunkZeroProgressLimit || p.cfg.ChunkMaintenance == nil { + return + } + if drop, ok := layer.(storage.ChunkStagedDiscarder); ok && drop.DiscardStagedIfUnchanged(after.StagedChunks, after.CutSeq) { + zeroProgress = 0 + select { + case kick <- struct{}{}: + default: + } + } + } if p.cfg.ChunkCaptureInterval > 0 { workers.Add(1) go func() { defer workers.Done() cutDone := make(chan struct{}) - p.chunkLoop(ctx, volumeID, layer, cutDone, cutWait) + p.chunkLoop(ctx, volumeID, layer, cutDone, cutWait, attempted) }() } if p.cfg.ChunkMaintenanceInterval > 0 && p.cfg.ChunkMaintenance != nil { workers.Add(1) - go func() { defer workers.Done(); p.chunkMaintenanceLoop(ctx, volumeID, layer, current, kick) }() + go func() { + defer workers.Done() + p.chunkMaintenanceLoop(ctx, volumeID, layer, current, kick, firstAttempt) + }() } if snapshots != nil { workers.Add(1) - go func() { defer workers.Done(); p.chunkSnapshotLoop(ctx, volumeID, layer, current, snapshots) }() + go func() { defer workers.Done(); p.chunkSnapshotLoop(ctx, volumeID, layer, current, snapshots, attempted) }() } timer := time.NewTicker(chunkSchedulePoll) defer timer.Stop() @@ -1009,7 +1051,7 @@ func (p *DurableProvider) KickMaintenance(volumeID string) bool { return true } -func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool, kick <-chan struct{}) { +func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool, kick <-chan struct{}, firstAttempt <-chan struct{}) { interval := p.cfg.ChunkMaintenanceInterval due := time.Now().Add(interval) if p.cfg.ChunkStagger { @@ -1032,6 +1074,14 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str } } } + if firstAttempt != nil { + select { + case <-ctx.Done(): + return + case <-firstAttempt: + } + firstAttempt = nil + } if ctx.Err() != nil || layer.Fenced() { return } diff --git a/seaweed-block/core/storage/chunk_periodic_cut.go b/seaweed-block/core/storage/chunk_periodic_cut.go index e30b8800d5..cb394d90b8 100644 --- a/seaweed-block/core/storage/chunk_periodic_cut.go +++ b/seaweed-block/core/storage/chunk_periodic_cut.go @@ -29,3 +29,24 @@ func (l *chunkLayerImpl) CutUnlessCutSince(ctx context.Context, seq uint64) (chu r, err := l.captureLocked(ctx, false) return r, false, err } + +// ChunkStagedDiscarder yields stalled uploads to cleaning. A pending publication +// is never discarded, and progress made by another cut invalidates the request. +type ChunkStagedDiscarder interface { + DiscardStagedIfUnchanged(staged, seq uint64) bool +} + +func (l *chunkLayerImpl) DiscardStagedIfUnchanged(staged, seq uint64) bool { + if !l.capMu.TryLock() { + return false + } + defer l.unlockCap() + l.stMu.Lock() + safe := !l.closed && l.pending == nil && !l.fenced && l.detached == nil && l.stats.StagedChunks == staged && l.stats.CutSeq == seq + l.stMu.Unlock() + if !safe { + return false + } + l.discardStaged() + return true +} diff --git a/seaweed-block/core/storage/chunk_stalled_discard_test.go b/seaweed-block/core/storage/chunk_stalled_discard_test.go new file mode 100644 index 0000000000..f4b5d9cea8 --- /dev/null +++ b/seaweed-block/core/storage/chunk_stalled_discard_test.go @@ -0,0 +1,35 @@ +package storage + +import "testing" + +func TestDiscardStagedRechecksCaptureState(t *testing.T) { + for _, name := range []string{"idle", "staging_advanced", "cut_advanced", "pending_commit", "fenced", "detached", "closed", "cut_running"} { + t.Run(name, func(t *testing.T) { + r := newFakeChunkRemote() + l := &chunkLayerImpl{remote: r, stats: chunkLayerStats{StagedChunks: 3, CutSeq: 2}, reusable: map[uint64]stagedChunk{1: {}}} + switch name { + case "staging_advanced": + l.stats.StagedChunks++ + case "cut_advanced": + l.stats.CutSeq++ + case "pending_commit": + l.pending = &chunkHead{} + case "fenced": + l.fenced = true + case "detached": + l.detached = &chunkCutResult{} + case "closed": + l.closed = true + case "cut_running": + l.capMu.Lock() + defer l.capMu.Unlock() + } + if got := l.DiscardStagedIfUnchanged(3, 2); got != (name == "idle") { + t.Fatalf("discard=%v for %s", got, name) + } + if (len(l.reusable) == 0) != (name == "idle") { + t.Fatal("staged uploads changed on a refused discard") + } + }) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7ac18c11c3..9d66a48f77 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -882,6 +882,7 @@ Notes: | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | Retired: B does not store per-chunk BirthLSN; `INV-SNAPK-COMMIT-REACH-001` protects the published object graph, and the surviving barrier-image test protects the cut image. | legacy M5 | — | — | — | ARCHIVED | | `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`); `TestChunkStageV3_MidUploadAbortReducesRetryBytes` (`core/storage/chunk_abort_upload_bytes_test.go`); `TestCutRevokedMidUploadKeepsItsUploads` (`core/storage/chunk_cut_revoke_reuse_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | +| `INV-CUT-RETRY-FAIRNESS-001` | New staging retries without backoff; zero progress backs off. Dirty-start cleaning follows cut attempt 1; K=3 stalled background attempts yield reusable staging, never a pending commit or an active/newer cut. | M5 Stage, M6 Clean (CUT-BUDGET B1/B3) | `core/frontend/durable/provider_chunk.go`; `core/frontend/durable/chunk_snapshot_schedule.go`; `core/storage/chunk_periodic_cut.go` | `TestCutLoopProgressRetriesWithoutBackoff`, `TestScheduledSnapshotProgressRetriesWithoutBackoff`, `TestDirtyStartCleaningWaitsForFirstCutAttempt`, `TestStalledCutYieldsSessionToCleaning` (`core/frontend/durable/cut_progress_test.go`); `TestDiscardStagedRechecksCaptureState` (`core/storage/chunk_stalled_discard_test.go`); `TestLayoutStalledSessionYieldAllowsCleaning` (`core/frontend/chunkstore/layout_stalled_discard_test.go`) | `CommitReach` `CBegin` (existing session exclusion; scheduling only) | ACTIVE | | `INV-CUT-STAGED-COUNT-001` | `Stats.StagedChunks` counts each chunk staging finished (remembered for reuse) in every cut attempt, an interrupted round included, and only grows; a re-staged chunk counts again; it is in-process. A cut's `PayloadNs` includes its staging rounds whether or not they uploaded. | M5 Stage (before the barrier) | `core/storage/chunk_cut_payload.go` `rememberPayload`, `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkStage_StagedChunksCountsFailedAttempts`, `TestChunkStage_StagedChunksCountsAnInterruptedRound`, `TestChunkStage_PayloadTimeCountsStagingWithoutUploads` (`core/storage/chunk_stage_accounting_test.go`) | — | ACTIVE | | `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication (a cut, or a fresh store's claim: `INV-CUT-FRESH-KNOWN-ZERO-001`) and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_test.go`) | `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-FRESH-KNOWN-ZERO-001` | A store this start created (in memory) and still fresh at its attach (marker present, no BASE) starts known-zero for each chunk its claimed HEAD does not name whose entry is still {LSN 0, UNKNOWN}. Order: retire the marker, then make the marking durable, then serve. | M1 Recovering → Serving (fresh attach: commit, marking, then serving) | `core/storage/chunk_fresh_known_zero.go` `freshKnownZeroCandidates`, `ApplyFreshKnownZero`; `core/frontend/durable/provider_chunk.go` `attachChunk`; `core/frontend/durable/provider.go` `openOrCreate` (`createdThisStart`; non-chunk implementations refuse chunk roots) | `TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks`, `TestFirstCutAgainstAClaimedHeadCertifiesUnnamedChunks`, `TestFirstCutOfARestoreTargetKeepsItsHydrationPath`, `TestExplicitWALStoreRefusesAFreshChunkRoot` (`core/frontend/durable/first_cut_known_zero_test.go`); `TestNoWriteReachesAFreshStoreBeforeItsAttachCommit`, `TestNoFetchOrFillReachesAFreshStoreBeforeItsAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeTheAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeAnyAttach`, `TestFreshKnownZeroCrashBetweenMarkerRetireAndMarking` (`core/frontend/durable/known_zero_premise_test.go`); `TestFreshKnownZeroNeverCertifiesARecordedWrite`, `TestFreshKnownZeroNotWithoutTheFreshPremise`, `TestFreshKnownZeroSkipsAChunkWrittenAfterTheSample`, `TestFreshKnownZeroNeedsThisStartsCreate` (`core/storage/chunk_fresh_known_zero_test.go`) | `KnownZero`. Premise: no write, fill or other implementation reaches a store before its attach commit; a marker an earlier start, an older binary or another opener left is never trusted (created-this-start is in memory). A crash between retirement and marking costs one scan. | ACTIVE | diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 6fdc85355d..1dcab4a7db 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -699,6 +699,21 @@ Space comes back in two steps. Neither is immediate. # or, in weed shell: volume.list and volume.vacuum -garbageThreshold 0.01 ``` +### Cut retries and cleaning after a dirty start + +Automatic cuts and scheduled snapshots retry at the next scheduling opportunity +when a failed attempt finished staging new chunks. An attempt with no new staging +keeps the ordinary doubling backoff. The per-attempt deadline is unchanged; retry +progress is in-process, and a restart recovers objects by their content names. + +When automatic cuts are enabled and the layer starts dirty, its first cleaning +pass waits for the first cut attempt to return. Clean starts and disabled automatic +cuts keep the ordinary cleaning schedule. After three consecutive failed background +attempts without staging progress, the holder drops its reusable staging session +and kicks cleaning. Progress or a successful cut resets that count. A running cut, +a newer completed cut or staging counter, and an unresolved commit prevent that +discard. The kernel's session exclusion and conditional removal remain authoritative. + ### SeaweedFS maintenance commands that destroy chunk volumes A walstore-chunk volume keeps its data in SeaweedFS as needles that **no file's chunk list names**: the volume's From ae8e50804471c18b0203e39c753b95a6f77c77f8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 28 Nov 2026 06:22:52 -0800 Subject: [PATCH 04/13] guard unchanged cleaning when startup cuts are disabled --- .../frontend/durable/cut_progress_test.go | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/seaweed-block/core/frontend/durable/cut_progress_test.go b/seaweed-block/core/frontend/durable/cut_progress_test.go index e901cfb7e8..739f8fd76c 100644 --- a/seaweed-block/core/frontend/durable/cut_progress_test.go +++ b/seaweed-block/core/frontend/durable/cut_progress_test.go @@ -172,3 +172,28 @@ func TestStalledCutYieldsSessionToCleaning(t *testing.T) { }) } } + +func TestCleaningNotDelayedForCleanOrAutomaticCutsDisabled(t *testing.T) { + for _, automatic := range []bool{false, true} { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + var layer storage.ChunkLayer = &progressLoopLayer{} // clean start + if !automatic { + layer = &yieldingLayer{} + } // dirty, but no automatic cut configured + var cleaned atomic.Int32 + p := &DurableProvider{cfg: ProviderConfig{ChunkMaintenanceInterval: time.Millisecond, ChunkMaintenance: func(context.Context, string) error { cleaned.Add(1); return nil }}} + if automatic { + p.cfg.ChunkCaptureInterval = time.Hour + } + go p.chunkBackground(ctx, cancel, "ordinary", layer, done, func() bool { return true }, nil, nil, nil) + defer func() { cancel(); <-done }() + time.Sleep(2 * time.Millisecond) + synctest.Wait() + if cleaned.Load() == 0 { + t.Fatal("ordinary cleaning schedule was delayed") + } + }) + } +} From 62ceffe78a9aa02af39fe2eebd1e6a9a33c23abb Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 28 Nov 2026 06:28:04 -0800 Subject: [PATCH 05/13] observe request cuts before cleaning and exclude unadmitted stalls --- .../frontend/durable/cut_progress_test.go | 105 ++++++++++++++---- .../core/frontend/durable/provider_chunk.go | 49 +++++--- seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/standalone-deployment.md | 14 ++- 4 files changed, 132 insertions(+), 38 deletions(-) diff --git a/seaweed-block/core/frontend/durable/cut_progress_test.go b/seaweed-block/core/frontend/durable/cut_progress_test.go index 739f8fd76c..4ca4484725 100644 --- a/seaweed-block/core/frontend/durable/cut_progress_test.go +++ b/seaweed-block/core/frontend/durable/cut_progress_test.go @@ -78,7 +78,7 @@ type firstAttemptLayer struct { } func (l *firstAttemptLayer) Stats() storage.ChunkLayerStats { - return storage.ChunkLayerStats{DirtyChunks: 1} + return storage.ChunkLayerStats{DirtyChunks: 1, CutsFailed: uint64(l.calls.Load())} } func (l *firstAttemptLayer) Cut(ctx context.Context) (storage.ChunkCutResult, error) { select { @@ -89,6 +89,7 @@ func (l *firstAttemptLayer) Cut(ctx context.Context) (storage.ChunkCutResult, er case <-l.release: case <-ctx.Done(): } + l.calls.Add(1) return storage.ChunkCutResult{}, context.DeadlineExceeded } func TestDirtyStartCleaningWaitsForFirstCutAttempt(t *testing.T) { @@ -97,8 +98,10 @@ func TestDirtyStartCleaningWaitsForFirstCutAttempt(t *testing.T) { done := make(chan struct{}) layer := &firstAttemptLayer{entered: make(chan struct{}, 1), release: make(chan struct{})} var cleaned atomic.Int32 - p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond, ChunkMaintenanceInterval: time.Millisecond, ChunkMaintenance: func(context.Context, string) error { cleaned.Add(1); return nil }}} - go p.chunkBackground(ctx, cancel, "dirty", layer, done, func() bool { return true }, nil, nil, nil) + p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond, ChunkMaintenanceInterval: time.Hour, ChunkMaintenance: func(context.Context, string) error { cleaned.Add(1); return nil }}} + kick := make(chan struct{}, 1) + kick <- struct{}{} + go p.chunkBackground(ctx, cancel, "dirty", layer, done, func() bool { return true }, nil, nil, kick) defer func() { cancel(); <-done }() time.Sleep(500 * time.Millisecond) synctest.Wait() @@ -111,7 +114,7 @@ func TestDirtyStartCleaningWaitsForFirstCutAttempt(t *testing.T) { t.Fatalf("%d cleaning passes ran before the dirty start's first cut returned", n) } close(layer.release) - time.Sleep(time.Millisecond) + time.Sleep(2 * chunkSchedulePoll) synctest.Wait() if cleaned.Load() == 0 { t.Fatal("cleaning never ran after the first cut attempt") @@ -122,16 +125,21 @@ func TestDirtyStartCleaningWaitsForFirstCutAttempt(t *testing.T) { type yieldingLayer struct { progressLoopLayer progressAt int32 + absent int + err error discarded atomic.Int32 } func (l *yieldingLayer) Stats() storage.ChunkLayerStats { - return storage.ChunkLayerStats{DirtyChunks: 1, StagedChunks: l.staged.Load()} + return storage.ChunkLayerStats{DirtyChunks: 1, StagedChunks: l.staged.Load(), CutsFailed: uint64(l.calls.Load()), AbsentChunks: l.absent} } func (l *yieldingLayer) Cut(context.Context) (storage.ChunkCutResult, error) { if l.calls.Add(1) == l.progressAt { l.staged.Add(1) } + if l.err != nil { + return storage.ChunkCutResult{}, l.err + } return storage.ChunkCutResult{}, context.DeadlineExceeded } func (l *yieldingLayer) DiscardStagedIfUnchanged(staged, seq uint64) bool { @@ -173,26 +181,85 @@ func TestStalledCutYieldsSessionToCleaning(t *testing.T) { } } -func TestCleaningNotDelayedForCleanOrAutomaticCutsDisabled(t *testing.T) { - for _, automatic := range []bool{false, true} { +func TestDirtyStartWithPeriodicCutsOffWaitsForRequestOrInterval(t *testing.T) { + for _, request := range []bool{false, true} { synctest.Test(t, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) - var layer storage.ChunkLayer = &progressLoopLayer{} // clean start - if !automatic { - layer = &yieldingLayer{} - } // dirty, but no automatic cut configured + layer := &firstAttemptLayer{entered: make(chan struct{}, 1), release: make(chan struct{})} var cleaned atomic.Int32 - p := &DurableProvider{cfg: ProviderConfig{ChunkMaintenanceInterval: time.Millisecond, ChunkMaintenance: func(context.Context, string) error { cleaned.Add(1); return nil }}} - if automatic { - p.cfg.ChunkCaptureInterval = time.Hour - } - go p.chunkBackground(ctx, cancel, "ordinary", layer, done, func() bool { return true }, nil, nil, nil) + p := &DurableProvider{cfg: ProviderConfig{ChunkMaintenanceInterval: time.Second, ChunkMaintenance: func(context.Context, string) error { cleaned.Add(1); return nil }}} + kick := make(chan struct{}, 1) + kick <- struct{}{} + go p.chunkBackground(ctx, cancel, "request", layer, done, func() bool { return true }, nil, nil, kick) defer func() { cancel(); <-done }() - time.Sleep(2 * time.Millisecond) synctest.Wait() - if cleaned.Load() == 0 { - t.Fatal("ordinary cleaning schedule was delayed") + if request { + go layer.Cut(ctx) + } + time.Sleep(400 * time.Millisecond) + synctest.Wait() + if cleaned.Load() != 0 { + t.Fatal("cleaning ran before any request cut finished or the interval elapsed") + } + if request { + close(layer.release) + } + time.Sleep(2 * chunkSchedulePoll) + synctest.Wait() + if request && cleaned.Load() != 1 { + t.Fatal("cleaning did not observe the request cut's completion") + } + if !request { + if cleaned.Load() != 0 { + t.Fatal("no-attempt fallback ran before the interval") + } + time.Sleep(500 * time.Millisecond) + synctest.Wait() + if cleaned.Load() != 1 { + t.Fatal("no-attempt fallback did not run after one interval") + } + } + }) + } +} + +func TestUnadmittedAttemptsDoNotDiscardStaging(t *testing.T) { + for _, skip := range []bool{false, true} { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + layer := &yieldingLayer{err: storage.ErrChunkCaptureRefused} + p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond, ChunkMaintenanceInterval: 30 * 24 * time.Hour, ChunkMaintenance: func(context.Context, string) error { return nil }}} + var snapshots *snapshotSlot + wait := 8 * time.Second + if skip { + p.cfg.ChunkCaptureInterval = 0 + layer.absent = 1 + wait = 4 * time.Hour + p.cfg.ChunkScheduledSnapshot = func(context.Context, string, time.Time, func(context.Context) (storage.ChunkHead, error)) error { + t.Error("restoring snapshot reached store") + return nil + } + snapshots = &snapshotSlot{s: newSnapshotSchedule("skip", 24*time.Hour, time.Now())} + snapshots.s.next = time.Now() + } + go p.chunkBackground(ctx, cancel, "unadmitted", layer, done, func() bool { return true }, snapshots, nil, make(chan struct{}, 1)) + defer func() { cancel(); <-done }() + time.Sleep(wait) + synctest.Wait() + if skip { + snapshots.mu.Lock() + n := snapshots.s.skipped[SnapshotSkipRestoring] + snapshots.mu.Unlock() + if n < 3 { + t.Fatal("did not exercise three snapshot skips") + } + } else if layer.calls.Load() < 3 { + t.Fatal("did not exercise three capture refusals") + } + if layer.discarded.Load() != 0 { + t.Fatal("unadmitted attempts discarded an unfinished session") } }) } diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 40df112281..ab889f13aa 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -952,23 +952,23 @@ func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.Ca // Both background publishers share this in-process stall count. The layer // rechecks its counters under its capture lock before discarding anything. var attemptMu sync.Mutex - var first sync.Once - firstAttempt := make(chan struct{}) - zeroProgress := 0 - if p.cfg.ChunkCaptureInterval <= 0 || layer.Stats().DirtyChunks == 0 { - first.Do(func() { close(firstAttempt) }) + var firstAttempt *maintenanceStart + initial := layer.Stats() + if initial.DirtyChunks > 0 { + firstAttempt = &maintenanceStart{attempts: cutAttempts(initial), deadline: time.Now().Add(p.cfg.ChunkMaintenanceInterval)} } + zeroProgress := 0 attempted := func(before, after storage.ChunkLayerStats, err error) { attemptMu.Lock() defer attemptMu.Unlock() - first.Do(func() { close(firstAttempt) }) if err == nil || after.StagedChunks > before.StagedChunks || after.CutSeq != before.CutSeq { zeroProgress = 0 return } - if errors.Is(err, hostlimit.ErrSlotsHeld) { - return - } // no attempt ran + var skip *SnapshotSkip + if errors.Is(err, hostlimit.ErrSlotsHeld) || errors.Is(err, storage.ErrChunkCaptureRefused) || errors.As(err, &skip) { + return // no attempt against the store ran + } zeroProgress++ if zeroProgress < chunkZeroProgressLimit || p.cfg.ChunkMaintenance == nil { return @@ -1051,7 +1051,22 @@ func (p *DurableProvider) KickMaintenance(volumeID string) bool { return true } -func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool, kick <-chan struct{}, firstAttempt <-chan struct{}) { +// maintenanceStart bounds only the first cleaning of an initially dirty layer. +// Completion counters include periodic, scheduled, and operator-request cuts. +type maintenanceStart struct { + attempts uint64 + deadline time.Time +} + +func cutAttempts(st storage.ChunkLayerStats) uint64 { + n := st.CutsOK + st.CutsNoop + st.CutsFailed + for _, refused := range st.CutsRefused { + n += refused + } + return n +} + +func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool, kick <-chan struct{}, firstAttempt *maintenanceStart) { interval := p.cfg.ChunkMaintenanceInterval due := time.Now().Add(interval) if p.cfg.ChunkStagger { @@ -1075,10 +1090,16 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str } } if firstAttempt != nil { - select { - case <-ctx.Done(): - return - case <-firstAttempt: + // The engine counters cover request cuts too, not just these workers. + // One interval bounds this scheduling wait; HEAD still decides safety. + for cutAttempts(layer.Stats()) == firstAttempt.attempts && time.Now().Before(firstAttempt.deadline) && !layer.Fenced() && current() { + pause := time.NewTimer(min(chunkSchedulePoll, time.Until(firstAttempt.deadline))) + select { + case <-ctx.Done(): + pause.Stop() + return + case <-pause.C: + } } firstAttempt = nil } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9d66a48f77..957da0af29 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -882,7 +882,7 @@ Notes: | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | Retired: B does not store per-chunk BirthLSN; `INV-SNAPK-COMMIT-REACH-001` protects the published object graph, and the surviving barrier-image test protects the cut image. | legacy M5 | — | — | — | ARCHIVED | | `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`); `TestChunkStageV3_MidUploadAbortReducesRetryBytes` (`core/storage/chunk_abort_upload_bytes_test.go`); `TestCutRevokedMidUploadKeepsItsUploads` (`core/storage/chunk_cut_revoke_reuse_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | -| `INV-CUT-RETRY-FAIRNESS-001` | New staging retries without backoff; zero progress backs off. Dirty-start cleaning follows cut attempt 1; K=3 stalled background attempts yield reusable staging, never a pending commit or an active/newer cut. | M5 Stage, M6 Clean (CUT-BUDGET B1/B3) | `core/frontend/durable/provider_chunk.go`; `core/frontend/durable/chunk_snapshot_schedule.go`; `core/storage/chunk_periodic_cut.go` | `TestCutLoopProgressRetriesWithoutBackoff`, `TestScheduledSnapshotProgressRetriesWithoutBackoff`, `TestDirtyStartCleaningWaitsForFirstCutAttempt`, `TestStalledCutYieldsSessionToCleaning` (`core/frontend/durable/cut_progress_test.go`); `TestDiscardStagedRechecksCaptureState` (`core/storage/chunk_stalled_discard_test.go`); `TestLayoutStalledSessionYieldAllowsCleaning` (`core/frontend/chunkstore/layout_stalled_discard_test.go`) | `CommitReach` `CBegin` (existing session exclusion; scheduling only) | ACTIVE | +| `INV-CUT-RETRY-FAIRNESS-001` | New staging retries without backoff; zero progress backs off. Dirty-start cleaning waits for any cut attempt or one maintenance interval. K=3 admitted stalled attempts yield reusable staging, never a pending or active/newer cut. | M5 Stage, M6 Clean (CUT-BUDGET B1/B3) | `core/frontend/durable/provider_chunk.go`; `core/frontend/durable/chunk_snapshot_schedule.go`; `core/storage/chunk_periodic_cut.go` | `TestCutLoopProgressRetriesWithoutBackoff`, `TestScheduledSnapshotProgressRetriesWithoutBackoff`, `TestDirtyStartCleaningWaitsForFirstCutAttempt`, `TestStalledCutYieldsSessionToCleaning` (`core/frontend/durable/cut_progress_test.go`); `TestDiscardStagedRechecksCaptureState` (`core/storage/chunk_stalled_discard_test.go`); `TestLayoutStalledSessionYieldAllowsCleaning` (`core/frontend/chunkstore/layout_stalled_discard_test.go`) | `CommitReach` `CBegin` (existing session exclusion; scheduling only) | ACTIVE | | `INV-CUT-STAGED-COUNT-001` | `Stats.StagedChunks` counts each chunk staging finished (remembered for reuse) in every cut attempt, an interrupted round included, and only grows; a re-staged chunk counts again; it is in-process. A cut's `PayloadNs` includes its staging rounds whether or not they uploaded. | M5 Stage (before the barrier) | `core/storage/chunk_cut_payload.go` `rememberPayload`, `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkStage_StagedChunksCountsFailedAttempts`, `TestChunkStage_StagedChunksCountsAnInterruptedRound`, `TestChunkStage_PayloadTimeCountsStagingWithoutUploads` (`core/storage/chunk_stage_accounting_test.go`) | — | ACTIVE | | `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication (a cut, or a fresh store's claim: `INV-CUT-FRESH-KNOWN-ZERO-001`) and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_test.go`) | `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-FRESH-KNOWN-ZERO-001` | A store this start created (in memory) and still fresh at its attach (marker present, no BASE) starts known-zero for each chunk its claimed HEAD does not name whose entry is still {LSN 0, UNKNOWN}. Order: retire the marker, then make the marking durable, then serve. | M1 Recovering → Serving (fresh attach: commit, marking, then serving) | `core/storage/chunk_fresh_known_zero.go` `freshKnownZeroCandidates`, `ApplyFreshKnownZero`; `core/frontend/durable/provider_chunk.go` `attachChunk`; `core/frontend/durable/provider.go` `openOrCreate` (`createdThisStart`; non-chunk implementations refuse chunk roots) | `TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks`, `TestFirstCutAgainstAClaimedHeadCertifiesUnnamedChunks`, `TestFirstCutOfARestoreTargetKeepsItsHydrationPath`, `TestExplicitWALStoreRefusesAFreshChunkRoot` (`core/frontend/durable/first_cut_known_zero_test.go`); `TestNoWriteReachesAFreshStoreBeforeItsAttachCommit`, `TestNoFetchOrFillReachesAFreshStoreBeforeItsAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeTheAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeAnyAttach`, `TestFreshKnownZeroCrashBetweenMarkerRetireAndMarking` (`core/frontend/durable/known_zero_premise_test.go`); `TestFreshKnownZeroNeverCertifiesARecordedWrite`, `TestFreshKnownZeroNotWithoutTheFreshPremise`, `TestFreshKnownZeroSkipsAChunkWrittenAfterTheSample`, `TestFreshKnownZeroNeedsThisStartsCreate` (`core/storage/chunk_fresh_known_zero_test.go`) | `KnownZero`. Premise: no write, fill or other implementation reaches a store before its attach commit; a marker an earlier start, an older binary or another opener left is never trusted (created-this-start is in memory). A crash between retirement and marking costs one scan. | ACTIVE | diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 1dcab4a7db..c7eb2c2c45 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -706,11 +706,17 @@ when a failed attempt finished staging new chunks. An attempt with no new stagin keeps the ordinary doubling backoff. The per-attempt deadline is unchanged; retry progress is in-process, and a restart recovers objects by their content names. -When automatic cuts are enabled and the layer starts dirty, its first cleaning -pass waits for the first cut attempt to return. Clean starts and disabled automatic -cuts keep the ordinary cleaning schedule. After three consecutive failed background +When the layer starts dirty, its first cleaning pass waits for the first cut +attempt of any kind (periodic, scheduled or requested) to return, or for one +maintenance interval from startup, whichever comes first. This also applies when +periodic cuts are disabled; it does not enable them. Clean starts are unchanged. After three consecutive failed background attempts without staging progress, the holder drops its reusable staging session -and kicks cleaning. Progress or a successful cut resets that count. A running cut, +and kicks cleaning. Capture refusals, restoring-snapshot skips and host-slot refusals do not count: +no store attempt ran. Progress or a successful cut resets the count. K counts +attempts, not elapsed time: the first two zero-progress waits are 1 and 2 seconds +for automatic cuts, or 1 and 2 minutes for scheduled snapshots, plus the time spent +in each attempt. Discard permits cleaning to remove unreferenced uploads; the next +cut reuses only content-named chunks that cleaning left behind. A running cut, a newer completed cut or staging counter, and an unresolved commit prevent that discard. The kernel's session exclusion and conditional removal remain authoritative. From 5cb39c5b3cba4a542ba4aa05204a4f1d265a9793 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 28 Nov 2026 06:35:16 -0800 Subject: [PATCH 06/13] retain request progress and prove stalled-session cleaning end to end --- .../frontend/durable/cut_progress_test.go | 72 ++++++++++++ .../durable/cut_stalled_layout_test.go | 108 ++++++++++++++++++ .../core/frontend/durable/provider_chunk.go | 19 ++- seaweed-block/docs/design/invariants.md | 3 +- 4 files changed, 200 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/cut_stalled_layout_test.go diff --git a/seaweed-block/core/frontend/durable/cut_progress_test.go b/seaweed-block/core/frontend/durable/cut_progress_test.go index 4ca4484725..459302423f 100644 --- a/seaweed-block/core/frontend/durable/cut_progress_test.go +++ b/seaweed-block/core/frontend/durable/cut_progress_test.go @@ -264,3 +264,75 @@ func TestUnadmittedAttemptsDoNotDiscardStaging(t *testing.T) { }) } } + +func TestRequestStagingBreaksBackgroundStallStreak(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + layer := &yieldingLayer{} + p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond, ChunkMaintenanceInterval: time.Hour, ChunkMaintenance: func(context.Context, string) error { return nil }}} + go p.chunkBackground(ctx, cancel, "request-progress", layer, done, func() bool { return true }, nil, nil, make(chan struct{}, 1)) + defer func() { cancel(); <-done }() + time.Sleep(2 * time.Second) + synctest.Wait() + if layer.calls.Load() != 2 { + t.Fatalf("want K-1 background stalls, got %d", layer.calls.Load()) + } + layer.staged.Add(1) // an interposed request stages a new chunk and fails + time.Sleep(1500 * time.Millisecond) + synctest.Wait() + if layer.calls.Load() != 3 || layer.discarded.Load() != 0 { + t.Fatalf("calls=%d discarded=%d: request progress must reset the streak", layer.calls.Load(), layer.discarded.Load()) + } + }) +} + +type timedProgressLayer struct { + progressLoopLayer + times chan time.Time +} + +func (l *timedProgressLayer) Cut(context.Context) (storage.ChunkCutResult, error) { + if l.calls.Add(1) == 1 { + l.staged.Add(1) + } + l.times <- time.Now() + return storage.ChunkCutResult{}, context.DeadlineExceeded +} +func TestProgressThenTwoStallsKeepDoublingWaits(t *testing.T) { + for _, scheduled := range []bool{false, true} { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + layer := &timedProgressLayer{times: make(chan time.Time, 16)} + p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond}} + duration, unit := 3500*time.Millisecond, time.Second + if scheduled { + unit = time.Minute + duration = 3*time.Minute + time.Second + p.cfg.ChunkScheduledSnapshot = func(ctx context.Context, _ string, _ time.Time, _ func(context.Context) (storage.ChunkHead, error)) error { + _, err := layer.Cut(ctx) + return err + } + slot := &snapshotSlot{s: newSnapshotSchedule("waits", 24*time.Hour, time.Now())} + slot.s.next = time.Now() + go func() { + defer close(done) + p.chunkSnapshotLoop(ctx, "waits", layer, func() bool { return true }, slot, nil) + }() + } else { + go p.chunkLoop(ctx, "waits", layer, done, nil, nil) + } + defer func() { cancel(); <-done }() + time.Sleep(duration) + synctest.Wait() + if len(layer.times) != 4 { + t.Fatalf("got %d attempts, want four", len(layer.times)) + } + ts := []time.Time{<-layer.times, <-layer.times, <-layer.times, <-layer.times} + if ts[1].Sub(ts[0]) > chunkSchedulePoll || ts[2].Sub(ts[1]) != unit || ts[3].Sub(ts[2]) != 2*unit { + t.Fatalf("retry gaps=%v,%v,%v; want immediate,%v,%v", ts[1].Sub(ts[0]), ts[2].Sub(ts[1]), ts[3].Sub(ts[2]), unit, 2*unit) + } + }) + } +} diff --git a/seaweed-block/core/frontend/durable/cut_stalled_layout_test.go b/seaweed-block/core/frontend/durable/cut_stalled_layout_test.go new file mode 100644 index 0000000000..e988f52163 --- /dev/null +++ b/seaweed-block/core/frontend/durable/cut_stalled_layout_test.go @@ -0,0 +1,108 @@ +package durable_test + +import ( + "context" + "sync/atomic" + "testing" + "testing/synctest" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type stalledLayoutUpload struct { + *chunkstore.LayoutRemote + puts atomic.Int32 +} + +func (r *stalledLayoutUpload) Put(context.Context, string, []byte) error { + r.puts.Add(1) + return context.DeadlineExceeded +} + +// Three actual failed cut attempts must reach guarded discard, the provider's +// maintenance kick, and the real kernel's conditional removal in one run. +func TestStalledBackgroundCutsCleanRealLayout(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) + ready := make(chan struct{}) + cleaned := make(chan int, 1) + var remote *stalledLayoutUpload + var p *durable.DurableProvider + cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: pcBlocks, BlockSize: 4096, ChunkBlocks: pcChunkBlocks, ChunkCOWSpillLimit: 2 * pcChunkBlocks * 4096, + ChunkSnapshotPeriod: time.Second, ChunkCutTimeout: 100 * time.Millisecond, ChunkMaintenanceInterval: 24 * time.Hour} + fixture.Configure(&cfg) + original := cfg.ChunkLayoutRemoteFor + cfg.ChunkLayoutRemoteFor = func(v string, me layout.HolderID) (storage.ChunkRemote, error) { + r, err := original(v, me) + if err != nil { + return nil, err + } + remote = &stalledLayoutUpload{LayoutRemote: r.(*chunkstore.LayoutRemote)} + return remote, nil + } + cfg.ChunkScheduledSnapshot = func(ctx context.Context, _ string, _ time.Time, cut func(context.Context) (storage.ChunkHead, error)) error { + select { + case <-ready: + case <-ctx.Done(): + return ctx.Err() + } + _, err := cut(ctx) + return err + } + cfg.ChunkMaintenance = func(ctx context.Context, _ string) error { + if remote.puts.Load() < 3 || fcutStats(t, p).CutsFailed != 3 { + t.Error("cleaning ran before K actual failed store attempts") + } + return remote.Clean(ctx, func(ctx context.Context, me layout.HolderID, session string) error { + st, err := fixture.Catalog.Store(fixture.Ref) + if err != nil { + return err + } + reader, err := layout.NewReader("/provider-test", fixture.Ref.Dir(), st.Fetch) + if err != nil { + return err + } + result, err := layout.RemoveUnreachable(ctx, st, reader, st, me, session, layout.Shard(15), []layout.ChunkName{layout.NameChunk(15, block(99))}) + select { + case cleaned <- len(result): + default: + } + return err + }) + } + p, err := durable.NewDurableProvider(cfg, v1View()) + if err != nil { + t.Fatal(err) + } + defer p.Close() + st := fcutOpen(t, context.Background(), p) + for i := 0; i < 4; i++ { + if _, err := st.Write(uint32(i*pcChunkBlocks), block(byte(i+1))); err != nil { + t.Fatal(err) + } + } + if _, err := st.Sync(); err != nil { + t.Fatal(err) + } + data := block(99) + if err := remote.LayoutRemote.Put(context.Background(), remote.ChunkKey(15, layout.Sum(data)), data); err != nil { + t.Fatal(err) + } + close(ready) + time.Sleep(4 * time.Minute) + synctest.Wait() + select { + case n := <-cleaned: + if n != 1 { + t.Fatalf("cleaning removed=%d, want the orphan", n) + } + default: + t.Fatal("K failed attempts never kicked real cleaning") + } + }) +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index ab889f13aa..2f724f14a4 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -710,7 +710,8 @@ const ( // - the dirty-chunk count never triggers a cut; // - automatic cuts are at least minSpacing apart (explicit ones are not // subject to it); -// - a failed automatic cut resets nothing and is retried after a backoff +// - a failed cut with new staging retries at the next poll; without +// progress it resets nothing and is retried after a backoff // doubling from backoffMin to backoffMax; any later successful cut (a // no-op cut and an explicit cut included) clears the backoff and // restarts the timer; @@ -958,9 +959,21 @@ func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.Ca firstAttempt = &maintenanceStart{attempts: cutAttempts(initial), deadline: time.Now().Add(p.cfg.ChunkMaintenanceInterval)} } zeroProgress := 0 + lastStaged, lastSeq := initial.StagedChunks, initial.CutSeq attempted := func(before, after storage.ChunkLayerStats, err error) { attemptMu.Lock() defer attemptMu.Unlock() + // Requests do not run this callback. Their intervening progress must + // still break the streak, even if this background attempt staged nothing. + intervened := before.StagedChunks != lastStaged || before.CutSeq != lastSeq + lastStaged = max(lastStaged, before.StagedChunks, after.StagedChunks) + lastSeq = max(lastSeq, before.CutSeq, after.CutSeq) + if intervened { + zeroProgress = 0 + } + if after.StagedChunks < lastStaged || after.CutSeq < lastSeq { + return + } if err == nil || after.StagedChunks > before.StagedChunks || after.CutSeq != before.CutSeq { zeroProgress = 0 return @@ -974,6 +987,7 @@ func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.Ca return } if drop, ok := layer.(storage.ChunkStagedDiscarder); ok && drop.DiscardStagedIfUnchanged(after.StagedChunks, after.CutSeq) { + log.Printf("durable: maintenance volume=%s: yielding staged session after %d zero-progress attempts", volumeID, zeroProgress) zeroProgress = 0 select { case kick <- struct{}{}: @@ -1092,6 +1106,9 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str if firstAttempt != nil { // The engine counters cover request cuts too, not just these workers. // One interval bounds this scheduling wait; HEAD still decides safety. + if cutAttempts(layer.Stats()) == firstAttempt.attempts && time.Now().Before(firstAttempt.deadline) { + log.Printf("durable: maintenance volume=%s: waiting for first cut attempt (startup interval remaining %s)", volumeID, time.Until(firstAttempt.deadline)) + } for cutAttempts(layer.Stats()) == firstAttempt.attempts && time.Now().Before(firstAttempt.deadline) && !layer.Fenced() && current() { pause := time.NewTimer(min(chunkSchedulePoll, time.Until(firstAttempt.deadline))) select { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 957da0af29..a43619205c 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -419,6 +419,7 @@ B stores snapshots, restore dependencies and the active session in HEAD. The tra | Restore | Record the target as a source dependent before creating its root and unclaimed HEAD; owner-qualified references resolve in the source pool. | `core/frontend/chunkstore/catalog_b.go` `BCatalog.Restore`; `core/frontend/chunkstore/layout/create.go` | `INV-SNAPK-COMMIT-REACH-001` | | Remove snapshot | Remove the name through a conditional HEAD transition; its objects remain governed by the roots and dependents still recorded. | `core/frontend/chunkstore/catalog_b.go` `DeleteSnapshot`; `core/frontend/chunkstore/layout/snapshots.go` | `INV-SNAPK-HEAD-WRITE-001` | | Clean | Cleaning excludes an open snapshot session. Read and validate HEAD reachability before marking an unreachable pool entry; delete only under the matching mark. | `core/frontend/chunkstore/layout/clean.go`; `core/frontend/chunkstore/layout/remove.go` `RemoveUnreachable` | `INV-SNAPK-CLEAN-EXCL-001`, `INV-SNAPK-REMOVE-MARK-001`, `INV-SNAPK-REMOVE-STOP-001` | +| Background cut/clean ordering | New staging retries promptly; zero progress backs off. Dirty-start cleaning waits for any completed cut or one interval. After K=3 admitted stalls, guarded discard releases the session and kicks cleaning; request progress resets the streak. | `core/frontend/durable/provider_chunk.go`; `core/storage/chunk_periodic_cut.go` | `INV-CUT-RETRY-FAIRNESS-001` | | Delete volume | Reserve deletion, check no live lease inside the deleting transition, release the reservation, remove objects and mark deleted. | `core/frontend/chunkstore/catalog_b.go` `DeleteVolume`; `core/frontend/chunkstore/layout/delete.go` | `INV-WS-DELETE-NO-LIVE-HOLDER-001` | --- @@ -882,7 +883,7 @@ Notes: | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | Retired: B does not store per-chunk BirthLSN; `INV-SNAPK-COMMIT-REACH-001` protects the published object graph, and the surviving barrier-image test protects the cut image. | legacy M5 | — | — | — | ARCHIVED | | `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`); `TestChunkStageV3_MidUploadAbortReducesRetryBytes` (`core/storage/chunk_abort_upload_bytes_test.go`); `TestCutRevokedMidUploadKeepsItsUploads` (`core/storage/chunk_cut_revoke_reuse_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | -| `INV-CUT-RETRY-FAIRNESS-001` | New staging retries without backoff; zero progress backs off. Dirty-start cleaning waits for any cut attempt or one maintenance interval. K=3 admitted stalled attempts yield reusable staging, never a pending or active/newer cut. | M5 Stage, M6 Clean (CUT-BUDGET B1/B3) | `core/frontend/durable/provider_chunk.go`; `core/frontend/durable/chunk_snapshot_schedule.go`; `core/storage/chunk_periodic_cut.go` | `TestCutLoopProgressRetriesWithoutBackoff`, `TestScheduledSnapshotProgressRetriesWithoutBackoff`, `TestDirtyStartCleaningWaitsForFirstCutAttempt`, `TestStalledCutYieldsSessionToCleaning` (`core/frontend/durable/cut_progress_test.go`); `TestDiscardStagedRechecksCaptureState` (`core/storage/chunk_stalled_discard_test.go`); `TestLayoutStalledSessionYieldAllowsCleaning` (`core/frontend/chunkstore/layout_stalled_discard_test.go`) | `CommitReach` `CBegin` (existing session exclusion; scheduling only) | ACTIVE | +| `INV-CUT-RETRY-FAIRNESS-001` | New staging retries without backoff; zero progress backs off. Dirty-start cleaning waits for any cut attempt or one maintenance interval. K=3 admitted stalled background attempts yield reusable staging, never a pending or active/newer cut. | M5 Stage, M6 Clean (CUT-BUDGET B1/B3) | `core/frontend/durable/provider_chunk.go`; `core/frontend/durable/chunk_snapshot_schedule.go`; `core/storage/chunk_periodic_cut.go` | `TestCutLoopProgressRetriesWithoutBackoff`, `TestScheduledSnapshotProgressRetriesWithoutBackoff`, `TestDirtyStartCleaningWaitsForFirstCutAttempt`, `TestStalledCutYieldsSessionToCleaning` (`core/frontend/durable/cut_progress_test.go`); `TestDiscardStagedRechecksCaptureState` (`core/storage/chunk_stalled_discard_test.go`); `TestLayoutStalledSessionYieldAllowsCleaning` (`core/frontend/chunkstore/layout_stalled_discard_test.go`) | `CommitReach` `CBegin` (existing session exclusion; scheduling only) | ACTIVE | | `INV-CUT-STAGED-COUNT-001` | `Stats.StagedChunks` counts each chunk staging finished (remembered for reuse) in every cut attempt, an interrupted round included, and only grows; a re-staged chunk counts again; it is in-process. A cut's `PayloadNs` includes its staging rounds whether or not they uploaded. | M5 Stage (before the barrier) | `core/storage/chunk_cut_payload.go` `rememberPayload`, `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkStage_StagedChunksCountsFailedAttempts`, `TestChunkStage_StagedChunksCountsAnInterruptedRound`, `TestChunkStage_PayloadTimeCountsStagingWithoutUploads` (`core/storage/chunk_stage_accounting_test.go`) | — | ACTIVE | | `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication (a cut, or a fresh store's claim: `INV-CUT-FRESH-KNOWN-ZERO-001`) and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_test.go`) | `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-FRESH-KNOWN-ZERO-001` | A store this start created (in memory) and still fresh at its attach (marker present, no BASE) starts known-zero for each chunk its claimed HEAD does not name whose entry is still {LSN 0, UNKNOWN}. Order: retire the marker, then make the marking durable, then serve. | M1 Recovering → Serving (fresh attach: commit, marking, then serving) | `core/storage/chunk_fresh_known_zero.go` `freshKnownZeroCandidates`, `ApplyFreshKnownZero`; `core/frontend/durable/provider_chunk.go` `attachChunk`; `core/frontend/durable/provider.go` `openOrCreate` (`createdThisStart`; non-chunk implementations refuse chunk roots) | `TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks`, `TestFirstCutAgainstAClaimedHeadCertifiesUnnamedChunks`, `TestFirstCutOfARestoreTargetKeepsItsHydrationPath`, `TestExplicitWALStoreRefusesAFreshChunkRoot` (`core/frontend/durable/first_cut_known_zero_test.go`); `TestNoWriteReachesAFreshStoreBeforeItsAttachCommit`, `TestNoFetchOrFillReachesAFreshStoreBeforeItsAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeTheAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeAnyAttach`, `TestFreshKnownZeroCrashBetweenMarkerRetireAndMarking` (`core/frontend/durable/known_zero_premise_test.go`); `TestFreshKnownZeroNeverCertifiesARecordedWrite`, `TestFreshKnownZeroNotWithoutTheFreshPremise`, `TestFreshKnownZeroSkipsAChunkWrittenAfterTheSample`, `TestFreshKnownZeroNeedsThisStartsCreate` (`core/storage/chunk_fresh_known_zero_test.go`) | `KnownZero`. Premise: no write, fill or other implementation reaches a store before its attach commit; a marker an earlier start, an older binary or another opener left is never trusted (created-this-start is in memory). A crash between retirement and marking costs one scan. | ACTIVE | From 6424b7f9d9215a75579f8cad0f22c4e82f1f16ef Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 28 Nov 2026 06:41:00 -0800 Subject: [PATCH 07/13] fix: keep first cleaning waiting through capture refusals --- .../frontend/durable/cut_progress_test.go | 61 +++++++++++++++++++ .../core/frontend/durable/provider_chunk.go | 9 +-- seaweed-block/docs/design/invariants.md | 4 +- seaweed-block/docs/standalone-deployment.md | 5 +- 4 files changed, 69 insertions(+), 10 deletions(-) diff --git a/seaweed-block/core/frontend/durable/cut_progress_test.go b/seaweed-block/core/frontend/durable/cut_progress_test.go index 459302423f..20c29117d3 100644 --- a/seaweed-block/core/frontend/durable/cut_progress_test.go +++ b/seaweed-block/core/frontend/durable/cut_progress_test.go @@ -7,6 +7,7 @@ import ( "testing/synctest" "time" + "github.com/seaweedfs/seaweed-block/core/hostlimit" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -336,3 +337,63 @@ func TestProgressThenTwoStallsKeepDoublingWaits(t *testing.T) { }) } } + +// Refusals change the engine's refusal counters without completing a store cut. +type refusedFirstAttemptLayer struct { + firstAttemptLayer + requests atomic.Int32 +} + +func (l *refusedFirstAttemptLayer) Stats() storage.ChunkLayerStats { + st := l.firstAttemptLayer.Stats() + st.CutsRefused = map[string]uint64{"admission": uint64(min(l.requests.Load(), 2))} + return st +} + +func (l *refusedFirstAttemptLayer) Cut(ctx context.Context) (storage.ChunkCutResult, error) { + if l.requests.Add(1) <= 2 { + return storage.ChunkCutResult{}, storage.ErrChunkCaptureRefused + } + return l.firstAttemptLayer.Cut(ctx) +} + +func TestDirtyStartCaptureRefusalsDoNotReleaseCleaning(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + layer := &refusedFirstAttemptLayer{firstAttemptLayer: firstAttemptLayer{entered: make(chan struct{}, 1), release: make(chan struct{})}} + var cleaned atomic.Int32 + const volume = "refused-first-cut" + const interval = time.Hour + p := &DurableProvider{cfg: ProviderConfig{ChunkStagger: true, ChunkMaintenanceInterval: interval, ChunkMaintenance: func(context.Context, string) error { cleaned.Add(1); return nil }}} + go p.chunkBackground(ctx, cancel, volume, layer, done, func() bool { return true }, nil, nil, nil) + defer func() { cancel(); <-done }() + synctest.Wait() + for range 2 { + if _, err := layer.Cut(ctx); err != storage.ErrChunkCaptureRefused { + t.Fatalf("expected capture refusal, got %v", err) + } + } + // Pass the ordinary staggered cleaning time, before the fallback bound. + due := hostlimit.Phase(volume+":maintenance", interval) + if due+4*chunkSchedulePoll >= interval { + t.Fatal("fixture needs room before the no-attempt fallback") + } + time.Sleep(due + 2*chunkSchedulePoll) + synctest.Wait() + if cleaned.Load() != 0 { + t.Fatal("two capture refusals released first cleaning without a store attempt") + } + go layer.Cut(ctx) + synctest.Wait() + if cleaned.Load() != 0 { + t.Fatal("cleaning ran while the first real attempt was still in flight") + } + close(layer.release) + time.Sleep(2 * chunkSchedulePoll) + synctest.Wait() + if cleaned.Load() != 1 { + t.Fatal("first completed store attempt did not release cleaning") + } + }) +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 2f724f14a4..cf08c68f0d 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -1066,18 +1066,15 @@ func (p *DurableProvider) KickMaintenance(volumeID string) bool { } // maintenanceStart bounds only the first cleaning of an initially dirty layer. -// Completion counters include periodic, scheduled, and operator-request cuts. +// Store-attempt counters include periodic, scheduled, and operator-request cuts. +// Refusals did not attempt the store and cannot release this startup wait. type maintenanceStart struct { attempts uint64 deadline time.Time } func cutAttempts(st storage.ChunkLayerStats) uint64 { - n := st.CutsOK + st.CutsNoop + st.CutsFailed - for _, refused := range st.CutsRefused { - n += refused - } - return n + return st.CutsOK + st.CutsNoop + st.CutsFailed } func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool, kick <-chan struct{}, firstAttempt *maintenanceStart) { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index a43619205c..78dbb6617d 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -419,7 +419,7 @@ B stores snapshots, restore dependencies and the active session in HEAD. The tra | Restore | Record the target as a source dependent before creating its root and unclaimed HEAD; owner-qualified references resolve in the source pool. | `core/frontend/chunkstore/catalog_b.go` `BCatalog.Restore`; `core/frontend/chunkstore/layout/create.go` | `INV-SNAPK-COMMIT-REACH-001` | | Remove snapshot | Remove the name through a conditional HEAD transition; its objects remain governed by the roots and dependents still recorded. | `core/frontend/chunkstore/catalog_b.go` `DeleteSnapshot`; `core/frontend/chunkstore/layout/snapshots.go` | `INV-SNAPK-HEAD-WRITE-001` | | Clean | Cleaning excludes an open snapshot session. Read and validate HEAD reachability before marking an unreachable pool entry; delete only under the matching mark. | `core/frontend/chunkstore/layout/clean.go`; `core/frontend/chunkstore/layout/remove.go` `RemoveUnreachable` | `INV-SNAPK-CLEAN-EXCL-001`, `INV-SNAPK-REMOVE-MARK-001`, `INV-SNAPK-REMOVE-STOP-001` | -| Background cut/clean ordering | New staging retries promptly; zero progress backs off. Dirty-start cleaning waits for any completed cut or one interval. After K=3 admitted stalls, guarded discard releases the session and kicks cleaning; request progress resets the streak. | `core/frontend/durable/provider_chunk.go`; `core/storage/chunk_periodic_cut.go` | `INV-CUT-RETRY-FAIRNESS-001` | +| Background cut/clean ordering | New staging retries promptly; zero progress backs off. Dirty-start cleaning waits for a completed store attempt or one interval. After K=3 admitted stalls, guarded discard releases the session and kicks cleaning; request progress resets the streak. | `core/frontend/durable/provider_chunk.go`; `core/storage/chunk_periodic_cut.go` | `INV-CUT-RETRY-FAIRNESS-001` | | Delete volume | Reserve deletion, check no live lease inside the deleting transition, release the reservation, remove objects and mark deleted. | `core/frontend/chunkstore/catalog_b.go` `DeleteVolume`; `core/frontend/chunkstore/layout/delete.go` | `INV-WS-DELETE-NO-LIVE-HOLDER-001` | --- @@ -883,7 +883,7 @@ Notes: | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | Retired: B does not store per-chunk BirthLSN; `INV-SNAPK-COMMIT-REACH-001` protects the published object graph, and the surviving barrier-image test protects the cut image. | legacy M5 | — | — | — | ARCHIVED | | `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`); `TestChunkStageV3_MidUploadAbortReducesRetryBytes` (`core/storage/chunk_abort_upload_bytes_test.go`); `TestCutRevokedMidUploadKeepsItsUploads` (`core/storage/chunk_cut_revoke_reuse_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | -| `INV-CUT-RETRY-FAIRNESS-001` | New staging retries without backoff; zero progress backs off. Dirty-start cleaning waits for any cut attempt or one maintenance interval. K=3 admitted stalled background attempts yield reusable staging, never a pending or active/newer cut. | M5 Stage, M6 Clean (CUT-BUDGET B1/B3) | `core/frontend/durable/provider_chunk.go`; `core/frontend/durable/chunk_snapshot_schedule.go`; `core/storage/chunk_periodic_cut.go` | `TestCutLoopProgressRetriesWithoutBackoff`, `TestScheduledSnapshotProgressRetriesWithoutBackoff`, `TestDirtyStartCleaningWaitsForFirstCutAttempt`, `TestStalledCutYieldsSessionToCleaning` (`core/frontend/durable/cut_progress_test.go`); `TestDiscardStagedRechecksCaptureState` (`core/storage/chunk_stalled_discard_test.go`); `TestLayoutStalledSessionYieldAllowsCleaning` (`core/frontend/chunkstore/layout_stalled_discard_test.go`) | `CommitReach` `CBegin` (existing session exclusion; scheduling only) | ACTIVE | +| `INV-CUT-RETRY-FAIRNESS-001` | New staging retries without backoff; zero progress backs off. Dirty-start cleaning waits for a completed store attempt or one maintenance interval. K=3 admitted stalled background attempts yield reusable staging, never a pending or active/newer cut. | M5 Stage, M6 Clean (CUT-BUDGET B1/B3) | `core/frontend/durable/provider_chunk.go`; `core/frontend/durable/chunk_snapshot_schedule.go`; `core/storage/chunk_periodic_cut.go` | `TestCutLoopProgressRetriesWithoutBackoff`, `TestScheduledSnapshotProgressRetriesWithoutBackoff`, `TestDirtyStartCleaningWaitsForFirstCutAttempt`, `TestDirtyStartCaptureRefusalsDoNotReleaseCleaning`, `TestStalledCutYieldsSessionToCleaning` (`core/frontend/durable/cut_progress_test.go`); `TestDiscardStagedRechecksCaptureState` (`core/storage/chunk_stalled_discard_test.go`); `TestLayoutStalledSessionYieldAllowsCleaning` (`core/frontend/chunkstore/layout_stalled_discard_test.go`) | `CommitReach` `CBegin` (existing session exclusion; scheduling only) | ACTIVE | | `INV-CUT-STAGED-COUNT-001` | `Stats.StagedChunks` counts each chunk staging finished (remembered for reuse) in every cut attempt, an interrupted round included, and only grows; a re-staged chunk counts again; it is in-process. A cut's `PayloadNs` includes its staging rounds whether or not they uploaded. | M5 Stage (before the barrier) | `core/storage/chunk_cut_payload.go` `rememberPayload`, `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkStage_StagedChunksCountsFailedAttempts`, `TestChunkStage_StagedChunksCountsAnInterruptedRound`, `TestChunkStage_PayloadTimeCountsStagingWithoutUploads` (`core/storage/chunk_stage_accounting_test.go`) | — | ACTIVE | | `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication (a cut, or a fresh store's claim: `INV-CUT-FRESH-KNOWN-ZERO-001`) and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_test.go`) | `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-FRESH-KNOWN-ZERO-001` | A store this start created (in memory) and still fresh at its attach (marker present, no BASE) starts known-zero for each chunk its claimed HEAD does not name whose entry is still {LSN 0, UNKNOWN}. Order: retire the marker, then make the marking durable, then serve. | M1 Recovering → Serving (fresh attach: commit, marking, then serving) | `core/storage/chunk_fresh_known_zero.go` `freshKnownZeroCandidates`, `ApplyFreshKnownZero`; `core/frontend/durable/provider_chunk.go` `attachChunk`; `core/frontend/durable/provider.go` `openOrCreate` (`createdThisStart`; non-chunk implementations refuse chunk roots) | `TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks`, `TestFirstCutAgainstAClaimedHeadCertifiesUnnamedChunks`, `TestFirstCutOfARestoreTargetKeepsItsHydrationPath`, `TestExplicitWALStoreRefusesAFreshChunkRoot` (`core/frontend/durable/first_cut_known_zero_test.go`); `TestNoWriteReachesAFreshStoreBeforeItsAttachCommit`, `TestNoFetchOrFillReachesAFreshStoreBeforeItsAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeTheAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeAnyAttach`, `TestFreshKnownZeroCrashBetweenMarkerRetireAndMarking` (`core/frontend/durable/known_zero_premise_test.go`); `TestFreshKnownZeroNeverCertifiesARecordedWrite`, `TestFreshKnownZeroNotWithoutTheFreshPremise`, `TestFreshKnownZeroSkipsAChunkWrittenAfterTheSample`, `TestFreshKnownZeroNeedsThisStartsCreate` (`core/storage/chunk_fresh_known_zero_test.go`) | `KnownZero`. Premise: no write, fill or other implementation reaches a store before its attach commit; a marker an earlier start, an older binary or another opener left is never trusted (created-this-start is in memory). A crash between retirement and marking costs one scan. | ACTIVE | diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index c7eb2c2c45..cc2e4aa063 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -707,9 +707,10 @@ keeps the ordinary doubling backoff. The per-attempt deadline is unchanged; retr progress is in-process, and a restart recovers objects by their content names. When the layer starts dirty, its first cleaning pass waits for the first cut -attempt of any kind (periodic, scheduled or requested) to return, or for one +attempt that reached the store (periodic, scheduled or requested) to return, or for one maintenance interval from startup, whichever comes first. This also applies when -periodic cuts are disabled; it does not enable them. Clean starts are unchanged. After three consecutive failed background +periodic cuts are disabled; it does not enable them. Refused cuts do not end this +wait because they did not reach the store. Clean starts are unchanged. After three consecutive failed background attempts without staging progress, the holder drops its reusable staging session and kicks cleaning. Capture refusals, restoring-snapshot skips and host-slot refusals do not count: no store attempt ran. Progress or a successful cut resets the count. K counts From 494a094c626b48bb884b872396471996776e4ff9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 28 Nov 2026 07:25:43 -0800 Subject: [PATCH 08/13] feat: resume holder cleaning and reclaim unused metadata Remove unnamed roots, segments and chunks through one conditional mark/delete writer. Resume chunk cursors after bounded passes; re-plan metadata first and retain the session initial root set through operator snapshot deletes. Add a local trigger of the existing snapshot schedule for qualification. --- .../core/frontend/chunkstore/catalog_b.go | 9 +- .../core/frontend/chunkstore/clean_b.go | 124 ++++++-- .../core/frontend/chunkstore/clean_b_test.go | 8 +- .../frontend/chunkstore/clean_cursor_test.go | 147 ++++++++++ .../chunkstore/clean_metadata_test.go | 41 +++ .../chunkstore/clean_opdelete_test.go | 2 +- .../chunkstore/layout/clean_metadata_test.go | 168 +++++++++++ .../chunkstore/layout/clean_scale_test.go | 91 ++++++ .../frontend/chunkstore/layout/guard_test.go | 29 +- .../core/frontend/chunkstore/layout/remove.go | 265 +++++++++++++----- .../frontend/chunkstore/layout/stale_test.go | 9 +- .../chunkstore/layout_clean_e2e_test.go | 2 +- .../durable/chunk_snapshot_schedule.go | 33 ++- .../core/frontend/durable/provider_chunk.go | 2 +- .../frontend/durable/snapshot_due_now_test.go | 55 ++++ .../core/host/volume/chunk_control.go | 33 +++ .../host/volume/chunk_schedule_now_test.go | 76 +++++ seaweed-block/docs/design/invariants.md | 18 +- seaweed-block/docs/standalone-deployment.md | 36 +++ 19 files changed, 1034 insertions(+), 114 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/clean_cursor_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/clean_metadata_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/clean_metadata_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/clean_scale_test.go create mode 100644 seaweed-block/core/frontend/durable/snapshot_due_now_test.go create mode 100644 seaweed-block/core/host/volume/chunk_schedule_now_test.go diff --git a/seaweed-block/core/frontend/chunkstore/catalog_b.go b/seaweed-block/core/frontend/chunkstore/catalog_b.go index 29545e8ed3..9f14ffe2b0 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_b.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_b.go @@ -6,6 +6,7 @@ import ( "fmt" "path" "sort" + "sync" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" ) @@ -24,9 +25,11 @@ func (v VolumeRef) Dir() string { return layout.VolumeDir(v.Name, v.ID) } // BCatalog is the volume catalog on the content-named layout: every // operation is a layout kernel step over the volume's filer store. type BCatalog struct { - f Filer - b Blobs - base string + f Filer + b Blobs + base string + cleanMu sync.Mutex + cursors map[VolumeRef]*cleanCursor } // NewBCatalog returns the catalog of the volumes under base. diff --git a/seaweed-block/core/frontend/chunkstore/clean_b.go b/seaweed-block/core/frontend/chunkstore/clean_b.go index 5fa92ad5ed..17e320ac76 100644 --- a/seaweed-block/core/frontend/chunkstore/clean_b.go +++ b/seaweed-block/core/frontend/chunkstore/clean_b.go @@ -4,62 +4,150 @@ import ( "context" "errors" "path" + "sort" "strconv" + "sync" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" ) -// cleanPage is the number of pool names one removal step plans at once -// (a variable only so tests can page with a small one). var cleanPage uint32 = 1000 -// CleanResult is what one cleaning pass removed. +// CleanResult counts names examined/deleted by this bounded pass, all kinds. type CleanResult struct { - Shards int // pool shards listed - Planned int // candidate names read - Removed int // names deleted + Shards int + Planned int + Removed int + Roots int + Segments int } -// RemoveUnreachableAll is the cleaning's removal step over every pool shard -// of v, page by page, for a holder whose clean(session) is open on HEAD -// (opened by the holder's layout remote, LayoutRemote.Clean): -// layout.RemoveUnreachable validates HEAD after reading each page's tags, -// so it removes nothing unless clean(session) is this holder's. +// The cursor is scheduling only: after a timeout a new session re-plans tags +// and validates HEAD; no cached safety decision survives the pass. Completing +// the last shard wraps to roots so earlier/new names are revisited next time. +type cleanCursor struct { + mu sync.Mutex + phase int // roots, segments, chunks + shard string + after string + poolAfter string +} + +func (c *BCatalog) cleaningCursor(v VolumeRef) *cleanCursor { + c.cleanMu.Lock() + defer c.cleanMu.Unlock() + if c.cursors == nil { + c.cursors = map[VolumeRef]*cleanCursor{} + } + cur := c.cursors[v] + if cur == nil { + cur = &cleanCursor{} + c.cursors[v] = cur + } + return cur +} + +// RemoveUnreachableAll resumes a bounded cleaning. Roots are removed before +// segments, then chunks; interruptions leave only unnamed content behind. func (c *BCatalog) RemoveUnreachableAll(ctx context.Context, v VolumeRef, me layout.HolderID, session string) (res CleanResult, err error) { + cur := c.cleaningCursor(v) + if !cur.mu.TryLock() { + return res, layout.ErrBusy + } + defer cur.mu.Unlock() s, r, err := c.open(v) if err != nil { return res, err } + cleaner := layout.NewCleaner(s, r, s, me, session) + // A resumed chunk cursor still starts this session with a metadata pass: + // cuts between bounded passes may have left additional unnamed roots. + if cur.phase == 2 { + cur.phase = 0 + cur.after = "" + } + for cur.phase < 2 { + if err := ctx.Err(); err != nil { + return res, err + } + kind := layout.RootDir + if cur.phase == 1 { + kind = layout.SegDir + } + entries, err := c.f.ListEntries(ctx, path.Join(c.base, v.Dir(), kind), "", cur.after, cleanPage) + if err != nil { + return res, err + } + names := make([]string, 0, len(entries)) + for _, e := range entries { + if e == nil || e.IsDirectory || e.Name <= cur.after { + return res, layout.ErrCorrupt + } + names = append(names, e.Name) + } + res.Planned += len(names) + out, err := cleaner.Page(ctx, kind, 0, names) + res.Removed += len(out.Names) + if kind == layout.RootDir { + res.Roots += len(out.Names) + } else { + res.Segments += len(out.Names) + } + if out.After != "" { + cur.after = path.Base(out.After) + } + if err != nil { + return res, err + } + if uint32(len(names)) < cleanPage { + cur.phase++ + cur.after = "" + } + } shards, err := s.List(ctx, path.Join(c.base, v.Dir(), layout.PoolDir)) if err != nil { return res, err } + sort.Strings(shards) for _, name := range shards { shard, perr := strconv.ParseUint(name, 10, 64) if perr != nil || strconv.FormatUint(shard, 10) != name { return res, errors.Join(layout.ErrCorrupt, errors.New("chunkstore: pool shard "+strconv.Quote(name))) } + if name < cur.shard { + continue + } + if name != cur.shard { + cur.shard = name + cur.poolAfter = "" + } res.Shards++ - after := "" for { - page, err := s.ListChunkCandidates(ctx, shard, after, cleanPage) + if err := ctx.Err(); err != nil { + return res, err + } + page, err := s.ListChunkCandidates(ctx, shard, cur.poolAfter, cleanPage) if err != nil { return res, err } - if len(page) == 0 { - break + names := make([]string, len(page)) + for i, n := range page { + names[i] = n.String() } res.Planned += len(page) - removed, err := layout.RemoveUnreachable(ctx, s, r, s, me, session, shard, page) - res.Removed += len(removed) + out, err := cleaner.Page(ctx, layout.PoolDir, shard, names) + res.Removed += len(out.Names) + if out.After != "" { + cur.poolAfter = path.Base(out.After) + } if err != nil { return res, err } if uint32(len(page)) < cleanPage { break } - after = page[len(page)-1].String() } } + cur.phase, cur.shard, cur.after, cur.poolAfter = 0, "", "", "" return res, nil } diff --git a/seaweed-block/core/frontend/chunkstore/clean_b_test.go b/seaweed-block/core/frontend/chunkstore/clean_b_test.go index 5b6c3b1e02..8d2849eb38 100644 --- a/seaweed-block/core/frontend/chunkstore/clean_b_test.go +++ b/seaweed-block/core/frontend/chunkstore/clean_b_test.go @@ -92,8 +92,8 @@ func TestBCatalog_CleanRemovesOnlyUnreachable(t *testing.T) { if err != nil { t.Fatal(err) } - if res.Shards != 2 || res.Planned != 3 || res.Removed != 2 { - t.Fatalf("clean: %+v; want 2 shards, 3 planned, 2 removed", res) + if res.Shards != 2 || res.Planned != 5 || res.Removed != 2 { + t.Fatalf("clean: %+v; want 2 shards, 5 planned (root, segment, 3 chunks), 2 removed", res) } for _, n := range orphans { if present(t, s, n) { @@ -269,14 +269,14 @@ func TestBCatalog_CleanAfterOverwriteAndSnapshotDelete(t *testing.T) { t.Fatal(err) } res, _, err := cleanVia(ctx, c, v, cleanHolder) - if err != nil || res.Removed != 1 { + if err != nil || res.Removed != 3 || res.Roots != 1 || res.Segments != 1 { t.Fatalf("clean: %+v %v; want exactly X's chunk removed", res, err) } after, err := c.listObjects(ctx, v) if err != nil { t.Fatal(err) } - if len(after) != len(before)-1 || present(t, s, cx) || !present(t, s, cy) { + if len(after) != len(before)-3 || present(t, s, cx) || !present(t, s, cy) { t.Fatalf("objects %d -> %d, X present %v, Y present %v; want one fewer, X gone, Y kept", len(before), len(after), present(t, s, cx), present(t, s, cy)) } h, _, err := c.ReadHead(ctx, v) diff --git a/seaweed-block/core/frontend/chunkstore/clean_cursor_test.go b/seaweed-block/core/frontend/chunkstore/clean_cursor_test.go new file mode 100644 index 0000000000..170fbd7b48 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/clean_cursor_test.go @@ -0,0 +1,147 @@ +package chunkstore + +import ( + "context" + "errors" + "path" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +type cleaningListHook struct { + Filer + before func(string, string) error +} + +func (f *cleaningListHook) ListEntries(ctx context.Context, dir, prefix, after string, limit uint32) ([]*filerpb.Entry, error) { + if f.before != nil { + if err := f.before(dir, after); err != nil { + return nil, err + } + } + return f.Filer.ListEntries(ctx, dir, prefix, after, limit) +} + +func orphanMetadata(t *testing.T, s *LayoutStore, chunk layout.ChunkName) layout.RootName { + t.Helper() + root, segs, err := layout.Build(map[uint64]layout.Ref{chunk.Index: {Owner: "v1", OwnerID: s.id, Chunk: chunk}}) + if err != nil { + t.Fatal(err) + } + rn, err := layout.PrepareRoot(context.Background(), s, root, segs, "abandoned") + if err != nil { + t.Fatal(err) + } + return rn +} + +func TestCleaningMetadataCounts(t *testing.T) { + ctx := context.Background() + c, v, s, orphans := cleanFixture(t) + dead := orphanMetadata(t, s, orphans[0]) + res, _, err := cleanVia(ctx, c, v, cleanHolder) + if err != nil { + t.Fatal(err) + } + if _, found, err := s.Stat(ctx, dead.Path()); err != nil || found { + t.Fatalf("unnamed root retained: found=%t err=%v", found, err) + } + if res.Roots != 1 || res.Segments != 1 { + t.Fatalf("metadata removal counts: %+v", res) + } + if err := headNamesMissing(ctx, c, v); err != nil { + t.Fatal(err) + } +} + +func TestCleaningInterruptsAfterMetadataBeforeChunks(t *testing.T) { + ctx := context.Background() + c, v, s, orphans := cleanFixture(t) + dead := orphanMetadata(t, s, orphans[0]) + f := &cleaningListHook{Filer: c.f} + c.f = f + stop := true + f.before = func(dir, after string) error { + if stop && dir == path.Join(s.root, layout.PoolDir) { + return context.DeadlineExceeded + } + return nil + } + if _, _, err := cleanVia(ctx, c, v, cleanHolder); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("interrupt: %v", err) + } + if _, found, err := s.Stat(ctx, dead.Path()); err != nil || found { + t.Fatalf("root was not removed before chunk phase: %t %v", found, err) + } + for _, n := range orphans { + if !present(t, s, n) { + t.Fatal("chunk removed before metadata phase finished") + } + } + stop = false + if _, _, err := cleanVia(ctx, c, v, cleanHolder); err != nil { + t.Fatal(err) + } + if err := headNamesMissing(ctx, c, v); err != nil { + t.Fatal(err) + } + objects, err := c.listObjects(ctx, v) + if err != nil || len(objects) != 3 { + t.Fatalf("after resumed clean: objects=%v err=%v; want one live root, segment and chunk", objects, err) + } + +} + +func TestCleaningCursorResumesAfterTimeoutAndWraps(t *testing.T) { + ctx := context.Background() + c, v, s, orphans := cleanFixture(t) + prev := cleanPage + cleanPage = 1 + t.Cleanup(func() { cleanPage = prev }) + f := &cleaningListHook{Filer: c.f} + c.f = f + fail := true + f.before = func(dir, after string) error { + if fail && dir == path.Join(s.root, layout.PoolDir, "1") { + return context.DeadlineExceeded + } + return nil + } + if _, _, err := cleanVia(ctx, c, v, cleanHolder); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("timeout: %v", err) + } + if present(t, s, orphans[0]) || !present(t, s, orphans[1]) { + t.Fatal("timeout did not split the two shards") + } + fail = false + lateRoot := orphanMetadata(t, s, orphans[1]) + f.before = func(dir, after string) error { + if dir == path.Join(s.root, layout.PoolDir, "0") { + return errors.New("cursor restarted before timed-out shard") + } + return nil + } + if _, _, err := cleanVia(ctx, c, v, cleanHolder); err != nil { + t.Fatal(err) + } + if present(t, s, orphans[1]) { + t.Fatal("resumed pass did not reach later shard") + } + if _, found, err := s.Stat(ctx, lateRoot.Path()); err != nil || found { + t.Fatalf("resumed chunk pass did not first remove newly abandoned metadata: %t %v", found, err) + } + f.before = nil + raw := []byte("new orphan") + n := layout.NameChunk(3, raw) + if err := layout.EnsureObject(ctx, s, n.Path(), raw, "new"); err != nil { + t.Fatal(err) + } + if _, _, err := cleanVia(ctx, c, v, cleanHolder); err != nil { + t.Fatal(err) + } + if present(t, s, n) { + t.Fatal("completed pass did not wrap around") + } +} diff --git a/seaweed-block/core/frontend/chunkstore/clean_metadata_test.go b/seaweed-block/core/frontend/chunkstore/clean_metadata_test.go new file mode 100644 index 0000000000..91c16f73dc --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/clean_metadata_test.go @@ -0,0 +1,41 @@ +package chunkstore + +import ( + "context" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "testing" +) + +func TestCleaningRemovesUnreferencedRootsAndSegments(t *testing.T) { + ctx := context.Background() + lh := newLayoutHost(t) + s, layer, remote := lh.attach("metadata", true, true) + defer s.Close() + writeSync(t, s, map[uint32][]byte{0: block(1)}) + remote.SetSnapshot("old", layout.SnapshotMeta{CreatedNs: 1, Class: layout.ClassSemantic}) + if _, err := layer.Capture(ctx); err != nil { + t.Fatal(err) + } + old := *lh.head().Current + writeSync(t, s, map[uint32][]byte{0: block(2)}) + remote.SetSnapshot("keep", layout.SnapshotMeta{CreatedNs: 2, Class: layout.ClassSemantic}) + if _, err := layer.Capture(ctx); err != nil { + t.Fatal(err) + } + if _, err := lh.cat.DeleteSnapshot(ctx, lh.v, "old"); err != nil { + t.Fatal(err) + } + if err := remote.Clean(ctx, func(ctx context.Context, me layout.HolderID, session string) error { + _, err := lh.cat.RemoveUnreachableAll(ctx, lh.v, me, session) + return err + }); err != nil { + t.Fatal(err) + } + st, _ := lh.cat.Store(lh.v) + if _, found, err := st.Stat(ctx, old.Path()); err != nil || found { + t.Fatalf("unnamed root retained: found=%t err=%v", found, err) + } + if _, found, err := st.Stat(ctx, lh.head().Current.Path()); err != nil || !found { + t.Fatalf("current root lost: found=%t err=%v", found, err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/clean_opdelete_test.go b/seaweed-block/core/frontend/chunkstore/clean_opdelete_test.go index 9bfa5a7991..f651165825 100644 --- a/seaweed-block/core/frontend/chunkstore/clean_opdelete_test.go +++ b/seaweed-block/core/frontend/chunkstore/clean_opdelete_test.go @@ -161,7 +161,7 @@ func TestBCatalog_OperatorSnapshotDeleteDuringACleaning(t *testing.T) { // Convergence: the next cleaning removes the chunk only s1 named. f.hook = nil res, _, err = cleanVia(ctx, c, v, cleanHolder) - if err != nil || res.Removed != 1 || present(t, s, cx) || !present(t, s, cy) { + if err != nil || res.Removed != 3 || res.Roots != 1 || res.Segments != 1 || present(t, s, cx) || !present(t, s, cy) { t.Fatalf("the next pass: %+v %v, X %v, Y %v; want X removed, Y kept", res, err, present(t, s, cx), present(t, s, cy)) } if err := headNamesMissing(ctx, c, v); err != nil { diff --git a/seaweed-block/core/frontend/chunkstore/layout/clean_metadata_test.go b/seaweed-block/core/frontend/chunkstore/layout/clean_metadata_test.go new file mode 100644 index 0000000000..3b59679237 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/clean_metadata_test.go @@ -0,0 +1,168 @@ +package layout + +import ( + "context" + "errors" + "path" + "testing" +) + +func metadataFixture(t *testing.T) (*memObjects, *Head, *Reader, RootName, []string) { + t.Helper() + o, h, _, _ := removeFixture(t) + root, segs, err := Build(manifest(ref("v1", 5, "e"))) + if err != nil { + t.Fatal(err) + } + rn, raw, err := NameRoot(root) + if err != nil { + t.Fatal(err) + } + o.put(rn.Path(), raw, "s0") + names := []string{rn.Path()} + for sn, b := range segs { + o.put(sn.Path(), b, "s0") + names = append(names, sn.Path()) + } + r, err := NewReader(removeBase, "v1", o.fetch) + if err != nil { + t.Fatal(err) + } + return o, h, r, rn, names +} + +func TestCleanerMetadataRetainsCurrentSnapshotAndDependent(t *testing.T) { + ctx := context.Background() + o, h, r, _, dead := metadataFixture(t) + h.State = StateLive + snap := h.Snapshots["daily"] + snap.Dependents = deps(snap.Root, "target") + h.Snapshots["daily"] = snap + for name, f := range map[string]func() (Head, bool, error){ + "operator": func() (Head, bool, error) { return h.DeleteSnapshot("daily") }, + "retention": func() (Head, bool, error) { return h.RetireSnapshot("daily", 100) }, + } { + if _, _, err := f(); !errors.Is(err, ErrHasDependents) { + t.Fatalf("%s removed dependent snapshot: %v", name, err) + } + } + cleaner := NewCleaner(&memHead{h: h}, r, o, me, "c1") + for _, kind := range []string{RootDir, SegDir} { + var names []string + for p := range o.objs { + if path.Dir(p) == path.Join(volRoot, kind) { + names = append(names, path.Base(p)) + } + } + if _, err := cleaner.Page(ctx, kind, 0, names); err != nil { + t.Fatal(err) + } + } + for _, rel := range dead { + if o.has(rel) { + t.Fatalf("unnamed metadata retained: %s", rel) + } + } + for _, rn := range HeadRoots(*h) { + if !o.has(rn.Path()) { + t.Fatalf("HEAD root removed: %s", rn) + } + } + if err := reachableMissing(h, o.data()); err != nil { + t.Fatal(err) + } +} + +func TestCleanerMetadataRefusesOutsideOwnCleaning(t *testing.T) { + for name, edit := range map[string]func(*Head){ + "idle": func(h *Head) { h.Activity = Activity{Kind: ActIdle} }, + "snapshot": func(h *Head) { h.Activity = Activity{Kind: ActSnap, Session: "s"} }, + "foreign": func(h *Head) { h.Epoch++ }, + "other clean": func(h *Head) { h.Activity.Session = "other" }, + } { + t.Run(name, func(t *testing.T) { + o, h, r, rn, _ := metadataFixture(t) + edit(h) + if _, err := NewCleaner(&memHead{h: h}, r, o, me, "c1").Page(context.Background(), RootDir, 0, []string{rn.String()}); err == nil || len(o.writes) != 0 { + t.Fatalf("err=%v writes=%v", err, o.writes) + } + }) + } +} + +func TestCleanerMetadataReuseDefeatsLateMarkAndDelete(t *testing.T) { + for _, kind := range []string{RootDir, SegDir} { + for _, when := range []string{"plan", "mark", "delete"} { + t.Run(kind+"/"+when, func(t *testing.T) { + o, h, r, _, dead := metadataFixture(t) + rel := dead[0] + if kind == SegDir { + rel = dead[1] + } + reuse := func() { + raw := append([]byte(nil), o.objs[o.full(rel)].data...) + if err := EnsureObject(context.Background(), o, rel, raw, "successor"); err != nil { + t.Fatal(err) + } + } + if when == "plan" { + o.afterStat = func(got string) { + if got == rel { + o.afterStat = nil + reuse() + } + } + } else { + o.hook = func(op, got string) { + if op == when && got == rel { + o.hook = nil + reuse() + } + } + } + if _, err := NewCleaner(&memHead{h: h}, r, o, me, "c1").Page(context.Background(), kind, 0, []string{path.Base(rel)}); err != nil { + t.Fatal(err) + } + if !o.has(rel) || o.objs[o.full(rel)].meta.Session != "successor" { + t.Fatal("late removal erased a reused object") + } + }) + } + } +} + +func TestCleanerRecreatesRemovedRootBeforeRenamingIt(t *testing.T) { + ctx := context.Background() + o, h, r, rn, dead := metadataFixture(t) + cleaner := NewCleaner(&memHead{h: h}, r, o, me, "c1") + for _, rel := range dead { + if _, err := cleaner.Page(ctx, path.Dir(rel), 0, []string{path.Base(rel)}); err != nil { + t.Fatal(err) + } + } + if o.has(rn.Path()) { + t.Fatal("root was not removed") + } + next := manifest(ref("v1", 5, "e")) + root, segs, err := Build(next) + if err != nil { + t.Fatal(err) + } + if err := EnsureObject(ctx, o, next[5].Chunk.Path(), []byte("e"), "again"); err != nil { + t.Fatal(err) + } + got, err := PrepareRoot(ctx, o, root, segs, "again") + if err != nil || got != rn { + t.Fatalf("recreate: %v", err) + } + prev := manifest(ref("v1", 0, "a"), ref("v1", 3, "b")) + h.Activity = Activity{Kind: ActSnap, Session: "again"} + st := &memHead{h: h} + published, err := RunCommit(ctx, st, o, "v1", me, CommitRequest{Session: "again", Prev: prev, Next: next, Position: 1, State: StateLive}) + if err != nil { + t.Fatal(err) + } + if err := reachableMissing(&published, o.data()); err != nil { + t.Fatal(err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/clean_scale_test.go b/seaweed-block/core/frontend/chunkstore/layout/clean_scale_test.go new file mode 100644 index 0000000000..42aa88dfda --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/clean_scale_test.go @@ -0,0 +1,91 @@ +package layout + +import ( + "context" + "sync" + "sync/atomic" + "testing" + "time" +) + +func TestCleanerReachableOncePerShardAndRechecksHead(t *testing.T) { + ctx := context.Background() + o, h, _, _ := removeFixture(t) + reads := map[string]int{} + r, err := NewReader(removeBase, "v1", func(ctx context.Context, p string) ([]byte, bool, error) { reads[p]++; return o.fetch(ctx, p) }) + if err != nil { + t.Fatal(err) + } + cleaner := NewCleaner(&memHead{h: h}, r, o, me, "c1") + for _, idx := range []uint64{5, 7} { + n := NameChunk(idx, []byte(map[uint64]string{5: "e", 7: "f"}[idx])) + if _, err := cleaner.Page(ctx, PoolDir, 0, []string{n.String()}); err != nil { + t.Fatal(err) + } + } + for _, rn := range HeadRoots(*h) { + if n := reads[volRoot+"/"+rn.Path()]; n != 1 { + t.Fatalf("root read %d times across pages", n) + } + } + h.Epoch++ + if _, err := cleaner.Page(ctx, PoolDir, 0, nil); err == nil { + t.Fatal("cached reachability bypassed the new HEAD identity") + } +} + +func TestCleanerPlansTagsInBoundedParallelBeforeHead(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + o, h, r, _, _ := metadataFixture(t) + var entered atomic.Int32 + var once sync.Once + release := make(chan struct{}) + s := &scriptedObjects{memObjects: o, script: func(ctx context.Context, _ string) error { + if entered.Add(1) == 2 { + once.Do(func() { close(release) }) + } + select { + case <-release: + return nil + case <-ctx.Done(): + return ctx.Err() + } + }} + st := &memHead{h: h} + st.afterRead = func() { + if s.active.Load() != 0 { + t.Error("HEAD read before all tag reads returned") + } + } + names := make([]string, 100) + for i := range names { + names[i] = NameChunk(uint64(i), []byte("absent")).String() + } + if _, err := NewCleaner(st, r, s, me, "c1").Page(ctx, PoolDir, 0, names); err != nil { + t.Fatal(err) + } + if p := s.peak.Load(); p < 2 || p > 32 { + t.Fatalf("parallel tag reads=%d; want 2..32", p) + } +} + +func TestCleanerKeepsInitialRootsThroughOperatorDelete(t *testing.T) { + ctx := context.Background() + o, h, _, _ := removeFixture(t) + r, err := NewReader(removeBase, "v1", o.fetch) + if err != nil { + t.Fatal(err) + } + cleaner := NewCleaner(&memHead{h: h}, r, o, me, "c1") + // Metadata has already been visited using the initial snapshot set. + if _, err := cleaner.Page(ctx, RootDir, 0, nil); err != nil { + t.Fatal(err) + } + h.Snapshots = nil + old := NameChunk(2, []byte("c")) + out, err := cleaner.Page(ctx, PoolDir, 0, []string{old.String()}) + if err != nil || len(out.Names) != 0 || !o.has(old.Path()) { + t.Fatalf("operator delete let chunks disappear beneath an earlier retained root: %+v %v", out, err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go index 0f7cb4d4ff..50f1324957 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go @@ -216,8 +216,8 @@ func guardFindings(code map[string]map[string]bool, decl, tests map[string]bool) } if strings.HasPrefix(name, "Delete") || strings.HasPrefix(name, "Remove") { for _, fn := range owners(by) { - if fn != "RemoveUnreachable" && fn != "DeleteVolume" { - bad = append(bad, fn+" uses "+name+": only RemoveUnreachable (mark-gated) and DeleteVolume (after HEAD deleting and the dependents released) remove") + if fn != "Cleaner.removePlanned" && fn != "DeleteVolume" { + bad = append(bad, fn+" uses "+name+": only Cleaner.removePlanned (mark-gated) and DeleteVolume (after HEAD deleting and the dependents released) remove") } } } @@ -286,6 +286,12 @@ func removerOrderFindings(t *testing.T, srcs map[string]string) []string { }) return leaves } + writer := "RemoveUnreachable" + for _, src := range srcs { + if strings.Contains(src, "func (c *Cleaner) removePlanned(") { + writer = "removePlanned" + } + } var bad []string for fname, src := range srcs { file, err := parser.ParseFile(token.NewFileSet(), fname, src, 0) @@ -294,7 +300,7 @@ func removerOrderFindings(t *testing.T, srcs map[string]string) []string { } for _, d := range file.Decls { fn, ok := d.(*ast.FuncDecl) - if !ok || fn.Body == nil || fn.Name.Name != "RemoveUnreachable" { + if !ok || fn.Body == nil || fn.Name.Name != writer { continue } deletes := 0 @@ -445,7 +451,7 @@ func TestGuard_Controls(t *testing.T) { "untested transition": {src: `func RunZz(ctx context.Context, st HeadStore) (Head, error) { return runTransition(ctx, st, nil) }`, want: "has no TestZz_Closure"}, "lease wait outside claim": {src: `func w(ctx context.Context, l LeaseWait) error { return l.OldLeaseEnded(ctx, 1) }`, want: "only RunClaim claims"}, "remover outside RemoveUnreachable": {src: `type p interface{ DeleteObject(context.Context, string) error } -func w(ctx context.Context, x p) error { return x.DeleteObject(ctx, "o") }`, want: "only RemoveUnreachable (mark-gated) and DeleteVolume"}, +func w(ctx context.Context, x p) error { return x.DeleteObject(ctx, "o") }`, want: "only Cleaner.removePlanned (mark-gated) and DeleteVolume"}, "claim without lease wait": {src: `func RunClaim(ctx context.Context, st HeadStore, lease LeaseWait, me HolderID) (Head, error) { return runTransition(ctx, st, func(h Head) (Head, bool, error) { return h, false, nil }) }`, want: "does not wait for the old lease", file: "claim.go"}, @@ -500,7 +506,7 @@ func w(ctx context.Context, x g) error { return x.NoLiveLease(ctx) }`, want: "on "a fourth HEAD create": {src: `func w(ctx context.Context, st NewVolumeStore, h Head) { _ = st.CreateHead(ctx, h) }`, want: "only createVolume creates a HEAD"}, "tombstone outside the operator's release": {src: `func w(ctx context.Context, t TargetStore, h Head) { _ = t.CreateDeletedHead(ctx, h) }`, want: "only the operator's release writes a tombstone"}, "remover method value": {src: `type p interface{ RemoveName(string) } -func w(x p) { f := x.RemoveName; f("o") }`, want: "only RemoveUnreachable (mark-gated) and DeleteVolume"}, +func w(x p) { f := x.RemoveName; f("o") }`, want: "only Cleaner.removePlanned (mark-gated) and DeleteVolume"}, } { srcs := packageSources(t, false) file := c.file @@ -524,22 +530,21 @@ func removeVariant(t *testing.T, mode string) string { t.Fatal(err) } src := strings.ReplaceAll(string(b), "\r\n", "\n") - gate := "if err := os.Mark(ctx, c.Path(), tag, session); err != nil {" + gate := "if err := c.os.Mark(ctx, rel, tag.meta, c.session); err != nil {" if !strings.Contains(src, gate) { t.Fatal("remove.go mark gate not found") } switch mode { case "ignored": - i := strings.Index(src, gate) - j := strings.Index(src[i:], "\n\t\t}\n") + i + len("\n\t\t}\n") - src = src[:i] + "_ = os.Mark(ctx, c.Path(), plan, session)\n" + src[j:] + src = strings.Replace(src, gate, "if err := error(nil); err != nil {", 1) case "second": - src = strings.Replace(src, "removed = append(removed, c)", "_ = os.DeleteMarked(ctx, c.Path(), session)\n\t\tremoved = append(removed, c)", 1) + src = strings.Replace(src, "out.Names = append(out.Names, rel)", "_ = c.os.DeleteMarked(ctx, rel, c.session)\n out.Names = append(out.Names, rel)", 1) case "other": - src = strings.Replace(src, "removed = append(removed, c)", "_ = os.RemoveOther(ctx, c.Path())\n\t\tremoved = append(removed, c)", 1) + src = strings.Replace(src, "out.Names = append(out.Names, rel)", "_ = c.os.RemoveOther(ctx, rel)\n out.Names = append(out.Names, rel)", 1) case "unconditional": - src = strings.Replace(src, "if err := os.DeleteMarked(ctx, c.Path(), session); err != nil {", "if err := os.DeleteObject(ctx, c.Path()); err != nil {", 1) + src = strings.Replace(src, "if err := c.os.DeleteMarked(ctx, rel, c.session); err != nil {", "if err := c.os.DeleteObject(ctx, rel); err != nil {", 1) } + i := strings.Index(src, ")\n") return src[i+2:] } diff --git a/seaweed-block/core/frontend/chunkstore/layout/remove.go b/seaweed-block/core/frontend/chunkstore/layout/remove.go index 7636cf7706..7f22387baf 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/remove.go +++ b/seaweed-block/core/frontend/chunkstore/layout/remove.go @@ -5,100 +5,239 @@ import ( "errors" "fmt" "sort" + "sync" ) -// RemoveUnreachable is the cleaning's removal (transition 7') for one pool -// shard, for the holder with its own clean(session) open at HEAD's epoch, -// in an order that makes its plan atomic with its HEAD view -// (read-validate-write): -// 1. read the tag (writer session, mark) of every candidate; -// 2. only then read HEAD, require it is still this holder's with -// clean(session), and compute what any root in it (current or -// snapshot) names in this volume's pool; -// 3. MARK each candidate no root names, expected the tag from step 1; -// 4. DELETE it, expected that mark. -// -// If a successor acted before step 2, HEAD is no longer this holder's and -// nothing is written. If it acted after, every tag from step 1 predates -// its writes: a session that names a chunk no root named at its Begin -// writes that chunk's entry (create, or reuse with a new tag), so the MARK -// or the DELETE fails its condition, however late it lands. No lease -// reasoning is needed. A candidate an earlier session marked and did not -// delete (it died in between) is planned again: its tag carries that -// mark, so the MARK replaces it, and the earlier session's late DELETE, -// conditional on its own mark, fails. Every unreachable name is therefore -// removed by the next completed cleaning. Chunks a restore target names stay live: the source's snapshot -// root names them while it has dependents. It returns the names it -// deleted, in index order. -func RemoveUnreachable(ctx context.Context, st HeadStore, r *Reader, os ObjectStore, me HolderID, session string, shard uint64, candidates []ChunkName) ([]ChunkName, error) { - if os == nil || r == nil { - return nil, errors.New("layout: removal needs a reader and an object store") +// Cleaner is one clean(session)'s removal plan. Tags are read before each +// authoritative HEAD view; only immutable reachability is cached between pages. +// It is used serially, and never survives a cleaning session or process restart. +type Cleaner struct { + tagParallel int + st HeadStore + r *Reader + os ObjectStore + me HolderID + session string + roots []RootName + rootsRead bool + metadata map[string]bool + shard uint64 + chunks map[ChunkName]bool +} + +// NewCleaner starts a per-session remover; Page validates HEAD before every write. +func NewCleaner(st HeadStore, r *Reader, os ObjectStore, me HolderID, session string) *Cleaner { + return &Cleaner{st: st, r: r, os: os, me: me, session: session, tagParallel: 32} +} + +// RemovalResult advances through names examined (including live objects), not +// merely deleted names. A failed candidate is left for the next pass to retry. +type RemovalResult struct { + Names []string + After string +} + +// Page removes unreferenced metadata (RootDir or SegDir) or chunks (PoolDir, +// with shard). Every name is validated before any store effect. Metadata pages +// must be visited roots first, then segments, before chunk pages. +func (c *Cleaner) Page(ctx context.Context, kind string, shard uint64, names []string) (RemovalResult, error) { + rels := make([]string, 0, len(names)) + for _, name := range names { + var rel string + switch kind { + case RootDir: + n, err := ParseRootName(name) + if err != nil { + return RemovalResult{}, err + } + rel = n.Path() + case SegDir: + n, err := ParseSegName(name) + if err != nil { + return RemovalResult{}, err + } + rel = n.Path() + case PoolDir: + n, err := ParseChunkName(name) + if err != nil { + return RemovalResult{}, err + } + if Shard(n.Index) != shard { + return RemovalResult{}, ErrMalformed + } + rel = n.Path() + default: + return RemovalResult{}, ErrMalformed + } + rels = append(rels, rel) } - sorted := append([]ChunkName(nil), candidates...) - sort.Slice(sorted, func(a, b int) bool { return sorted[a].Index < sorted[b].Index }) - plan := map[ChunkName]ObjectMeta{} - for _, c := range sorted { - if Shard(c.Index) != shard { - continue - } - meta, found, err := os.Stat(ctx, c.Path()) - if err != nil { - return nil, err - } - if found { - plan[c] = meta + return c.removePlanned(ctx, rels, kind, shard) +} + +// removePlanned is the single mark/delete writer for all content-named objects: +// tags -> HEAD + holder/clean validation -> reachability -> conditional mark -> +// conditional delete. A reuse after planning or marking defeats the late write. +func (c *Cleaner) removePlanned(ctx context.Context, rels []string, kind string, shard uint64) (out RemovalResult, err error) { + if c.os == nil || c.r == nil { + return out, errors.New("layout: removal needs a reader and an object store") + } + type tag struct { + meta ObjectMeta + found bool + err error + } + tags := make([]tag, len(rels)) + // Bounded parallel tag reads finish before HEAD is read. Their original order + // determines the first error, independent of completion order. + var wg sync.WaitGroup + jobs := make(chan int) + for range min(c.tagParallel, len(rels)) { + wg.Add(1) + go func() { + defer wg.Done() + for i := range jobs { + tags[i].meta, tags[i].found, tags[i].err = c.os.Stat(ctx, rels[i]) + } + }() + } + for i := range rels { + jobs <- i + } + close(jobs) + wg.Wait() + for _, t := range tags { + if t.err != nil { + return out, t.err } } - h, found, err := st.ReadHead(ctx) + h, found, err := c.st.ReadHead(ctx) if err != nil { - return nil, err + return out, err } if !found { - return nil, ErrHeadAbsent + return out, ErrHeadAbsent } - if err := h.holderErr(me); err != nil { - return nil, err + if err := h.holderErr(c.me); err != nil { + return out, err } - if h.Activity != (Activity{Kind: ActClean, Session: session}) { - return nil, fmt.Errorf("%w: HEAD has %s(%s), not clean(%s)", ErrNoSession, h.Activity.Kind, h.Activity.Session, session) + if h.Activity != (Activity{Kind: ActClean, Session: c.session}) { + return out, fmt.Errorf("%w: HEAD has %s(%s), not clean(%s)", ErrNoSession, h.Activity.Kind, h.Activity.Session, c.session) } - live, err := reachable(ctx, r, h, shard) - if err != nil { - return nil, err + roots := HeadRoots(h) + if !c.rootsRead { + c.roots = roots + c.rootsRead = true + } else { + // Operators may un-name snapshots during a pass. Keep the initial superset + // until this session ends, so chunks are not deleted beneath a root that the + // earlier metadata phase retained. A new root requires a fresh pass/view. + for _, rn := range roots { + seen := false + for _, old := range c.roots { + if rn == old { + seen = true + break + } + } + if !seen { + return out, ErrPrecondition + } + } } - var removed []ChunkName - for _, c := range sorted { - tag, planned := plan[c] - if !planned || live[c] { + live := map[string]bool{} + if kind == PoolDir { + if c.chunks == nil || c.shard != shard { + c.chunks, err = reachable(ctx, c.r, c.roots, shard) + c.shard = shard + if err != nil { + return out, err + } + } + for n := range c.chunks { + live[n.Path()] = true + } + } else { + if c.metadata == nil { + c.metadata = map[string]bool{} + for _, rn := range c.roots { + img, e := c.r.Open(ctx, rn) + if e != nil { + c.metadata = nil + return out, e + } + c.metadata[rn.Path()] = true + for _, sn := range img.root.Segments { + c.metadata[sn.Path()] = true + } + } + } + live = c.metadata + } + for i, rel := range rels { + if err := ctx.Err(); err != nil { + return out, err + } + tag := tags[i] + if !tag.found || live[rel] { + out.After = rel continue } - if err := os.Mark(ctx, c.Path(), tag, session); err != nil { + if err := c.os.Mark(ctx, rel, tag.meta, c.session); err != nil { if errors.Is(err, ErrPrecondition) { - continue // written since the plan + out.After = rel + continue } - return removed, fmt.Errorf("layout: mark %s: %w", c, err) + return out, fmt.Errorf("layout: mark %s: %w", rel, err) } - if err := os.DeleteMarked(ctx, c.Path(), session); err != nil { + if err := c.os.DeleteMarked(ctx, rel, c.session); err != nil { if errors.Is(err, ErrPrecondition) { - continue // reused since the mark + out.After = rel + continue } - return removed, fmt.Errorf("layout: delete %s: %w", c, err) + return out, fmt.Errorf("layout: delete %s: %w", rel, err) } - removed = append(removed, c) + out.Names = append(out.Names, rel) + out.After = rel } - return removed, nil + return out, nil +} + +// RemoveUnreachable is the chunk-only compatibility boundary. A full pass uses +// one Cleaner across its pages so each shard's reachable set is resolved once. +func RemoveUnreachable(ctx context.Context, st HeadStore, r *Reader, os ObjectStore, me HolderID, session string, shard uint64, candidates []ChunkName) ([]ChunkName, error) { + sorted := append([]ChunkName(nil), candidates...) + sort.Slice(sorted, func(a, b int) bool { return sorted[a].Index < sorted[b].Index }) + var names []string + for _, n := range sorted { + if Shard(n.Index) == shard { + names = append(names, n.String()) + } + } + cleaner := NewCleaner(st, r, os, me, session) + cleaner.tagParallel = 1 // The chunk-only boundary preserves serial planning. + res, err := cleaner.Page(ctx, PoolDir, shard, names) + var removed []ChunkName + for _, rel := range res.Names { + for _, n := range sorted { + if n.Path() == rel { + removed = append(removed, n) + break + } + } + } + return removed, err } // reachable returns this volume's chunk names in shard that any root in h // names. A root or segment that cannot be read is an error: nothing is // removed on a partial view. -func reachable(ctx context.Context, r *Reader, h Head, shard uint64) (map[ChunkName]bool, error) { +func reachable(ctx context.Context, r *Reader, roots []RootName, shard uint64) (map[ChunkName]bool, error) { own, err := r.VolumeID(ctx, r.vol) if err != nil { return nil, err } live := map[ChunkName]bool{} - for _, rn := range HeadRoots(h) { + for _, rn := range roots { if err := r.EachRef(ctx, rn, shard, func(_ uint64, ref Ref) bool { if ref.OwnerID == own { live[ref.Chunk] = true diff --git a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go index 333c6c5ec1..0a4423998e 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go @@ -109,7 +109,14 @@ func TestHolderFunctions_RefuseAStaleHolder(t *testing.T) { t.Errorf("CheckCommitObjects by %s over a snap(s) HEAD held by %s passed", who, me.Holder) } } - covered := map[string]bool{"RemoveUnreachable": true, "Start": true, "startCheck": true, "DetachedBy": true, "CheckCommitObjects": true, "commitChecked": true} + // The constructor has no effect; every Page still checks the supplied holder. + for who, caller := range callers { + o, h, r, rn, _ := metadataFixture(t) + if _, err := NewCleaner(&memHead{h: h}, r, o, caller, "c1").Page(context.Background(), RootDir, 0, []string{rn.String()}); !errors.Is(err, ErrNotHolder) || len(o.writes) != 0 { + t.Errorf("Cleaner by %s: %v writes=%v", who, err, o.writes) + } + } + covered := map[string]bool{"NewCleaner": true, "RemoveUnreachable": true, "Start": true, "startCheck": true, "DetachedBy": true, "CheckCommitObjects": true, "commitChecked": true} var missing []string for fname, src := range packageSources(t, false) { file, err := parser.ParseFile(token.NewFileSet(), fname, src, 0) diff --git a/seaweed-block/core/frontend/chunkstore/layout_clean_e2e_test.go b/seaweed-block/core/frontend/chunkstore/layout_clean_e2e_test.go index f6f683c7c3..d1adf966b9 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_clean_e2e_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_clean_e2e_test.go @@ -77,7 +77,7 @@ func TestLayoutRemote_CleanAfterOverwriteAndSnapshotDelete(t *testing.T) { if _, err := lh.cat.DeleteSnapshot(ctx, lh.v, "s1"); err != nil { t.Fatal(err) } - if res := clean(); res.Removed != 1 { + if res := clean(); res.Removed != 3 || res.Roots != 1 || res.Segments != 1 { t.Fatalf("clean after deleting s1: %+v; want exactly the overwritten chunk", res) } if after := poolObjects(t, lh.cat, lh.v); after != before-1 { diff --git a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go index 5a9c324c6c..70ebd28735 100644 --- a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go +++ b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go @@ -192,8 +192,30 @@ func earlier(a, b time.Time) time.Time { // snapshotSlot guards one running loop's schedule: the loop records // outcomes, status readers read it. type snapshotSlot struct { - mu sync.Mutex - s *snapshotSchedule + mu sync.Mutex + s *snapshotSchedule + dueNow chan struct{} // coalesced explicit trigger; set before the loop starts +} + +// ScheduleSnapshotNow asks the existing daily/weekly loop for an attempt now. +// It neither creates a second snapshot writer nor changes the configured slots. +func (p *DurableProvider) ScheduleSnapshotNow(volumeID string) bool { + p.mu.Lock() + defer p.mu.Unlock() + h := p.volumes[volumeID] + if h == nil || h.snapshots == nil || h.snapshots.dueNow == nil || h.chunkStop == nil || h.chunkDone == nil { + return false + } + select { + case <-h.chunkDone: + return false + default: + } + select { + case h.snapshots.dueNow <- struct{}{}: + default: + } + return true } func (sl *snapshotSlot) status(now time.Time) ScheduledSnapshotStatus { @@ -236,6 +258,13 @@ func (p *DurableProvider) chunkSnapshotLoop(ctx context.Context, volumeID string case <-ctx.Done(): return case <-timer.C: + case <-slot.dueNow: + if !timer.Stop() { + select { + case <-timer.C: + default: + } + } } if ctx.Err() != nil || layer.Fenced() || !current() { return diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index cf08c68f0d..8f472ad354 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -432,7 +432,7 @@ func (p *DurableProvider) startChunkLoop(volumeID string, h *volHandle, layer st if !snapshotsOn { h.snapshots = nil } else if h.snapshots == nil { - h.snapshots = &snapshotSlot{s: newSnapshotSchedule(volumeID, p.cfg.ChunkSnapshotPeriod, time.Now())} + h.snapshots = &snapshotSlot{s: newSnapshotSchedule(volumeID, p.cfg.ChunkSnapshotPeriod, time.Now()), dueNow: make(chan struct{}, 1)} } if p.cfg.ChunkCaptureInterval <= 0 { h.cutWait = nil diff --git a/seaweed-block/core/frontend/durable/snapshot_due_now_test.go b/seaweed-block/core/frontend/durable/snapshot_due_now_test.go new file mode 100644 index 0000000000..1f5922a983 --- /dev/null +++ b/seaweed-block/core/frontend/durable/snapshot_due_now_test.go @@ -0,0 +1,55 @@ +package durable + +import ( + "context" + "github.com/seaweedfs/seaweed-block/core/storage" + "testing" + "testing/synctest" + "time" +) + +func TestScheduledSnapshotDueNowUsesExistingLoop(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + slot := &snapshotSlot{s: newSnapshotSchedule("v1", 24*time.Hour, time.Now()), dueNow: make(chan struct{}, 1)} + slot.s.next = time.Now().Add(24 * time.Hour) + calls := 0 + p := &DurableProvider{volumes: map[string]*volHandle{"v1": {snapshots: slot, chunkStop: cancel, chunkDone: done}}} + p.cfg.ChunkScheduledSnapshot = func(context.Context, string, time.Time, func(context.Context) (storage.ChunkHead, error)) error { + calls++ + return nil + } + go func() { + defer close(done) + p.chunkSnapshotLoop(ctx, "v1", &progressLoopLayer{}, func() bool { return true }, slot, nil) + }() + defer func() { cancel(); <-done }() + synctest.Wait() + if calls != 0 { + t.Fatal("schedule ran before due") + } + trigger, ok := any(p).(interface{ ScheduleSnapshotNow(string) bool }) + if !ok { + t.Fatal("scheduled due-now hook is not wired") + } + if !trigger.ScheduleSnapshotNow("v1") { + t.Fatal("running schedule refused trigger") + } + synctest.Wait() + if calls != 1 { + t.Fatalf("attempts=%d; want one existing scheduled callback", calls) + } + if !slot.due().After(time.Now()) { + t.Fatal("trigger changed the subsequent daily schedule") + } + if trigger.ScheduleSnapshotNow("missing") { + t.Fatal("trigger accepted unknown volume") + } + cancel() + <-done + if trigger.ScheduleSnapshotNow("v1") { + t.Fatal("trigger accepted an ended loop") + } + }) +} diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index ce965837b0..8309c0648f 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -239,6 +239,7 @@ func (s *StatusServer) chunkMux() http.Handler { mux.HandleFunc("/chunk/snapshot", s.handleChunkSnapshot) mux.HandleFunc("/chunk/snapshots", s.handleChunkSnapshots) mux.HandleFunc("/chunk/snapshot/delete", s.handleChunkSnapshotDelete) + mux.HandleFunc("/chunk/schedule/now", s.handleChunkScheduleNow) mux.HandleFunc("/chunk/detach", s.handleChunkDetach) // Any other /chunk path: a typed JSON 404, like every other /chunk // error, not net/http's plain-text page. @@ -553,6 +554,30 @@ func (s *StatusServer) handleChunkSnapshotDelete(w http.ResponseWriter, r *http. writeChunkJSON(w, http.StatusOK, chunkstore.SnapshotDeleteBody{VolumeID: req.VolumeID, Name: req.Name, State: state}) } +// This is an explicit trigger of the configured schedule, not a new snapshot +// writer. The normal scheduler retains admission, retry and retention behavior. +func (s *StatusServer) handleChunkScheduleNow(w http.ResponseWriter, r *http.Request) { + if !s.chunkAdmit(w, r, http.MethodPost) { + return + } + var req struct { + VolumeID string `json:"volumeID"` + } + if !decodeChunkBody(w, r, &req) { + return + } + ctl := s.chunkTarget(w, req.VolumeID) + if ctl == nil { + return + } + trigger, ok := ctl.(interface{ ScheduleSnapshotNow(string) bool }) + if !ok || !trigger.ScheduleSnapshotNow(req.VolumeID) { + writeChunkErr(w, http.StatusConflict, "schedule_not_running", false, "volume %q has no running snapshot schedule", req.VolumeID) + return + } + writeChunkJSON(w, http.StatusOK, map[string]string{"volumeID": req.VolumeID, "state": "queued"}) +} + func (s *StatusServer) handleChunkDetach(w http.ResponseWriter, r *http.Request) { if !s.chunkAdmit(w, r, http.MethodPost) { return @@ -735,6 +760,14 @@ func (c *chunkControl) DeleteSnapshot(ctx context.Context, volumeID, name string return "deleted", nil } +func (c *chunkControl) ScheduleSnapshotNow(volumeID string) bool { + if _, err := c.catalogVolume(volumeID); err != nil { + return false + } + trigger, ok := c.p.(interface{ ScheduleSnapshotNow(string) bool }) + return ok && trigger.ScheduleSnapshotNow(volumeID) +} + func (c *chunkControl) Usage(ctx context.Context, volumeID string) (chunkstore.Usage, error) { v, err := c.catalogVolume(volumeID) if err != nil { diff --git a/seaweed-block/core/host/volume/chunk_schedule_now_test.go b/seaweed-block/core/host/volume/chunk_schedule_now_test.go new file mode 100644 index 0000000000..be9ab6c6f3 --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_schedule_now_test.go @@ -0,0 +1,76 @@ +package volume + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +type scheduleNowControl struct { + fakeChunkControl + queued bool + calls int +} + +func TestChunkScheduleNowOptInAndProviderForwarding(t *testing.T) { + p := &scheduleNowProvider{} + ctl := NewChunkControl(p, &chunkstore.BCatalog{}, chunkstore.VolumeRef{Name: "v1", ID: layout.VolumeID{1}}) + trigger := ctl.(interface{ ScheduleSnapshotNow(string) bool }) + if !trigger.ScheduleSnapshotNow("v1") || trigger.ScheduleSnapshotNow("other") || p.calls != 1 { + t.Fatal("control did not forward only its own volume to the configured provider") + } + s := chunkServer(t, ctl, false) + if _, err := s.Start("127.0.0.1:0"); err != nil { + t.Fatal(err) + } + defer s.Close(context.Background()) + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/chunk/schedule/now", strings.NewReader(`{"volumeID":"v1"}`)) + req.RemoteAddr = "127.0.0.1:1000" + s.srv.Handler.ServeHTTP(w, req) + if w.Code != http.StatusNotFound || p.calls != 1 { + t.Fatalf("disabled endpoint: %d calls=%d", w.Code, p.calls) + } +} + +type scheduleNowProvider struct { + fakeChunkProvider + calls int +} + +func (p *scheduleNowProvider) ScheduleSnapshotNow(string) bool { p.calls++; return true } + +func (c *scheduleNowControl) ScheduleSnapshotNow(string) bool { c.calls++; return c.queued } + +func TestChunkScheduleNowRunsOnlyThroughEnabledLocalControl(t *testing.T) { + c := &scheduleNowControl{queued: true} + s := chunkServer(t, c, true) + w := serve(t, s, http.MethodPost, "/chunk/schedule/now", `{"volumeID":"v1"}`, "") + if w.Code != http.StatusOK || c.calls != 1 { + t.Fatalf("due-now: status=%d calls=%d body=%s", w.Code, c.calls, w.Body.String()) + } + for _, tc := range []struct { + method, body, remote string + code int + }{ + {http.MethodGet, `{"volumeID":"v1"}`, "", http.StatusMethodNotAllowed}, + {http.MethodPost, `{"volumeID":"other"}`, "", http.StatusNotFound}, + {http.MethodPost, `{"volumeID":"v1"}`, "192.0.2.1:1000", http.StatusForbidden}, + } { + if got := serve(t, s, tc.method, "/chunk/schedule/now", tc.body, tc.remote); got.Code != tc.code { + t.Fatalf("refusal status=%d want=%d", got.Code, tc.code) + } + } + if c.calls != 1 { + t.Fatal("refused transport reached schedule") + } + c.queued = false + if got := serve(t, s, http.MethodPost, "/chunk/schedule/now", `{"volumeID":"v1"}`, ""); got.Code != http.StatusConflict { + t.Fatalf("disabled schedule status=%d", got.Code) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 78dbb6617d..026355c163 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -418,7 +418,7 @@ B stores snapshots, restore dependencies and the active session in HEAD. The tra | Abort or settle | Keep reusable uploads in their session; retain an unresolved proposal for settlement. Dropped work aborts the open session; a landed commit has already ended it. | `core/storage/chunk_layer.go` `discardStaged`, `captureLocked`, `Close`; `core/frontend/chunkstore/layout_remote.go` `AbortOpenSession` | `INV-CUT-INTENT-CLOSE-001`, `INV-WS-CAS-UNKNOWN-001` | | Restore | Record the target as a source dependent before creating its root and unclaimed HEAD; owner-qualified references resolve in the source pool. | `core/frontend/chunkstore/catalog_b.go` `BCatalog.Restore`; `core/frontend/chunkstore/layout/create.go` | `INV-SNAPK-COMMIT-REACH-001` | | Remove snapshot | Remove the name through a conditional HEAD transition; its objects remain governed by the roots and dependents still recorded. | `core/frontend/chunkstore/catalog_b.go` `DeleteSnapshot`; `core/frontend/chunkstore/layout/snapshots.go` | `INV-SNAPK-HEAD-WRITE-001` | -| Clean | Cleaning excludes an open snapshot session. Read and validate HEAD reachability before marking an unreachable pool entry; delete only under the matching mark. | `core/frontend/chunkstore/layout/clean.go`; `core/frontend/chunkstore/layout/remove.go` `RemoveUnreachable` | `INV-SNAPK-CLEAN-EXCL-001`, `INV-SNAPK-REMOVE-MARK-001`, `INV-SNAPK-REMOVE-STOP-001` | +| Clean | Cleaning excludes an open snapshot session. Read tags, validate HEAD, then conditionally mark/delete unreferenced roots, segments and chunks in that order. | `core/frontend/chunkstore/layout/clean.go`; `core/frontend/chunkstore/layout/remove.go` `Cleaner.removePlanned` | `INV-SNAPK-CLEAN-EXCL-001`, `INV-SNAPK-REMOVE-MARK-001`, `INV-SNAPK-REMOVE-STOP-001` | | Background cut/clean ordering | New staging retries promptly; zero progress backs off. Dirty-start cleaning waits for a completed store attempt or one interval. After K=3 admitted stalls, guarded discard releases the session and kicks cleaning; request progress resets the streak. | `core/frontend/durable/provider_chunk.go`; `core/storage/chunk_periodic_cut.go` | `INV-CUT-RETRY-FAIRNESS-001` | | Delete volume | Reserve deletion, check no live lease inside the deleting transition, release the reservation, remove objects and mark deleted. | `core/frontend/chunkstore/catalog_b.go` `DeleteVolume`; `core/frontend/chunkstore/layout/delete.go` | `INV-WS-DELETE-NO-LIVE-HOLDER-001` | @@ -527,7 +527,7 @@ stateDiagram-v2 clean --> idle: Claim(e, claim id), c void idle --> clean: BeginClean(c) clean --> idle: EndClean(c) - clean --> clean: RemoveUnreachable(shard) + clean --> clean: roots, segments, chunk shards (conditional removal) idle --> deleting: MarkDeleting (no holder, no dependents) deleting --> deleted: MarkDeleted (after release and pool) ``` @@ -543,7 +543,9 @@ stateDiagram-v2 | any (Start) | idle at epoch e, claim id k | Start only: at HEAD's epoch it continues on the root carrying HEAD's claim id at or above HEAD's position, else refuses; above, a fresh root or the continuing lineage claims, validated against the HEAD the claim updates | start.go `Start`; claim.go `RunClaim` | `INV-SNAPK-START-ROOT-001`, `INV-SNAPK-START-LINEAGE-001`, `INV-SNAPK-START-POSITION-001`, `INV-SNAPK-START-ACTIVITY-001` | | idle | clean(c) | holder at HEAD's epoch (epoch, server and claim id); activity idle (clean(c) again is a replay) | clean.go `Head.BeginClean` | `INV-SNAPK-CLEAN-EXCL-001` | | clean(c) | idle | holder at HEAD's epoch (epoch, server and claim id); activity clean(c); over idle it succeeds without a write | clean.go `Head.EndClean` | `INV-SNAPK-CLEAN-EXCL-001` | -| clean(c) | clean(c), names removed | holder at HEAD's epoch (epoch, server and claim id) with clean(c) open (HEAD read once, after BeginClean); a name is deleted only if no root in HEAD (current or snapshot) names it in this volume's pool; each removal is a mark conditional on the plan's metadata, then a delete conditional on that mark | remove.go `RemoveUnreachable` | `INV-SNAPK-REMOVE-MARK-001` | +| clean(c) | clean(c), names removed | holder at HEAD's epoch (epoch, server and claim id) with clean(c) open (HEAD read once, after BeginClean); a name is deleted only if no root in HEAD (current or snapshot) names it in this volume's pool; each removal is a mark conditional on the plan's metadata, then a delete conditional on that mark | remove.go `RemoveUnreachable` | `INV-CLEAN-METADATA-001` | Cleaning preserves Current and snapshot roots and their segments. Dependents keep their snapshot in HEAD. Unnamed roots go before segments and chunks; reuse defeats conditional removal. | M9 clean | `core/frontend/chunkstore/layout/remove.go`; `core/frontend/chunkstore/clean_b.go` | `TestCleanerMetadataRetainsCurrentSnapshotAndDependent`, `TestCleanerMetadataReuseDefeatsLateMarkAndDelete`, `TestCleanerRecreatesRemovedRootBeforeRenamingIt` (`core/frontend/chunkstore/layout/clean_metadata_test.go`); `TestCleaningInterruptsAfterMetadataBeforeChunks` (`core/frontend/chunkstore/clean_cursor_test.go`) | CommitReach2 CPlan, CView, LandMark, LandDel | ACTIVE | +| `INV-CLEAN-CURSOR-001` | A bounded pass resumes at its phase, shard and last completed name, wraps after the final shard, and revalidates HEAD after each parallel tag plan. Reachability uses a conservative initial root set only within one session. | M9 clean (liveness) | `core/frontend/chunkstore/clean_b.go`; `core/frontend/chunkstore/layout/remove.go` | `TestCleaningCursorResumesAfterTimeoutAndWraps` (`core/frontend/chunkstore/clean_cursor_test.go`); `TestCleanerReachableOncePerShardAndRechecksHead`, `TestCleanerPlansTagsInBoundedParallelBeforeHead` (`core/frontend/chunkstore/layout/clean_scale_test.go`) | CommitReach2 CView | ACTIVE | +| `INV-SNAPK-REMOVE-MARK-001` | | idle (live or detached) | deleting | the master reserved the volume for delete (no line granted after), then no line holds a live lease, checked between the HEAD read and the update; no open activity, no snapshot with dependents; deleting again is a replay | delete.go `Head.MarkDeleting`, `RunMarkDeleting` (`DeleteAuthority`) | `INV-SNAPK-DELETE-ORDER-001` | | absent | deleted (tombstone) | the operator's remove-dependent, for a restore target without HEAD (never created, or a restore died between its two creates); one exclusive create, so a later HEAD create of the restore fails; a HEAD appearing first refuses | delete.go `OperatorReleaseDependent` (`TargetStore.CreateDeletedHead`) | `INV-SNAPK-TOMBSTONE-001`, `INV-SNAPK-HEAD-WRITE-001` | | source: any live | source: target released | by the target's volume id, from every snapshot: from DeleteVolume once the target's HEAD is deleting, or from the operator's command once the target is deleted, of another id, no longer naming the source, or tombstoned; an absent target writes nothing | delete.go `Head.ReleaseDependent`, `RunReleaseDependent`, `OperatorReleaseDependent` | `INV-SNAPK-RELEASE-001`, `INV-SNAPK-RELEASE-CALLERS-001`, `INV-SNAPK-RELEASE-OPERATOR-001` | @@ -1076,7 +1078,7 @@ Notes: |---|---|---|---|---|---|---| | `INV-SNAPK-NAME-CANONICAL-001` | A chunk is named by its index and the SHA-256 of its bytes under `pool//`; a segment and a root are named by the SHA-256 of their canonical encoding, and decoding refuses any bytes the encoder would not write, so an object has one encoding and one name. | Content-named layout (no state transition) | `core/frontend/chunkstore/layout` `layout.go` `ParseChunkName`, `DecodeSegment`, `DecodeRoot` | `TestParseChunkName_RoundTripAndRefusals`, `TestDecodeSegment_RefusesNonCanonical`, `TestRoot_Refusals`, `TestBuild_ShardsAndIncrementalReuse` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-HEAD-WRITE-001` | HEAD changes only by one conditional update on its generation through `runTransition`; no path in the package creates a HEAD, and an absent HEAD is refused. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `runTransition`; `HeadStore` (read and conditional update only) | `TestGuard_WritersTransitionsAndRemovers`, `TestRunBegin` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-HEAD-GUARD-001` | A source scan refuses any other use of `UpdateHead`, a transition without its closure and interrupt tests, and any store remover other than the mark-gated RemoveUnreachable and the ordered DeleteVolume. | M9 every transition | `core/frontend/chunkstore/layout` (source scan of the package) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-HEAD-GUARD-001` | A source scan refuses any other use of `UpdateHead`, a transition without its closure and interrupt tests, and any store remover other than the mark-gated Cleaner.removePlanned and the ordered DeleteVolume. | M9 every transition | `core/frontend/chunkstore/layout` (source scan of the package) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-HEAD-CODEC-001` | HEAD is canonical JSON with at most 100 snapshots and sorted unique dependents; unknown fields, non-canonical bytes and names that are not valid UTF-8 are refused at encode and decode, and the next HEAD is checked before it is written. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `Head.check`, `Head.Encode`, `DecodeHead` | `TestHead_GoldenEncodingRoundTrip`, `TestHead_Refusals`, `TestHead_RefusesInvalidUTF8` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-BEGIN-001` | Begin opens snap(s) only for the holder at HEAD's epoch and only from idle; a re-run of the open session writes nothing; killed at its write and re-run, it ends in snap(s) at one generation step. | M9 idle → snap | `core/frontend/chunkstore/layout` `head.go` `Head.Begin`, `RunBegin` | `TestBegin_Closure`, `TestRunBegin_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-ABORT-001` | Abort closes the holder's own snap(s) and changes nothing else; after its own crash a holder rolls the open session back before beginning another; over idle Abort writes nothing and its success never says whether the work was committed. | M9 snap → idle (Abort) | `core/frontend/chunkstore/layout` `head.go` `Head.Abort`, `RunAbort`; `core/frontend/durable/provider_layout.go` `settleLayoutStop` | `TestLayoutStopAbortMustConfirmItsOutcome`, `TestLayoutRemote_AbortOpenSessionDoesNotWaitForAHeldCommit`, `TestLayoutRemote_AbortOpenSessionFencesAForeignHead`, `TestLayoutRemoteSessionFieldSites`, `TestAbort_Closure`, `TestAbort_IdleMeansNoActivityRemains`, `TestAbort_RollBackAfterOwnCrash`, `TestRunAbort_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | @@ -1088,10 +1090,10 @@ Notes: | `INV-SNAPK-CLEAN-EXCL-001` | A cleaning and a snapshot exclude each other through HEAD's one activity field, so no name is removed while a snapshot is open; a claim voids an open cleaning. | M9 idle → clean → idle | `core/frontend/chunkstore/layout` `clean.go` `Head.BeginClean`, `Head.EndClean` | `TestBeginClean_Closure`, `TestEndClean_Closure`, `TestEndClean_IdleMeansNoActivityRemains`, `TestClean_ExcludesSnapshot`, `TestRunBeginClean_InterruptAtEveryStep`, `TestRunEndClean_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-CLEAN-HOLDER-PASS-001` | The holder's periodic cleaning runs as the identity Start established: Begin refuses any other holder, claim or epoch; a pass with no identity, or whose retention failed, removes nothing; every opened cleaning is closed, also on error. | M9 idle → clean → idle (holder pass) | `core/frontend/chunkstore/clean_b.go` `BCatalog.Clean`; `cmd/blockvolume/chunk_maintenance.go` `newChunkMaintenance` | `TestBCatalog_CleanIsHolderOnly`, `TestBCatalog_CleanClosesOnError`, `TestBCatalog_CleanRemovesOnlyUnreachable`, `TestBCatalog_CleanWaitsForAnOpenSnapshot`, `TestBCatalog_CleanAfterOverwriteAndSnapshotDelete` (`core/frontend/chunkstore/clean_b_test.go`); `TestMaintenanceCleansOnlyAsTheHolder`, `TestMaintenanceRetentionFailureNeverStartsCleaning` (`cmd/blockvolume/chunk_maintenance_test.go`) | — | ACTIVE | | `INV-SNAPK-READ-MISSING-001` | A read resolves root, segment, chunk; an index the root does not name is zeros; a root, segment or chunk the root reaches but the store lacks is ErrMissing, never zeros; bytes that do not hash to their name are ErrCorrupt; a foreign chunk is read from its owner's pool. | Content-named layout (read path, no state transition) | `core/frontend/chunkstore/layout` `read.go` `Reader.Open`, `Image.Segment`, `Image.Chunk` | `TestRead_AbsentIndexIsZeros`, `TestRead_ForeignChunkFromSourcePool`, `TestRead_MissingObjectIsAnErrorNeverZeros`, `TestRead_FetchFailureAndCorruption`, `TestRead_SegmentOfAnotherShardRefused` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-REMOVE-MARK-001` | A pool name is removed only inside the holder's own cleaning, when no root in HEAD names it: tags read first, HEAD read and validated after, then a mark conditional on the tag and a delete conditional on the mark. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_RemovesOnlyWhatNoRootNames`, `TestCleaningPass_InterruptAtEveryStep`, `TestHolderFunctions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-REMOVE-STOP-001` | A reuse of an object after the plan, or after the mark, makes the remover's mark or delete fail its condition, however late it lands; an unreadable root stops the pass before any write; an open snapshot refuses it. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_ASuccessorAfterTheHeadViewDefeatsTheMark`, `TestRemoveUnreachable_ASuccessorBeforeTheHeadViewStopsThePass`, `TestRemoveUnreachable_AReuseAfterThePlanDefeatsTheMark`, `TestRemoveUnreachable_AReuseDefeatsALateMarkOrDelete`, `TestRemoveUnreachable_NothingRemovedOnAPartialView`, `TestRemoveUnreachable_RefusedOutsideItsCleaning` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-REMOVE-CONVERGE-001` | A name a cleaning marked and did not delete (the remover died in between) is planned again by the next cleaning: the re-mark replaces the old mark, so the dead remover's late delete fails, and every unreachable name goes once a cleaning completes. | M9 clean → clean | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_ReclaimsAnAbandonedMark`, `TestCleaningPass_InterruptAtEveryStep`, `TestLayoutStoreCleaningReclaimsAnAbandonedMark` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-REMOVE-GUARD-001` | A source scan requires DeleteMarked as RemoveUnreachable's only removal, each immediately after an if on its Mark's error that leaves: an unconditional delete, an ignored mark, a reused mark or another method fails. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` (source scan of `remove.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-REMOVE-MARK-001` | A content-named object is removed only inside the holder's own cleaning, when no root in HEAD names it: tags read first, HEAD read and validated after, then a mark conditional on the tag and a delete conditional on the mark. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_RemovesOnlyWhatNoRootNames`, `TestCleaningPass_InterruptAtEveryStep`, `TestHolderFunctions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-REMOVE-STOP-001` | A reuse of an object after the plan, or after the mark, makes the remover's mark or delete fail its condition, however late it lands; an unreadable root stops the pass before any write; an open snapshot refuses it. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_ASuccessorAfterTheHeadViewDefeatsTheMark`, `TestRemoveUnreachable_ASuccessorBeforeTheHeadViewStopsThePass`, `TestRemoveUnreachable_AReuseAfterThePlanDefeatsTheMark`, `TestRemoveUnreachable_AReuseDefeatsALateMarkOrDelete`, `TestRemoveUnreachable_NothingRemovedOnAPartialView`, `TestRemoveUnreachable_RefusedOutsideItsCleaning` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-REMOVE-CONVERGE-001` | A name a cleaning marked and did not delete (the remover died in between) is planned again by the next cleaning: the re-mark replaces the old mark, so the dead remover's late delete fails, and every unreachable name goes once a cleaning completes. | M9 clean → clean | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_ReclaimsAnAbandonedMark`, `TestCleaningPass_InterruptAtEveryStep`, `TestLayoutStoreCleaningReclaimsAnAbandonedMark` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-REMOVE-GUARD-001` | A source scan requires DeleteMarked as Cleaner.removePlanned's only removal, each immediately after an if on its Mark's error that leaves: an unconditional delete, an ignored mark, a reused mark or another method fails. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` (source scan of `remove.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-REUSE-001` | Writing an object for a session creates it, or reuses an existing one by a conditional update that sets the session and clears any mark; a commit names only objects its session wrote or reused, unmarked. | M9 snap → idle (Upload, Commit) | `core/frontend/chunkstore/layout` `objects.go` `EnsureObject`; `commit.go` `RunCommit` | `TestEnsureObject`, `TestRunCommit_NeedsObjectsOfItsOwnSession`, `TestSnapshotSession_InterruptAtEveryStep`, `TestLayoutStoreCreateExistsReclaimsOnlyItsUnusedUpload`, `TestLayoutStoreCreateUnknownOutcomeKeepsItsUpload` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-START-LAYOUT-ID-001` | The launcher's full layout id must match VOLUME and HEAD, even when id8 collides; mismatch is ErrIdentity and startup exits 78 without claiming or serving. The flag comes from the master's volume record. | M9 Start refusal | `core/frontend/chunkstore/layout_create.go` `ReadVolumeRecord`; `core/frontend/chunkstore/layout_store.go` `ReadHead`; `core/frontend/durable/provider_startup.go`; `cmd/blockvolume/process_exit.go`; `core/lifecycle/workload_plan.go` | `TestLayoutIDMismatchIsTypedAndExits78`; `TestLauncherCarriesTheMasterLayoutIdentity`; `TestG15d_WorkloadPlan_BlankPoolRF2CreatesReplicaWorkloads` | K1; full identity, not the directory suffix | ACTIVE | | `INV-SNAPK-IDENTITY-001` | A volume is identified by the random id in its VOLUME record, never by its name alone; HEAD carries the volume id and refuses to encode without it. | Content-named layout; M9 every transition | `core/frontend/chunkstore/layout` `volume.go` `Volume`, `VolumeID`; `head.go` `Head.check` | `TestVolumeID_RandomAndParsed`, `TestVolume_GoldenEncodingRoundTrip`, `TestHead_GoldenEncodingRoundTrip`, `TestHead_Refusals` | — (the snapshot kernel model is not in this repository) | ACTIVE | diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index cc2e4aa063..23c16af3ae 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -792,6 +792,42 @@ A restore makes a new volume from a snapshot. The new volume reads every chunk i - **`ops chunk release` is a repair step, not part of this procedure.** `sw-block ops chunk release --master MASTER --source v1 --target v2 --chunk-filer FILER` removes a restore target from its source snapshot's dependents. It works only when the target no longer names the source's chunks (it was deleted), or when the target never got its first HEAD (an interrupted restore). In the second case it first tombstones the target's name, so that name can never be created. A live target is refused with `target_live`. + ### Comparing master and holder revisions `ClusterEvidenceService.GetClusterStatus.product_revision` and the holder's local `GET /status?volume=` field `Version` both report component-independent buildinfo provenance as ` modified=`. The modified flag is appended so clean and modified source trees do not compare equal. Compare these values to check for different source revisions; the holder field is read on its host through the existing loopback status endpoint. Neither value is carried in `HeartbeatReport`. An absent value or `unknown` revision/modified field means provenance is unavailable: even matching unknown values do not establish equal builds. Matching provenance does not prove byte-identical binaries, and two dirty trees can differ despite matching revision/modified fields; the daemon's `--version` reports these same fields with its component name. These fields are diagnostic and do not affect readiness, leases or admissions. + +### Resuming cleaning passes + +A holder's cleaning removes unreferenced roots first, then segments, then chunk +objects. Current and every snapshot root remain reachable; a restore dependent +prevents its source snapshot from being deleted, including by retention. +Each object is marked conditionally on its planned tag and deleted conditionally +on that mark. An object reused by a successor defeats those late writes. + +The bounded pass retains an in-process phase, shard and name cursor. Its next +pass resumes there after a timeout and wraps to the beginning after the last +shard. Restarting the process resets the cursor. Every new pass re-reads tags and +HEAD; the cursor carries no authority. Tag reads run with bounded concurrency, +and a shard's reachable set is resolved once against that session's initial +root set. Snapshot deletes keep that conservative superset until the session +ends; an unexpected newly named root stops the pass for a fresh plan. Planned/removed counts include metadata; +root and segment removals are also counted separately. + +### Request a scheduled snapshot now + +With `--chunk-control-endpoint`, a volume whose daily/weekly schedule is enabled +accepts a local request to make an attempt now: + +```sh +curl --fail -H 'Content-Type: application/json' \ + -d '{"volumeID":"v1"}' http://127.0.0.1:9181/chunk/schedule/now +``` + +The reply is `{"volumeID":"v1","state":"queued"}`; it confirms scheduling, not +snapshot completion. Check scheduled-snapshot status for its result. This runs +the existing scheduler's capture, admission, retry and retention steps. It does +not enable an off schedule or change the subsequent daily/weekly slots. An off +or stopped schedule returns `schedule_not_running`. The route shares the other +chunk control routes' opt-in and loopback-only restrictions. + From 35b6ec74716ad7e30fecf3636d3df4876353873c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 28 Nov 2026 07:30:35 -0800 Subject: [PATCH 09/13] test: classify shared remover HEAD reads and absent metadata --- .../core/frontend/chunkstore/head_readers_test.go | 10 +++++++++- .../core/frontend/chunkstore/layout/guard_test.go | 12 ++++++------ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index 42f20c1487..8df4870c86 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -38,7 +38,7 @@ var headReaders = map[string]string{ "core/host/volume/chunk_control.go ListSnapshots -> ReadHead": "refuses ErrHeadAbsent without creating HEAD (TestChunkControlUsesTheBoundLayoutIdentity)", "core/frontend/chunkstore/layout/delete.go OperatorReleaseDependent -> ReadHead": "reads the source's HEAD (absent: refuses ErrHeadAbsent) and the target's: a target without HEAD (never created, or a restore that died between its VOLUME and its HEAD) gets a deleted HEAD written exclusively before the release (probe LayoutOperatorRelease)", "core/frontend/chunkstore/layout/start.go Start -> ReadHead": "refuses ErrHeadAbsent and creates nothing (probe LayoutStart)", - "core/frontend/chunkstore/layout/remove.go RemoveUnreachable -> ReadHead": "refuses ErrHeadAbsent and writes nothing to the objects (probe LayoutRemoval)", + "core/frontend/chunkstore/layout/remove.go removePlanned -> ReadHead": "refuses ErrHeadAbsent and writes nothing to chunks, roots or segments (probe LayoutRemoval)", "core/frontend/chunkstore/layout/snapshots.go RunAddDependent -> ReadHead": "refuses ErrHeadAbsent before reading any root and writes nothing (probe LayoutAddDependent)", "core/frontend/chunkstore/catalog_b.go DeleteVolume -> ReadHead": "refuses ErrHeadAbsent before any write (probe BCatalog)", "core/frontend/chunkstore/catalog_b.go ReadHead -> ReadHead": "found=false to the caller, which reports no HEAD (probe BCatalog)", @@ -237,6 +237,14 @@ func TestHeadReaders_AbsentHeadProbes(t *testing.T) { if _, err := layout.RemoveUnreachable(ctx, &absentLayoutHead{}, r, pool, layout.HolderID{Epoch: 1, Holder: "h"}, "c", 0, []layout.ChunkName{layout.NameChunk(1, []byte("x"))}); !errors.Is(err, layout.ErrHeadAbsent) { t.Fatalf("layout removal over an absent HEAD: %v; want ErrHeadAbsent", err) } + for kind, name := range map[string]string{ + layout.RootDir: (layout.RootName{Hash: layout.Sum([]byte("root"))}).String(), + layout.SegDir: (layout.SegName{Hash: layout.Sum([]byte("segment"))}).String(), + } { + if _, err := layout.NewCleaner(&absentLayoutHead{}, r, pool, layout.HolderID{Epoch: 1, Holder: "h"}, "c").Page(ctx, kind, 0, []string{name}); !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatalf("%s removal over absent HEAD: %v", kind, err) + } + } if pool.writes != 0 { t.Fatalf("layout removal over an absent HEAD wrote %d times to the objects", pool.writes) } diff --git a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go index 50f1324957..0beb4f1438 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/guard_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/guard_test.go @@ -128,8 +128,8 @@ func owners(m map[string]bool) []string { // - Release of a dependent: RunReleaseDependent is used only by // DeleteVolume (its own HEAD is deleting) and OperatorReleaseDependent, // which reads the target's HEAD before it releases. -// - Pool: a name starting with Delete or Remove is used only in -// RemoveUnreachable, whose only removal is DeleteMarked, each right +// - Objects: a name starting with Delete or Remove is used only in +// Cleaner.removePlanned, whose only removal is DeleteMarked, each right // after a gate on its Mark's error, and in DeleteVolume, whose steps run // in the delete's order: no holder, HEAD deleting, the dependents // released, the objects deleted (conditional on the volume id), HEAD @@ -227,7 +227,7 @@ func guardFindings(code map[string]map[string]bool, decl, tests map[string]bool) } // removerOrderFindings checks the removal rule (7') in the sources: in -// RemoveUnreachable the only removal call is DeleteMarked (a delete +// Cleaner.removePlanned the only removal call is DeleteMarked (a delete // conditional on the remover's own mark), and each is IMMEDIATELY // preceded, in the same block, by a mark gate: an if statement whose init // calls Mark and whose body leaves on its error (return or continue). An @@ -321,17 +321,17 @@ func removerOrderFindings(t *testing.T, srcs map[string]string) []string { deletes++ for _, name := range names { if name != "DeleteMarked" { - bad = append(bad, "RemoveUnreachable calls "+name+": its only removal is DeleteMarked, conditional on its own mark") + bad = append(bad, "Cleaner.removePlanned calls "+name+": its only removal is DeleteMarked, conditional on its own mark") } } if i == 0 || !markGate(blk.List[i-1]) { - bad = append(bad, "RemoveUnreachable removes without a mark gate immediately before it (an if on Mark's error that leaves)") + bad = append(bad, "Cleaner.removePlanned removes without a mark gate immediately before it (an if on Mark's error that leaves)") } } return true }) if deletes == 0 { - bad = append(bad, "RemoveUnreachable is declared and has no delete: the scan is broken") + bad = append(bad, "Cleaner.removePlanned is declared and has no delete: the scan is broken") } } } From be2ad6c65b816df85ec8081415f6bbc2e6db5e9a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 28 Nov 2026 07:39:15 -0800 Subject: [PATCH 10/13] observe snapshot removal in holder maintenance --- .../frontend/chunkstore/head_readers_test.go | 1 + .../durable/maintenance_lineage_test.go | 3 +- .../durable/maintenance_probe_test.go | 139 ++++++++++++++++++ .../core/frontend/durable/provider_chunk.go | 86 +++++++++++ seaweed-block/docs/design/invariants.md | 6 +- seaweed-block/docs/standalone-deployment.md | 7 + 6 files changed, 238 insertions(+), 4 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/maintenance_probe_test.go diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index 8df4870c86..0f2e071676 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -24,6 +24,7 @@ import ( // pins it. "GAP" marks a reader that takes an absent HEAD for an empty // one; a change that treats an absent HEAD as unknown flips those probes. var headReaders = map[string]string{ + "core/frontend/durable/provider_chunk.go maintenanceSnapshots -> ReadHead": "absent or failed reads do not infer snapshot deletion or ask for cleaning (TestMaintenanceNoticesSnapshotDeleteWithoutNotification)", "core/frontend/durable/provider_seal_replay.go readLayoutSeal -> ReadHead": "absent, unreadable and foreign layout proof refuse without cached success (TestLayoutPlainDetachReplayAfterRestartNeedsNoLegacyFactory)", "core/frontend/durable/provider_layout.go settleLayoutStop -> ReadHead": "absent refuses unknown stop outcome, never resumes (probe TestLayoutStopAbortMustConfirmItsOutcome)", "core/frontend/durable/provider_layout.go startLayoutRoot -> ReadHead": "the diagnostic re-read after Start refusal cannot turn an absent HEAD into a claim; Start already refused it (probe TestLayoutStoreMissingHEADRefusesStart)", diff --git a/seaweed-block/core/frontend/durable/maintenance_lineage_test.go b/seaweed-block/core/frontend/durable/maintenance_lineage_test.go index ca73eb8122..d407495d57 100644 --- a/seaweed-block/core/frontend/durable/maintenance_lineage_test.go +++ b/seaweed-block/core/frontend/durable/maintenance_lineage_test.go @@ -13,7 +13,8 @@ import ( type maintenanceStubLayer struct{ storage.ChunkLayer } -func (maintenanceStubLayer) Fenced() bool { return false } +func (maintenanceStubLayer) Fenced() bool { return false } +func (maintenanceStubLayer) Stats() storage.ChunkLayerStats { return storage.ChunkLayerStats{} } func TestMaintenanceRejectsForeignLineageBeforeAdmission(t *testing.T) { for _, field := range []string{"epoch", "replica", "endpoint", "handle", "layer"} { t.Run(field, func(t *testing.T) { diff --git a/seaweed-block/core/frontend/durable/maintenance_probe_test.go b/seaweed-block/core/frontend/durable/maintenance_probe_test.go new file mode 100644 index 0000000000..b687184b60 --- /dev/null +++ b/seaweed-block/core/frontend/durable/maintenance_probe_test.go @@ -0,0 +1,139 @@ +package durable + +import ( + "context" + "errors" + "testing" + "testing/synctest" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +type maintenanceProbeStore struct { + layout.StartStore + head layout.Head + found bool + err error + reads int +} + +func TestMaintenanceSnapshotProbeKeepsBusyRetryAndDirtyStartGate(t *testing.T) { + for _, dirty := range []bool{false, true} { + t.Run(map[bool]string{false: "busy", true: "dirty-start"}[dirty], func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + st := &maintenanceProbeStore{found: true, head: layout.Head{Snapshots: map[string]layout.Snapshot{"a": {}}}} + layer := &firstAttemptLayer{} + passes := 0 + p := &DurableProvider{cfg: ProviderConfig{ + ChunkMaintenanceInterval: time.Hour, + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return st, nil }, + ChunkMaintenance: func(context.Context, string) error { + passes++ + if passes == 1 { + return layout.ErrBusy + } + return nil + }, + }} + var start *maintenanceStart + if dirty { + start = &maintenanceStart{deadline: time.Now().Add(time.Hour)} + } + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + p.chunkMaintenanceLoop(ctx, "v1", layer, func() bool { return true }, nil, start) + }() + defer func() { cancel(); <-done }() + synctest.Wait() + delete(st.head.Snapshots, "a") + time.Sleep(30 * time.Second) + synctest.Wait() + if dirty { + if passes != 0 { + t.Fatal("snapshot probe bypassed first store attempt") + } + layer.calls.Add(1) + time.Sleep(chunkSchedulePoll) + synctest.Wait() + } + if passes != 1 { + t.Fatalf("first pass=%d", passes) + } + time.Sleep(30 * time.Second) + synctest.Wait() + if passes != 2 { + t.Fatalf("busy retry=%d; waited for ordinary interval", passes) + } + }) + }) + } +} + +func (s *maintenanceProbeStore) ReadHead(context.Context) (layout.Head, bool, error) { + s.reads++ + return s.head, s.found, s.err +} + +func TestMaintenanceNoticesSnapshotDeleteWithoutNotification(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + st := &maintenanceProbeStore{found: true, head: layout.Head{Snapshots: map[string]layout.Snapshot{"a": {}, "b": {}}}} + passes := 0 + p := &DurableProvider{cfg: ProviderConfig{ + ChunkMaintenanceInterval: time.Hour, + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return st, nil }, + ChunkMaintenance: func(context.Context, string) error { passes++; return nil }, + }} + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + p.chunkMaintenanceLoop(ctx, "v1", &progressLoopLayer{}, func() bool { return true }, nil, nil) + }() + defer func() { cancel(); <-done }() + synctest.Wait() + if st.reads != 1 || passes != 0 { + t.Fatalf("baseline: reads=%d passes=%d", st.reads, passes) + } + delete(st.head.Snapshots, "a") + st.err = errors.New("filer unavailable") + time.Sleep(30 * time.Second) + synctest.Wait() + if passes != 0 { + t.Fatal("failed read inferred a deletion") + } + st.err = nil + st.found = false + time.Sleep(30 * time.Second) + synctest.Wait() + if passes != 0 { + t.Fatal("absent HEAD inferred a deletion") + } + st.found = true + time.Sleep(30 * time.Second) + synctest.Wait() + if passes != 1 || st.reads != 4 { + t.Fatalf("delete: reads=%d passes=%d", st.reads, passes) + } + time.Sleep(30 * time.Second) + synctest.Wait() + if passes != 1 || st.reads != 5 { + t.Fatalf("unchanged: reads=%d passes=%d", st.reads, passes) + } + st.head.Snapshots["c"] = layout.Snapshot{} + time.Sleep(30 * time.Second) + synctest.Wait() + if passes != 1 { + t.Fatal("growing snapshot set triggered cleaning") + } + delete(st.head.Snapshots, "c") + st.head.Snapshots["d"] = layout.Snapshot{} // equal count still contains a deletion + time.Sleep(30 * time.Second) + synctest.Wait() + if passes != 2 { + t.Fatal("new snapshot's deletion was not noticed") + } + }) +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 8f472ad354..c7c918a23e 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -1042,6 +1042,30 @@ func (p *DurableProvider) maintenanceCurrent(volumeID string, h *volHandle, laye // (a cut session open: the cleaning never runs during one) is tried again. var maintenanceKickRetry = 30 * time.Second // a var only so tests can shorten it +// maintenanceSnapshotProbeInterval costs one HEAD read per attached volume per +// 30 seconds (about 7 reads/s at 200 volumes). This is a scheduling hint only; +// the existing cleaning session still requires an idle, matching HEAD. +const maintenanceSnapshotProbeInterval = 30 * time.Second + +func (p *DurableProvider) maintenanceSnapshots(ctx context.Context, volumeID string) (map[string]struct{}, error) { + st, err := p.cfg.ChunkLayoutHeadFor(volumeID) + if err != nil { + return nil, err + } + h, found, err := st.ReadHead(ctx) + if err != nil { + return nil, err + } + if !found { + return nil, layout.ErrHeadAbsent + } + names := make(map[string]struct{}, len(h.Snapshots)) + for name := range h.Snapshots { + names[name] = struct{}{} + } + return names, nil +} + // KickMaintenance asks the volume's maintenance loop for one pass now, as // after a snapshot delete. It reports whether a running loop was there to // ask (a stopped or ended loop is not); kicks coalesce, and the pass is the @@ -1085,12 +1109,71 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str } timer := time.NewTimer(time.Until(due)) defer timer.Stop() + var probe <-chan time.Time + var seen, observed map[string]struct{} + readSnapshots := func() { + if ctx.Err() != nil || layer.Fenced() || !current() { + return + } + timeout := p.cfg.ChunkMaintenanceTimeout + if timeout <= 0 { + timeout = time.Minute + } + _ = boundedPass(ctx, layer, current, timeout, func(readCtx context.Context) error { + names, err := p.maintenanceSnapshots(readCtx, volumeID) + if err == nil { + observed = names + } + return err + }) + } + if p.cfg.ChunkLayoutHeadFor != nil { + tick := time.NewTicker(maintenanceSnapshotProbeInterval) + defer tick.Stop() + probe = tick.C + readSnapshots() // establish a baseline without asking for a pass + seen = observed + } kicked := false for { select { case <-ctx.Done(): return case <-timer.C: + case <-probe: + if ctx.Err() != nil || layer.Fenced() || !current() { + return + } + observed = nil + readSnapshots() + if observed == nil { + continue + } // unknown is never an empty set + missing := false + for name := range seen { + if _, ok := observed[name]; !ok { + missing = true + break + } + } + if seen == nil { + seen = make(map[string]struct{}) + } + // Remember additions too: deleting one before the next ordinary pass + // must still be noticed. Keep missing names pending until a pass ends. + for name := range observed { + seen[name] = struct{}{} + } + if !missing { + continue + } + kicked = true + if !timer.Stop() { + select { + case <-timer.C: + default: + } + } case <-kick: kicked = true if !timer.Stop() { @@ -1130,6 +1213,9 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str err := boundedPass(ctx, layer, current, timeout, func(passCtx context.Context) error { return p.cfg.ChunkMaintenance(passCtx, volumeID) }) + if err == nil && observed != nil { + seen = observed + } if err != nil && ctx.Err() == nil { log.Printf("durable: maintenance volume=%s: %v", volumeID, err) } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 026355c163..9ad5f49960 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -543,9 +543,7 @@ stateDiagram-v2 | any (Start) | idle at epoch e, claim id k | Start only: at HEAD's epoch it continues on the root carrying HEAD's claim id at or above HEAD's position, else refuses; above, a fresh root or the continuing lineage claims, validated against the HEAD the claim updates | start.go `Start`; claim.go `RunClaim` | `INV-SNAPK-START-ROOT-001`, `INV-SNAPK-START-LINEAGE-001`, `INV-SNAPK-START-POSITION-001`, `INV-SNAPK-START-ACTIVITY-001` | | idle | clean(c) | holder at HEAD's epoch (epoch, server and claim id); activity idle (clean(c) again is a replay) | clean.go `Head.BeginClean` | `INV-SNAPK-CLEAN-EXCL-001` | | clean(c) | idle | holder at HEAD's epoch (epoch, server and claim id); activity clean(c); over idle it succeeds without a write | clean.go `Head.EndClean` | `INV-SNAPK-CLEAN-EXCL-001` | -| clean(c) | clean(c), names removed | holder at HEAD's epoch (epoch, server and claim id) with clean(c) open (HEAD read once, after BeginClean); a name is deleted only if no root in HEAD (current or snapshot) names it in this volume's pool; each removal is a mark conditional on the plan's metadata, then a delete conditional on that mark | remove.go `RemoveUnreachable` | `INV-CLEAN-METADATA-001` | Cleaning preserves Current and snapshot roots and their segments. Dependents keep their snapshot in HEAD. Unnamed roots go before segments and chunks; reuse defeats conditional removal. | M9 clean | `core/frontend/chunkstore/layout/remove.go`; `core/frontend/chunkstore/clean_b.go` | `TestCleanerMetadataRetainsCurrentSnapshotAndDependent`, `TestCleanerMetadataReuseDefeatsLateMarkAndDelete`, `TestCleanerRecreatesRemovedRootBeforeRenamingIt` (`core/frontend/chunkstore/layout/clean_metadata_test.go`); `TestCleaningInterruptsAfterMetadataBeforeChunks` (`core/frontend/chunkstore/clean_cursor_test.go`) | CommitReach2 CPlan, CView, LandMark, LandDel | ACTIVE | -| `INV-CLEAN-CURSOR-001` | A bounded pass resumes at its phase, shard and last completed name, wraps after the final shard, and revalidates HEAD after each parallel tag plan. Reachability uses a conservative initial root set only within one session. | M9 clean (liveness) | `core/frontend/chunkstore/clean_b.go`; `core/frontend/chunkstore/layout/remove.go` | `TestCleaningCursorResumesAfterTimeoutAndWraps` (`core/frontend/chunkstore/clean_cursor_test.go`); `TestCleanerReachableOncePerShardAndRechecksHead`, `TestCleanerPlansTagsInBoundedParallelBeforeHead` (`core/frontend/chunkstore/layout/clean_scale_test.go`) | CommitReach2 CView | ACTIVE | -| `INV-SNAPK-REMOVE-MARK-001` | +| clean(c) | clean(c), names removed | holder at HEAD's epoch, server and claim id with clean(c) open; candidate tags precede each HEAD validation; unreachable roots, then segments, then chunks; mark conditional on the planned tag, delete conditional on its own mark | remove.go `Cleaner.removePlanned` | `INV-SNAPK-REMOVE-MARK-001`, `INV-CLEAN-METADATA-001`, `INV-CLEAN-CURSOR-001` | | idle (live or detached) | deleting | the master reserved the volume for delete (no line granted after), then no line holds a live lease, checked between the HEAD read and the update; no open activity, no snapshot with dependents; deleting again is a replay | delete.go `Head.MarkDeleting`, `RunMarkDeleting` (`DeleteAuthority`) | `INV-SNAPK-DELETE-ORDER-001` | | absent | deleted (tombstone) | the operator's remove-dependent, for a restore target without HEAD (never created, or a restore died between its two creates); one exclusive create, so a later HEAD create of the restore fails; a HEAD appearing first refuses | delete.go `OperatorReleaseDependent` (`TargetStore.CreateDeletedHead`) | `INV-SNAPK-TOMBSTONE-001`, `INV-SNAPK-HEAD-WRITE-001` | | source: any live | source: target released | by the target's volume id, from every snapshot: from DeleteVolume once the target's HEAD is deleting, or from the operator's command once the target is deleted, of another id, no longer naming the source, or tombstoned; an absent target writes nothing | delete.go `Head.ReleaseDependent`, `RunReleaseDependent`, `OperatorReleaseDependent` | `INV-SNAPK-RELEASE-001`, `INV-SNAPK-RELEASE-CALLERS-001`, `INV-SNAPK-RELEASE-OPERATOR-001` | @@ -1090,6 +1088,8 @@ Notes: | `INV-SNAPK-CLEAN-EXCL-001` | A cleaning and a snapshot exclude each other through HEAD's one activity field, so no name is removed while a snapshot is open; a claim voids an open cleaning. | M9 idle → clean → idle | `core/frontend/chunkstore/layout` `clean.go` `Head.BeginClean`, `Head.EndClean` | `TestBeginClean_Closure`, `TestEndClean_Closure`, `TestEndClean_IdleMeansNoActivityRemains`, `TestClean_ExcludesSnapshot`, `TestRunBeginClean_InterruptAtEveryStep`, `TestRunEndClean_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-CLEAN-HOLDER-PASS-001` | The holder's periodic cleaning runs as the identity Start established: Begin refuses any other holder, claim or epoch; a pass with no identity, or whose retention failed, removes nothing; every opened cleaning is closed, also on error. | M9 idle → clean → idle (holder pass) | `core/frontend/chunkstore/clean_b.go` `BCatalog.Clean`; `cmd/blockvolume/chunk_maintenance.go` `newChunkMaintenance` | `TestBCatalog_CleanIsHolderOnly`, `TestBCatalog_CleanClosesOnError`, `TestBCatalog_CleanRemovesOnlyUnreachable`, `TestBCatalog_CleanWaitsForAnOpenSnapshot`, `TestBCatalog_CleanAfterOverwriteAndSnapshotDelete` (`core/frontend/chunkstore/clean_b_test.go`); `TestMaintenanceCleansOnlyAsTheHolder`, `TestMaintenanceRetentionFailureNeverStartsCleaning` (`cmd/blockvolume/chunk_maintenance_test.go`) | — | ACTIVE | | `INV-SNAPK-READ-MISSING-001` | A read resolves root, segment, chunk; an index the root does not name is zeros; a root, segment or chunk the root reaches but the store lacks is ErrMissing, never zeros; bytes that do not hash to their name are ErrCorrupt; a foreign chunk is read from its owner's pool. | Content-named layout (read path, no state transition) | `core/frontend/chunkstore/layout` `read.go` `Reader.Open`, `Image.Segment`, `Image.Chunk` | `TestRead_AbsentIndexIsZeros`, `TestRead_ForeignChunkFromSourcePool`, `TestRead_MissingObjectIsAnErrorNeverZeros`, `TestRead_FetchFailureAndCorruption`, `TestRead_SegmentOfAnotherShardRefused` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-CLEAN-METADATA-001` | Cleaning preserves Current and snapshot roots and their segments. Dependents keep their snapshot in HEAD. Unnamed roots go before segments and chunks; reuse defeats conditional removal. | M9 clean | `core/frontend/chunkstore/layout/remove.go`; `core/frontend/chunkstore/clean_b.go` | `TestCleanerMetadataRetainsCurrentSnapshotAndDependent`, `TestCleanerMetadataReuseDefeatsLateMarkAndDelete`, `TestCleanerRecreatesRemovedRootBeforeRenamingIt` (`core/frontend/chunkstore/layout/clean_metadata_test.go`); `TestCleaningInterruptsAfterMetadataBeforeChunks` (`core/frontend/chunkstore/clean_cursor_test.go`) | CommitReach2 CPlan, CView, LandMark, LandDel | ACTIVE | +| `INV-CLEAN-CURSOR-001` | A bounded pass resumes at its phase, shard and last completed name, wraps after the final shard, and revalidates HEAD after each parallel tag plan. Reachability uses a conservative initial root set only within one session. | M9 clean (liveness) | `core/frontend/chunkstore/clean_b.go`; `core/frontend/chunkstore/layout/remove.go` | `TestCleaningCursorResumesAfterTimeoutAndWraps` (`core/frontend/chunkstore/clean_cursor_test.go`); `TestCleanerReachableOncePerShardAndRechecksHead`, `TestCleanerPlansTagsInBoundedParallelBeforeHead` (`core/frontend/chunkstore/layout/clean_scale_test.go`) | CommitReach2 CView | ACTIVE | | `INV-SNAPK-REMOVE-MARK-001` | A content-named object is removed only inside the holder's own cleaning, when no root in HEAD names it: tags read first, HEAD read and validated after, then a mark conditional on the tag and a delete conditional on the mark. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_RemovesOnlyWhatNoRootNames`, `TestCleaningPass_InterruptAtEveryStep`, `TestHolderFunctions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-REMOVE-STOP-001` | A reuse of an object after the plan, or after the mark, makes the remover's mark or delete fail its condition, however late it lands; an unreadable root stops the pass before any write; an open snapshot refuses it. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_ASuccessorAfterTheHeadViewDefeatsTheMark`, `TestRemoveUnreachable_ASuccessorBeforeTheHeadViewStopsThePass`, `TestRemoveUnreachable_AReuseAfterThePlanDefeatsTheMark`, `TestRemoveUnreachable_AReuseDefeatsALateMarkOrDelete`, `TestRemoveUnreachable_NothingRemovedOnAPartialView`, `TestRemoveUnreachable_RefusedOutsideItsCleaning` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-REMOVE-CONVERGE-001` | A name a cleaning marked and did not delete (the remover died in between) is planned again by the next cleaning: the re-mark replaces the old mark, so the dead remover's late delete fails, and every unreachable name goes once a cleaning completes. | M9 clean → clean | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_ReclaimsAnAbandonedMark`, `TestCleaningPass_InterruptAtEveryStep`, `TestLayoutStoreCleaningReclaimsAnAbandonedMark` | — (the snapshot kernel model is not in this repository) | ACTIVE | diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 23c16af3ae..f26d199a29 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -802,6 +802,13 @@ A restore makes a new volume from a snapshot. The new volume reads every chunk i A holder's cleaning removes unreferenced roots first, then segments, then chunk objects. Current and every snapshot root remain reachable; a restore dependent prevents its source snapshot from being deleted, including by retention. +The holder's maintenance loop probes HEAD every 30 seconds and asks for an early +pass when a previously observed snapshot name disappears, including after a +master-resolved snapshot delete. There is no notification channel or lease-loop +work. This adds one HEAD read per volume per 30 seconds (about 7 reads/s for 200 +volumes), plus a baseline read when maintenance starts. A failed or absent HEAD +read never means the snapshot set is empty. Space returns over several bounded +passes as the cleaning cursor advances; a probe does not bypass an active cut. Each object is marked conditionally on its planned tag and deleted conditionally on that mark. An object reused by a successor defeats those late writes. From 13fe1190f622b89ce9faac1997badd9467879b6f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 28 Nov 2026 07:42:51 -0800 Subject: [PATCH 11/13] skip snapshot probes during holder activity --- .../frontend/chunkstore/head_readers_test.go | 2 +- .../core/frontend/chunkstore/layout_remote.go | 27 ++++++ .../chunkstore/layout_snapshot_probe_test.go | 84 +++++++++++++++++++ .../durable/maintenance_probe_test.go | 24 +++++- .../core/frontend/durable/provider_chunk.go | 28 +++---- seaweed-block/docs/standalone-deployment.md | 8 +- 6 files changed, 152 insertions(+), 21 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout_snapshot_probe_test.go diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index 0f2e071676..d831973adb 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -24,7 +24,7 @@ import ( // pins it. "GAP" marks a reader that takes an absent HEAD for an empty // one; a change that treats an absent HEAD as unknown flips those probes. var headReaders = map[string]string{ - "core/frontend/durable/provider_chunk.go maintenanceSnapshots -> ReadHead": "absent or failed reads do not infer snapshot deletion or ask for cleaning (TestMaintenanceNoticesSnapshotDeleteWithoutNotification)", + "core/frontend/chunkstore/layout_remote.go ProbeSnapshots -> ReadHead": "absent or failed reads do not infer snapshot deletion; open local activity skips the read (TestMaintenanceNoticesSnapshotDeleteWithoutNotification, TestLayoutSnapshotProbeSkipsOpenActivityWithoutReadingHEAD)", "core/frontend/durable/provider_seal_replay.go readLayoutSeal -> ReadHead": "absent, unreadable and foreign layout proof refuse without cached success (TestLayoutPlainDetachReplayAfterRestartNeedsNoLegacyFactory)", "core/frontend/durable/provider_layout.go settleLayoutStop -> ReadHead": "absent refuses unknown stop outcome, never resumes (probe TestLayoutStopAbortMustConfirmItsOutcome)", "core/frontend/durable/provider_layout.go startLayoutRoot -> ReadHead": "the diagnostic re-read after Start refusal cannot turn an absent HEAD into a claim; Start already refused it (probe TestLayoutStoreMissingHEADRefusesStart)", diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote.go b/seaweed-block/core/frontend/chunkstore/layout_remote.go index 2f4a742ea5..1c12423ba9 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_remote.go +++ b/seaweed-block/core/frontend/chunkstore/layout_remote.go @@ -82,6 +82,33 @@ type pendingSnapshot struct { meta layout.SnapshotMeta } +// ProbeSnapshots reads only the snapshot names for maintenance scheduling. A +// nil set means skipped: never wait behind a runtime call or probe inside an +// open cut/cleaning. Holding mu across the read keeps a new local activity from +// opening between the idle check and the read. This neither rolls back activity +// nor changes the engine view; the cleaning kernel remains the safety gate. +func (l *LayoutRemote) ProbeSnapshots(ctx context.Context) (map[string]struct{}, error) { + if !l.mu.TryLock() { + return nil, nil + } + defer l.mu.Unlock() + if l.session != "" || l.cleaning != "" { + return nil, nil + } + h, found, err := l.st.ReadHead(ctx) + if err != nil { + return nil, err + } + if !found { + return nil, layout.ErrHeadAbsent + } + names := make(map[string]struct{}, len(h.Snapshots)) + for name := range h.Snapshots { + names[name] = struct{}{} + } + return names, nil +} + var ( _ storage.ChunkRemote = (*LayoutRemote)(nil) _ storage.ChunkKeyer = (*LayoutRemote)(nil) diff --git a/seaweed-block/core/frontend/chunkstore/layout_snapshot_probe_test.go b/seaweed-block/core/frontend/chunkstore/layout_snapshot_probe_test.go new file mode 100644 index 0000000000..eb5fac0e26 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_snapshot_probe_test.go @@ -0,0 +1,84 @@ +package chunkstore + +import ( + "context" + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +type probeReadCounter struct { + sessionStore + reads int + absent bool + err error +} + +func (s *probeReadCounter) ReadHead(ctx context.Context) (layout.Head, bool, error) { + s.reads++ + if s.err != nil || s.absent { + return layout.Head{}, false, s.err + } + return s.sessionStore.ReadHead(ctx) +} + +func TestLayoutSnapshotProbeSkipsOpenActivityWithoutReadingHEAD(t *testing.T) { + lh := newLayoutHost(t) + r, err := NewLayoutRemote(lh.cat, lh.v, lh.me) + if err != nil { + t.Fatal(err) + } + probe, ok := any(r).(interface { + ProbeSnapshots(context.Context) (map[string]struct{}, error) + }) + if !ok { + t.Fatal("layout runtime has no idle-only snapshot probe") + } + count := &probeReadCounter{sessionStore: r.st} + r.st = count + ctx := context.Background() + names, err := probe.ProbeSnapshots(ctx) + if err != nil || names == nil || count.reads != 1 { + t.Fatalf("idle: %v %v reads=%d", names, err, count.reads) + } + r.mu.Lock() + names, err = probe.ProbeSnapshots(ctx) + r.mu.Unlock() + if err != nil || names != nil || count.reads != 1 { + t.Fatal("probe waited for busy runtime or read HEAD") + } + if _, err = r.Begin(ctx); err != nil { + t.Fatal(err) + } + before := count.reads + names, err = probe.ProbeSnapshots(ctx) + if err != nil || names != nil || count.reads != before { + t.Fatal("probe read HEAD inside staged session") + } + if _, err = r.AbortOpenSession(ctx); err != nil { + t.Fatal(err) + } + err = r.Clean(ctx, func(context.Context, layout.HolderID, string) error { + before := count.reads + names, err := probe.ProbeSnapshots(ctx) + if err != nil || names != nil || count.reads != before { + t.Fatal("probe read HEAD during cleaning") + } + return nil + }) + if err != nil { + t.Fatal(err) + } + count.absent = true + names, err = probe.ProbeSnapshots(ctx) + if names != nil || !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatalf("absent HEAD: %v %v", names, err) + } + count.absent = false + count.err = errors.New("filer unavailable") + names, err = probe.ProbeSnapshots(ctx) + if names != nil || !errors.Is(err, count.err) { + t.Fatalf("failed HEAD: %v %v", names, err) + } +} diff --git a/seaweed-block/core/frontend/durable/maintenance_probe_test.go b/seaweed-block/core/frontend/durable/maintenance_probe_test.go index b687184b60..8d56e192bd 100644 --- a/seaweed-block/core/frontend/durable/maintenance_probe_test.go +++ b/seaweed-block/core/frontend/durable/maintenance_probe_test.go @@ -8,10 +8,11 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" ) type maintenanceProbeStore struct { - layout.StartStore + storage.ChunkRemote head layout.Head found bool err error @@ -27,7 +28,7 @@ func TestMaintenanceSnapshotProbeKeepsBusyRetryAndDirtyStartGate(t *testing.T) { passes := 0 p := &DurableProvider{cfg: ProviderConfig{ ChunkMaintenanceInterval: time.Hour, - ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return st, nil }, + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return nil, nil }, ChunkMaintenance: func(context.Context, string) error { passes++ if passes == 1 { @@ -40,6 +41,7 @@ func TestMaintenanceSnapshotProbeKeepsBusyRetryAndDirtyStartGate(t *testing.T) { if dirty { start = &maintenanceStart{deadline: time.Now().Add(time.Hour)} } + p.volumes = map[string]*volHandle{"v1": {layoutRemote: st}} ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) go func() { @@ -77,15 +79,31 @@ func (s *maintenanceProbeStore) ReadHead(context.Context) (layout.Head, bool, er return s.head, s.found, s.err } +func (s *maintenanceProbeStore) ProbeSnapshots(ctx context.Context) (map[string]struct{}, error) { + h, found, err := s.ReadHead(ctx) + if err != nil { + return nil, err + } + if !found { + return nil, layout.ErrHeadAbsent + } + names := make(map[string]struct{}, len(h.Snapshots)) + for n := range h.Snapshots { + names[n] = struct{}{} + } + return names, nil +} + func TestMaintenanceNoticesSnapshotDeleteWithoutNotification(t *testing.T) { synctest.Test(t, func(t *testing.T) { st := &maintenanceProbeStore{found: true, head: layout.Head{Snapshots: map[string]layout.Snapshot{"a": {}, "b": {}}}} passes := 0 p := &DurableProvider{cfg: ProviderConfig{ ChunkMaintenanceInterval: time.Hour, - ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return st, nil }, + ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return nil, nil }, ChunkMaintenance: func(context.Context, string) error { passes++; return nil }, }} + p.volumes = map[string]*volHandle{"v1": {layoutRemote: st}} ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) go func() { diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index c7c918a23e..fb836d1f92 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -1048,22 +1048,20 @@ var maintenanceKickRetry = 30 * time.Second // a var only so tests can shorten i const maintenanceSnapshotProbeInterval = 30 * time.Second func (p *DurableProvider) maintenanceSnapshots(ctx context.Context, volumeID string) (map[string]struct{}, error) { - st, err := p.cfg.ChunkLayoutHeadFor(volumeID) - if err != nil { - return nil, err + p.mu.Lock() + h := p.volumes[volumeID] + var remote storage.ChunkRemote + if h != nil { + remote = h.layoutRemote } - h, found, err := st.ReadHead(ctx) - if err != nil { - return nil, err - } - if !found { - return nil, layout.ErrHeadAbsent - } - names := make(map[string]struct{}, len(h.Snapshots)) - for name := range h.Snapshots { - names[name] = struct{}{} - } - return names, nil + p.mu.Unlock() + probe, ok := remote.(interface { + ProbeSnapshots(context.Context) (map[string]struct{}, error) + }) + if !ok { + return nil, nil + } // no attached runtime, no scheduling inference + return probe.ProbeSnapshots(ctx) } // KickMaintenance asks the volume's maintenance loop for one pass now, as diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index f26d199a29..cab7cc5352 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -805,8 +805,12 @@ prevents its source snapshot from being deleted, including by retention. The holder's maintenance loop probes HEAD every 30 seconds and asks for an early pass when a previously observed snapshot name disappears, including after a master-resolved snapshot delete. There is no notification channel or lease-loop -work. This adds one HEAD read per volume per 30 seconds (about 7 reads/s for 200 -volumes), plus a baseline read when maintenance starts. A failed or absent HEAD +work. A busy runtime or an open cut session/cleaning skips the probe without a +HEAD read. When idle this adds one HEAD read per volume per 30 seconds (about +7 reads/s for 200 volumes), plus a baseline read when maintenance starts. The +200-volume and AG1b (thousands of volumes per host) qualification rows measure +this added read rate per host against filer capacity; above 1% the probe design +must be revisited. A failed or absent HEAD read never means the snapshot set is empty. Space returns over several bounded passes as the cleaning cursor advances; a probe does not bypass an active cut. Each object is marked conditionally on its planned tag and deleted conditionally From 8499e59b748f4fce1861db597e1bec5c04a56241 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 28 Nov 2026 07:50:37 -0800 Subject: [PATCH 12/13] preserve cleaning order and scheduled worker lifetime --- .../core/frontend/chunkstore/clean_b.go | 27 ++++--- .../frontend/chunkstore/clean_cursor_test.go | 60 ++++++++++++++ .../chunkstore/clean_dependents_test.go | 81 +++++++++++++++++++ .../layout/snapshot_dependents_guard_test.go | 42 ++++++++++ .../durable/chunk_snapshot_schedule.go | 23 +++++- .../frontend/durable/snapshot_due_now_test.go | 31 ++++++- seaweed-block/docs/design/invariants.md | 17 ++-- seaweed-block/docs/releases/README.md | 1 + .../docs/releases/cleaning-convergence.md | 23 ++++++ seaweed-block/docs/standalone-deployment.md | 7 +- 10 files changed, 288 insertions(+), 24 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/clean_dependents_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/layout/snapshot_dependents_guard_test.go create mode 100644 seaweed-block/docs/releases/cleaning-convergence.md diff --git a/seaweed-block/core/frontend/chunkstore/clean_b.go b/seaweed-block/core/frontend/chunkstore/clean_b.go index 17e320ac76..5011cf7eb2 100644 --- a/seaweed-block/core/frontend/chunkstore/clean_b.go +++ b/seaweed-block/core/frontend/chunkstore/clean_b.go @@ -26,11 +26,12 @@ type CleanResult struct { // and validates HEAD; no cached safety decision survives the pass. Completing // the last shard wraps to roots so earlier/new names are revisited next time. type cleanCursor struct { - mu sync.Mutex - phase int // roots, segments, chunks - shard string - after string - poolAfter string + mu sync.Mutex + phase int // roots, segments, chunks + shard string + after string + segmentAfter string + poolAfter string } func (c *BCatalog) cleaningCursor(v VolumeRef) *cleanCursor { @@ -60,12 +61,13 @@ func (c *BCatalog) RemoveUnreachableAll(ctx context.Context, v VolumeRef, me lay return res, err } cleaner := layout.NewCleaner(s, r, s, me, session) - // A resumed chunk cursor still starts this session with a metadata pass: - // cuts between bounded passes may have left additional unnamed roots. - if cur.phase == 2 { - cur.phase = 0 - cur.after = "" + // Every new session starts at the first root: between sessions an operator + // may un-name one whose segments this session would otherwise remove first. + // Preserve segment/chunk progress, but never carry a root-phase view forward. + if cur.phase == 1 { + cur.segmentAfter = cur.after } + cur.phase, cur.after = 0, "" for cur.phase < 2 { if err := ctx.Err(); err != nil { return res, err @@ -102,6 +104,11 @@ func (c *BCatalog) RemoveUnreachableAll(ctx context.Context, v VolumeRef, me lay if uint32(len(names)) < cleanPage { cur.phase++ cur.after = "" + if cur.phase == 1 { + cur.after = cur.segmentAfter + } else { + cur.segmentAfter = "" + } } } shards, err := s.List(ctx, path.Join(c.base, v.Dir(), layout.PoolDir)) diff --git a/seaweed-block/core/frontend/chunkstore/clean_cursor_test.go b/seaweed-block/core/frontend/chunkstore/clean_cursor_test.go index 170fbd7b48..c4a3946f88 100644 --- a/seaweed-block/core/frontend/chunkstore/clean_cursor_test.go +++ b/seaweed-block/core/frontend/chunkstore/clean_cursor_test.go @@ -1,6 +1,7 @@ package chunkstore import ( + "bytes" "context" "errors" "path" @@ -10,6 +11,65 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" ) +func TestCleaningSegmentResumeReplansRootsBeforeRemovingSegments(t *testing.T) { + ctx := context.Background() + previousPage := cleanPage + cleanPage = 1 + t.Cleanup(func() { cleanPage = previousPage }) + c, v, s, _ := cleanFixture(t) + h, _, _ := s.ReadHead(ctx) + oldRoot := *h.Current + x := layout.NameChunk(1, bytes.Repeat([]byte{7}, 4096)) + yData := bytes.Repeat([]byte{8}, 4096) + y := layout.NameChunk(1, yData) + m1 := map[uint64]layout.Ref{1: {Owner: v.Name, OwnerID: v.ID, Chunk: x}} + m2 := map[uint64]layout.Ref{1: {Owner: v.Name, OwnerID: v.ID, Chunk: y}} + commitImage(t, s, v.Name, "next", m1, m2, map[uint64][]byte{1: yData}, 2, "") + f := &cleaningListHook{Filer: c.f} + c.f = f + interrupt := true + f.before = func(dir, after string) error { + if dir == path.Join(s.root, layout.SegDir) { + if interrupt { + if after != "" { + return context.DeadlineExceeded + } + return nil // finish one segment page before interruption + } + if _, found, err := s.Stat(ctx, oldRoot.Path()); err != nil || found { + t.Fatalf("segment resume preceded removal of un-named root: found=%t err=%v", found, err) + } + } + return nil + } + if _, _, err := cleanVia(ctx, c, v, cleanHolder); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("interrupt: %v", err) + } + if c.cleaningCursor(v).phase != 1 { + t.Fatal("did not interrupt inside segment phase") + } + if c.cleaningCursor(v).after == "" { + t.Fatal("interruption did not retain segment progress") + } + if _, err := c.DeleteSnapshot(ctx, v, "s"); err != nil { + t.Fatal(err) + } + interrupt = false + if _, _, err := cleanVia(ctx, c, v, cleanHolder); err != nil { + t.Fatal(err) + } + _, r, _ := c.open(v) + h, _, _ = s.ReadHead(ctx) + img, err := r.Open(ctx, *h.Current) + if err != nil { + t.Fatal(err) + } + got, err := img.Chunk(ctx, 1) + if err != nil || !bytes.Equal(got.Data, yData) { + t.Fatalf("live image: %v %v", got, err) + } +} + type cleaningListHook struct { Filer before func(string, string) error diff --git a/seaweed-block/core/frontend/chunkstore/clean_dependents_test.go b/seaweed-block/core/frontend/chunkstore/clean_dependents_test.go new file mode 100644 index 0000000000..40340a0f04 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/clean_dependents_test.go @@ -0,0 +1,81 @@ +package chunkstore + +import ( + "bytes" + "context" + "errors" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/retain" +) + +func TestDependentSnapshotSurvivesOperatorExpiryAndRetentionPrune(t *testing.T) { + for _, route := range []string{"operator", "expiry", "prune"} { + t.Run(route, func(t *testing.T) { + ctx := context.Background() + c, v, _, _ := cleanFixture(t) + now := time.Unix(10000, 0) + meta := layout.SnapshotMeta{CreatedNs: 1, Class: layout.ClassSemantic} + if route == "expiry" { + meta.ExpiresNs = now.Add(-time.Second).UnixNano() + } + snapshotWithMeta(t, c, v, "dependent", meta, "dep", 2) + snapshotWithMeta(t, c, v, "newer", layout.SnapshotMeta{CreatedNs: 2, Class: layout.ClassSemantic}, "new", 3) + target := newRef(t, "target") + if _, err := c.Restore(ctx, v, "dependent", target); err != nil { + t.Fatal(err) + } + if err := c.SetRetention(ctx, v, retain.Policy{KeepNewest: 1}); err != nil { + t.Fatal(err) + } + if route == "operator" { + if _, err := c.DeleteSnapshot(ctx, v, "dependent"); !errors.Is(err, layout.ErrHasDependents) { + t.Fatalf("operator: %v", err) + } + } else { + dry, err := c.Retain(ctx, v, now, true) + if err != nil { + t.Fatal(err) + } + planned := false + for _, n := range dry.Deleted { + planned = planned || n == "dependent" + } + if !planned { + t.Fatal("dependent was not a planned retention victim") + } + res, err := c.Retain(ctx, v, now, false) + if err != nil { + t.Fatal(err) + } + if names(res.Refused) != "dependent" { + t.Fatalf("retention did not report refusal: %+v", res) + } + } + h, found, err := c.ReadHead(ctx, v) + if err != nil || !found || len(h.Snapshots["dependent"].Dependents) != 1 { + t.Fatalf("snapshot lost: %+v %v", h, err) + } + if _, _, err := cleanVia(ctx, c, v, cleanHolder); err != nil { + t.Fatal(err) + } + s, r, err := c.open(target) + if err != nil { + t.Fatal(err) + } + th, _, err := s.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + img, err := r.Open(ctx, *th.Current) + if err != nil { + t.Fatal(err) + } + if got, err := img.Chunk(ctx, 1); err != nil || !bytes.Equal(got.Data, bytes.Repeat([]byte{7}, 4096)) { + t.Fatalf("restore after clean: %v %v", got, err) + } + }) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/snapshot_dependents_guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/snapshot_dependents_guard_test.go new file mode 100644 index 0000000000..9835211324 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/snapshot_dependents_guard_test.go @@ -0,0 +1,42 @@ +package layout + +import ( + "context" + "errors" + "testing" +) + +// All snapshot-removal transitions converge on DeleteSnapshot. Retention's +// additional pin check must never bypass the dependent check on that same HEAD. +func TestSnapshotWithDependentsSurvivesEveryRemovalTransition(t *testing.T) { + for _, state := range []string{StateLive, StateDetached} { + for _, call := range []string{"delete", "retire", "run-delete", "run-retire"} { + t.Run(string(state)+"/"+call, func(t *testing.T) { + h := idleHead() + h.State = state + rn := RootName{Hash: Sum([]byte("root"))} + h.Current = &rn + h.Snapshots = map[string]Snapshot{"dependent": {Root: rn, Dependents: deps(rn, "target")}} + st := &memHead{h: &h} + ctx := context.Background() + var err error + switch call { + case "delete": + _, _, err = h.DeleteSnapshot("dependent") + case "retire": + _, _, err = h.RetireSnapshot("dependent", 100) + case "run-delete": + _, err = RunDeleteSnapshot(ctx, st, "dependent") + case "run-retire": + _, err = RunRetireSnapshot(ctx, st, "dependent", 100) + } + if !errors.Is(err, ErrHasDependents) { + t.Fatalf("dependent removal: %v", err) + } + if len(st.h.Snapshots["dependent"].Dependents) != 1 || st.h.Snapshots["dependent"].Root != rn { + t.Fatal("dependent snapshot left HEAD") + } + }) + } + } +} diff --git a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go index 70ebd28735..cf3a56d312 100644 --- a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go +++ b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go @@ -192,9 +192,11 @@ func earlier(a, b time.Time) time.Time { // snapshotSlot guards one running loop's schedule: the loop records // outcomes, status readers read it. type snapshotSlot struct { - mu sync.Mutex - s *snapshotSchedule - dueNow chan struct{} // coalesced explicit trigger; set before the loop starts + mu sync.Mutex + s *snapshotSchedule + dueNow chan struct{} // coalesced explicit trigger; set before the loop starts + workerDone chan struct{} // the snapshot worker, not the aggregate background group + workerCtx context.Context } // ScheduleSnapshotNow asks the existing daily/weekly loop for an attempt now. @@ -211,6 +213,16 @@ func (p *DurableProvider) ScheduleSnapshotNow(volumeID string) bool { return false default: } + h.snapshots.mu.Lock() + defer h.snapshots.mu.Unlock() + if h.snapshots.workerDone == nil || h.snapshots.workerCtx.Err() != nil { + return false + } + select { + case <-h.snapshots.workerDone: + return false + default: + } select { case h.snapshots.dueNow <- struct{}{}: default: @@ -243,6 +255,11 @@ func (sl *snapshotSlot) record(now time.Time, err error) { // recorded. chunkBackground joins it with its other workers // (INV-MAINT-JOIN). func (p *DurableProvider) chunkSnapshotLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool, slot *snapshotSlot, attempted func(storage.ChunkLayerStats, storage.ChunkLayerStats, error)) { + slot.mu.Lock() + workerDone := make(chan struct{}) + slot.workerDone, slot.workerCtx = workerDone, ctx + slot.mu.Unlock() + defer close(workerDone) timer := time.NewTimer(time.Until(slot.due())) defer timer.Stop() timeout := 2 * p.cfg.ChunkCutTimeout diff --git a/seaweed-block/core/frontend/durable/snapshot_due_now_test.go b/seaweed-block/core/frontend/durable/snapshot_due_now_test.go index 1f5922a983..00580293b2 100644 --- a/seaweed-block/core/frontend/durable/snapshot_due_now_test.go +++ b/seaweed-block/core/frontend/durable/snapshot_due_now_test.go @@ -2,10 +2,11 @@ package durable import ( "context" - "github.com/seaweedfs/seaweed-block/core/storage" "testing" "testing/synctest" "time" + + "github.com/seaweedfs/seaweed-block/core/storage" ) func TestScheduledSnapshotDueNowUsesExistingLoop(t *testing.T) { @@ -53,3 +54,31 @@ func TestScheduledSnapshotDueNowUsesExistingLoop(t *testing.T) { } }) } + +func TestScheduledSnapshotDueNowRefusesEndedWorkerWithBackgroundAlive(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + background := make(chan struct{}) + worker := make(chan struct{}) + slot := &snapshotSlot{s: newSnapshotSchedule("v1", 24*time.Hour, time.Now()), dueNow: make(chan struct{}, 1)} + p := &DurableProvider{volumes: map[string]*volHandle{"v1": {snapshots: slot, chunkStop: cancel, chunkDone: background}}} + current := true + go func() { + defer close(worker) + p.chunkSnapshotLoop(ctx, "v1", &progressLoopLayer{}, func() bool { return current }, slot, nil) + }() + synctest.Wait() + current = false + slot.dueNow <- struct{}{} + <-worker + if p.ScheduleSnapshotNow("v1") { + t.Fatal("queued into ended snapshot worker while background group stayed alive") + } + select { + case <-background: + t.Fatal("test closed aggregate background") + default: + } + }) +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9ad5f49960..57968f630a 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1076,7 +1076,7 @@ Notes: |---|---|---|---|---|---|---| | `INV-SNAPK-NAME-CANONICAL-001` | A chunk is named by its index and the SHA-256 of its bytes under `pool//`; a segment and a root are named by the SHA-256 of their canonical encoding, and decoding refuses any bytes the encoder would not write, so an object has one encoding and one name. | Content-named layout (no state transition) | `core/frontend/chunkstore/layout` `layout.go` `ParseChunkName`, `DecodeSegment`, `DecodeRoot` | `TestParseChunkName_RoundTripAndRefusals`, `TestDecodeSegment_RefusesNonCanonical`, `TestRoot_Refusals`, `TestBuild_ShardsAndIncrementalReuse` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-HEAD-WRITE-001` | HEAD changes only by one conditional update on its generation through `runTransition`; no path in the package creates a HEAD, and an absent HEAD is refused. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `runTransition`; `HeadStore` (read and conditional update only) | `TestGuard_WritersTransitionsAndRemovers`, `TestRunBegin` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-HEAD-GUARD-001` | A source scan refuses any other use of `UpdateHead`, a transition without its closure and interrupt tests, and any store remover other than the mark-gated Cleaner.removePlanned and the ordered DeleteVolume. | M9 every transition | `core/frontend/chunkstore/layout` (source scan of the package) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-HEAD-GUARD-001` | A source scan refuses any other use of `UpdateHead`, a transition without its closure and interrupt tests, and any store remover other than the mark-gated Cleaner.removePlanned and the ordered DeleteVolume. | M9 every transition | `core/frontend/chunkstore/layout` (source scan of the package) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE | | `INV-SNAPK-HEAD-CODEC-001` | HEAD is canonical JSON with at most 100 snapshots and sorted unique dependents; unknown fields, non-canonical bytes and names that are not valid UTF-8 are refused at encode and decode, and the next HEAD is checked before it is written. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `Head.check`, `Head.Encode`, `DecodeHead` | `TestHead_GoldenEncodingRoundTrip`, `TestHead_Refusals`, `TestHead_RefusesInvalidUTF8` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-BEGIN-001` | Begin opens snap(s) only for the holder at HEAD's epoch and only from idle; a re-run of the open session writes nothing; killed at its write and re-run, it ends in snap(s) at one generation step. | M9 idle → snap | `core/frontend/chunkstore/layout` `head.go` `Head.Begin`, `RunBegin` | `TestBegin_Closure`, `TestRunBegin_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-ABORT-001` | Abort closes the holder's own snap(s) and changes nothing else; after its own crash a holder rolls the open session back before beginning another; over idle Abort writes nothing and its success never says whether the work was committed. | M9 snap → idle (Abort) | `core/frontend/chunkstore/layout` `head.go` `Head.Abort`, `RunAbort`; `core/frontend/durable/provider_layout.go` `settleLayoutStop` | `TestLayoutStopAbortMustConfirmItsOutcome`, `TestLayoutRemote_AbortOpenSessionDoesNotWaitForAHeldCommit`, `TestLayoutRemote_AbortOpenSessionFencesAForeignHead`, `TestLayoutRemoteSessionFieldSites`, `TestAbort_Closure`, `TestAbort_IdleMeansNoActivityRemains`, `TestAbort_RollBackAfterOwnCrash`, `TestRunAbort_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | @@ -1088,12 +1088,15 @@ Notes: | `INV-SNAPK-CLEAN-EXCL-001` | A cleaning and a snapshot exclude each other through HEAD's one activity field, so no name is removed while a snapshot is open; a claim voids an open cleaning. | M9 idle → clean → idle | `core/frontend/chunkstore/layout` `clean.go` `Head.BeginClean`, `Head.EndClean` | `TestBeginClean_Closure`, `TestEndClean_Closure`, `TestEndClean_IdleMeansNoActivityRemains`, `TestClean_ExcludesSnapshot`, `TestRunBeginClean_InterruptAtEveryStep`, `TestRunEndClean_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-CLEAN-HOLDER-PASS-001` | The holder's periodic cleaning runs as the identity Start established: Begin refuses any other holder, claim or epoch; a pass with no identity, or whose retention failed, removes nothing; every opened cleaning is closed, also on error. | M9 idle → clean → idle (holder pass) | `core/frontend/chunkstore/clean_b.go` `BCatalog.Clean`; `cmd/blockvolume/chunk_maintenance.go` `newChunkMaintenance` | `TestBCatalog_CleanIsHolderOnly`, `TestBCatalog_CleanClosesOnError`, `TestBCatalog_CleanRemovesOnlyUnreachable`, `TestBCatalog_CleanWaitsForAnOpenSnapshot`, `TestBCatalog_CleanAfterOverwriteAndSnapshotDelete` (`core/frontend/chunkstore/clean_b_test.go`); `TestMaintenanceCleansOnlyAsTheHolder`, `TestMaintenanceRetentionFailureNeverStartsCleaning` (`cmd/blockvolume/chunk_maintenance_test.go`) | — | ACTIVE | | `INV-SNAPK-READ-MISSING-001` | A read resolves root, segment, chunk; an index the root does not name is zeros; a root, segment or chunk the root reaches but the store lacks is ErrMissing, never zeros; bytes that do not hash to their name are ErrCorrupt; a foreign chunk is read from its owner's pool. | Content-named layout (read path, no state transition) | `core/frontend/chunkstore/layout` `read.go` `Reader.Open`, `Image.Segment`, `Image.Chunk` | `TestRead_AbsentIndexIsZeros`, `TestRead_ForeignChunkFromSourcePool`, `TestRead_MissingObjectIsAnErrorNeverZeros`, `TestRead_FetchFailureAndCorruption`, `TestRead_SegmentOfAnotherShardRefused` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-CLEAN-METADATA-001` | Cleaning preserves Current and snapshot roots and their segments. Dependents keep their snapshot in HEAD. Unnamed roots go before segments and chunks; reuse defeats conditional removal. | M9 clean | `core/frontend/chunkstore/layout/remove.go`; `core/frontend/chunkstore/clean_b.go` | `TestCleanerMetadataRetainsCurrentSnapshotAndDependent`, `TestCleanerMetadataReuseDefeatsLateMarkAndDelete`, `TestCleanerRecreatesRemovedRootBeforeRenamingIt` (`core/frontend/chunkstore/layout/clean_metadata_test.go`); `TestCleaningInterruptsAfterMetadataBeforeChunks` (`core/frontend/chunkstore/clean_cursor_test.go`) | CommitReach2 CPlan, CView, LandMark, LandDel | ACTIVE | -| `INV-CLEAN-CURSOR-001` | A bounded pass resumes at its phase, shard and last completed name, wraps after the final shard, and revalidates HEAD after each parallel tag plan. Reachability uses a conservative initial root set only within one session. | M9 clean (liveness) | `core/frontend/chunkstore/clean_b.go`; `core/frontend/chunkstore/layout/remove.go` | `TestCleaningCursorResumesAfterTimeoutAndWraps` (`core/frontend/chunkstore/clean_cursor_test.go`); `TestCleanerReachableOncePerShardAndRechecksHead`, `TestCleanerPlansTagsInBoundedParallelBeforeHead` (`core/frontend/chunkstore/layout/clean_scale_test.go`) | CommitReach2 CView | ACTIVE | -| `INV-SNAPK-REMOVE-MARK-001` | A content-named object is removed only inside the holder's own cleaning, when no root in HEAD names it: tags read first, HEAD read and validated after, then a mark conditional on the tag and a delete conditional on the mark. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_RemovesOnlyWhatNoRootNames`, `TestCleaningPass_InterruptAtEveryStep`, `TestHolderFunctions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-REMOVE-STOP-001` | A reuse of an object after the plan, or after the mark, makes the remover's mark or delete fail its condition, however late it lands; an unreadable root stops the pass before any write; an open snapshot refuses it. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_ASuccessorAfterTheHeadViewDefeatsTheMark`, `TestRemoveUnreachable_ASuccessorBeforeTheHeadViewStopsThePass`, `TestRemoveUnreachable_AReuseAfterThePlanDefeatsTheMark`, `TestRemoveUnreachable_AReuseDefeatsALateMarkOrDelete`, `TestRemoveUnreachable_NothingRemovedOnAPartialView`, `TestRemoveUnreachable_RefusedOutsideItsCleaning` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-REMOVE-CONVERGE-001` | A name a cleaning marked and did not delete (the remover died in between) is planned again by the next cleaning: the re-mark replaces the old mark, so the dead remover's late delete fails, and every unreachable name goes once a cleaning completes. | M9 clean → clean | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_ReclaimsAnAbandonedMark`, `TestCleaningPass_InterruptAtEveryStep`, `TestLayoutStoreCleaningReclaimsAnAbandonedMark` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAPK-REMOVE-GUARD-001` | A source scan requires DeleteMarked as Cleaner.removePlanned's only removal, each immediately after an if on its Mark's error that leaves: an unconditional delete, an ignored mark, a reused mark or another method fails. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` (source scan of `remove.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-CLEAN-DEPENDENTS-001` | A snapshot with restore dependents never leaves HEAD through operator deletion or retention expiry/pruning; its root stays in HeadRoots, so cleaning needs no separate Dependent.Root walk. | M9 snapshot remove (K: HEAD) | `core/frontend/chunkstore/layout/snapshots.go`; `core/frontend/chunkstore/retain_b.go` | `TestSnapshotWithDependentsSurvivesEveryRemovalTransition` (`core/frontend/chunkstore/layout/snapshot_dependents_guard_test.go`); `TestDependentSnapshotSurvivesOperatorExpiryAndRetentionPrune` (`core/frontend/chunkstore/clean_dependents_test.go`) | CommitReach2 assumption A5; rows 71-75 and model-code trace | ACTIVE | +| `INV-CLEAN-SNAPSHOT-PROBE-001` | A 30-second holder probe reads only snapshot names; open local activity or a busy runtime skips the read. Missing names ask for ordinary cleaning; unknown reads imply nothing. The probe neither rolls back activity nor changes the engine view. | M9 maintenance scheduling (K: HEAD) | `core/frontend/chunkstore/layout_remote.go` `ProbeSnapshots`; `core/frontend/durable/provider_chunk.go` | `TestLayoutSnapshotProbeSkipsOpenActivityWithoutReadingHEAD` (`core/frontend/chunkstore/layout_snapshot_probe_test.go`); `TestMaintenanceNoticesSnapshotDeleteWithoutNotification` (`core/frontend/durable/maintenance_probe_test.go`) | CommitReach2 CBegin (scheduling only; BeginClean remains the idle guard) | ACTIVE | +| `INV-SCHEDULE-DUE-NOW-001` | The local opt-in due-now request queues only a running configured schedule, using its existing worker and admission. A cancelled or ended snapshot worker refuses even while the aggregate background group remains alive. | M9 scheduled capture (K: HEAD) | `core/frontend/durable/chunk_snapshot_schedule.go`; `core/host/volume/chunk_control.go` | `TestScheduledSnapshotDueNowUsesExistingLoop`, `TestScheduledSnapshotDueNowRefusesEndedWorkerWithBackgroundAlive` (`core/frontend/durable/snapshot_due_now_test.go`); `TestChunkScheduleNowRunsOnlyThroughEnabledLocalControl` (`core/host/volume/chunk_schedule_now_test.go`) | EngineAdapter.StartStop; CommitReach WCommit (ordinary capture) | ACTIVE | +| `INV-CLEAN-METADATA-001` | Cleaning preserves Current and snapshot roots and their segments. Dependents keep their snapshot in HEAD. Unnamed roots go before segments and chunks; reuse defeats conditional removal. | M9 clean | `core/frontend/chunkstore/layout/remove.go`; `core/frontend/chunkstore/clean_b.go` | `TestCleanerMetadataRetainsCurrentSnapshotAndDependent`, `TestCleanerMetadataReuseDefeatsLateMarkAndDelete`, `TestCleanerRecreatesRemovedRootBeforeRenamingIt` (`core/frontend/chunkstore/layout/clean_metadata_test.go`); `TestCleaningInterruptsAfterMetadataBeforeChunks` (`core/frontend/chunkstore/clean_cursor_test.go`) ; `TestCleaningSegmentResumeReplansRootsBeforeRemovingSegments` (`core/frontend/chunkstore/clean_cursor_test.go`) | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE | +| `INV-CLEAN-CURSOR-001` | Every new session scans roots first, preserves segment/chunk progress, and wraps after the final shard. Each page validates HEAD after parallel tags; reachability caches a conservative root set only within that session. | M9 clean (liveness) | `core/frontend/chunkstore/clean_b.go`; `core/frontend/chunkstore/layout/remove.go` | `TestCleaningCursorResumesAfterTimeoutAndWraps` (`core/frontend/chunkstore/clean_cursor_test.go`); `TestCleanerReachableOncePerShardAndRechecksHead`, `TestCleanerPlansTagsInBoundedParallelBeforeHead` (`core/frontend/chunkstore/layout/clean_scale_test.go`) | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE | +| `INV-SNAPK-REMOVE-MARK-001` | A content-named object is removed only inside the holder's own cleaning, when no root in HEAD names it: tags read first, HEAD read and validated after, then a mark conditional on the tag and a delete conditional on the mark. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_RemovesOnlyWhatNoRootNames`, `TestCleaningPass_InterruptAtEveryStep`, `TestHolderFunctions_RefuseAStaleHolder` | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE | +| `INV-SNAPK-REMOVE-STOP-001` | A reuse of an object after the plan, or after the mark, makes the remover's mark or delete fail its condition, however late it lands; an unreadable root stops the pass before any write; an open snapshot refuses it. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_ASuccessorAfterTheHeadViewDefeatsTheMark`, `TestRemoveUnreachable_ASuccessorBeforeTheHeadViewStopsThePass`, `TestRemoveUnreachable_AReuseAfterThePlanDefeatsTheMark`, `TestRemoveUnreachable_AReuseDefeatsALateMarkOrDelete`, `TestRemoveUnreachable_NothingRemovedOnAPartialView`, `TestRemoveUnreachable_RefusedOutsideItsCleaning` | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE | +| `INV-SNAPK-REMOVE-CONVERGE-001` | A name a cleaning marked and did not delete (the remover died in between) is planned again by the next cleaning: the re-mark replaces the old mark, so the dead remover's late delete fails, and every unreachable name goes once a cleaning completes. | M9 clean → clean | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_ReclaimsAnAbandonedMark`, `TestCleaningPass_InterruptAtEveryStep`, `TestLayoutStoreCleaningReclaimsAnAbandonedMark` | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE | +| `INV-SNAPK-REMOVE-GUARD-001` | A source scan requires DeleteMarked as Cleaner.removePlanned's only removal, each immediately after an if on its Mark's error that leaves: an unconditional delete, an ignored mark, a reused mark or another method fails. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` (source scan of `remove.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE | | `INV-SNAPK-REUSE-001` | Writing an object for a session creates it, or reuses an existing one by a conditional update that sets the session and clears any mark; a commit names only objects its session wrote or reused, unmarked. | M9 snap → idle (Upload, Commit) | `core/frontend/chunkstore/layout` `objects.go` `EnsureObject`; `commit.go` `RunCommit` | `TestEnsureObject`, `TestRunCommit_NeedsObjectsOfItsOwnSession`, `TestSnapshotSession_InterruptAtEveryStep`, `TestLayoutStoreCreateExistsReclaimsOnlyItsUnusedUpload`, `TestLayoutStoreCreateUnknownOutcomeKeepsItsUpload` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-START-LAYOUT-ID-001` | The launcher's full layout id must match VOLUME and HEAD, even when id8 collides; mismatch is ErrIdentity and startup exits 78 without claiming or serving. The flag comes from the master's volume record. | M9 Start refusal | `core/frontend/chunkstore/layout_create.go` `ReadVolumeRecord`; `core/frontend/chunkstore/layout_store.go` `ReadHead`; `core/frontend/durable/provider_startup.go`; `cmd/blockvolume/process_exit.go`; `core/lifecycle/workload_plan.go` | `TestLayoutIDMismatchIsTypedAndExits78`; `TestLauncherCarriesTheMasterLayoutIdentity`; `TestG15d_WorkloadPlan_BlankPoolRF2CreatesReplicaWorkloads` | K1; full identity, not the directory suffix | ACTIVE | | `INV-SNAPK-IDENTITY-001` | A volume is identified by the random id in its VOLUME record, never by its name alone; HEAD carries the volume id and refuses to encode without it. | Content-named layout; M9 every transition | `core/frontend/chunkstore/layout` `volume.go` `Volume`, `VolumeID`; `head.go` `Head.check` | `TestVolumeID_RandomAndParsed`, `TestVolume_GoldenEncodingRoundTrip`, `TestHead_GoldenEncodingRoundTrip`, `TestHead_Refusals` | — (the snapshot kernel model is not in this repository) | ACTIVE | diff --git a/seaweed-block/docs/releases/README.md b/seaweed-block/docs/releases/README.md index 9149cea04e..69db9043a0 100644 --- a/seaweed-block/docs/releases/README.md +++ b/seaweed-block/docs/releases/README.md @@ -5,6 +5,7 @@ what a user or reviewer can actually run, what QA evidence backs it, and what is still outside the supported boundary. - [v1.0.0](v1.0.0.md) +- [Planned cleaning convergence after v1.0.0](cleaning-convergence.md) - [Holder identity and pre-release upgrades](holder-identity.md) - [One live process per volume per host](one-process-per-volume.md) - [Local disk headroom at volume create](local-disk-headroom.md) diff --git a/seaweed-block/docs/releases/cleaning-convergence.md b/seaweed-block/docs/releases/cleaning-convergence.md new file mode 100644 index 0000000000..d592d0be47 --- /dev/null +++ b/seaweed-block/docs/releases/cleaning-convergence.md @@ -0,0 +1,23 @@ +# Planned cleaning changes after v1.0.0 + +These changes are proposed for v1.0.1. They are not a claim about v1.0.0 or +qualification of a published binary. The v1.0.0 release note's cleaning limits +describe that release; this change replaces those limits when it is released. + +- Cleaning removes unreferenced roots, then segments, then chunks. It no longer + waits for volume deletion to reclaim abandoned roots and segments. +- Bounded passes preserve segment and chunk shard/name progress. Every new + session first scans roots again, then resumes the cursor, and a completed pass + wraps. Space may return over several passes; a process restart resets progress. +- A snapshot with restore dependents stays in HEAD when an operator or retention + tries to delete it. Its root therefore remains reachable throughout cleaning. +- The holder notices removed snapshot names through a 30-second HEAD probe, + skipping open sessions/cleaning. The 200-volume and AG1b measurements must + report its read rate per host and filer-capacity percentage; above 1% requires + revisiting the design. +- The local opt-in schedule control can queue an immediate daily/weekly attempt + through the existing worker. Queued is not completed; an ended worker refuses. + +See [cleaning and the schedule command](../standalone-deployment.md#resuming-cleaning-passes). +Linux/race qualification and the production-layout CLI verifier evidence remain +separate gates. A live graph/count check is not a `verify`-clean result. diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index cab7cc5352..ccba22bfaf 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -816,9 +816,10 @@ passes as the cleaning cursor advances; a probe does not bypass an active cut. Each object is marked conditionally on its planned tag and deleted conditionally on that mark. An object reused by a successor defeats those late writes. -The bounded pass retains an in-process phase, shard and name cursor. Its next -pass resumes there after a timeout and wraps to the beginning after the last -shard. Restarting the process resets the cursor. Every new pass re-reads tags and +The bounded pass retains in-process segment and chunk shard/name progress. Each +new session starts at the first root before resuming that progress: a snapshot +may have been deleted since the previous session. It wraps to the beginning +after the last shard. Restarting the process resets the cursor. Every new pass re-reads tags and HEAD; the cursor carries no authority. Tag reads run with bounded concurrency, and a shard's reachable set is resolved once against that session's initial root set. Snapshot deletes keep that conservative superset until the session From 80cb6eb74aff956b2773d936512079bdfb90a618 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 28 Nov 2026 17:39:23 -0800 Subject: [PATCH 13/13] test: enumerate the snapshot probe session read --- .../core/frontend/chunkstore/layout_stop_session_test.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout_stop_session_test.go b/seaweed-block/core/frontend/chunkstore/layout_stop_session_test.go index 1610fc3921..20b34d6ad9 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_stop_session_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_stop_session_test.go @@ -30,7 +30,9 @@ func TestLayoutRemoteSessionFieldSites(t *testing.T) { // Begin returns the session it opened; CASHead checks that it survived // a concurrent operator HEAD write before retrying, and keys its skip of // the object check to the session CheckCommit checked (checked.session). - if !reflect.DeepEqual(fields, map[string]int{"openSessionLocked": 2, "rollBackLocked": 1, "Begin": 1, "PutPaced": 1, "CASHead": 5, "CheckCommit": 2, "prepareCommitLocked": 1, "CommitPendingSnapshot": 2, "writeRootLocked": 1, "Clean": 1, "syncSessionLocked": 3, "takeAbandonLocked": 1}) { + // ProbeSnapshots skips open activity + // (TestLayoutSnapshotProbeSkipsOpenActivityWithoutReadingHEAD). + if !reflect.DeepEqual(fields, map[string]int{"openSessionLocked": 2, "rollBackLocked": 1, "Begin": 1, "PutPaced": 1, "CASHead": 5, "CheckCommit": 2, "prepareCommitLocked": 1, "CommitPendingSnapshot": 2, "writeRootLocked": 1, "Clean": 1, "syncSessionLocked": 3, "takeAbandonLocked": 1, "ProbeSnapshots": 1}) { t.Fatal("session field sites changed; enumerate and probe them", fields) } }