From 4061d64b490068510dac6c4af1212fc1ab70bcee Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 19:15:01 -0800 Subject: [PATCH 01/34] storage, durable: OnPublishSettled hook after each confirmed publication Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/durable/provider.go | 6 + .../core/frontend/durable/provider_chunk.go | 10 ++ .../durable/provider_chunk_sched_test.go | 40 ++++++ seaweed-block/core/storage/chunk_base_v3.go | 4 +- seaweed-block/core/storage/chunk_layer.go | 22 +-- seaweed-block/core/storage/chunk_precopy.go | 2 +- .../core/storage/chunk_publish_settled.go | 45 ++++++ .../storage/chunk_publish_settled_test.go | 132 ++++++++++++++++++ seaweed-block/core/storage/chunk_seam.go | 7 + 9 files changed, 257 insertions(+), 11 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_publish_settled.go create mode 100644 seaweed-block/core/storage/chunk_publish_settled_test.go diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 5aa210bce9..1ee76dba1f 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -192,6 +192,12 @@ type ProviderConfig struct { // call back into the provider. OnChunkDetach func(volumeID string) uint64 OnChunkDetachResumed func(volumeID string, attempt uint64) + // ChunkOnPublishSettled, optional, is called once per confirmed + // publication of a chunk volume's HEAD, with the HEAD before and after it + // (storage.ChunkLayerConfig.OnPublishSettled). It runs on the publishing + // caller after the capture lock is released; ctx ends when the volume's + // layer closes. + ChunkOnPublishSettled func(ctx context.Context, volumeID string, prev, next storage.ChunkHead) // ChunkDirtyThreshold is the number of candidate chunks above which // a cut pre-copies (stages) chunks before its barrier, in rounds of // this size; copy-before-write copies the rest outside the barrier. diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 32e83250d0..91c3d9070a 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -374,6 +374,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h remote = &manifestBoundRemote{closeBoundRemote: bound, builder: builder} } cfg := storage.ChunkLayerConfig{ + OnPublishSettled: p.publishSettledHook(volumeID), ChunkBlocks: p.cfg.ChunkBlocks, RestoreChunkBytes: uint64(ws.BlockSize()) * uint64(p.cfg.ChunkBlocks), HeadCoolingWindow: p.cfg.ChunkHeadCoolingWindow, @@ -1104,3 +1105,12 @@ func (r *manifestBoundRemote) PrepareManifest(ctx context.Context, base, next st defer end() return r.builder.PrepareManifest(c, base, next, chunkBytes) } + +// publishSettledHook adapts ChunkOnPublishSettled to one volume's layer. +func (p *DurableProvider) publishSettledHook(volumeID string) func(context.Context, storage.ChunkHead, storage.ChunkHead) { + hook := p.cfg.ChunkOnPublishSettled + if hook == nil { + return nil + } + return func(ctx context.Context, prev, next storage.ChunkHead) { hook(ctx, volumeID, prev, next) } +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go b/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go index 6e75b9234d..3874095477 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go @@ -4,6 +4,8 @@ package durable_test import ( "context" + "fmt" + "sync" "testing" "time" @@ -162,3 +164,41 @@ func TestWALStoreChunk_StatusHasNoChunkSectionForWALStore(t *testing.T) { t.Fatalf("walstore status: %+v", st) } } + +// ChunkOnPublishSettled sees every confirmed publication of a volume, with +// its volume id and the HEAD before and after it; a no-op capture is not one. +func TestWALStoreChunk_PublishSettledHook(t *testing.T) { + remote := storage.NewMemChunkRemote() + var mu sync.Mutex + var got []string + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, + NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + ChunkOnPublishSettled: func(_ context.Context, volumeID string, prev, next storage.ChunkHead) { + mu.Lock() + got = append(got, fmt.Sprintf("%s:%d->%d", volumeID, prev.Gen, next.Gen)) + mu.Unlock() + }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + s := openRecovered(t, p) + for i, lba := range []uint32{1, 0, pcChunkBlocks + 1} { + if lba != 0 { + if _, err := s.Write(lba, block(byte(i+1))); err != nil { + t.Fatal(err) + } + } + if _, err := p.CaptureVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + } + mu.Lock() + defer mu.Unlock() + if len(got) != 2 || got[0] != "v1:0->1" || got[1] != "v1:1->2" { + t.Fatalf("reports %v; want [v1:0->1 v1:1->2] (the middle capture changed nothing)", got) + } +} diff --git a/seaweed-block/core/storage/chunk_base_v3.go b/seaweed-block/core/storage/chunk_base_v3.go index b908fe6eff..07b9190d55 100644 --- a/seaweed-block/core/storage/chunk_base_v3.go +++ b/seaweed-block/core/storage/chunk_base_v3.go @@ -29,7 +29,7 @@ func (l *chunkLayerImpl) holdBaseTransitionV3() (func(), error) { } l.stMu.Unlock() if refusal != nil { - l.capMu.Unlock() + l.unlockCap() done() return nil, fmt.Errorf("storage: BASE transition refused: %w", refusal) } @@ -56,7 +56,7 @@ func (l *chunkLayerImpl) holdBaseTransitionV3() (func(), error) { if d.BaseState == BaseInstalled && presenceDurable && l.s.OwnerChunkAttachDurableV3() { l.s.AllowBaseRetirementV3() } - l.capMu.Unlock() + l.unlockCap() done() }, nil } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 5c32d22aeb..693c09d9c4 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -69,7 +69,10 @@ type chunkLayerImpl struct { ctx context.Context // cancelled by Close cancel context.CancelFunc - wg sync.WaitGroup // captures and fills in flight + // settled: confirmed publications not yet reported to + // cfg.OnPublishSettled (stMu). + settled []headTransition + wg sync.WaitGroup // captures and fills in flight cowMu sync.Mutex // window admission only; never held during reads or joins cow *cutCOWWindow @@ -528,12 +531,12 @@ func (s *WALStore) installFetchedBlock(lba uint32, data []byte, stillAbsent func func (l *chunkLayerImpl) BeginBaseInstall() error { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() return fmt.Errorf("%w: BASE state must be published by the descriptor install protocol", errV3NotYet) } func (l *chunkLayerImpl) EndBaseInstall(frontier uint64) error { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() if cp := l.s.CheckpointLSN(); cp < frontier { return fmt.Errorf("storage: EndBaseInstall: frontier %d is not durable (checkpoint %d)", frontier, cp) } @@ -592,7 +595,7 @@ func (l *chunkLayerImpl) admit() (err error) { func (l *chunkLayerImpl) Cut(ctx context.Context) (chunkCutResult, error) { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() return l.captureLocked(ctx, false) } @@ -606,7 +609,7 @@ func (l *chunkLayerImpl) Capture(ctx context.Context) (uint64, error) { func (l *chunkLayerImpl) MakeRemoteDurable(ctx context.Context, t uint64) error { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() l.stMu.Lock() fenced, detached := l.fenced, l.detached != nil l.stMu.Unlock() @@ -1120,7 +1123,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch func (l *chunkLayerImpl) Detach(ctx context.Context) (chunkCutResult, error) { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() if r, ok := l.storedDetach(); ok { return r, nil } @@ -1141,7 +1144,7 @@ func (l *chunkLayerImpl) Detach(ctx context.Context) (chunkCutResult, error) { // successful cancel. resolvePending would re-propose the detach instead. func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (detachSettlement, chunkCutResult, error) { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() if r, ok := l.storedDetach(); ok { return detachApplied, r, nil } @@ -1198,6 +1201,7 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (detachSettlement, ch l.pendingDetach, l.pendingCut, l.pendingBase = false, chunkCutResult{}, chunkHeadVersion{} switch { case sameProposal(cur, *pending): + l.noteSettled(l.head, cur) l.head, l.remoteLSN = copyHead(cur), cur.RemoteLSN cut.Head = copyHead(cur) l.detached = &cut @@ -1326,6 +1330,7 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { l.pendingDetach, l.pendingCut, l.pendingBase = false, chunkCutResult{}, chunkHeadVersion{} switch { case sameProposal(cur, *pending): + l.noteSettled(l.head, cur) l.head, l.remoteLSN = copyHead(cur), cur.RemoteLSN if wasDetach { cut.Head = copyHead(cur) @@ -1605,6 +1610,7 @@ func (l *chunkLayerImpl) abortCut(all bool) { func (l *chunkLayerImpl) finishCut(head chunkHead, h uint64, changed []uint64, newKeys map[uint64]string) { l.stMu.Lock() defer l.stMu.Unlock() + l.noteSettled(l.head, head) l.head, l.remoteLSN, l.pending = copyHead(head), h, nil l.reusable = nil l.inflight = map[uint64]bool{} @@ -1633,7 +1639,7 @@ func isAllZero(b []byte) bool { func (l *chunkLayerImpl) EvictChunk(idx uint64) error { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() if idx >= l.numChunks { return fmt.Errorf("%w: chunk %d out of range", errChunkEvictRefused, idx) } diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index fdb1c142ed..93d9a68484 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -135,7 +135,7 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context if err := l.lockPrecopy(ctx); err != nil { return ChunkCutResult{}, err } - defer l.capMu.Unlock() + defer l.unlockCap() if err := ctx.Err(); err != nil { return ChunkCutResult{}, err } diff --git a/seaweed-block/core/storage/chunk_publish_settled.go b/seaweed-block/core/storage/chunk_publish_settled.go new file mode 100644 index 0000000000..37d20bcc8d --- /dev/null +++ b/seaweed-block/core/storage/chunk_publish_settled.go @@ -0,0 +1,45 @@ +package storage + +// headTransition is one confirmed publication: HEAD moved from prev to next. +type headTransition struct{ prev, next chunkHead } + +// noteSettled records a confirmed publication for OnPublishSettled. l.stMu +// held; prev is the HEAD the layer held before next. +func (l *chunkLayerImpl) noteSettled(prev, next chunkHead) { + if l.cfg.OnPublishSettled == nil || next.Gen == prev.Gen { // a no-op cut publishes nothing + return + } + l.settled = append(l.settled, headTransition{prev: copyHead(prev), next: copyHead(next)}) +} + +// unlockCap releases the capture lock, then reports the publications +// confirmed under it. +func (l *chunkLayerImpl) unlockCap() { + l.capMu.Unlock() + l.runPublishSettled() +} + +// runPublishSettled calls OnPublishSettled for every recorded publication, +// in publication order, outside the capture and state locks, registered with +// Close. A closing layer drops them. +func (l *chunkLayerImpl) runPublishSettled() { + hook := l.cfg.OnPublishSettled + if hook == nil { + return + } + l.stMu.Lock() + ts := l.settled + l.settled = nil + l.stMu.Unlock() + if len(ts) == 0 { + return + } + done, err := l.register() + if err != nil { + return + } + defer done() + for _, t := range ts { + hook(l.ctx, t.prev, t.next) + } +} diff --git a/seaweed-block/core/storage/chunk_publish_settled_test.go b/seaweed-block/core/storage/chunk_publish_settled_test.go new file mode 100644 index 0000000000..f2b4a12641 --- /dev/null +++ b/seaweed-block/core/storage/chunk_publish_settled_test.go @@ -0,0 +1,132 @@ +package storage + +import ( + "context" + "errors" + "sync" + "testing" +) + +type settledLog struct { + mu sync.Mutex + got [][2]uint64 // {prev gen, next gen} + // capFree records, per call, whether the capture lock was free. + capFree []bool +} + +func (s *settledLog) hook(l *chunkLayerImpl) func(context.Context, ChunkHead, ChunkHead) { + return func(_ context.Context, prev, next ChunkHead) { + free := l.capMu.TryLock() + if free { + l.capMu.Unlock() + } + s.mu.Lock() + s.got = append(s.got, [2]uint64{prev.Gen, next.Gen}) + s.capFree = append(s.capFree, free) + s.mu.Unlock() + } +} + +func (s *settledLog) snapshot() ([][2]uint64, []bool) { + s.mu.Lock() + defer s.mu.Unlock() + return append([][2]uint64(nil), s.got...), append([]bool(nil), s.capFree...) +} + +func attachWithSettled(t *testing.T, f *fakeChunkRemote) (*WALStore, *chunkLayerImpl, *settledLog) { + t.Helper() + s, _ := newChunkTestStore(t) + layer := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl) + log := &settledLog{} + layer.cfg.OnPublishSettled = log.hook(layer) + return s, layer, log +} + +// Each confirmed publication is reported once, with the HEAD before and +// after it, after the capture lock is released; a no-op cut reports nothing. +func TestChunkPublishSettled_ReportsEachPublication(t *testing.T) { + f := newFakeChunkRemote() + s, layer, log := attachWithSettled(t, f) + w := newWriteLog() + w.write(t, s, 2, 0x22) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if _, err := layer.Cut(ctTimeout(t)); err != nil { // nothing new: no-op + t.Fatal(err) + } + w.write(t, s, 9, 0x29) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + got, free := log.snapshot() + if len(got) != 2 || got[0] != [2]uint64{0, 1} || got[1] != [2]uint64{1, 2} { + t.Fatalf("reports %v; want [0->1 1->2]", got) + } + for i, ok := range free { + if !ok { + t.Fatalf("report %d ran under the capture lock", i) + } + } +} + +// A CAS whose outcome was unknown, found applied by a later cut, is reported +// when it is settled, before that cut's own publication. +func TestChunkPublishSettled_ReportsALatePublication(t *testing.T) { + f := newFakeChunkRemote() + s, layer, log := attachWithSettled(t, f) + w := newWriteLog() + w.write(t, s, 2, 0x22) + f.mu.Lock() + f.casModes = []fakeCASMode{casAppliedLost} + f.afterCAS = func(f *fakeChunkRemote) { f.failGet = errors.New("HEAD unreadable") } + f.mu.Unlock() + if _, err := layer.Cut(ctTimeout(t)); err == nil { + t.Fatal("cut with an unresolved CAS succeeded") + } + if got, _ := log.snapshot(); len(got) != 0 { + t.Fatalf("reports %v before the CAS was resolved", got) + } + f.mu.Lock() + f.failGet = nil + f.mu.Unlock() + w.write(t, s, 9, 0x29) + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + got, _ := log.snapshot() + if len(got) != 2 || got[0] != [2]uint64{0, 1} || got[1] != [2]uint64{1, 2} { + t.Fatalf("reports %v; want the late publication 0->1, then 1->2", got) + } +} + +// A closing layer drops reports it has not run; without a hook nothing is +// recorded. +func TestChunkPublishSettled_ClosedAndUnset(t *testing.T) { + f := newFakeChunkRemote() + _, layer, log := attachWithSettled(t, f) + layer.stMu.Lock() + layer.settled = append(layer.settled, headTransition{prev: chunkHead{Gen: 1}, next: chunkHead{Gen: 2}}) + layer.stMu.Unlock() + if err := layer.Close(); err != nil { + t.Fatal(err) + } + layer.runPublishSettled() + if got, _ := log.snapshot(); len(got) != 0 { + t.Fatalf("reports %v after Close", got) + } + + s2, _ := newChunkTestStore(t) + plain := mustAttach(t, s2, newFakeChunkRemote(), ctConfig(1)).(*chunkLayerImpl) + w := newWriteLog() + w.write(t, s2, 2, 0x22) + if _, err := plain.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + plain.stMu.Lock() + n := len(plain.settled) + plain.stMu.Unlock() + if n != 0 { + t.Fatalf("%d publications recorded without a hook", n) + } +} diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 2fda490f07..7acfbdf112 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -310,6 +310,13 @@ func validChunkIntentID(id string) bool { // chunkLayerConfig configures one attachment. type chunkLayerConfig struct { + // OnPublishSettled, when set, is called once per confirmed publication + // (a cut, a detach, or an earlier unresolved CAS found applied), with the + // HEAD before and after it. It runs on the publishing caller after the + // capture lock is released, in publication order, registered with Close; + // hooks of different callers may run concurrently. ctx ends with Close. + // A closing layer drops pending reports. + OnPublishSettled func(ctx context.Context, prev, next ChunkHead) // ChunkBlocks is the number of consecutive blocks per chunk (1024 for // 4 KiB blocks and 4 MiB chunks). ChunkBlocks uint32 From 4d7cea7d869a3202b597189b512889fcdd9e3ee1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 19:35:07 -0800 Subject: [PATCH 02/34] storage: deliver publication reports serialized and in order; Close drops the rest Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_layer.go | 8 +- .../core/storage/chunk_publish_settled.go | 54 +++-- .../storage/chunk_publish_settled_test.go | 184 ++++++++++++++++++ seaweed-block/core/storage/chunk_seam.go | 10 +- 4 files changed, 231 insertions(+), 25 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 693c09d9c4..2d507a3c9a 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -70,9 +70,11 @@ type chunkLayerImpl struct { ctx context.Context // cancelled by Close cancel context.CancelFunc // settled: confirmed publications not yet reported to - // cfg.OnPublishSettled (stMu). - settled []headTransition - wg sync.WaitGroup // captures and fills in flight + // cfg.OnPublishSettled, in publication order; settledDraining: a caller + // is delivering them (both stMu). + settled []headTransition + settledDraining bool + wg sync.WaitGroup // captures and fills in flight cowMu sync.Mutex // window admission only; never held during reads or joins cow *cutCOWWindow diff --git a/seaweed-block/core/storage/chunk_publish_settled.go b/seaweed-block/core/storage/chunk_publish_settled.go index 37d20bcc8d..fe41e34512 100644 --- a/seaweed-block/core/storage/chunk_publish_settled.go +++ b/seaweed-block/core/storage/chunk_publish_settled.go @@ -3,8 +3,9 @@ package storage // headTransition is one confirmed publication: HEAD moved from prev to next. type headTransition struct{ prev, next chunkHead } -// noteSettled records a confirmed publication for OnPublishSettled. l.stMu -// held; prev is the HEAD the layer held before next. +// noteSettled records a confirmed publication for OnPublishSettled, in +// publication order. l.stMu held; prev is the HEAD the layer held before +// next. func (l *chunkLayerImpl) noteSettled(prev, next chunkHead) { if l.cfg.OnPublishSettled == nil || next.Gen == prev.Gen { // a no-op cut publishes nothing return @@ -12,34 +13,51 @@ func (l *chunkLayerImpl) noteSettled(prev, next chunkHead) { l.settled = append(l.settled, headTransition{prev: copyHead(prev), next: copyHead(next)}) } -// unlockCap releases the capture lock, then reports the publications -// confirmed under it. +// unlockCap releases the capture lock, then delivers the publications +// recorded so far. func (l *chunkLayerImpl) unlockCap() { l.capMu.Unlock() l.runPublishSettled() } -// runPublishSettled calls OnPublishSettled for every recorded publication, -// in publication order, outside the capture and state locks, registered with -// Close. A closing layer drops them. +// runPublishSettled delivers recorded publications to OnPublishSettled one +// at a time, in publication order, outside the capture and state locks. One +// caller at a time drains the queue (any other caller only leaves its +// reports queued for it, so a hook that publishes again cannot deadlock); +// the drainer is registered with Close. Once Close has begun, no further +// report is delivered: the rest are dropped. func (l *chunkLayerImpl) runPublishSettled() { hook := l.cfg.OnPublishSettled if hook == nil { return } l.stMu.Lock() - ts := l.settled - l.settled = nil + if l.settledDraining || len(l.settled) == 0 { + l.stMu.Unlock() + return + } + if l.closed { + l.settled = nil + l.stMu.Unlock() + return + } + l.settledDraining = true + l.wg.Add(1) // under stMu while not closed: Close's wait covers this drain l.stMu.Unlock() - if len(ts) == 0 { - return - } - done, err := l.register() - if err != nil { - return - } - defer done() - for _, t := range ts { + defer l.wg.Done() + for { + l.stMu.Lock() + if l.closed { + l.settled = nil + } + if len(l.settled) == 0 { + l.settledDraining = false + l.stMu.Unlock() + return + } + t := l.settled[0] + l.settled = l.settled[1:] + l.stMu.Unlock() hook(l.ctx, t.prev, t.next) } } diff --git a/seaweed-block/core/storage/chunk_publish_settled_test.go b/seaweed-block/core/storage/chunk_publish_settled_test.go index f2b4a12641..2e03073d42 100644 --- a/seaweed-block/core/storage/chunk_publish_settled_test.go +++ b/seaweed-block/core/storage/chunk_publish_settled_test.go @@ -5,6 +5,7 @@ import ( "errors" "sync" "testing" + "time" ) type settledLog struct { @@ -130,3 +131,186 @@ func TestChunkPublishSettled_ClosedAndUnset(t *testing.T) { t.Fatalf("%d publications recorded without a hook", n) } } + +func waitClosed(t *testing.T, ch <-chan struct{}, what string) { + t.Helper() + select { + case <-ch: + case <-time.After(10 * time.Second): + t.Fatalf("timed out waiting for %s", what) + } +} + +// Overlapping publishers: while the first report's hook is held, a second +// publisher's cut completes and returns; its report is delivered after the +// first, never concurrently with it. +func TestChunkPublishSettled_OverlappingPublishersStayOrdered(t *testing.T) { + f := newFakeChunkRemote() + s, _ := newChunkTestStore(t) + layer := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl) + entered, release := make(chan struct{}), make(chan struct{}) + var once, rel sync.Once + t.Cleanup(func() { rel.Do(func() { close(release) }) }) + var mu sync.Mutex + var got [][2]uint64 + active, maxActive := 0, 0 + layer.cfg.OnPublishSettled = func(_ context.Context, prev, next ChunkHead) { + mu.Lock() + active++ + maxActive = max(maxActive, active) + got = append(got, [2]uint64{prev.Gen, next.Gen}) + first := len(got) == 1 + mu.Unlock() + if first { + once.Do(func() { close(entered) }) + <-release + } + mu.Lock() + active-- + mu.Unlock() + } + w := newWriteLog() + w.write(t, s, 2, 0x22) + aDone := make(chan error, 1) + go func() { _, err := layer.Cut(context.Background()); aDone <- err }() + t.Cleanup(func() { + rel.Do(func() { close(release) }) + select { + case <-aDone: + case <-time.After(10 * time.Second): + t.Error("the first publisher never returned") + } + }) + waitClosed(t, entered, "the first report") + w.write(t, s, 9, 0x29) + bDone := make(chan error, 1) + go func() { _, err := layer.Cut(context.Background()); bDone <- err }() + select { + case err := <-bDone: + if err != nil { + t.Fatal(err) + } + case <-time.After(10 * time.Second): + t.Fatal("the second publisher waited on the first report's hook") + } + mu.Lock() + n := len(got) + mu.Unlock() + if n != 1 { + t.Fatalf("%d reports delivered while the first was held; want 1", n) + } + rel.Do(func() { close(release) }) + select { + case err := <-aDone: + aDone <- err + if err != nil { + t.Fatal(err) + } + case <-time.After(10 * time.Second): + t.Fatal("the first publisher did not finish") + } + mu.Lock() + defer mu.Unlock() + if len(got) != 2 || got[0] != [2]uint64{0, 1} || got[1] != [2]uint64{1, 2} || maxActive != 1 { + t.Fatalf("reports %v (max concurrent %d); want [0->1 1->2], one at a time", got, maxActive) + } +} + +// Close during the first of two queued reports: the first hook sees its +// context end, Close waits for it, and the second report is never delivered. +func TestChunkPublishSettled_CloseDropsUnstartedReports(t *testing.T) { + f := newFakeChunkRemote() + s, _ := newChunkTestStore(t) + layer := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl) + entered, release := make(chan struct{}), make(chan struct{}) + var rel sync.Once + t.Cleanup(func() { rel.Do(func() { close(release) }) }) + var hookCtx context.Context + var mu sync.Mutex + calls := 0 + layer.cfg.OnPublishSettled = func(ctx context.Context, _, _ ChunkHead) { + mu.Lock() + calls++ + n := calls + mu.Unlock() + if n == 1 { + hookCtx = ctx + close(entered) + <-release + } + } + layer.stMu.Lock() + layer.settled = append(layer.settled, headTransition{prev: chunkHead{Gen: 0}, next: chunkHead{Gen: 1}}, headTransition{prev: chunkHead{Gen: 1}, next: chunkHead{Gen: 2}}) + layer.stMu.Unlock() + drained := make(chan struct{}) + go func() { layer.runPublishSettled(); close(drained) }() + waitClosed(t, entered, "the first report") + closeDone := make(chan error, 1) + go func() { closeDone <- layer.Close() }() + t.Cleanup(func() { + rel.Do(func() { close(release) }) + select { + case <-closeDone: + case <-time.After(10 * time.Second): + t.Error("Close never returned") + } + }) + waitClosed(t, hookCtx.Done(), "Close cancelling the hook's context") + select { + case err := <-closeDone: + closeDone <- err + t.Fatal("Close returned while a report hook was running") + case <-time.After(200 * time.Millisecond): + } + rel.Do(func() { close(release) }) + waitClosed(t, drained, "the drain to end") + select { + case err := <-closeDone: + closeDone <- err + if err != nil { + t.Fatal(err) + } + case <-time.After(10 * time.Second): + t.Fatal("Close did not return") + } + mu.Lock() + defer mu.Unlock() + if calls != 1 { + t.Fatalf("%d reports delivered; want the second dropped after Close began", calls) + } +} + +// A hook may publish again: its own report follows, in order, with no +// deadlock. +func TestChunkPublishSettled_HookThatPublishes(t *testing.T) { + f := newFakeChunkRemote() + s, _ := newChunkTestStore(t) + layer := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl) + w := newWriteLog() + var got [][2]uint64 + nested := false + layer.cfg.OnPublishSettled = func(ctx context.Context, prev, next ChunkHead) { + got = append(got, [2]uint64{prev.Gen, next.Gen}) + if !nested { + nested = true + w.write(t, s, 9, 0x29) + if _, err := layer.Cut(ctx); err != nil { + t.Errorf("cut from the hook: %v", err) + } + } + } + w.write(t, s, 2, 0x22) + done := make(chan error, 1) + go func() { _, err := layer.Cut(context.Background()); done <- err }() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(10 * time.Second): + t.Fatal("a hook that publishes deadlocked") + } + if len(got) != 2 || got[0] != [2]uint64{0, 1} || got[1] != [2]uint64{1, 2} { + t.Fatalf("reports %v; want [0->1 1->2]", got) + } +} diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 7acfbdf112..ec35ea5f1c 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -312,10 +312,12 @@ func validChunkIntentID(id string) bool { type chunkLayerConfig struct { // OnPublishSettled, when set, is called once per confirmed publication // (a cut, a detach, or an earlier unresolved CAS found applied), with the - // HEAD before and after it. It runs on the publishing caller after the - // capture lock is released, in publication order, registered with Close; - // hooks of different callers may run concurrently. ctx ends with Close. - // A closing layer drops pending reports. + // HEAD before and after it. Calls are serialized and in publication + // order, outside the capture lock, on whichever publishing caller is + // draining the reports (a publisher may return before its own report is + // delivered by the drainer). The drainer is registered with Close; ctx + // ends with Close, and once Close has begun no further report is + // delivered. A hook may publish again (its report is delivered after). OnPublishSettled func(ctx context.Context, prev, next ChunkHead) // ChunkBlocks is the number of consecutive blocks per chunk (1024 for // 4 KiB blocks and 4 MiB chunks). From 29dab5e1d71e3c16ca0c020177c00f5e69a9730c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 19:35:08 -0800 Subject: [PATCH 03/34] chunkstore: ShareGuard seam for snapshot and fork (no-op by default) Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/catalog.go | 29 ++++ .../core/frontend/chunkstore/share_guard.go | 61 +++++++ .../frontend/chunkstore/share_guard_test.go | 164 ++++++++++++++++++ .../core/host/volume/chunk_control.go | 8 + .../host/volume/chunk_control_order_test.go | 35 ++++ 5 files changed, 297 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/share_guard.go create mode 100644 seaweed-block/core/frontend/chunkstore/share_guard_test.go diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index eb6fd6f4eb..3c872c4d09 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -250,6 +250,11 @@ type SnapshotRequest struct { // SourceReadAt is when the caller obtained the HEAD it snapshots (the // cut's return); OpDeadline counts from it. Zero means now. SourceReadAt time.Time + // ShareToken is the ShareGuard token of a caller that began the share + // before it obtained the HEAD (the owner's seal: Begin, then the cut). + // Empty: CreateSnapshot begins the share itself and refuses a HEAD that + // is no longer current. Unused without a guard; never stored. + ShareToken string } // ListOptions pages a snapshot listing. @@ -295,6 +300,8 @@ type Catalog struct { // retainHook, when set, runs at the named stages of a Retain pass (a // test seam for interleavings; see hookPlanned). retainHook func(stage, name string) + // guard, when set, is told about every share of a volume's chunks. + guard ShareGuard } // NewCatalog returns the catalog for the chunk base directory base (the @@ -859,6 +866,12 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe if !ok { return SnapshotInfo{}, catErr(CodeNotChunkVolume, false, nil, "volume %s has no VOLUME entry", vol) } + shareToken := req.ShareToken + if shareToken == "" { + if shareToken, err = c.beginShare(ctx, vol, head); err != nil { + return SnapshotInfo{}, err + } + } // Take the name: this request's record, or an earlier attempt's of it. attempt, err := c.claimName(ctx, vol, root, req, head.Gen) @@ -919,6 +932,11 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe return SnapshotInfo{}, catErr(CodeDeadlineExceeded, true, nil, "snapshot %s/%s: %v since the cut, over the %v deadline; nothing written", vol, req.Name, c.now().Sub(readAt), c.deadline()) } dir := path.Join(root, snapsDir, req.Name) + if err := c.finishShare(ctx, vol, shareToken, head); err != nil { + // Clean abort: the snapshot entry was never sent. + c.dropIntent(ctx, root, id) + return SnapshotInfo{}, err + } pctx, cancel := c.publishCtx(ctx, deadline) outcome, got, cerr := c.createResolved(ctx, pctx, dir, e, attempt) cancel() @@ -1223,6 +1241,12 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) // write on the parent attempt's entry, which retention's delete mark // is conditioned against (see retention.go). readAt := c.now() + var shareToken string + if c.guard != nil { // the shared HEAD is the snapshot's, read below + if shareToken, err = c.guard.Begin(ctx, req.Source); err != nil { + return ForkResult{}, remoteErr(err, "share guard for %s", req.Source) + } + } snap, err := c.claimForkParent(ctx, req) if err != nil { return ForkResult{}, err @@ -1313,6 +1337,11 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) c.dropIntent(ctx, dstRoot, id) return ForkResult{}, catErr(CodeDeadlineExceeded, true, nil, "fork %s: %v since reading the snapshot, over the %v deadline; HEAD not written", req.Target, c.now().Sub(readAt), c.deadline()) } + if err := c.finishShare(ctx, req.Source, shareToken, src); err != nil { + // Clean abort: HEAD was never sent. + c.dropIntent(ctx, dstRoot, id) + return ForkResult{}, err + } // Under this request's VOLUME only this request's attempts write HEAD // (attach refuses a fork without HEAD), so a HEAD found there completes // the fork; if it is another attempt's and this create is unsettled, diff --git a/seaweed-block/core/frontend/chunkstore/share_guard.go b/seaweed-block/core/frontend/chunkstore/share_guard.go new file mode 100644 index 0000000000..1f4ba19c7c --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/share_guard.go @@ -0,0 +1,61 @@ +package chunkstore + +import ( + "context" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// ShareGuard is told about every sharer of a volume's chunks. A snapshot or +// fork calls Begin before it obtains the HEAD it will reference, and Finish, +// with that HEAD, right before it activates its result; an error from either +// aborts the share before anything is activated. A token Begin returned and +// nobody finished is the guard's to expire. +// +// No guard (the default) changes nothing: no call is made and no check is +// added. +type ShareGuard interface { + Begin(ctx context.Context, vol string) (token string, err error) + Finish(ctx context.Context, vol, token string, head storage.ChunkHead) error +} + +// SetShareGuard installs g (nil removes it). Set it before the catalog is +// used. +func (c *Catalog) SetShareGuard(g ShareGuard) { c.guard = g } + +// ShareGuard returns the installed guard, or nil. +func (c *Catalog) ShareGuard() ShareGuard { return c.guard } + +// beginShare starts a share of vol's chunks for a caller that passes the +// HEAD in: with a guard, it begins the share, then refuses unless head is +// still vol's current HEAD (a share that obtained an older HEAD could +// reference chunks superseded meanwhile). token is "" without a guard. +func (c *Catalog) beginShare(ctx context.Context, vol string, head storage.ChunkHead) (token string, err error) { + if c.guard == nil { + return "", nil + } + token, err = c.guard.Begin(ctx, vol) + if err != nil { + return "", remoteErr(err, "share guard for %s", vol) + } + cur, ok, err := c.ReadHead(ctx, vol) + if err != nil { + return "", err + } + if !ok || cur.Gen != head.Gen || cur.Epoch != head.Epoch { + return "", catErr(CodeOutcomeUnknown, true, nil, "volume %s: the HEAD to share (gen %d) is no longer current (gen %d); retry", vol, head.Gen, cur.Gen) + } + return token, nil +} + +// finishShare finishes a share before its result is activated; no-op +// without a guard. +func (c *Catalog) finishShare(ctx context.Context, vol, token string, head storage.ChunkHead) error { + if c.guard == nil { + return nil + } + if err := c.guard.Finish(ctx, vol, token, head); err != nil { + return remoteErr(err, "share guard for %s refused the share", vol) + } + return nil +} diff --git a/seaweed-block/core/frontend/chunkstore/share_guard_test.go b/seaweed-block/core/frontend/chunkstore/share_guard_test.go new file mode 100644 index 0000000000..42b839a9d1 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/share_guard_test.go @@ -0,0 +1,164 @@ +package chunkstore + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// recGuard records Begin and Finish; onFinish runs inside Finish. +type recGuard struct { + mu sync.Mutex + events []string + n int + finishErr error + onFinish func() +} + +func (g *recGuard) Begin(_ context.Context, vol string) (string, error) { + g.mu.Lock() + defer g.mu.Unlock() + g.n++ + g.events = append(g.events, "begin:"+vol) + return fmt.Sprintf("tok-%d", g.n), nil +} + +func (g *recGuard) Finish(_ context.Context, vol, token string, head storage.ChunkHead) error { + if g.onFinish != nil { + g.onFinish() + } + g.mu.Lock() + defer g.mu.Unlock() + g.events = append(g.events, fmt.Sprintf("finish:%s:%s:%d", vol, token, head.Gen)) + return g.finishErr +} + +func (g *recGuard) list() []string { + g.mu.Lock() + defer g.mu.Unlock() + return append([]string(nil), g.events...) +} + +func countUnder(f *fakeFiler, prefix string) int { + f.mu.Lock() + defer f.mu.Unlock() + n := 0 + for k := range f.entries { + if strings.HasPrefix(k, prefix) { + n++ + } + } + return n +} + +// A snapshot of a passed-in HEAD begins the share, checks the HEAD is still +// current, and finishes it before the snapshot entry is written. +func TestShareGuard_SnapshotFinishesBeforeActivation(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + g := &recGuard{} + g.onFinish = func() { + if n := countUnder(f, catBase+"/v1/snaps/s1/"); n != 0 { + t.Errorf("snapshot entry written before Finish (%d entries)", n) + } + } + c.SetShareGuard(g) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + want := []string{"begin:v1", fmt.Sprintf("finish:v1:tok-1:%d", h.Gen)} + if got := g.list(); len(got) != 2 || got[0] != want[0] || got[1] != want[1] { + t.Fatalf("guard events %v; want %v", got, want) + } + if countUnder(f, catBase+"/v1/snaps/s1/") == 0 { + t.Fatal("snapshot not written after a successful Finish") + } +} + +// A refused Finish aborts the snapshot: nothing activated, its intent dropped. +func TestShareGuard_RefusedFinishAbortsTheSnapshot(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + intents := countUnder(f, catBase+"/v1/intents/") + c.SetShareGuard(&recGuard{finishErr: errors.New("token expired")}) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err == nil { + t.Fatal("snapshot activated after a refused Finish") + } + if n := countUnder(f, catBase+"/v1/snaps/s1/"); n != 0 { + t.Fatalf("%d snapshot entries after a refused Finish", n) + } + if n := countUnder(f, catBase+"/v1/intents/"); n != intents { + t.Fatalf("intents %d -> %d; want the snapshot's intent dropped", intents, n) + } +} + +// A passed-in HEAD that is no longer current is refused before Finish. +func TestShareGuard_StaleHeadIsRefused(t *testing.T) { + f, b, c, h := catalogFixture(t) + ctx := context.Background() + publishSource(t, f, b, "v1", map[uint64][]byte{5: chunkBytes(0x20)}) // HEAD moves on + g := &recGuard{} + c.SetShareGuard(g) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err == nil { + t.Fatal("snapshot of a superseded HEAD accepted with a guard") + } + for _, e := range g.list() { + if strings.HasPrefix(e, "finish:") { + t.Fatalf("Finish called for a refused share: %v", g.list()) + } + } + if n := countUnder(f, catBase+"/v1/snaps/s1/"); n != 0 { + t.Fatalf("%d snapshot entries for a refused share", n) + } +} + +// A caller that began the share itself passes its token: no second Begin. +func TestShareGuard_CallerToken(t *testing.T) { + _, _, c, h := catalogFixture(t) + g := &recGuard{} + c.SetShareGuard(g) + if _, err := c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "s1", RequestID: "r", ShareToken: "owner-tok"}, h); err != nil { + t.Fatal(err) + } + if got := g.list(); len(got) != 1 || got[0] != fmt.Sprintf("finish:v1:owner-tok:%d", h.Gen) { + t.Fatalf("guard events %v; want only Finish with the caller's token", got) + } +} + +// A fork begins the share before reading the snapshot and finishes it with +// the snapshot's HEAD before writing the child's HEAD; a refused Finish +// writes no child HEAD. +func TestShareGuard_Fork(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + g := &recGuard{} + g.onFinish = func() { + if countUnder(f, catBase+"/v2/HEAD") != 0 { + t.Error("child HEAD written before Finish") + } + } + c.SetShareGuard(g) + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork-1"}); err != nil { + t.Fatal(err) + } + want := []string{"begin:v1", fmt.Sprintf("finish:v1:tok-1:%d", h.Gen)} + if got := g.list(); len(got) != 2 || got[0] != want[0] || got[1] != want[1] { + t.Fatalf("guard events %v; want %v", got, want) + } + + c.SetShareGuard(&recGuard{finishErr: errors.New("token expired")}) + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "fork-2"}); err == nil { + t.Fatal("fork activated after a refused Finish") + } + if countUnder(f, catBase+"/v3/HEAD") != 0 { + t.Fatal("child HEAD written after a refused Finish") + } +} diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 3308ce2d34..3ecce1b157 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -578,6 +578,14 @@ func (c *chunkControl) Snapshot(ctx context.Context, volumeID string, req ChunkS if info, replayed, err := c.cat.SnapshotReplay(ctx, volumeID, sreq); err != nil || replayed { return info, err } + // The share begins before the cut that produces the sealed HEAD. + if g := c.cat.ShareGuard(); g != nil { + token, err := g.Begin(ctx, volumeID) + if err != nil { + return chunkstore.SnapshotInfo{}, err + } + sreq.ShareToken = token + } // A named seal is urgent even without a minimum LSN. r, err := c.p.CutVolume(hostlimit.WithClass(ctx, hostlimit.Urgent), volumeID, 0) if err != nil { diff --git a/seaweed-block/core/host/volume/chunk_control_order_test.go b/seaweed-block/core/host/volume/chunk_control_order_test.go index 87f19228ea..46d9c288fd 100644 --- a/seaweed-block/core/host/volume/chunk_control_order_test.go +++ b/seaweed-block/core/host/volume/chunk_control_order_test.go @@ -96,3 +96,38 @@ func TestChunkControl_InvalidLabelRefusedBeforeCutting(t *testing.T) { t.Fatalf("snapshot with an invalid label: %v (cuts %d); want invalid_label without a cut", err, fp.cuts) } } + +// ownerGuard records, at Begin, how many cuts the provider had taken. +type ownerGuard struct { + cutsAtBegin []int + finishes []string + fp *fakeChunkProvider +} + +func (g *ownerGuard) Begin(context.Context, string) (string, error) { + g.cutsAtBegin = append(g.cutsAtBegin, g.fp.cuts) + return "owner", nil +} + +func (g *ownerGuard) Finish(_ context.Context, vol, token string, head storage.ChunkHead) error { + g.finishes = append(g.finishes, vol+":"+token) + return nil +} + +// The owner's seal begins the share BEFORE the cut that produces the sealed +// HEAD, and the catalog finishes it with that token (no second Begin). +func TestChunkControl_SnapshotBeginsShareBeforeTheCut(t *testing.T) { + ctx := context.Background() + fp, ctl := adapterFixture(t) + g := &ownerGuard{fp: fp} + ctl.(*chunkControl).cat.SetShareGuard(g) + if _, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r"}); err != nil { + t.Fatal(err) + } + if len(g.cutsAtBegin) != 1 || g.cutsAtBegin[0] != 0 || fp.cuts != 1 { + t.Fatalf("Begin saw %v cuts (cuts now %d); want one Begin before the one cut", g.cutsAtBegin, fp.cuts) + } + if len(g.finishes) != 1 || g.finishes[0] != "v1:owner" { + t.Fatalf("finishes %v; want one Finish with the owner's token", g.finishes) + } +} From b657923019057c54e217f59ae157ecf9ea90d71d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 19:35:08 -0800 Subject: [PATCH 04/34] chunkstore: export GC's per-key reclaim step as ChunkRemote.ReclaimKey Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/chunk_remote.go | 26 ++++++++++ seaweed-block/core/frontend/chunkstore/gc.go | 46 +++++++++++------- .../frontend/chunkstore/reclaim_key_test.go | 47 +++++++++++++++++++ 3 files changed, 102 insertions(+), 17 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/reclaim_key_test.go diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index 4c8dcc5da0..45b932b572 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -218,6 +218,32 @@ func (r *ChunkRemote) Get(ctx context.Context, key string) ([]byte, error) { return r.b.Get(ctx, fid) } +// ReclaimKey deletes the needle bound to one of this volume's own keys +// with GC's step (reclaimBinding): the binding is tombstoned, the exact fid +// deleted, the binding kept for ever and marked done. It decides nothing: +// the caller must know that no HEAD, snapshot, fork or intent references +// key. An owner-qualified key is refused. +func (r *ChunkRemote) ReclaimKey(ctx context.Context, key string, blobs BlobDeleter) error { + if err := storage.ValidChunkKey(key); err != nil { + return fmt.Errorf("%w: %v", ErrInvalidKey, err) + } + if strings.HasPrefix(key, "@") { + return fmt.Errorf("%w: %q is owner-qualified; a volume reclaims only its own keys", ErrInvalidKey, key) + } + name, err := keyName(key) + if err != nil { + return err + } + e, err := r.f.LookupEntry(ctx, r.keyDir(), name) + if err != nil { + return fmt.Errorf("chunkstore: chunk key %q: %w", key, err) + } + if len(e.GetChunks()) != 0 || string(e.Extended[extKind]) != kindChunkKey || len(e.Extended[extFid]) == 0 { + return fmt.Errorf("chunkstore: chunk key %q: entry is not a chunk key binding", key) + } + return reclaimBinding(ctx, r.f, blobs, r.keyDir(), e) +} + // Delete is not supported; see ErrDeleteUnsupported. func (r *ChunkRemote) Delete(context.Context, string) error { return ErrDeleteUnsupported } diff --git a/seaweed-block/core/frontend/chunkstore/gc.go b/seaweed-block/core/frontend/chunkstore/gc.go index 7e8bf522f5..7d6e23111d 100644 --- a/seaweed-block/core/frontend/chunkstore/gc.go +++ b/seaweed-block/core/frontend/chunkstore/gc.go @@ -331,23 +331,7 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e if err = ctx.Err(); err != nil { return result, err } - // Preserve the immutable binding forever: removing it would allow Put - // to rebind a key that once existed. The tombstone also permits retry - // after a failed physical delete without losing the fid. - if string(b.entry.Extended[extGCDeleted]) != "1" { - e := proto.Clone(b.entry).(*filerpb.Entry) - e.Extended[extGCDeleted] = []byte("1") - expected := map[string][]byte{extKind: []byte(kindChunkKey), extFid: b.entry.Extended[extFid], extGCDeleted: nil} - if err = g.cat.f.UpdateEntry(ctx, path.Dir(p), e, expected); err != nil { - return result, err - } - } - if err = g.blobs.DeleteBlob(ctx, string(b.entry.Extended[extFid])); err != nil { - return result, err - } - e := proto.Clone(b.entry).(*filerpb.Entry) - e.Extended[extGCDeleted] = []byte("done") - if err = g.cat.f.UpdateEntry(ctx, path.Dir(p), e, map[string][]byte{extFid: b.entry.Extended[extFid], extGCDeleted: []byte("1")}); err != nil { + if err = reclaimBinding(ctx, g.cat.f, g.blobs, path.Dir(p), b.entry); err != nil { return result, err } result.Reclaimed++ @@ -388,3 +372,31 @@ func (b gcBlobReader) Get(ctx context.Context, fid string) ([]byte, error) { } return reader.Get(ctx, fid) } + +// reclaimBinding deletes the needle a key binding names, keeping the binding +// for ever: removing it would allow Put to rebind a key that once existed. +// The binding first gets a conditional swb.gc.deleted=1 tombstone (which +// also lets a failed physical delete be retried without losing the fid), +// then the exact fid is deleted, then the tombstone becomes done. A binding +// already done is left as it is. The caller decides that nothing references +// the key. +func reclaimBinding(ctx context.Context, f Filer, blobs BlobDeleter, dir string, entry *filerpb.Entry) error { + switch string(entry.Extended[extGCDeleted]) { + case "done": + return nil + case "1": + default: + e := proto.Clone(entry).(*filerpb.Entry) + e.Extended[extGCDeleted] = []byte("1") + expected := map[string][]byte{extKind: []byte(kindChunkKey), extFid: entry.Extended[extFid], extGCDeleted: nil} + if err := f.UpdateEntry(ctx, dir, e, expected); err != nil { + return err + } + } + if err := blobs.DeleteBlob(ctx, string(entry.Extended[extFid])); err != nil { + return err + } + e := proto.Clone(entry).(*filerpb.Entry) + e.Extended[extGCDeleted] = []byte("done") + return f.UpdateEntry(ctx, dir, e, map[string][]byte{extFid: entry.Extended[extFid], extGCDeleted: []byte("1")}) +} diff --git a/seaweed-block/core/frontend/chunkstore/reclaim_key_test.go b/seaweed-block/core/frontend/chunkstore/reclaim_key_test.go new file mode 100644 index 0000000000..25acbb33d0 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/reclaim_key_test.go @@ -0,0 +1,47 @@ +package chunkstore + +import ( + "context" + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// ReclaimKey is GC's step for one own key: the binding is tombstoned and +// kept, the needle deleted; repeating it is a no-op; a qualified key is +// refused. +func TestChunkRemote_ReclaimKey(t *testing.T) { + f, b := newFakeFiler(), newFakeBlobs() + r, err := NewChunkRemote(f, b, catBase+"/v1") + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + if err := r.Put(ctx, "k1", []byte("payload")); err != nil { + t.Fatal(err) + } + fid := r.fids["k1"] + if err := r.ReclaimKey(ctx, "k1", gcBlobs{b}); err != nil { + t.Fatal(err) + } + e, err := f.LookupEntry(ctx, r.keyDir(), "k1") + if err != nil { + t.Fatalf("binding removed: %v", err) + } + if string(e.Extended[extGCDeleted]) != "done" || string(e.Extended[extFid]) != fid { + t.Fatalf("binding after reclaim: %q fid %q; want done, same fid", e.Extended[extGCDeleted], e.Extended[extFid]) + } + if _, err := b.Get(ctx, fid); err == nil { + t.Fatal("needle still readable after reclaim") + } + if err := r.ReclaimKey(ctx, "k1", gcBlobs{b}); err != nil { + t.Fatalf("repeated reclaim: %v", err) + } + if err := r.Put(ctx, "k1", []byte("again")); !errors.Is(err, storage.ErrChunkKeyExists) { + t.Fatalf("rebinding a reclaimed key: %v", err) + } + if err := r.ReclaimKey(ctx, "@v0/k1", gcBlobs{b}); err == nil { + t.Fatal("reclaim of an owner-qualified key accepted") + } +} From 591a5a3b1c19d3686db611ccf4596d6fe0efbf31 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 20:08:27 -0800 Subject: [PATCH 05/34] chunkstore, sw-block: verify the remote image against HEAD and snapshots Add Catalog.Verify and 'sw-block ops chunk verify': a read-only check of a volume's remote image at three depths (meta, bindings, data). GC's mark does not look up the bindings of the keys it roots and never reads chunk data, so a missing binding or a damaged needle was found only by a guest read. A miss is reported only if its root still names the chunk: verify re-reads HEAD (superseded during verify) or the snapshot attempt (root deleted during verify) before reporting, since a pass can outlive GC's grace. A needle is NEEDLE_MISSING only when the store answers not found; any other read failure is retried and then reported as READ_ERROR (not verified). Exit code 3 means the pass completed with findings. The single-filer start check now also runs in the shared dial path of the 'ops chunk' commands and in gc. Co-Authored-By: Claude Fable 5.2 --- seaweed-block/README.md | 1 + seaweed-block/cmd/sw-block/chunk.go | 31 +- seaweed-block/cmd/sw-block/chunk_gc.go | 3 + .../sw-block/chunk_manifest_fixture_test.go | 2 +- seaweed-block/cmd/sw-block/chunk_verify.go | 154 ++ .../cmd/sw-block/chunk_verify_test.go | 245 +++ seaweed-block/cmd/sw-block/main.go | 2 + seaweed-block/core/frontend/chunkstore/GC.md | 120 ++ .../core/frontend/chunkstore/fake_test.go | 2 +- .../core/frontend/chunkstore/remote.go | 8 +- .../core/frontend/chunkstore/swfs.go | 26 +- .../core/frontend/chunkstore/verify.go | 1365 +++++++++++++++++ .../core/frontend/chunkstore/verify_test.go | 942 ++++++++++++ 13 files changed, 2893 insertions(+), 8 deletions(-) create mode 100644 seaweed-block/cmd/sw-block/chunk_verify.go create mode 100644 seaweed-block/cmd/sw-block/chunk_verify_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/verify.go create mode 100644 seaweed-block/core/frontend/chunkstore/verify_test.go diff --git a/seaweed-block/README.md b/seaweed-block/README.md index d5f6be76d4..9921dedaa4 100644 --- a/seaweed-block/README.md +++ b/seaweed-block/README.md @@ -131,6 +131,7 @@ sw-block ops chunk fork --chunk-filer --source v1 --snapshot s1 --t sw-block ops chunk detach --volume v1 --status-addr # final cut and release; resume elsewhere sw-block ops chunk volume-delete --volume v2 --chunk-filer --master --request-id del-v2 sw-block ops chunk gc --chunk-filer --master # preview; --apply to reclaim +sw-block ops chunk verify --volume v1 --chunk-filer # read-only check of the remote image ``` `volume-delete` is refused while the volume is attached or has snapshots. diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go index ec9ac529ab..c828d5149b 100644 --- a/seaweed-block/cmd/sw-block/chunk.go +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -28,23 +28,44 @@ import ( ) const ( - chunkExitFailed = 1 + chunkExitFailed = 1 + // chunkExitFindings: the command completed and found problems (verify). + chunkExitFindings = 3 defaultChunkPathCLI = "/swblock/chunks" chunkResponseLimit = 64 << 20 ) -// dialChunkFiler opens the filer for the direct commands; tests replace it. +// dialChunkFiler opens the filer for the direct commands and refuses unless +// it is the only filer of its group, the same start check blockvolume makes +// (chunkstore.CheckSingleFiler): a compare-and-swap on one of several +// filers does not exclude a writer on another. Tests replace it. var dialChunkFiler = func(addr string) (chunkstore.Filer, func() error, error) { c, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{FilerGRPC: addr}) if err != nil { return nil, nil, err } + if err := c.CheckSingleFiler(context.Background()); err != nil { + _ = c.Close() + return nil, nil, err + } return c, c.Close, nil } +// codeNotSingleFilerCLI: the filer is not the only filer of its group. +const codeNotSingleFilerCLI = "not_single_filer" + +// chunkDialFail reports a failed dialChunkFiler: a multi-filer refusal is a +// failure (exit 1), anything else a bad --chunk-filer (exit 2). +func chunkDialFail(name string, err error, stdout, stderr io.Writer) int { + if errors.Is(err, chunkstore.ErrNotSingleFiler) { + return chunkFail(name, stdout, stderr, chunkExitFailed, codeNotSingleFilerCLI, err.Error(), false) + } + return chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) +} + func runOpsChunk(args []string, stdout, stderr io.Writer) int { if len(args) == 0 { - return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show|gc|usage|retain|volume-delete", false) + return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show|gc|usage|retain|verify|volume-delete", false) } switch args[0] { case "gc": @@ -67,6 +88,8 @@ func runOpsChunk(args []string, stdout, stderr io.Writer) int { return chunkUsage(args[1:], stdout, stderr) case "retain": return chunkRetain(args[1:], stdout, stderr) + case "verify": + return chunkVerify(args[1:], stdout, stderr) case "volume-delete": return chunkVolumeDelete(args[1:], stdout, stderr) default: @@ -249,7 +272,7 @@ func chunkCatalog(name, filer, base string, stdout, stderr io.Writer) (*chunksto } f, closeFn, err := dialChunkFiler(filer) if err != nil { - return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + return nil, nil, chunkDialFail(name, err, stdout, stderr) } cat, err := chunkstore.NewCatalog(f, base) if err != nil { diff --git a/seaweed-block/cmd/sw-block/chunk_gc.go b/seaweed-block/cmd/sw-block/chunk_gc.go index a5a8cdfc61..4615ff18ee 100644 --- a/seaweed-block/cmd/sw-block/chunk_gc.go +++ b/seaweed-block/cmd/sw-block/chunk_gc.go @@ -37,6 +37,9 @@ func chunkGC(args []string, stdout, stderr io.Writer) int { return chunkFail("gc", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer and --master are required; durations must be positive and grace must exceed the operation deadline", false) } f, closeFn, e := dialChunkFiler(filer) + if errors.Is(e, chunkstore.ErrNotSingleFiler) { + return chunkDialFail("gc", e, stdout, stderr) + } if e != nil { return chunkResult("gc", nil, e, stdout, stderr) } diff --git a/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go b/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go index e9e52d078c..99dd726bf2 100644 --- a/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go +++ b/seaweed-block/cmd/sw-block/chunk_manifest_fixture_test.go @@ -33,7 +33,7 @@ func (f *manifestFixtureFiler) Get(_ context.Context, id string) ([]byte, error) defer f.mu.Unlock() b, ok := f.blobs[id] if !ok { - return nil, chunkstore.ErrNotFound + return nil, fmt.Errorf("%w: %w", chunkstore.ErrBlobNotFound, chunkstore.ErrNotFound) } return append([]byte(nil), b...), nil } diff --git a/seaweed-block/cmd/sw-block/chunk_verify.go b/seaweed-block/cmd/sw-block/chunk_verify.go new file mode 100644 index 0000000000..af5fc66dcd --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_verify.go @@ -0,0 +1,154 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/ops" +) + +// chunkVerify: sw-block ops chunk verify --volume v --chunk-filer host:port +// checks the volume's remote image against its HEAD (and, on request, its +// snapshots), read-only (chunkstore.Catalog.Verify). Exit 0: clean; 3: the +// pass completed with findings; 1: it could not complete (the partial result +// is printed with the error); 2: usage. +func chunkVerify(args []string, stdout, stderr io.Writer) int { + fs := chunkFlagSet("verify", stderr) + var ( + volumeID, filer, base, snapshot, depth string + allSnapshots bool + concurrency int + bytesPerSec int64 + timeout time.Duration + ) + fs.StringVar(&volumeID, "volume", "", "volume id") + fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port") + fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") + fs.StringVar(&snapshot, "snapshot", "", "also check this snapshot") + fs.BoolVar(&allSnapshots, "all-snapshots", false, "also check every snapshot") + fs.StringVar(&depth, "depth", string(chunkstore.VerifyBindings), "meta, bindings or data (data reads every chunk once)") + fs.IntVar(&concurrency, "concurrency", chunkstore.DefaultVerifyConcurrency, "chunk reads in flight (depth data)") + fs.Int64Var(&bytesPerSec, "bytes-per-sec", chunkstore.DefaultVerifyBytesPerSecond, "pace chunk reads (depth data); 0 leaves them unpaced") + fs.DurationVar(&timeout, "timeout", 10*time.Minute, "bound for the whole pass; required with --depth data") + if err := fs.Parse(args); err != nil { + return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + timeoutSet := false + fs.Visit(func(f *flag.Flag) { + if f.Name == "timeout" { + timeoutSet = true + } + }) + usage := func(msg string) int { + return chunkFail("verify", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, msg, false) + } + d := chunkstore.VerifyDepth(depth) + switch { + case fs.NArg() != 0: + return usage("unexpected arguments") + case volumeID == "": + return usage("--volume is required") + case d != chunkstore.VerifyMeta && d != chunkstore.VerifyBindings && d != chunkstore.VerifyData: + return usage(fmt.Sprintf("--depth %q: meta, bindings or data", depth)) + case snapshot != "" && allSnapshots: + return usage("--snapshot and --all-snapshots do not combine") + case d == chunkstore.VerifyData && !timeoutSet: + return usage("--depth data reads every chunk: give an explicit --timeout for the pass") + case timeout <= 0 || concurrency <= 0 || bytesPerSec < 0: + return usage("--timeout and --concurrency must be positive and --bytes-per-sec not negative") + } + cat, closeFn, exit := chunkCatalog("verify", filer, base, stdout, stderr) + if exit >= 0 { + return exit + } + defer closeFn() + if bytesPerSec == 0 { + bytesPerSec = -1 // the library's "unpaced" + } + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + res, err := cat.Verify(ctx, volumeID, chunkstore.VerifyOptions{Depth: d, Snapshot: snapshot, AllSnapshots: allSnapshots, + Concurrency: concurrency, BytesPerSecond: bytesPerSec}) + if err != nil { + return verifyIncomplete(res, err, stdout, stderr) + } + out, err := verifyJSON(res) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk verify: %v\n", err) + return chunkExitFailed + } + if err := writeAll(stdout, out); err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk verify: write the result: %v\n", err) + return chunkExitFailed + } + if len(res.Findings) != 0 { + fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %d findings %v\n", volumeID, len(res.Findings), res.FindingsByClass) + if res.ChunksNotRead != 0 { + // READ_ERROR is not damage: those objects were not verified. + fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %d could not be read and were not verified; re-run\n", volumeID, res.ChunksNotRead) + } + return chunkExitFindings + } + return ops.VolumeStatusExitOK +} + +// verifyJSON is the result as one JSON object whose findings array holds +// one finding per line. +func verifyJSON(res chunkstore.VerifyResult) ([]byte, error) { + findings := res.Findings + res.Findings = nil + head, err := json.Marshal(res) + if err != nil { + return nil, err + } + const tail = `"findings":null}` + if !bytes.HasSuffix(head, []byte(tail)) { + return nil, errors.New("verify result: unexpected field order") + } + var buf bytes.Buffer + buf.Write(head[:len(head)-len(tail)]) + buf.WriteString(`"findings":[`) + for i, f := range findings { + line, err := json.Marshal(f) + if err != nil { + return nil, err + } + if i > 0 { + buf.WriteByte(',') + } + buf.WriteByte('\n') + buf.Write(line) + } + if len(findings) > 0 { + buf.WriteByte('\n') + } + buf.WriteString("]}\n") + return buf.Bytes(), nil +} + +// verifyIncomplete prints the error body with the partial result under +// "verify", and fails. +func verifyIncomplete(res chunkstore.VerifyResult, err error, stdout, stderr io.Writer) int { + body := struct { + chunkErrBody + Verify chunkstore.VerifyResult `json:"verify"` + }{Verify: res} + body.Code, body.Message = codeInternalCLI, err.Error() + var ce *chunkstore.CatalogError + switch { + case errors.As(err, &ce): + body.Code, body.Message, body.Retryable = ce.Code, ce.Detail(), ce.Retryable + case errors.Is(err, context.DeadlineExceeded): + body.Code, body.Retryable = chunkstore.CodeDeadlineExceeded, true + } + fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %s (incomplete)\n", body.Code, body.Message) + chunkResult("verify", body, nil, stdout, stderr) + return chunkExitFailed +} diff --git a/seaweed-block/cmd/sw-block/chunk_verify_test.go b/seaweed-block/cmd/sw-block/chunk_verify_test.go new file mode 100644 index 0000000000..0037cd8587 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_verify_test.go @@ -0,0 +1,245 @@ +package main + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net" + "net/url" + "path" + "strings" + "testing" + + "google.golang.org/grpc" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/masterpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// verifyCLIFixture is volume v1 with two published chunks on an in-memory +// filer and blob store; it returns the store and the HEAD. +func verifyCLIFixture(t *testing.T) (*manifestFixtureFiler, storage.ChunkHead) { + t.Helper() + ctx := context.Background() + mem := newManifestFixtureFiler(chunkstore.NewMemFiler()) + prev := dialChunkFiler + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + t.Cleanup(func() { dialChunkFiler = prev }) + cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI) + if err != nil { + t.Fatal(err) + } + if _, err := cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { + t.Fatal(err) + } + r, err := chunkstore.NewChunkRemote(mem, mem, defaultChunkPathCLI+"/v1") + if err != nil { + t.Fatal(err) + } + cur, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + h := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 42, Chunks: map[uint64]storage.ChunkRef{}} + for idx := uint64(0); idx < 2; idx++ { + data := bytes.Repeat([]byte{byte(0x30 + idx)}, 8*4096) + key := fmt.Sprintf("chunks/e1/c%d/k", idx) + if err := r.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + h.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + } + h, ids, err := r.PrepareManifest(ctx, cur, h, 8*4096) + if err != nil { + t.Fatal(err) + } + if h.Gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h); err != nil { + t.Fatal(err) + } + for _, id := range ids { + if err := r.DeleteIntent(ctx, id); err != nil { + t.Fatal(err) + } + } + return mem, h +} + +func decodeVerify(t *testing.T, out string) chunkstore.VerifyResult { + t.Helper() + var res chunkstore.VerifyResult + if err := json.Unmarshal([]byte(out), &res); err != nil || res.VolumeID == "" { + t.Fatalf("stdout is not a verify result: %q (%v)", out, err) + } + return res +} + +// verify's exit codes: 0 clean, 3 completed with findings, 1 could not +// complete, 2 usage; the result is one JSON object with one finding per line. +func TestOpsChunk_VerifyExitCodes(t *testing.T) { + mem, h := verifyCLIFixture(t) + filer := []string{"--volume", "v1", "--chunk-filer", "filer:18888"} + + code, out, errs := runChunk(append([]string{"verify"}, filer...)...) + res := decodeVerify(t, out) + if code != 0 || !res.Complete || res.Depth != chunkstore.VerifyBindings || len(res.Findings) != 0 || res.ChunksChecked != 2 || + !strings.Contains(out, `"findings":[]`) || len(res.HeadGens) != 1 || res.HeadGens[0] != h.Gen { + t.Fatalf("clean verify: %d %q %q", code, out, errs) + } + code, out, errs = runChunk(append([]string{"verify", "--depth", "data", "--timeout", "10s", "--bytes-per-sec", "0"}, filer...)...) + if res = decodeVerify(t, out); code != 0 || res.DistinctChunksRead != 2 || res.BytesRead != 2*8*4096 { + t.Fatalf("clean data verify: %d %q %q", code, out, errs) + } + + // A binding gone: completed with a finding. + own := strings.TrimPrefix(h.Chunks[1].Key, "@v1/") + if err := mem.DeleteEntry(context.Background(), path.Join(defaultChunkPathCLI, "v1", "keys"), url.PathEscape(own), nil); err != nil { + t.Fatal(err) + } + code, out, errs = runChunk(append([]string{"verify"}, filer...)...) + res = decodeVerify(t, out) + if chunkExitFindings != 3 || code != chunkExitFindings || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != chunkstore.FindingBindingMissing || + res.FindingsByClass[chunkstore.FindingBindingMissing] != 1 || !strings.Contains(errs, "1 findings") { + t.Fatalf("verify with a missing binding: %d %q %q", code, out, errs) + } + lines := strings.Split(strings.TrimSpace(out), "\n") + if len(lines) != 3 || !strings.HasPrefix(lines[1], `{"volume":"v1"`) || !strings.Contains(lines[1], `"class":"BINDING_MISSING"`) || lines[2] != "]}" { + t.Fatalf("findings are not one per line:\n%s", out) + } + + // Could not complete: the error body, with what was covered. + code, out, _ = runChunk("verify", "--volume", "nope", "--chunk-filer", "filer:18888") + if e := chunkErrorOut(t, out); code != chunkExitFailed || e.Code != chunkstore.CodeNotChunkVolume || !strings.Contains(out, `"verify":{`) { + t.Fatalf("verify of a missing volume: %d %q", code, out) + } + + for _, args := range [][]string{ + {"verify", "--chunk-filer", "f:1"}, // no volume + {"verify", "--volume", "v1"}, // no filer + {"verify", "--volume", "v1", "--chunk-filer", "f:1", "--depth", "all"}, // bad depth + {"verify", "--volume", "v1", "--chunk-filer", "f:1", "--depth", "data"}, // data without --timeout + {"verify", "--volume", "v1", "--chunk-filer", "f:1", "--snapshot", "s1", "--all-snapshots"}, + {"verify", "--volume", "v1", "--chunk-filer", "f:1", "--concurrency", "0"}, + {"verify", "--volume", "v1", "--chunk-filer", "f:1", "--bytes-per-sec", "-1"}, + {"verify", "--volume", "v1", "--chunk-filer", "f:1", "extra"}, + {"verify", "--volume", "v1", "--chunk-filer", "f:1", "--bogus"}, + } { + code, out, _ := runChunk(args...) + if code != 2 || chunkErrorOut(t, out).Code != codeBadRequestCLI { + t.Fatalf("%v: exit %d %q; want 2 and bad_request", args, code, out) + } + } + if code, out, _ := runChunk("verify", "--volume", "v1", "--chunk-filer", "f:1", "--depth", "data"); !strings.Contains(out, "--timeout") { + t.Fatalf("data without --timeout: %d %q; want the reason", code, out) + } +} + +// unreadableStore fails every read of one needle with an error that is not +// "not found" (a volume server answering 503). +type unreadableStore struct { + *manifestFixtureFiler + fid string +} + +func (s unreadableStore) Get(ctx context.Context, fid string) ([]byte, error) { + if fid == s.fid { + return nil, fmt.Errorf("chunkstore: read %s: http 503 from volume:8080", fid) + } + return s.manifestFixtureFiler.Get(ctx, fid) +} + +// A chunk that cannot be read is READ_ERROR (not verified), and the pass +// exits 3: it did not verify everything. +func TestOpsChunk_VerifyReadErrorExits3(t *testing.T) { + mem, h := verifyCLIFixture(t) + own := strings.TrimPrefix(h.Chunks[0].Key, "@v1/") + e, err := mem.LookupEntry(context.Background(), path.Join(defaultChunkPathCLI, "v1", "keys"), url.PathEscape(own)) + if err != nil { + t.Fatal(err) + } + store := unreadableStore{mem, string(e.Extended["swb.fid"])} + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return store, func() error { return nil }, nil } + code, out, errs := runChunk("verify", "--volume", "v1", "--chunk-filer", "filer:18888", "--depth", "data", "--timeout", "10s") + res := decodeVerify(t, out) + if code != chunkExitFindings || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != chunkstore.FindingReadError || + res.ChunksNotRead != 1 || res.ReadRetries != 2 || !strings.Contains(errs, "not verified") { + t.Fatalf("verify with an unreadable chunk: %d %q %q", code, out, errs) + } +} + +type cliConfigFiler struct { + filerpb.UnimplementedSeaweedFilerServer + masters []string +} + +func (f *cliConfigFiler) GetFilerConfiguration(context.Context, *filerpb.GetFilerConfigurationRequest) (*filerpb.GetFilerConfigurationResponse, error) { + return &filerpb.GetFilerConfigurationResponse{Masters: f.masters}, nil +} + +type cliNodesMaster struct { + masterpb.UnimplementedSeaweedServer + filers []string +} + +func (m *cliNodesMaster) ListClusterNodes(context.Context, *masterpb.ListClusterNodesRequest) (*masterpb.ListClusterNodesResponse, error) { + resp := &masterpb.ListClusterNodesResponse{} + for _, a := range m.filers { + resp.ClusterNodes = append(resp.ClusterNodes, &masterpb.ListClusterNodesResponse_ClusterNode{Address: a}) + } + return resp, nil +} + +func serveGRPC(t *testing.T, register func(*grpc.Server)) string { + t.Helper() + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + srv := grpc.NewServer() + register(srv) + go func() { _ = srv.Serve(lis) }() + t.Cleanup(srv.Stop) + return lis.Addr().String() +} + +// singleFilerCluster serves a fake filer whose one master lists the filers +// filersOf(self) for its group; it returns the filer's gRPC address. +func singleFilerCluster(t *testing.T, filersOf func(self string) []string) string { + t.Helper() + f := &cliConfigFiler{} + filerAddr := serveGRPC(t, func(s *grpc.Server) { filerpb.RegisterSeaweedFilerServer(s, f) }) + _, filerPort, _ := net.SplitHostPort(filerAddr) + m := &cliNodesMaster{filers: filersOf("127.0.0.1:8888." + filerPort)} + masterAddr := serveGRPC(t, func(s *grpc.Server) { masterpb.RegisterSeaweedServer(s, m) }) + _, masterPort, _ := net.SplitHostPort(masterAddr) + f.masters = []string{"127.0.0.1:9333." + masterPort} + return filerAddr +} + +// The catalog commands make blockvolume's start check through the real +// dial path: a filer group with another filer is refused before anything is +// read or written. +func TestOpsChunk_RefusesMultiFiler(t *testing.T) { + two := singleFilerCluster(t, func(self string) []string { return []string{self, "127.0.0.1:8889.18889"} }) + for _, args := range [][]string{ + {"verify", "--volume", "v1", "--chunk-filer", two}, + {"snapshot-delete", "--volume", "v1", "--name", "s1", "--chunk-filer", two}, + {"usage", "--volume", "v1", "--chunk-filer", two}, + {"gc", "--chunk-filer", two, "--master", "127.0.0.1:1"}, + } { + code, out, errs := runChunk(args...) + if e := chunkErrorOut(t, out); code != chunkExitFailed || e.Code != codeNotSingleFilerCLI || e.Retryable || !strings.Contains(errs, "exactly one filer") { + t.Fatalf("%s against two filers: exit %d %q %q; want 1 and not_single_filer", args[0], code, out, errs) + } + } + // The only filer of its group passes the check; the command then goes on + // (this fake filer serves nothing else, so it fails later, differently). + one := singleFilerCluster(t, func(self string) []string { return []string{self} }) + code, out, errs := runChunk("verify", "--volume", "v1", "--chunk-filer", one, "--timeout", "5s") + if e := chunkErrorOut(t, out); code != chunkExitFailed || e.Code == codeNotSingleFilerCLI { + t.Fatalf("verify against the only filer: exit %d %q %q; want past the check", code, out, errs) + } +} diff --git a/seaweed-block/cmd/sw-block/main.go b/seaweed-block/cmd/sw-block/main.go index 52633a9426..281e893852 100644 --- a/seaweed-block/cmd/sw-block/main.go +++ b/seaweed-block/cmd/sw-block/main.go @@ -2295,6 +2295,8 @@ func usage(w io.Writer) { fmt.Fprintln(w, " sw-block ops chunk fork --chunk-filer [--chunk-path /swblock/chunks] --source --snapshot --target [--request-id ] [--label k=v]...") fmt.Fprintln(w, " sw-block ops chunk show --volume --chunk-filer [--chunk-path /swblock/chunks]") fmt.Fprintln(w, " sw-block ops chunk gc --chunk-filer --master [--chunk-path /swblock/chunks] [--apply] [--grace 1h] [--intent-ttl 1h] [--timeout 1m]") + fmt.Fprintln(w, " sw-block ops chunk verify --volume --chunk-filer [--chunk-path /swblock/chunks] [--snapshot |--all-snapshots] [--depth meta|bindings|data]") + fmt.Fprintln(w, " [--concurrency 2] [--bytes-per-sec 33554432] [--timeout ] (read-only; exit 0 clean, 3 findings, 1 incomplete; --depth data needs --timeout)") fmt.Fprintln(w, " sw-block ops volume-unheld --path (exit 0: no process on this host holds it; local filesystems only)") } diff --git a/seaweed-block/core/frontend/chunkstore/GC.md b/seaweed-block/core/frontend/chunkstore/GC.md index 8a3ad3bb9f..4a7ff80102 100644 --- a/seaweed-block/core/frontend/chunkstore/GC.md +++ b/seaweed-block/core/frontend/chunkstore/GC.md @@ -103,3 +103,123 @@ This test requires the binary and fails rather than skips when it is absent. It It advances only the GC clock to exercise grace admission deterministically; network services, conditional metadata writes, authority RPC and blob deletion are real. It is not an elapsed-time soak or a lab qualification. + +## Single filer + +Every catalog command (`verify`, `usage`, `show`, `snapshots`, +`snapshot-delete`, `fork`, `retain`, `gc`, `volume-delete`) makes the same start +check as blockvolume: it asks the filer for its masters and filer group, and +refuses unless a master lists exactly one filer in that group and it is the +`--chunk-filer` given. The refusal exits 1 with code `not_single_filer`. The +masters the filer reports must be reachable from where the command runs. + +## Verify + +`sw-block ops chunk verify` compares one volume's remote image with what its +HEAD, and optionally its snapshots, say. It is read-only: it writes no intent, +mark, tombstone or binding, and deletes nothing. + +```sh +sw-block ops chunk verify --volume v1 --chunk-filer 127.0.0.1:18888 \ + [--chunk-path /swblock/chunks] [--snapshot s1 | --all-snapshots] \ + [--depth meta|bindings|data] [--concurrency 2] [--bytes-per-sec 33554432] \ + [--timeout 10m] +``` + +HEAD is always checked. `--snapshot` adds one named snapshot; `--all-snapshots` +adds every published snapshot that is not being deleted. Each depth includes the +one before it: + +- `meta`: the HEAD root decodes and is self-consistent; its chunk size and chunk + indices fit the VOLUME geometry; every segment a checked root names is + readable, matches its SHA-256 and decodes strictly; the same for each checked + snapshot's embedded HEAD; for a fork, its fork record's digest matches an + attempt of the parent snapshot at the recorded generation. +- `bindings` (the default): also, every chunk key a checked root references has + a binding in its owner's `keys/` (a fork's `@owner/key` resolves to the owner + volume), of the right kind, with a fid, without filer chunks, and not + tombstoned by GC. Each owner's `keys/` is listed once. GC's mark does not make + this check: it never looks up the bindings of the keys it roots. +- `data`: also, every distinct chunk (owner and key, across all checked roots) + is read once, and its SHA-256 must equal the reference and its length the + chunk size, the rule a guest read applies. `--depth data` requires an explicit + `--timeout`. Reads are bounded by `--concurrency` and paced by + `--bytes-per-sec` (0 leaves them unpaced). + +Old capture intents below HEAD's epoch that name no key HEAD references are +reported as `INTENT_STALE`. This is a hint only: whether GC may expire an intent +remains GC's decision, with blockmaster authority. + +The output is one JSON object: the HEAD generations and snapshots covered, +segments and chunks checked, distinct chunks and bytes read, the two recheck +counters below, findings by class, and the findings, one per line. Each finding +names the volume, the root (`HEAD gen N`, `snapshot name/attempt`, an intent or +the VOLUME fork record), the chunk index or segment, the owner, key and fid, a +class and a detail. Classes: `ROOT_INVALID`, `GEOMETRY`, `SEGMENT_UNREADABLE`, +`BINDING_MISSING`, `BINDING_TOMBSTONED`, `NEEDLE_MISSING`, `CONTENT_MISMATCH`, +`SIZE_MISMATCH`, `FORK_RECORD_MISMATCH`, `INTENT_STALE`, `READ_ERROR`. + +`NEEDLE_MISSING` means the blob store answered that the needle does not exist +(for SeaweedFS: HTTP 404 from every location). Any other read failure, such as a +timeout, a refused or reset connection, or another HTTP status, is retried twice +with a short backoff. If it still fails, the chunk or segment is reported as +`READ_ERROR`, with the error in the detail. `READ_ERROR` is not evidence of +damage: it means that object was **not verified**. Re-run verify, after fixing +the store's reachability if needed. The summary counts these objects separately +in `chunksNotRead`, and `readRetries` counts the retried reads. Both rechecks +below apply to `READ_ERROR` as they do to a miss. + +### Running beside a live owner and beside GC + +Segments and chunks are immutable and written before the root that names them, +so a root read once and the segments it names are a consistent view. But nothing +registers a reader with GC: a chunk that leaves a root can be collected once +GC's grace has passed, and a long pass can outlive that. Two rechecks keep such +a chunk from being reported: + +- **Superseded during verify.** A miss under a HEAD root is a finding only if the + current HEAD still names that key at that index. On a miss, verify reads HEAD + again (the root and the one segment covering the index); if the key is gone, + the miss is counted in `supersededDuringVerify`, not reported. +- **Root deleted during verify.** A miss under a snapshot is a finding only if + that exact snapshot attempt still exists and is active. On a miss, verify reads + the snapshot's name record and attempt entry again; if the attempt is gone, + aborted or marked deleting, the miss is counted in `rootDeletedDuringVerify`, + not reported, and the snapshot is listed in `snapshotsDeletedDuringVerify` as + not fully covered. + +A finding describes the image at the time of its recheck: the recheck and the +report are two steps, so a root that is superseded or deleted right after the +recheck can still appear in the findings. Run verify again to confirm a +finding against the current roots. + +A chunk that several checked roots name is reported once, under the first root +that still names it (HEAD first). The HEAD view is also refreshed at least every +2 minutes during a long pass; only segments whose key changed are read again, +and chunks the pass has not seen are added. The result therefore states "every +chunk named by the listed HEAD generations at the time it was checked", not "the +image at one instant". + +### What verify cannot check + +- Orphan needles: a needle uploaded whose binding was never written cannot be + enumerated. +- Which block inside a chunk is bad: there is one SHA-256 per chunk. +- A data chunk's size without reading it: bindings and references store no size. +- The HEAD root against an independent value: no checksum of the root is stored. +- Whether the image equals the volume's content at its remote LSN: only the + holder's local volume could say. +- Past HEAD generations, forced-move lost ranges (kept outside the filer), and + any verification history (nothing records it). +- Each replica of a needle: a read stops at the first replica that answers. + +### Exit codes + +- `0`: the pass completed with no finding. +- `3`: the pass completed with findings. This includes `READ_ERROR`: the pass + did not verify everything. +- `1`: the pass could not complete (the deadline passed, the filer failed, the + volume or snapshot does not exist, or the filer is not the only one of its + group). The error body `{code,message,retryable}` is printed with the partial + result under `verify`. +- `2`: usage error. diff --git a/seaweed-block/core/frontend/chunkstore/fake_test.go b/seaweed-block/core/frontend/chunkstore/fake_test.go index 9f3ddcfb15..adfcc42ed1 100644 --- a/seaweed-block/core/frontend/chunkstore/fake_test.go +++ b/seaweed-block/core/frontend/chunkstore/fake_test.go @@ -256,7 +256,7 @@ func (b *fakeBlobs) Get(_ context.Context, fid string) ([]byte, error) { b.gets++ d, ok := b.data[fid] if !ok { - return nil, errors.New("fake: no such fid " + fid) + return nil, fmt.Errorf("fake: no such fid %s: %w", fid, ErrBlobNotFound) } return append([]byte(nil), d...), nil } diff --git a/seaweed-block/core/frontend/chunkstore/remote.go b/seaweed-block/core/frontend/chunkstore/remote.go index 78dd8dd4b9..cd8e87f18a 100644 --- a/seaweed-block/core/frontend/chunkstore/remote.go +++ b/seaweed-block/core/frontend/chunkstore/remote.go @@ -40,7 +40,9 @@ type Blobs interface { // Put stores data as a new needle and returns its fid. A fid is never // reused, so a Put can never overwrite data another manifest references. Put(ctx context.Context, data []byte) (fid string, err error) - // Get returns the whole needle payload. + // Get returns the whole needle payload. When the store reports the + // needle absent (not merely unreachable), the error wraps + // ErrBlobNotFound. Get(ctx context.Context, fid string) ([]byte, error) } @@ -54,4 +56,8 @@ var ( // ErrInvalidKey: a chunk key is malformed, or names an owner that is // not a plain volume id, or is qualified where only own keys are allowed. ErrInvalidKey = errors.New("chunkstore: invalid chunk key") + // ErrBlobNotFound: the blob store answered that the needle does not + // exist (SWFS: HTTP 404 from every location). A timeout, a refused + // connection or any other status is not this error. + ErrBlobNotFound = errors.New("chunkstore: needle not found") ) diff --git a/seaweed-block/core/frontend/chunkstore/swfs.go b/seaweed-block/core/frontend/chunkstore/swfs.go index 1180b84e87..185ee304e8 100644 --- a/seaweed-block/core/frontend/chunkstore/swfs.go +++ b/seaweed-block/core/frontend/chunkstore/swfs.go @@ -261,19 +261,43 @@ func (c *SWFS) Get(ctx context.Context, fid string) ([]byte, error) { return nil, err } var lastErr error + allNotFound := true for _, host := range urls { b, err := c.getFrom(ctx, host, fid) if err == nil { return b, nil } lastErr = err + var se *blobStatusError + if !errors.As(err, &se) || se.code != http.StatusNotFound { + allNotFound = false + } } c.mu.Lock() delete(c.vidCache, vid) c.mu.Unlock() + if allNotFound && lastErr != nil { + lastErr = &blobNotFoundError{lastErr} + } return nil, fmt.Errorf("chunkstore: read %s: %w", fid, lastErr) } +// blobStatusError is a volume server's non-200 answer to a needle GET. +type blobStatusError struct { + code int + host string +} + +func (e *blobStatusError) Error() string { return fmt.Sprintf("http %d from %s", e.code, e.host) } + +// blobNotFoundError marks a read every location answered 404: it reads as +// the last location's error and matches ErrBlobNotFound. +type blobNotFoundError struct{ err error } + +func (e *blobNotFoundError) Error() string { return e.err.Error() } +func (e *blobNotFoundError) Unwrap() error { return e.err } +func (e *blobNotFoundError) Is(target error) bool { return target == ErrBlobNotFound } + func (c *SWFS) getFrom(ctx context.Context, host, fid string) ([]byte, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+host+"/"+fid, nil) if err != nil { @@ -285,7 +309,7 @@ func (c *SWFS) getFrom(ctx context.Context, host, fid string) ([]byte, error) { } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("http %d from %s", resp.StatusCode, host) + return nil, &blobStatusError{code: resp.StatusCode, host: host} } return io.ReadAll(resp.Body) } diff --git a/seaweed-block/core/frontend/chunkstore/verify.go b/seaweed-block/core/frontend/chunkstore/verify.go new file mode 100644 index 0000000000..77b35066a9 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/verify.go @@ -0,0 +1,1365 @@ +package chunkstore + +// Verify: a read-only check of one volume's remote image against what its +// HEAD (and, on request, its snapshots) say. It writes nothing to the filer +// or the blob store: no intent, no mark, no tombstone, no binding. +// +// Depths, each including the one before: +// +// - meta: the HEAD root decodes and is self-consistent; its geometry +// matches VOLUME; every segment a selected root names is readable and +// passes its SHA-256 and strict decode; a fork's record matches the +// parent snapshot it was made from. +// - bindings (the default): every chunk key a selected root references +// has a sound binding in its owner's keys/ (one listing per owner), +// not tombstoned by GC. +// - data: every distinct chunk (owner + key, across all selected roots) +// is fetched once; its SHA-256 must equal the reference and its length +// the chunk size (the rule the chunk layer applies on a read miss). +// +// Running beside a live owner and beside GC: segments and chunks are +// immutable and written before the root that names them, so a root read +// once and the segments it names are a consistent view. A chunk that leaves +// HEAD can be collected after GC's grace, so a miss under a HEAD root is a +// finding only if the current HEAD still names that key at that index: on a +// miss, HEAD is read again (the root and the one segment), and a key it no +// longer names is counted as superseded during verify. A snapshot can be +// deleted during the pass, and its chunks are then kept only for the grace, +// so a miss under a snapshot is a finding only if that exact attempt still +// exists and is active (its name record and attempt entry are read again); +// otherwise it is counted as root deleted during verify, and the snapshot is +// listed as not fully covered. A chunk several selected roots name is one +// finding, reported under the first of them that still names it. The HEAD view is +// refreshed at least every RefreshInterval during the binding and data +// phases; only segments whose key changed are read again, and the result +// lists every HEAD generation the pass covered. +// +// A needle is NEEDLE_MISSING only when the store reports it absent +// (ErrBlobNotFound). Any other read failure is retried; if it persists it is +// READ_ERROR, which means "not verified", not "damaged". Both rechecks above +// apply to it. +// +// A finding never stops the pass. Only an inability to continue does (the +// context ended, the filer failed): Verify then returns the partial result, +// with Complete false, and the error. + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "path" + "sort" + "strings" + "sync" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// VerifyDepth selects how far Verify checks. +type VerifyDepth string + +const ( + VerifyMeta VerifyDepth = "meta" + VerifyBindings VerifyDepth = "bindings" + VerifyData VerifyDepth = "data" +) + +const ( + // DefaultVerifyConcurrency bounds the chunk reads in flight. + DefaultVerifyConcurrency = 2 + // DefaultVerifyBytesPerSecond paces chunk reads. + DefaultVerifyBytesPerSecond int64 = 32 << 20 + // DefaultVerifyRefresh is the longest a pass works from one HEAD view; + // it stays below the operation deadline, the shortest time a chunk + // that just left HEAD is still guaranteed to be kept by GC. + DefaultVerifyRefresh = 2 * time.Minute + // DefaultVerifyIntentStaleAge is the age past which a capture intent + // below HEAD's epoch is reported as stale (the gc --intent-ttl default). + DefaultVerifyIntentStaleAge = time.Hour +) + +// Finding classes. +const ( + FindingRootInvalid = "ROOT_INVALID" + FindingGeometry = "GEOMETRY" + FindingSegmentUnreadable = "SEGMENT_UNREADABLE" + FindingBindingMissing = "BINDING_MISSING" + FindingBindingTombstoned = "BINDING_TOMBSTONED" + FindingNeedleMissing = "NEEDLE_MISSING" + FindingContentMismatch = "CONTENT_MISMATCH" + FindingSizeMismatch = "SIZE_MISMATCH" + FindingForkRecordMismatch = "FORK_RECORD_MISMATCH" + FindingIntentStale = "INTENT_STALE" + // FindingReadError is not proof of damage: a needle (chunk or segment) + // could not be read for a reason other than the store reporting it + // absent, after retries. That object was not verified; re-run. + FindingReadError = "READ_ERROR" +) + +// A read the store does not answer with "not found" is tried this many +// times in all, the retries spaced by verifyRetryBackoff times the attempt. +const verifyReadAttempts = 3 + +var verifyRetryBackoff = 50 * time.Millisecond + +// VerifyOptions configures a Verify pass. Zero values take the defaults. +type VerifyOptions struct { + // Depth is meta, bindings (default) or data. + Depth VerifyDepth + // Snapshot adds the named snapshot to the roots checked; AllSnapshots + // adds every published snapshot not marked deleting. HEAD is always + // checked. At most one of the two may be set. + Snapshot string + AllSnapshots bool + // Concurrency bounds the chunk reads in flight (depth data). + Concurrency int + // BytesPerSecond paces chunk reads: 0 is the default, a negative value + // leaves them unpaced. + BytesPerSecond int64 + // RefreshInterval is the longest the pass works from one HEAD view. + RefreshInterval time.Duration + // IntentStaleAge is the age past which a capture intent below HEAD's + // epoch that names no key HEAD references is reported (a hint only). + IntentStaleAge time.Duration + + // hook, when set, runs at the named stages of a pass (a test seam). + hook func(stage string) +} + +// Verify stages passed to the hook. +const ( + verifyHookHeadWalked = "head-walked" // the first HEAD view has been read and walked + verifyHookRootsWalked = "roots-walked" // the selected snapshots have been read and walked too +) + +// VerifyFinding is one problem found. Segment is set for a segment's own +// problem, Index for a chunk's. +type VerifyFinding struct { + Volume string `json:"volume"` + Root string `json:"root"` + Segment *uint64 `json:"segment,omitempty"` + Index *uint64 `json:"index,omitempty"` + Owner string `json:"owner,omitempty"` + Key string `json:"key,omitempty"` + FID string `json:"fid,omitempty"` + Class string `json:"class"` + Detail string `json:"detail"` +} + +// VerifyResult is a pass's summary and findings. Complete is false when the +// pass could not finish; the counters then cover what it did. +type VerifyResult struct { + VolumeID string `json:"volumeID"` + Depth VerifyDepth `json:"depth"` + Complete bool `json:"complete"` + // HeadGens are the HEAD generations the pass covered, in order. + HeadGens []uint64 `json:"headGens"` + // Snapshots are the snapshots checked, as name/attempt. + Snapshots []string `json:"snapshots"` + // SegmentsChecked counts segment references checked (per root); + // SegmentReads the segment objects actually read. + SegmentsChecked int `json:"segmentsChecked"` + SegmentReads int `json:"segmentReads"` + // ChunksChecked counts chunk references checked (root, index); + // DistinctChunks the distinct chunks (owner, key) among them. + ChunksChecked int `json:"chunksChecked"` + DistinctChunks int `json:"distinctChunks"` + // DistinctChunksRead and BytesRead count the chunk data read. + DistinctChunksRead int `json:"distinctChunksRead"` + BytesRead int64 `json:"bytesRead"` + // SupersededDuringVerify counts misses under a HEAD root whose key the + // current HEAD no longer names (not findings). + SupersededDuringVerify int `json:"supersededDuringVerify"` + // RootDeletedDuringVerify counts misses under a snapshot whose attempt + // was deleted (or aborted, or is gone) by the time of the report (not + // findings). + RootDeletedDuringVerify int `json:"rootDeletedDuringVerify"` + // SnapshotsDeletedDuringVerify lists, as name/attempt, the checked + // snapshots deleted during the pass: they are not fully covered. + SnapshotsDeletedDuringVerify []string `json:"snapshotsDeletedDuringVerify"` + // ForkSourceGone: this volume is a fork whose source volume no longer + // exists, so its fork record could not be compared with the parent + // snapshot. Not a finding. + ForkSourceGone bool `json:"forkSourceGone,omitempty"` + // ChunksNotRead counts the READ_ERROR findings: chunks or segments that + // could not be read, so were not verified. ReadRetries counts the + // retried reads. + ChunksNotRead int `json:"chunksNotRead"` + ReadRetries int `json:"readRetries"` + FindingsByClass map[string]int `json:"findingsByClass"` + Findings []VerifyFinding `json:"findings"` +} + +// Verify checks vol's remote image at opts.Depth; see the top of this file. +func (c *Catalog) Verify(ctx context.Context, vol string, opts VerifyOptions) (VerifyResult, error) { + res := VerifyResult{VolumeID: vol, HeadGens: []uint64{}, Snapshots: []string{}, SnapshotsDeletedDuringVerify: []string{}, + FindingsByClass: map[string]int{}, Findings: []VerifyFinding{}} + if opts.Depth == "" { + opts.Depth = VerifyBindings + } + res.Depth = opts.Depth + if opts.Depth != VerifyMeta && opts.Depth != VerifyBindings && opts.Depth != VerifyData { + return res, catErr(CodeInvalidName, false, nil, "verify depth %q: meta, bindings or data", opts.Depth) + } + if opts.Snapshot != "" && opts.AllSnapshots { + return res, catErr(CodeInvalidName, false, nil, "verify: a named snapshot and all snapshots do not combine") + } + if opts.Snapshot != "" { + if err := CheckSnapshotName(opts.Snapshot); err != nil { + return res, err + } + } + if opts.Concurrency <= 0 { + opts.Concurrency = DefaultVerifyConcurrency + } + if opts.BytesPerSecond == 0 { + opts.BytesPerSecond = DefaultVerifyBytesPerSecond + } + if opts.RefreshInterval <= 0 { + opts.RefreshInterval = DefaultVerifyRefresh + } + if opts.IntentStaleAge <= 0 { + opts.IntentStaleAge = DefaultVerifyIntentStaleAge + } + root, err := c.volRoot(vol) + if err != nil { + return res, err + } + v := &verifier{c: c, vol: vol, root: root, opts: opts, res: &res, blobs: c.blobs, + segs: map[verifySegKey]verifiedSegment{}, chunks: map[string]*verifyChunk{}, deletedSnaps: map[verifyRoot]bool{}, + pacer: &verifyPacer{rate: opts.BytesPerSecond}} + err = v.run(ctx) + sort.SliceStable(res.Findings, func(i, j int) bool { return findingLess(res.Findings[i], res.Findings[j]) }) + for _, f := range res.Findings { + res.FindingsByClass[f.Class]++ + } + res.DistinctChunks = len(v.chunks) + if err != nil { + return res, err + } + res.Complete = true + return res, nil +} + +// verifySegKey names a segment reference: a segment object is immutable, so +// one verified under the same reference needs no second read. +type verifySegKey struct { + group, chunkBytes uint64 + ref storage.ChunkSegment +} + +type verifiedSegment struct { + chunks map[uint64]storage.ChunkRef + fid string + tombstoned bool +} + +// verifyRoot names a root a pass checks: HEAD (head set) or one snapshot +// attempt (name and attempt). +type verifyRoot struct { + label string + head bool + name, attempt string +} + +// verifyUse is one root's reference to a chunk. +type verifyUse struct { + root verifyRoot + idx uint64 + sha [32]byte +} + +// verifyChunk is one distinct chunk (owner volume + the owner's own key). +type verifyChunk struct { + id string + owner, key string + uses []verifyUse + fid string + bound bool // a sound, untombstoned binding was found +} + +type verifier struct { + c *Catalog + vol string + root string + opts VerifyOptions + blobs Blobs + pacer *verifyPacer + + geo Geometry + chunkBytes uint64 + nChunks uint64 + + mu sync.Mutex + res *VerifyResult + segs map[verifySegKey]verifiedSegment // verified segments, by reference + chunks map[string]*verifyChunk // by identity + pending []*verifyChunk // not yet checked at depth bindings/data + + snapRoots []verifyRoot // the snapshots checked + deletedSnaps map[verifyRoot]bool // snapshots found deleted during the pass (permanent) + + head storage.ChunkHead // the current HEAD view (root only) + hasHead bool + lastRefresh time.Time + badRefresh bool +} + +func (v *verifier) hook(stage string) { + if v.opts.hook != nil { + v.opts.hook(stage) + } +} + +func (v *verifier) finding(f VerifyFinding) { + f.Volume = v.vol + v.mu.Lock() + v.res.Findings = append(v.res.Findings, f) + if f.Class == FindingReadError { + v.res.ChunksNotRead++ + } + v.mu.Unlock() +} + +func isContextErr(ctx context.Context, err error) bool { + return ctx.Err() != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) +} + +// fetch reads one needle. A needle the store reports absent (ErrBlobNotFound) +// and a context error are returned at once; any other failure is retried, +// up to verifyReadAttempts reads in all, before it is returned. +func (v *verifier) fetch(ctx context.Context, fid string) ([]byte, error) { + for attempt := 1; ; attempt++ { + data, err := v.blobs.Get(ctx, fid) + if err == nil || errors.Is(err, ErrBlobNotFound) || isContextErr(ctx, err) || attempt == verifyReadAttempts { + return data, err + } + v.mu.Lock() + v.res.ReadRetries++ + v.mu.Unlock() + t := time.NewTimer(verifyRetryBackoff * time.Duration(attempt)) + select { + case <-t.C: + case <-ctx.Done(): + t.Stop() + return nil, ctx.Err() + } + } +} + +// readErrorDetail describes a read that failed for a reason other than "not found". +func readErrorDetail(err error) string { + return fmt.Sprintf("not verified: could not read the needle in %d attempts (re-run): %v", verifyReadAttempts, err) +} + +// verifyPrefetched serves one needle already read, so the shared segment +// decoder verifies exactly the bytes fetch returned. +type verifyPrefetched struct { + fid string + body []byte +} + +func (p verifyPrefetched) Put(context.Context, []byte) (string, error) { + return "", errors.New("chunkstore: verify is read-only") +} + +func (p verifyPrefetched) Get(_ context.Context, fid string) ([]byte, error) { + if fid != p.fid { + return nil, fmt.Errorf("chunkstore: verify: unexpected needle %s", fid) + } + return p.body, nil +} + +func (v *verifier) superseded() { + v.mu.Lock() + v.res.SupersededDuringVerify++ + v.mu.Unlock() +} + +// abortErr turns a failure that stops the pass into its error: a context +// error stays one (the CLI reports deadline_exceeded), anything else from +// the filer is remote_unavailable. +func abortErr(ctx context.Context, err error, format string, a ...any) error { + if ctx.Err() != nil { + return fmt.Errorf("chunkstore: verify: %s: %w", fmt.Sprintf(format, a...), ctx.Err()) + } + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return fmt.Errorf("chunkstore: verify: %s: %w", fmt.Sprintf(format, a...), err) + } + if CodeOf(err) != "" { + return err + } + return remoteErr(err, format, a...) +} + +func headLabel(gen uint64) string { return fmt.Sprintf("HEAD gen %d", gen) } + +func (v *verifier) run(ctx context.Context) error { + vi, ok, err := v.c.ReadVolume(ctx, v.vol) + if err != nil { + if CodeOf(err) == CodeRemoteUnavailable || ctx.Err() != nil { + return abortErr(ctx, err, "read VOLUME of %s", v.vol) + } + v.finding(VerifyFinding{Root: "VOLUME", Class: FindingRootInvalid, Detail: err.Error()}) + return nil + } + if !ok { + return catErr(CodeNotChunkVolume, false, nil, "volume %s has no VOLUME entry", v.vol) + } + v.geo = vi.Geometry + v.chunkBytes = uint64(v.geo.ChunkBlocks) * uint64(v.geo.BlockSize) + if v.geo.ChunkBlocks > 0 { + v.nChunks = (v.geo.NumBlocks + uint64(v.geo.ChunkBlocks) - 1) / uint64(v.geo.ChunkBlocks) + } + if v.chunkBytes == 0 { + v.finding(VerifyFinding{Root: "VOLUME", Class: FindingGeometry, Detail: fmt.Sprintf("VOLUME geometry %+v has no chunk size", v.geo)}) + } + if err := v.forkRecord(ctx, vi); err != nil { + return err + } + + // HEAD: the root once, then the segments it names. + e, err := v.c.f.LookupEntry(ctx, v.root, headName) + switch { + case errors.Is(err, ErrNotFound): + v.finding(VerifyFinding{Root: "HEAD", Class: FindingRootInvalid, Detail: "the volume has a VOLUME entry but no HEAD"}) + case err != nil: + return abortErr(ctx, err, "read HEAD of %s", v.vol) + default: + h, derr := decodeHead(path.Join(v.root, headName), e) + if derr != nil { + v.finding(VerifyFinding{Root: "HEAD", Class: FindingRootInvalid, Detail: derr.Error()}) + break + } + v.head, v.hasHead, v.lastRefresh = h, true, time.Now() + hr := verifyRoot{label: headLabel(h.Gen), head: true} + v.res.HeadGens = append(v.res.HeadGens, h.Gen) + chunks, err := v.walk(ctx, hr, h) + if err != nil { + return err + } + v.addUses(hr, chunks, false) + if err := v.intents(ctx, h, chunks); err != nil { + return err + } + } + v.hook(verifyHookHeadWalked) + + if err := v.snapshots(ctx); err != nil { + return err + } + v.hook(verifyHookRootsWalked) + if v.opts.Depth != VerifyMeta { + for first := true; len(v.pending) > 0; first = false { + batch := v.pending + v.pending = nil + if err := v.checkBindings(ctx, batch, first); err != nil { + return err + } + if v.opts.Depth == VerifyData { + if err := v.checkData(ctx, batch); err != nil { + return err + } + } + if err := v.maybeRefresh(ctx); err != nil { + return err + } + } + } + // Name the snapshots deleted during the pass: not fully covered. + for _, s := range v.snapRoots { + if _, _, err := v.snapshotActive(ctx, s); err != nil { + return err + } + } + for _, s := range v.snapRoots { + if v.deletedSnaps[s] { + v.res.SnapshotsDeletedDuringVerify = append(v.res.SnapshotsDeletedDuringVerify, s.name+"/"+s.attempt) + } + } + return nil +} + +// ---- roots and segments ---- + +// segIssue is why a segment could not be used. +type segIssue struct { + class, fid, detail string +} + +// segment returns the verified chunks of h's segment group (keys +// owner-qualified), reading it unless this pass already verified the same +// reference. A non-nil issue is a problem with the segment; an error stops +// the pass. tombstoned reports a segment binding GC has tombstoned. +func (v *verifier) segment(ctx context.Context, h storage.ChunkHead, group uint64) (chunks map[uint64]storage.ChunkRef, fid string, tombstoned bool, issue *segIssue, err error) { + ref := h.Segments[group] + k := verifySegKey{group: group, chunkBytes: h.ChunkBytes, ref: ref} + v.mu.Lock() + cached, ok := v.segs[k] + v.mu.Unlock() + if ok { + return cached.chunks, cached.fid, cached.tombstoned, nil, nil + } + if v.blobs == nil { + return nil, "", false, nil, errors.New("chunkstore: verify needs a blob reader for segmented roots") + } + r, err := NewChunkRemote(v.c.f, v.blobs, v.root) + if err != nil { + return nil, "", false, nil, err + } + dir, name, err := r.keyLocation(ref.Key) + if err != nil { + return nil, "", false, &segIssue{FindingSegmentUnreadable, "", err.Error()}, nil + } + e, err := v.c.f.LookupEntry(ctx, dir, name) + if errors.Is(err, ErrNotFound) { + return nil, "", false, &segIssue{FindingSegmentUnreadable, "", "segment binding not found"}, nil + } + if err != nil { + return nil, "", false, nil, abortErr(ctx, err, "read segment binding %s/%s", dir, name) + } + if bad := bindingProblem(e); bad != "" { + return nil, "", false, &segIssue{FindingSegmentUnreadable, string(e.Extended[extFid]), "segment binding: " + bad}, nil + } + fid = string(e.Extended[extFid]) + tombstoned = len(e.Extended[extGCDeleted]) != 0 + v.mu.Lock() + v.res.SegmentReads++ + v.mu.Unlock() + body, err := v.fetch(ctx, fid) + switch { + case err == nil: + case isContextErr(ctx, err): + return nil, "", false, nil, abortErr(ctx, err, "read segment %s", ref.Key) + case errors.Is(err, ErrBlobNotFound): + return nil, fid, tombstoned, &segIssue{FindingSegmentUnreadable, fid, "segment needle not found: " + err.Error()}, nil + default: + return nil, fid, tombstoned, &segIssue{FindingReadError, fid, readErrorDetail(err)}, nil + } + // Verify the bytes read through the same decoder GC and the chunk + // layer use (hash, size bound, strict decode, contents). + r, err = NewChunkRemote(v.c.f, verifyPrefetched{fid, body}, v.root) + if err != nil { + return nil, "", false, nil, err + } + r.mu.Lock() + r.fids[ref.Key] = fid + r.mu.Unlock() + one := storage.ChunkHead{Segments: map[uint64]storage.ChunkSegment{group: ref}, ChunkBytes: h.ChunkBytes, + ManifestChunkCount: ref.Count, RemoteLSN: h.RemoteLSN, State: storage.ChunkHeadActive} + resolved, err := r.resolveManifest(ctx, one) + if err != nil { + return nil, fid, tombstoned, &segIssue{FindingSegmentUnreadable, fid, err.Error()}, nil + } + v.mu.Lock() + v.segs[k] = verifiedSegment{resolved.Chunks, fid, tombstoned} + v.mu.Unlock() + return resolved.Chunks, fid, tombstoned, nil, nil +} + +// bindingProblem is what makes e unusable as a chunk key binding, or "". +func bindingProblem(e *filerpb.Entry) string { + switch { + case e.GetIsDirectory(): + return "is a directory" + case len(e.GetChunks()) != 0: + return fmt.Sprintf("carries %d filer chunks", len(e.GetChunks())) + case string(e.Extended[extKind]) != kindChunkKey: + return fmt.Sprintf("kind %q, want %q", e.Extended[extKind], kindChunkKey) + case len(e.Extended[extFid]) == 0: + return "no fid" + } + return "" +} + +// walk checks one root (meta depth) and returns its chunk map. +func (v *verifier) walk(ctx context.Context, r verifyRoot, h storage.ChunkHead) (map[uint64]storage.ChunkRef, error) { + label := r.label + out := map[uint64]storage.ChunkRef{} + if h.Segments == nil { + for idx, ref := range h.Chunks { + out[idx] = ref + } + } else { + if h.ChunkBytes != v.chunkBytes { + v.finding(VerifyFinding{Root: label, Class: FindingGeometry, + Detail: fmt.Sprintf("root chunk_bytes %d, VOLUME chunk size %d", h.ChunkBytes, v.chunkBytes)}) + } + groups := make([]uint64, 0, len(h.Segments)) + for g := range h.Segments { + groups = append(groups, g) + } + sort.Slice(groups, func(i, j int) bool { return groups[i] < groups[j] }) + for _, g := range groups { + ref := h.Segments[g] + v.mu.Lock() + v.res.SegmentsChecked++ + v.mu.Unlock() + chunks, fid, tomb, issue, err := v.segment(ctx, h, g) + if err != nil { + return out, err + } + group := g + if tomb && v.opts.Depth != VerifyMeta { + if err := v.segmentMiss(ctx, r, group, ref, VerifyFinding{Class: FindingBindingTombstoned, FID: fid, Detail: "segment binding tombstoned by GC"}); err != nil { + return out, err + } + } + if issue != nil { + if err := v.segmentMiss(ctx, r, group, ref, VerifyFinding{Class: issue.class, FID: issue.fid, Detail: issue.detail}); err != nil { + return out, err + } + continue + } + for idx, cr := range chunks { + out[idx] = cr + } + } + } + idxs := sortedIndexes(out) + for _, idx := range idxs { + if idx >= v.nChunks { + i := idx + owner, key := splitIdentity(chunkIdentity(v.vol, out[idx].Key)) + v.finding(VerifyFinding{Root: label, Index: &i, Owner: owner, Key: key, Class: FindingGeometry, + Detail: fmt.Sprintf("chunk index %d outside the volume (%d chunks)", idx, v.nChunks)}) + } + } + return out, nil +} + +// segmentMiss reports a segment problem, unless it is under a HEAD root +// that no longer names that segment, or under a snapshot deleted since. +func (v *verifier) segmentMiss(ctx context.Context, r verifyRoot, group uint64, ref storage.ChunkSegment, f VerifyFinding) error { + if r.head { + h, ok, err := v.readHeadRoot(ctx) + switch { + case errors.Is(err, errUndecodableHead): + // cannot excuse the miss: report it + case err != nil: + return err + case !ok || h.Segments[group] != ref: + v.superseded() + return nil + } + } else { + active, _, err := v.snapshotActive(ctx, r) + if err != nil { + return err + } + if !active { + v.rootDeleted() + return nil + } + } + f.Root, f.Segment, f.Owner, f.Key = r.label, &group, ref.Owner, ref.Key + v.finding(f) + return nil +} + +func (v *verifier) rootDeleted() { + v.mu.Lock() + v.res.RootDeletedDuringVerify++ + v.mu.Unlock() +} + +// snapshotActive reads snapshot r again: its name record must still name +// r's attempt, and the attempt entry must still exist, active. A name +// record that is gone or names another attempt, or an attempt entry that is +// gone, aborted or marked deleting, means r was deleted (permanently: the +// attempt path is never reused). An entry that does not decode cannot +// excuse a miss: it counts as active, with a nil head. +func (v *verifier) snapshotActive(ctx context.Context, r verifyRoot) (active bool, head *storage.ChunkHead, err error) { + v.mu.Lock() + gone := v.deletedSnaps[r] + v.mu.Unlock() + if gone { + return false, nil, nil + } + deleted := func() (bool, *storage.ChunkHead, error) { + v.mu.Lock() + v.deletedSnaps[r] = true + v.mu.Unlock() + return false, nil, nil + } + ne, err := v.c.f.LookupEntry(ctx, path.Join(v.root, snapNamesDir), r.name) + if errors.Is(err, ErrNotFound) { + return deleted() + } + if err != nil { + return false, nil, abortErr(ctx, err, "re-read snapshot name %s/%s", v.vol, r.name) + } + rec, err := decodeNameRecord(path.Join(v.root, snapNamesDir, r.name), ne) + if err == nil && rec.Attempt != r.attempt { + return deleted() + } + dir := path.Join(v.root, snapsDir, r.name) + e, err := v.c.f.LookupEntry(ctx, dir, r.attempt) + if errors.Is(err, ErrNotFound) { + return deleted() + } + if err != nil { + return false, nil, abortErr(ctx, err, "re-read snapshot %s/%s/%s", v.vol, r.name, r.attempt) + } + if st := string(e.Extended[extSnapState]); st == SnapAborted || st == SnapDeleting || len(e.Extended[extSnapDeletedNs]) != 0 { + return deleted() + } + info, _, err := decodeSnap(path.Join(dir, r.attempt), e) + if err != nil { + return true, nil, nil + } + h := info.Head() + return true, &h, nil +} + +// readHeadRoot reads the current HEAD root. ok is false when there is none; +// a HEAD that does not decode is errUndecodableHead. +func (v *verifier) readHeadRoot(ctx context.Context) (storage.ChunkHead, bool, error) { + e, err := v.c.f.LookupEntry(ctx, v.root, headName) + if errors.Is(err, ErrNotFound) { + return storage.ChunkHead{}, false, nil + } + if err != nil { + return storage.ChunkHead{}, false, abortErr(ctx, err, "re-read HEAD of %s", v.vol) + } + h, err := decodeHead(path.Join(v.root, headName), e) + if err != nil { + return storage.ChunkHead{}, false, errUndecodableHead + } + return h, true, nil +} + +// errUndecodableHead: a re-read HEAD that does not decode cannot excuse a +// miss; the caller reports it. +var errUndecodableHead = errors.New("chunkstore: verify: HEAD does not decode") + +// stillNamed reports whether root r still names chunk identity id at index +// idx at report time, and counts why when it does not. For HEAD it reads +// the root again and, for a segmented root, the one segment covering idx +// (superseded during verify when the key is gone). For a snapshot it reads +// the name record and the attempt again (root deleted during verify when +// the attempt is no longer active). Anything it cannot read or decode +// counts as still naming the chunk: a miss is never excused on a guess. +func (v *verifier) stillNamed(ctx context.Context, r verifyRoot, idx uint64, id string) (bool, error) { + var h storage.ChunkHead + if r.head { + cur, ok, err := v.readHeadRoot(ctx) + if errors.Is(err, errUndecodableHead) { + return true, nil + } + if err != nil { + return false, err + } + if !ok { + v.superseded() + return false, nil + } + h = cur + } else { + active, head, err := v.snapshotActive(ctx, r) + if err != nil { + return false, err + } + if !active { + v.rootDeleted() + return false, nil + } + if head == nil { + return true, nil + } + h = *head + } + named, err := v.names(ctx, h, idx, id) + if err == nil && !named { + v.superseded() + } + return named, err +} + +// names reports whether root h names chunk identity id at index idx. +func (v *verifier) names(ctx context.Context, h storage.ChunkHead, idx uint64, id string) (bool, error) { + if h.Segments == nil { + ref, has := h.Chunks[idx] + return has && chunkIdentity(v.vol, ref.Key) == id, nil + } + if h.ChunkBytes == 0 { + return true, nil + } + group := idx / (manifestSegmentBytes / h.ChunkBytes) + if _, has := h.Segments[group]; !has { + return false, nil + } + chunks, _, _, issue, err := v.segment(ctx, h, group) + if err != nil { + return false, err + } + if issue != nil { + return true, nil + } + ref, has := chunks[idx] + return has && chunkIdentity(v.vol, ref.Key) == id, nil +} + +// addUses records r's chunk references. onlyNew (a refreshed HEAD) +// adds only chunks this pass has not seen: an unchanged key was already +// checked, and its content cannot have changed. +func (v *verifier) addUses(r verifyRoot, chunks map[uint64]storage.ChunkRef, onlyNew bool) { + v.mu.Lock() + defer v.mu.Unlock() + for _, idx := range sortedIndexes(chunks) { + ref := chunks[idx] + id := chunkIdentity(v.vol, ref.Key) + w := v.chunks[id] + if w != nil && onlyNew { + continue + } + if w == nil { + owner, key := splitIdentity(id) + w = &verifyChunk{id: id, owner: owner, key: key} + v.chunks[id] = w + v.pending = append(v.pending, w) + } + w.uses = append(w.uses, verifyUse{root: r, idx: idx, sha: ref.SHA256}) + v.res.ChunksChecked++ + } +} + +func sortedIndexes(m map[uint64]storage.ChunkRef) []uint64 { + out := make([]uint64, 0, len(m)) + for idx := range m { + out = append(out, idx) + } + sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) + return out +} + +// splitIdentity splits a chunkIdentity into the owner volume and its key. +func splitIdentity(id string) (owner, key string) { + owner, key, _ = strings.Cut(id, "\x00") + return owner, key +} + +// ---- snapshots and fork record ---- + +func (v *verifier) snapshots(ctx context.Context) error { + if v.opts.Snapshot != "" { + ref, ok, err := v.c.resolveSnap(ctx, v.vol, v.opts.Snapshot) + if err != nil { + if CodeOf(err) == CodeRemoteUnavailable || ctx.Err() != nil { + return abortErr(ctx, err, "read snapshot %s/%s", v.vol, v.opts.Snapshot) + } + v.finding(VerifyFinding{Root: "snapshot " + v.opts.Snapshot, Class: FindingRootInvalid, Detail: err.Error()}) + return nil + } + if !ok || ref.entry == nil || ref.info.State == SnapAborted { + return catErr(CodeSnapshotNotFound, false, nil, "snapshot %s/%s", v.vol, v.opts.Snapshot) + } + if ref.info.State == SnapDeleting { + return catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted; GC may already reclaim its chunks", v.vol, v.opts.Snapshot) + } + return v.snapshot(ctx, ref.info) + } + if !v.opts.AllSnapshots { + return nil + } + dir := path.Join(v.root, snapNamesDir) + after := "" + for { + page, err := v.c.f.ListEntries(ctx, dir, "", after, listPage) + if err != nil { + return abortErr(ctx, err, "list snapshots of %s", v.vol) + } + for _, e := range page { + if e.GetName() <= after { + return remoteErr(nil, "non-advancing snapshot listing of %s", v.vol) + } + after = e.GetName() + ref, ok, err := v.c.resolveSnap(ctx, v.vol, e.GetName()) + if err != nil { + if CodeOf(err) == CodeRemoteUnavailable || ctx.Err() != nil { + return abortErr(ctx, err, "read snapshot %s/%s", v.vol, e.GetName()) + } + v.finding(VerifyFinding{Root: "snapshot " + e.GetName(), Class: FindingRootInvalid, Detail: err.Error()}) + continue + } + if !ok || ref.entry == nil || ref.info.State == SnapAborted || ref.info.State == SnapDeleting { + continue + } + if err := v.snapshot(ctx, ref.info); err != nil { + return err + } + } + if len(page) < listPage { + return nil + } + } +} + +func (v *verifier) snapshot(ctx context.Context, s SnapshotInfo) error { + r := verifyRoot{label: "snapshot " + s.Name + "/" + s.attempt, name: s.Name, attempt: s.attempt} + v.res.Snapshots = append(v.res.Snapshots, s.Name+"/"+s.attempt) + v.snapRoots = append(v.snapRoots, r) + if s.geo != (Geometry{}) && s.geo != v.geo { + v.finding(VerifyFinding{Root: r.label, Class: FindingGeometry, Detail: fmt.Sprintf("snapshot geometry %+v, VOLUME %+v", s.geo, v.geo)}) + } + chunks, err := v.walk(ctx, r, s.Head()) + if err != nil { + return err + } + v.addUses(r, chunks, false) + return nil +} + +// forkRecord checks a fork's record against the parent snapshot it names: +// some attempt of that snapshot, at the recorded source generation, must +// have exactly the recorded HEAD digest (attempt entries are never +// removed, so a parent snapshot deleted or renamed since still answers). +func (v *verifier) forkRecord(ctx context.Context, vi VolumeInfo) error { + fr := vi.Fork + if vi.Origin != OriginFork || fr == nil { + return nil + } + const label = "VOLUME fork record" + mismatch := func(format string, a ...any) error { + v.finding(VerifyFinding{Root: label, Owner: fr.Source, Class: FindingForkRecordMismatch, Detail: fmt.Sprintf(format, a...)}) + return nil + } + if CheckVolumeID(fr.Source) != nil || CheckSnapshotName(fr.Snapshot) != nil { + return mismatch("fork record names source %q snapshot %q", fr.Source, fr.Snapshot) + } + dir := path.Join(v.c.base, fr.Source, snapsDir, fr.Snapshot) + after := "" + sawGen := false + for { + page, err := v.c.f.ListEntries(ctx, dir, "", after, listPage) + if err != nil { + return abortErr(ctx, err, "list attempts of %s/%s", fr.Source, fr.Snapshot) + } + for _, e := range page { + if e.GetName() <= after { + return remoteErr(nil, "non-advancing attempt listing of %s/%s", fr.Source, fr.Snapshot) + } + after = e.GetName() + info, _, err := decodeSnap(path.Join(dir, e.GetName()), e) + if err != nil || info.State == SnapAborted || info.HeadGen != fr.SourceGen { + continue + } + sawGen = true + if info.digest == fr.HeadSHA256 { + return nil + } + } + if len(page) < listPage { + break + } + } + if sawGen { + return mismatch("no attempt of snapshot %s/%s at gen %d has HEAD digest %s", fr.Source, fr.Snapshot, fr.SourceGen, fr.HeadSHA256) + } + // The source volume itself may have been deleted since the fork: its + // snapshot records went with it and there is nothing to compare with. + // That is not damage to this volume, whose chunks are checked through + // its own roots. + if _, ok, err := v.c.ReadVolume(ctx, fr.Source); err != nil { + return abortErr(ctx, err, "read fork source %s", fr.Source) + } else if !ok { + v.res.ForkSourceGone = true + return nil + } + return mismatch("no attempt of snapshot %s/%s at gen %d found", fr.Source, fr.Snapshot, fr.SourceGen) +} + +// ---- intents ---- + +// intents reports capture intents that look stale: below HEAD's epoch, +// older than IntentStaleAge, and naming no key HEAD references. It is a +// hint; whether GC may expire one is GC's decision, with blockmaster +// authority. An intent that does not decode is an invalid GC root. +func (v *verifier) intents(ctx context.Context, h storage.ChunkHead, chunks map[uint64]storage.ChunkRef) error { + named := map[string]bool{} + for _, ref := range chunks { + named[chunkIdentity(v.vol, ref.Key)] = true + } + for _, ref := range h.Segments { + named[chunkIdentity(v.vol, ref.Key)] = true + } + now := v.c.now() + dir := path.Join(v.root, intentsDir) + after := "" + for { + page, err := v.c.f.ListEntries(ctx, dir, "", after, listPage) + if err != nil { + return abortErr(ctx, err, "list intents of %s", v.vol) + } + for _, e := range page { + if e.GetName() <= after { + return remoteErr(nil, "non-advancing intent listing of %s", v.vol) + } + after = e.GetName() + in, err := decodeIntent(path.Join(dir, e.GetName()), e) + if err != nil { + v.finding(VerifyFinding{Root: "intent " + e.GetName(), Class: FindingRootInvalid, Detail: err.Error()}) + continue + } + if strings.HasPrefix(in.Holder, "snapshot:") || strings.HasPrefix(in.Holder, "fork:") { + continue // copy intents never expire by epoch + } + age := now.Sub(time.Unix(0, in.CreatedNs)) + if in.Epoch >= h.Epoch || age <= v.opts.IntentStaleAge { + continue + } + bound := false + for _, k := range in.Keys { + if named[chunkIdentity(v.vol, k)] { + bound = true + break + } + } + if bound { + continue + } + v.finding(VerifyFinding{Root: "intent " + in.ID, Class: FindingIntentStale, + Detail: fmt.Sprintf("capture intent of %q at epoch %d below HEAD epoch %d, %s old, naming %d keys HEAD does not reference", + in.Holder, in.Epoch, h.Epoch, age.Round(time.Second), len(in.Keys))}) + } + if len(page) < listPage { + return nil + } + } +} + +// ---- refresh ---- + +// maybeRefresh reads HEAD again once RefreshInterval has passed since the +// last view. A new generation is walked (only segments whose reference +// changed are read) and its chunks this pass has not seen are queued. +func (v *verifier) maybeRefresh(ctx context.Context) error { + if !v.hasHead || time.Since(v.lastRefresh) < v.opts.RefreshInterval { + return nil + } + v.lastRefresh = time.Now() + e, err := v.c.f.LookupEntry(ctx, v.root, headName) + if errors.Is(err, ErrNotFound) { + return nil + } + if err != nil { + return abortErr(ctx, err, "refresh HEAD of %s", v.vol) + } + h, err := decodeHead(path.Join(v.root, headName), e) + if err != nil { + if !v.badRefresh { + v.badRefresh = true + v.finding(VerifyFinding{Root: "HEAD", Class: FindingRootInvalid, Detail: "refreshed HEAD: " + err.Error()}) + } + return nil + } + if h.Gen == v.head.Gen && h.Epoch == v.head.Epoch { + return nil + } + hr := verifyRoot{label: headLabel(h.Gen), head: true} + v.res.HeadGens = append(v.res.HeadGens, h.Gen) + chunks, err := v.walk(ctx, hr, h) + if err != nil { + return err + } + v.addUses(hr, chunks, true) + v.head = h + return nil +} + +// ---- bindings ---- + +// checkBindings checks the binding of every chunk in batch. The first batch +// lists each owner's keys/ once; chunks not found in a listing (bound after +// it, or queued by a refresh) are looked up one by one. +func (v *verifier) checkBindings(ctx context.Context, batch []*verifyChunk, list bool) error { + found := map[*verifyChunk]*filerpb.Entry{} + if list { + byOwner := map[string]map[string]*verifyChunk{} + var owners []string + for _, w := range batch { + name, err := keyName(w.key) + if err != nil { + continue + } + if byOwner[w.owner] == nil { + byOwner[w.owner] = map[string]*verifyChunk{} + owners = append(owners, w.owner) + } + byOwner[w.owner][name] = w + } + sort.Strings(owners) + for _, owner := range owners { + if err := v.maybeRefresh(ctx); err != nil { + return err + } + if CheckVolumeID(owner) != nil { + continue + } + want := byOwner[owner] + dir := path.Join(v.c.base, owner, keysDir) + after := "" + for { + page, err := v.c.f.ListEntries(ctx, dir, "", after, listPage) + if err != nil { + return abortErr(ctx, err, "list the chunk keys of %s", owner) + } + for _, e := range page { + if e.GetName() <= after { + return remoteErr(nil, "non-advancing chunk key listing of %s", owner) + } + after = e.GetName() + if w := want[e.GetName()]; w != nil { + found[w] = e + } + } + if len(page) < listPage { + break + } + } + } + } + for _, w := range batch { + e := found[w] + if e == nil { + var err error + if e, err = v.lookupBinding(ctx, w); err != nil { + return err + } + } + if err := v.evaluateBinding(ctx, w, e); err != nil { + return err + } + } + return nil +} + +// lookupBinding reads w's binding directly; nil when it does not exist. +func (v *verifier) lookupBinding(ctx context.Context, w *verifyChunk) (*filerpb.Entry, error) { + if CheckVolumeID(w.owner) != nil { + return nil, nil + } + name, err := keyName(w.key) + if err != nil { + return nil, nil + } + dir := path.Join(v.c.base, w.owner, keysDir) + e, err := v.c.f.LookupEntry(ctx, dir, name) + if errors.Is(err, ErrNotFound) { + return nil, nil + } + if err != nil { + return nil, abortErr(ctx, err, "read chunk key binding %s/%s", dir, name) + } + return e, nil +} + +func (v *verifier) evaluateBinding(ctx context.Context, w *verifyChunk, e *filerpb.Entry) error { + if e == nil { + return v.miss(ctx, w, FindingBindingMissing, fmt.Sprintf("no binding in %s/keys", w.owner)) + } + w.fid = string(e.Extended[extFid]) + if bad := bindingProblem(e); bad != "" { + return v.miss(ctx, w, FindingBindingMissing, "invalid binding: "+bad) + } + if t := e.Extended[extGCDeleted]; len(t) != 0 { + return v.miss(ctx, w, FindingBindingTombstoned, fmt.Sprintf("binding tombstoned by GC (%s=%s)", extGCDeleted, t)) + } + w.bound = true + return nil +} + +// miss reports a miss of w under all of its roots. +func (v *verifier) miss(ctx context.Context, w *verifyChunk, class, detail string) error { + return v.missUses(ctx, w, w.uses, class, func(verifyUse) string { return detail }) +} + +// missUses reports a miss of w as at most one finding: under the first of +// uses whose root still names w at that index at report time (HEAD first, +// then snapshots in the order checked). A root that no longer names it is +// counted (superseded, or root deleted, during verify) and not reported. +func (v *verifier) missUses(ctx context.Context, w *verifyChunk, uses []verifyUse, class string, detail func(verifyUse) string) error { + for _, u := range uses { + still, err := v.stillNamed(ctx, u.root, u.idx, w.id) + if err != nil { + return err + } + if !still { + continue + } + idx := u.idx + v.finding(VerifyFinding{Root: u.root.label, Index: &idx, Owner: w.owner, Key: w.key, FID: w.fid, Class: class, Detail: detail(u)}) + return nil + } + return nil +} + +// ---- data ---- + +// checkData fetches every bound chunk of batch once, at bounded concurrency +// and paced, and checks it against each reference. +func (v *verifier) checkData(ctx context.Context, batch []*verifyChunk) error { + if v.blobs == nil { + return errors.New("chunkstore: verify needs a blob reader for depth data") + } + jobs := make(chan *verifyChunk) + var ( + wg sync.WaitGroup + errMu sync.Mutex + firstEr error + ) + setErr := func(err error) { + errMu.Lock() + if firstEr == nil { + firstEr = err + } + errMu.Unlock() + } + getErr := func() error { + errMu.Lock() + defer errMu.Unlock() + return firstEr + } + wctx, cancel := context.WithCancel(ctx) + defer cancel() + for i := 0; i < v.opts.Concurrency; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for w := range jobs { + if err := v.readChunk(wctx, w); err != nil { + setErr(err) + cancel() + } + } + }() + } + dispatch := func() error { + for _, w := range batch { + if !w.bound { + continue + } + if err := getErr(); err != nil { + return err + } + if err := v.maybeRefresh(ctx); err != nil { + return err + } + if err := v.pacer.wait(wctx, int64(v.chunkBytes)); err != nil { + if werr := getErr(); werr != nil { + return werr + } + return abortErr(ctx, err, "pace chunk reads") + } + select { + case jobs <- w: + case <-wctx.Done(): + if err := getErr(); err != nil { + return err + } + return abortErr(ctx, wctx.Err(), "read chunks of %s", v.vol) + } + } + return nil + } + derr := dispatch() + close(jobs) + wg.Wait() + if err := getErr(); err != nil { + return err + } + return derr +} + +func (v *verifier) readChunk(ctx context.Context, w *verifyChunk) error { + data, err := v.fetch(ctx, w.fid) + switch { + case err == nil: + case isContextErr(ctx, err): + return abortErr(ctx, err, "read chunk %s", w.fid) + case errors.Is(err, ErrBlobNotFound): + return v.miss(ctx, w, FindingNeedleMissing, err.Error()) + default: + return v.miss(ctx, w, FindingReadError, readErrorDetail(err)) + } + v.mu.Lock() + v.res.DistinctChunksRead++ + v.res.BytesRead += int64(len(data)) + v.mu.Unlock() + if uint64(len(data)) != v.chunkBytes { + return v.miss(ctx, w, FindingSizeMismatch, fmt.Sprintf("needle holds %d bytes, chunk size %d", len(data), v.chunkBytes)) + } + sum := sha256.Sum256(data) + var mismatched []verifyUse + for _, u := range w.uses { + if sum != u.sha { + mismatched = append(mismatched, u) + } + } + return v.missUses(ctx, w, mismatched, FindingContentMismatch, func(u verifyUse) string { + return fmt.Sprintf("needle SHA-256 %s, reference %s", hex.EncodeToString(sum[:]), hex.EncodeToString(u.sha[:])) + }) +} + +// verifyPacer spaces reads so they average at most rate bytes per second. +type verifyPacer struct { + mu sync.Mutex + rate int64 // <= 0: unpaced + next time.Time +} + +func (p *verifyPacer) wait(ctx context.Context, n int64) error { + if p == nil || p.rate <= 0 || n <= 0 { + return ctx.Err() + } + p.mu.Lock() + now := time.Now() + if p.next.Before(now) { + p.next = now + } + start := p.next + p.next = p.next.Add(time.Duration(float64(n) / float64(p.rate) * float64(time.Second))) + p.mu.Unlock() + d := time.Until(start) + if d <= 0 { + return ctx.Err() + } + t := time.NewTimer(d) + defer t.Stop() + select { + case <-t.C: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func findingLess(a, b VerifyFinding) bool { + if a.Root != b.Root { + return a.Root < b.Root + } + if (a.Index == nil) != (b.Index == nil) { + return a.Index == nil // a root's and its segments' findings first + } + if as, bs := ptrOr(a.Segment), ptrOr(b.Segment); as != bs { + return as < bs + } + if ai, bi := ptrOr(a.Index), ptrOr(b.Index); ai != bi { + return ai < bi + } + if a.Key != b.Key { + return a.Key < b.Key + } + return a.Class < b.Class +} + +func ptrOr(p *uint64) uint64 { + if p == nil { + return 0 + } + return *p +} diff --git a/seaweed-block/core/frontend/chunkstore/verify_test.go b/seaweed-block/core/frontend/chunkstore/verify_test.go new file mode 100644 index 0000000000..f9d19030fa --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/verify_test.go @@ -0,0 +1,942 @@ +package chunkstore + +import ( + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "path" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// A geometry with three segments' worth of chunks (one segment covers a +// logical GiB: 32768 chunks of 32 KiB), so a test can damage one segment +// and see the others still checked. +var verifyGeo = Geometry{NumBlocks: 3 * 32768 * 8, BlockSize: 4096, ChunkBlocks: 8} + +const ( + verifyChunkBytes = 8 * 4096 + verifyPer = 32768 // chunks per segment at verifyGeo +) + +// countingBlobs counts reads per fid, and fails reads of a fid on request +// with a transient (not "not found") error. +type countingBlobs struct { + gcBlobs + mu sync.Mutex + gets map[string]int + fail map[string]int // reads of fid still to fail; negative: every read +} + +var errTransient = errors.New("read tcp 127.0.0.1:8080: connection reset by peer") + +func (b *countingBlobs) Get(ctx context.Context, fid string) ([]byte, error) { + b.mu.Lock() + b.gets[fid]++ + n := b.fail[fid] + if n > 0 { + b.fail[fid] = n - 1 + } + b.mu.Unlock() + if n != 0 { + return nil, fmt.Errorf("chunkstore: read %s: %w", fid, errTransient) + } + return b.gcBlobs.Get(ctx, fid) +} + +// failReads makes the next n reads of fid fail (n < 0: all of them). +func (b *countingBlobs) failReads(fid string, n int) { + b.mu.Lock() + defer b.mu.Unlock() + b.fail[fid] = n +} + +func (b *countingBlobs) reads(fid string) int { + b.mu.Lock() + defer b.mu.Unlock() + return b.gets[fid] +} + +type verifyFixture struct { + t *testing.T + f *fakeFiler + b gcBlobs + cb *countingBlobs + c *Catalog + tag int +} + +func newVerifyFixture(t *testing.T, vols ...string) *verifyFixture { + t.Helper() + fx := &verifyFixture{t: t, f: newFakeFiler(), b: gcBlobs{newFakeBlobs()}} + fx.cb = &countingBlobs{gcBlobs: fx.b, gets: map[string]int{}, fail: map[string]int{}} + c, err := NewCatalog(manifestFilerBlobs{fx.f, fx.cb}, catBase) + if err != nil { + t.Fatal(err) + } + fx.c = c + for _, vol := range vols { + if err := fx.f.CreateEntry(context.Background(), catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + if _, err := c.EnsureVolume(context.Background(), vol, verifyGeo); err != nil { + t.Fatal(err) + } + } + return fx +} + +func verifyData(fill byte) []byte { + b := make([]byte, verifyChunkBytes) + for i := range b { + b[i] = fill + byte(i%7) + } + return b +} + +// publish installs a new HEAD for vol: the current chunks when keep is set, +// with set written under fresh keys over them. +func (fx *verifyFixture) publish(vol string, set map[uint64][]byte, keep bool) storage.ChunkHead { + fx.t.Helper() + ctx := context.Background() + r, err := NewChunkRemote(fx.f, fx.b, path.Join(catBase, vol)) + if err != nil { + fx.t.Fatal(err) + } + cur, err := r.GetHead(ctx) + if err != nil { + fx.t.Fatal(err) + } + next := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: max(cur.RemoteLSN, 42) + 1, Chunks: map[uint64]storage.ChunkRef{}} + if keep { + for idx, ref := range cur.Chunks { + next.Chunks[idx] = ref + } + } + for idx, data := range set { + fx.tag++ + key := fmt.Sprintf("chunks/t%d/c%d", fx.tag, idx) + if err := r.Put(ctx, key, data); err != nil { + fx.t.Fatal(err) + } + next.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + } + next, ids, err := r.PrepareManifest(ctx, cur, next, verifyChunkBytes) + if err != nil { + fx.t.Fatal(err) + } + gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, next) + if err != nil { + fx.t.Fatal(err) + } + next.Gen = gen + for _, id := range ids { + if err := r.DeleteIntent(ctx, id); err != nil { + fx.t.Fatal(err) + } + } + return next +} + +// binding returns the directory and name of a qualified key's binding. +func bindingOf(t *testing.T, qkey string) (string, string) { + t.Helper() + owner, own, ok := strings.Cut(strings.TrimPrefix(qkey, "@"), "/") + if !ok || !strings.HasPrefix(qkey, "@") { + t.Fatalf("key %q is not owner-qualified", qkey) + } + return path.Join(catBase, owner, keysDir), url.PathEscape(own) +} + +func (fx *verifyFixture) fid(qkey string) string { + fx.t.Helper() + dir, name := bindingOf(fx.t, qkey) + e, err := fx.f.LookupEntry(context.Background(), dir, name) + if err != nil { + fx.t.Fatalf("binding of %s: %v", qkey, err) + } + return string(e.Extended[extFid]) +} + +func (fx *verifyFixture) deleteBinding(qkey string) { + fx.t.Helper() + dir, name := bindingOf(fx.t, qkey) + if err := fx.f.DeleteEntry(context.Background(), dir, name, nil); err != nil { + fx.t.Fatal(err) + } +} + +func (fx *verifyFixture) tombstone(qkey string) { + fx.t.Helper() + dir, name := bindingOf(fx.t, qkey) + fx.f.bumpExtended(path.Join(dir, name), extGCDeleted, "done") +} + +// needle edits the stored bytes of fid (nil deletes the needle). +func (fx *verifyFixture) needle(fid string, edit func([]byte) []byte) { + fx.t.Helper() + fx.b.mu.Lock() + defer fx.b.mu.Unlock() + d, ok := fx.b.data[fid] + if !ok { + fx.t.Fatalf("no needle %s", fid) + } + if out := edit(append([]byte(nil), d...)); out == nil { + delete(fx.b.data, fid) + } else { + fx.b.data[fid] = out + } +} + +func flipByte(d []byte) []byte { d[len(d)/2] ^= 0xff; return d } +func truncate(d []byte) []byte { return d[:len(d)-4096] } +func dropNeedle([]byte) []byte { return nil } + +func (fx *verifyFixture) verify(vol string, opts VerifyOptions) VerifyResult { + fx.t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + res, err := fx.c.Verify(ctx, vol, opts) + if err != nil { + fx.t.Fatalf("verify %s %+v: %v", vol, opts, err) + } + if !res.Complete { + fx.t.Fatalf("verify %s: incomplete without an error: %+v", vol, res) + } + return res +} + +// classes renders findings as "CLASS@index" (or "CLASS@seg"), in order. +func classes(res VerifyResult) []string { + var out []string + for _, f := range res.Findings { + switch { + case f.Index != nil: + out = append(out, fmt.Sprintf("%s@%d", f.Class, *f.Index)) + case f.Segment != nil: + out = append(out, fmt.Sprintf("%s@seg%d", f.Class, *f.Segment)) + default: + out = append(out, f.Class) + } + } + return out +} + +func wantClasses(t *testing.T, what string, res VerifyResult, want ...string) { + t.Helper() + got := classes(res) + if strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("%s: findings %v, want %v\n%+v", what, got, want, res.Findings) + } + n := 0 + for _, c := range res.FindingsByClass { + n += c + } + if n != len(res.Findings) { + t.Fatalf("%s: findingsByClass %v does not count %d findings", what, res.FindingsByClass, len(res.Findings)) + } +} + +func allDepths() []VerifyDepth { return []VerifyDepth{VerifyMeta, VerifyBindings, VerifyData} } + +// A healthy volume with three segments and a snapshot verifies clean at +// every depth; the shared segments are read once. +func TestVerify_CleanVolumeAllDepths(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2), 2 * verifyPer: verifyData(3)}, false) + if _, err := fx.c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { + t.Fatal(err) + } + for _, d := range allDepths() { + res := fx.verify("v1", VerifyOptions{Depth: d, AllSnapshots: true}) + wantClasses(t, string(d), res) + if len(res.HeadGens) != 1 || res.HeadGens[0] != h.Gen || len(res.Snapshots) != 1 || !strings.HasPrefix(res.Snapshots[0], "s1/") || + res.SegmentsChecked != 6 || res.SegmentReads != 3 || res.ChunksChecked != 6 || res.DistinctChunks != 3 { + t.Fatalf("%s: summary %+v", d, res) + } + wantRead := 0 + if d == VerifyData { + wantRead = 3 + } + if res.DistinctChunksRead != wantRead || res.BytesRead != int64(wantRead*verifyChunkBytes) { + t.Fatalf("%s: read %d chunks, %d bytes; want %d chunks", d, res.DistinctChunksRead, res.BytesRead, wantRead) + } + } +} + +// The gap the default depth closes: GC's mark never looks a rooted key up, +// so a HEAD key whose binding is missing passes it; verify reports it. +func TestVerify_MissingBindingGCPassesVerifyReports(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fx.deleteBinding(h.Chunks[1].Key) + + now := time.Now().Add(24 * time.Hour) + g, err := NewCollector(fx.c, fx.b, GCConfig{Grace: time.Hour, IntentTTL: time.Hour, Now: func() time.Time { return now }, + IssuedEpoch: func(context.Context, string) (uint64, error) { return 1, nil }}) + if err != nil { + t.Fatal(err) + } + if _, err := g.Preview(context.Background()); err != nil { + t.Fatalf("GC mark: %v; the gap is that it passes", err) + } + + wantClasses(t, "meta", fx.verify("v1", VerifyOptions{Depth: VerifyMeta})) + res := fx.verify("v1", VerifyOptions{}) + wantClasses(t, "default depth", res, "BINDING_MISSING@1") + f := res.Findings[0] + if res.Depth != VerifyBindings || f.Volume != "v1" || f.Root != headLabel(h.Gen) || f.Owner != "v1" || !strings.HasPrefix(h.Chunks[1].Key, "@v1/"+f.Key) { + t.Fatalf("finding %+v (depth %s)", f, res.Depth) + } +} + +// A flipped byte is invisible to metadata; depth data catches it. +func TestVerify_FlippedByteDataOnly(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fx.needle(fx.fid(h.Chunks[0].Key), flipByte) + wantClasses(t, "bindings", fx.verify("v1", VerifyOptions{Depth: VerifyBindings})) + res := fx.verify("v1", VerifyOptions{Depth: VerifyData}) + wantClasses(t, "data", res, "CONTENT_MISMATCH@0") + if res.Findings[0].FID != fx.fid(h.Chunks[0].Key) { + t.Fatalf("finding fid %q", res.Findings[0].FID) + } +} + +func TestVerify_TruncatedNeedleSizeMismatch(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fx.needle(fx.fid(h.Chunks[1].Key), truncate) + wantClasses(t, "data", fx.verify("v1", VerifyOptions{Depth: VerifyData}), "SIZE_MISMATCH@1") +} + +func TestVerify_MissingNeedle(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fx.needle(fx.fid(h.Chunks[0].Key), dropNeedle) + wantClasses(t, "bindings", fx.verify("v1", VerifyOptions{Depth: VerifyBindings})) + res := fx.verify("v1", VerifyOptions{Depth: VerifyData}) + wantClasses(t, "data", res, "NEEDLE_MISSING@0") + // The store said "not found": that answer is not retried. + if res.ReadRetries != 0 || res.ChunksNotRead != 0 || fx.cb.reads(fx.fid(h.Chunks[0].Key)) != 1 { + t.Fatalf("not-found needle: %d retries, %d not read, %d reads; want 0, 0, 1", + res.ReadRetries, res.ChunksNotRead, fx.cb.reads(fx.fid(h.Chunks[0].Key))) + } +} + +// A read that fails once with an error other than "not found" is retried +// and then verifies: no finding. +func TestVerify_TransientReadIsRetried(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + chunk, seg := fx.fid(h.Chunks[0].Key), fx.fid(h.Segments[0].Key) + fx.cb.failReads(chunk, 1) + fx.cb.failReads(seg, 1) + res := fx.verify("v1", VerifyOptions{Depth: VerifyData}) + wantClasses(t, "transient", res) + if res.ReadRetries != 2 || res.ChunksNotRead != 0 || res.DistinctChunksRead != 2 || fx.cb.reads(chunk) != 2 || fx.cb.reads(seg) != 2 { + t.Fatalf("transient errors: %d retries, %d not read, %d chunks read, reads chunk %d segment %d; want 2, 0, 2, 2, 2", + res.ReadRetries, res.ChunksNotRead, res.DistinctChunksRead, fx.cb.reads(chunk), fx.cb.reads(seg)) + } +} + +// A read that keeps failing with an error other than "not found" is +// READ_ERROR (not verified), never NEEDLE_MISSING or SEGMENT_UNREADABLE. +func TestVerify_PersistentReadErrorIsNotAMissingNeedle(t *testing.T) { + t.Run("chunk", func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fid := fx.fid(h.Chunks[0].Key) + fx.cb.failReads(fid, -1) + res := fx.verify("v1", VerifyOptions{Depth: VerifyData}) + wantClasses(t, "chunk read error", res, "READ_ERROR@0") + f := res.Findings[0] + if res.ChunksNotRead != 1 || res.ReadRetries != 2 || fx.cb.reads(fid) != 3 || f.FID != fid || + !strings.Contains(f.Detail, "not verified") || !strings.Contains(f.Detail, errTransient.Error()) { + t.Fatalf("chunk read error: %d not read, %d retries, %d reads, finding %+v", res.ChunksNotRead, res.ReadRetries, fx.cb.reads(fid), f) + } + }) + t.Run("segment", func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2)}, false) + fx.cb.failReads(fx.fid(h.Segments[0].Key), -1) + res := fx.verify("v1", VerifyOptions{}) + wantClasses(t, "segment read error", res, "READ_ERROR@seg0") + if res.ChunksNotRead != 1 || res.ChunksChecked != 1 { + t.Fatalf("segment read error: %+v", res) + } + }) +} + +// SWFS reports a needle absent (ErrBlobNotFound) only when every location +// answers 404; the error text is what it was before. +func TestSWFS_GetNotFoundIsErrBlobNotFound(t *testing.T) { + server := func(status int) string { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(status) })) + t.Cleanup(s.Close) + return strings.TrimPrefix(s.URL, "http://") + } + missing, broken := server(http.StatusNotFound), server(http.StatusInternalServerError) + for _, tc := range []struct { + name string + hosts []string + notFound bool + }{ + {"every location 404", []string{missing, missing}, true}, + {"one location 500", []string{missing, broken}, false}, + {"only 500", []string{broken}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + var locs []*filerpb.Location + for _, h := range tc.hosts { + locs = append(locs, &filerpb.Location{Url: h}) + } + c := startFakeFiler(t, &fakeFilerGRPC{lookupVol: &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{"7": {Locations: locs}}}}) + _, err := c.Get(context.Background(), "7,0000dead") + last := tc.hosts[len(tc.hosts)-1] + status := 404 + if last == broken { + status = 500 + } + if err == nil || errors.Is(err, ErrBlobNotFound) != tc.notFound || err.Error() != fmt.Sprintf("chunkstore: read 7,0000dead: http %d from %s", status, last) { + t.Fatalf("Get: %v (not found %v), want not found %v", err, errors.Is(err, ErrBlobNotFound), tc.notFound) + } + }) + } +} + +// A root that names a binding GC tombstoned: the chunk is gone or going. +func TestVerify_TombstonedBinding(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fx.tombstone(h.Chunks[0].Key) + fx.needle(fx.fid(h.Chunks[0].Key), dropNeedle) + wantClasses(t, "bindings", fx.verify("v1", VerifyOptions{}), "BINDING_TOMBSTONED@0") + // No read of a tombstoned binding's needle: one finding, not two. + res := fx.verify("v1", VerifyOptions{Depth: VerifyData}) + wantClasses(t, "data", res, "BINDING_TOMBSTONED@0") + if res.DistinctChunksRead != 1 { + t.Fatalf("read %d chunks, want only the sound one", res.DistinctChunksRead) + } +} + +// A corrupt segment and a segment whose binding is gone are each a finding; +// the pass goes on to the other segments and their chunks. +func TestVerify_UnreadableSegmentContinues(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2), 2 * verifyPer: verifyData(3)}, false) + fx.needle(fx.fid(h.Segments[0].Key), flipByte) + fx.deleteBinding(h.Segments[1].Key) + fx.deleteBinding(h.Chunks[2*verifyPer].Key) + res := fx.verify("v1", VerifyOptions{}) + wantClasses(t, "bindings", res, "SEGMENT_UNREADABLE@seg0", "SEGMENT_UNREADABLE@seg1", fmt.Sprintf("BINDING_MISSING@%d", 2*verifyPer)) + if res.SegmentsChecked != 3 || res.ChunksChecked != 1 { + t.Fatalf("summary %+v", res) + } + if !strings.Contains(res.Findings[0].Detail, "hash") || res.Findings[0].Key != h.Segments[0].Key { + t.Fatalf("corrupt segment finding %+v", res.Findings[0]) + } +} + +// A chunk that leaves HEAD and is collected while the pass runs is not a +// finding under HEAD (it is counted as superseded during verify); the same +// miss under a snapshot that still names it is one. +func TestVerify_SupersededDuringPass(t *testing.T) { + type damage struct { + name string + depth VerifyDepth + apply func(fx *verifyFixture, qkey string) + class string + } + cases := []damage{ + {"binding deleted", VerifyBindings, func(fx *verifyFixture, k string) { + fid := fx.fid(k) + fx.deleteBinding(k) + fx.needle(fid, dropNeedle) + }, FindingBindingMissing}, + {"binding tombstoned", VerifyBindings, func(fx *verifyFixture, k string) { + fx.tombstone(k) + fx.needle(fx.fid(k), dropNeedle) + }, FindingBindingTombstoned}, + {"needle deleted", VerifyData, func(fx *verifyFixture, k string) { fx.needle(fx.fid(k), dropNeedle) }, FindingNeedleMissing}, + {"needle overwritten", VerifyData, func(fx *verifyFixture, k string) { fx.needle(fx.fid(k), flipByte) }, FindingContentMismatch}, + {"needle unreadable", VerifyData, func(fx *verifyFixture, k string) { fx.cb.failReads(fx.fid(k), -1) }, FindingReadError}, + } + for _, tc := range cases { + for _, withSnap := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/snapshot=%v", tc.name, withSnap), func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + if withSnap { + if _, err := fx.c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { + t.Fatal(err) + } + } + old := h.Chunks[0].Key + hooked := 0 + opts := VerifyOptions{Depth: tc.depth, AllSnapshots: withSnap} + opts.hook = func(stage string) { + if stage != verifyHookHeadWalked { + return + } + hooked++ + // After verify read HEAD: the owner replaces chunk 0 and GC + // collects the old one. + fx.publish("v1", map[uint64][]byte{0: verifyData(9)}, true) + tc.apply(fx, old) + } + res := fx.verify("v1", opts) + if !withSnap { + wantClasses(t, "HEAD only", res) + } else { + wantClasses(t, "with the snapshot", res, tc.class+"@0") + if !strings.HasPrefix(res.Findings[0].Root, "snapshot s1/") { + t.Fatalf("finding root %q, want the snapshot", res.Findings[0].Root) + } + } + if hooked != 1 || res.SupersededDuringVerify != 1 || len(res.HeadGens) != 1 || res.HeadGens[0] != h.Gen { + t.Fatalf("hooked %d, superseded %d, gens %v; want 1, 1, [%d]", hooked, res.SupersededDuringVerify, res.HeadGens, h.Gen) + } + }) + } + } +} + +// A miss under a snapshot is a finding only while that attempt is still +// active: a snapshot deleted during the pass, whose chunk is then +// collected, is counted as root deleted during verify and listed as not +// fully covered, not reported. +func TestVerify_SnapshotDeletedDuringPass(t *testing.T) { + cases := []struct { + name string + depth VerifyDepth + apply func(fx *verifyFixture, qkey string) + class string + }{ + {"binding deleted", VerifyBindings, func(fx *verifyFixture, k string) { + fid := fx.fid(k) + fx.deleteBinding(k) + fx.needle(fid, dropNeedle) + }, FindingBindingMissing}, + {"needle overwritten", VerifyData, func(fx *verifyFixture, k string) { fx.needle(fx.fid(k), flipByte) }, FindingContentMismatch}, + {"needle truncated", VerifyData, func(fx *verifyFixture, k string) { fx.needle(fx.fid(k), truncate) }, FindingSizeMismatch}, + {"needle unreadable", VerifyData, func(fx *verifyFixture, k string) { fx.cb.failReads(fx.fid(k), -1) }, FindingReadError}, + } + for _, tc := range cases { + for _, deleteSnap := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/deleted=%v", tc.name, deleteSnap), func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + s, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h) + if err != nil { + t.Fatal(err) + } + // HEAD moves on before the pass: only the snapshot names the old chunk 0. + fx.publish("v1", map[uint64][]byte{0: verifyData(9)}, true) + old := h.Chunks[0].Key + opts := VerifyOptions{Depth: tc.depth, AllSnapshots: true} + opts.hook = func(stage string) { + if stage != verifyHookRootsWalked { + return + } + if deleteSnap { + if st, err := fx.c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || st != SnapDeleting { + t.Errorf("delete s1: %q %v", st, err) + } + } + tc.apply(fx, old) + } + res := fx.verify("v1", opts) + if len(res.Snapshots) != 1 { + t.Fatalf("snapshots checked %v", res.Snapshots) + } + if !deleteSnap { + wantClasses(t, "active snapshot", res, tc.class+"@0") + if res.RootDeletedDuringVerify != 0 || len(res.SnapshotsDeletedDuringVerify) != 0 || !strings.HasPrefix(res.Findings[0].Root, "snapshot s1/") { + t.Fatalf("active snapshot: %+v", res) + } + return + } + wantClasses(t, "deleted snapshot", res) + if res.RootDeletedDuringVerify != 1 || res.SupersededDuringVerify != 0 || + len(res.SnapshotsDeletedDuringVerify) != 1 || res.SnapshotsDeletedDuringVerify[0] != res.Snapshots[0] { + t.Fatalf("deleted snapshot: root deleted %d, superseded %d, deleted list %v (checked %v, created %+v)", + res.RootDeletedDuringVerify, res.SupersededDuringVerify, res.SnapshotsDeletedDuringVerify, res.Snapshots, s.Name) + } + }) + } + } +} + +// A chunk named by HEAD (superseded during the pass) and by a snapshot that +// is still active is one finding, under the snapshot. +func TestVerify_SharedChunkReportedUnderStillNamingRoot(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { + t.Fatal(err) + } + opts := VerifyOptions{Depth: VerifyData, AllSnapshots: true} + opts.hook = func(stage string) { + if stage == verifyHookRootsWalked { + fx.publish("v1", map[uint64][]byte{0: verifyData(9)}, true) + fx.needle(fx.fid(h.Chunks[0].Key), dropNeedle) + } + } + res := fx.verify("v1", opts) + wantClasses(t, "shared chunk", res, "NEEDLE_MISSING@0") + if !strings.HasPrefix(res.Findings[0].Root, "snapshot s1/") || res.SupersededDuringVerify != 1 || res.RootDeletedDuringVerify != 0 { + t.Fatalf("finding under %q, superseded %d, root deleted %d; want the snapshot, 1, 0", + res.Findings[0].Root, res.SupersededDuringVerify, res.RootDeletedDuringVerify) + } +} + +// A HEAD that advances mid-pass: the result lists both generations, and +// only the segment whose key changed is read again. +func TestVerify_HeadRefreshRewalksChangedSegments(t *testing.T) { + for _, d := range []VerifyDepth{VerifyBindings, VerifyData} { + t.Run(string(d), func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2), 2 * verifyPer: verifyData(3)}, false) + var h2 storage.ChunkHead + opts := VerifyOptions{Depth: d, RefreshInterval: time.Millisecond} + opts.hook = func(stage string) { + if stage == verifyHookHeadWalked { + h2 = fx.publish("v1", map[uint64][]byte{verifyPer: verifyData(7)}, true) + time.Sleep(3 * time.Millisecond) // past the refresh interval + } + } + res := fx.verify("v1", opts) + wantClasses(t, "refresh", res) + if len(res.HeadGens) != 2 || res.HeadGens[0] != h1.Gen || res.HeadGens[1] != h2.Gen { + t.Fatalf("covered gens %v, want [%d %d]", res.HeadGens, h1.Gen, h2.Gen) + } + if h2.Segments[0] != h1.Segments[0] || h2.Segments[2] != h1.Segments[2] || h2.Segments[1] == h1.Segments[1] { + t.Fatal("fixture: the new HEAD should change only segment 1") + } + if res.SegmentReads != 4 || res.SegmentsChecked != 6 { + t.Fatalf("segment reads %d (checked %d); want 3 + 1 changed", res.SegmentReads, res.SegmentsChecked) + } + if res.DistinctChunks != 4 || res.ChunksChecked != 4 { + t.Fatalf("chunks %d distinct, %d checked; want the 3 first and the 1 new", res.DistinctChunks, res.ChunksChecked) + } + if d == VerifyData && (res.DistinctChunksRead != 4 || fx.cb.reads(fx.fid(h2.Chunks[verifyPer].Key)) != 1) { + t.Fatalf("read %d chunks; want 4, the new one included", res.DistinctChunksRead) + } + }) + } +} + +// A chunk shared by HEAD and two snapshots is fetched once. +func TestVerify_DedupSharedChunkReadOnce(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + for _, n := range []string{"s1", "s2"} { + if _, err := fx.c.CreateSnapshot(context.Background(), "v1", SnapshotRequest{Name: n, RequestID: "r-" + n}, h); err != nil { + t.Fatal(err) + } + } + res := fx.verify("v1", VerifyOptions{Depth: VerifyData, AllSnapshots: true}) + wantClasses(t, "dedup", res) + if res.ChunksChecked != 6 || res.DistinctChunks != 2 || res.DistinctChunksRead != 2 || len(res.Snapshots) != 2 { + t.Fatalf("summary %+v", res) + } + for _, idx := range []uint64{0, 1} { + if n := fx.cb.reads(fx.fid(h.Chunks[idx].Key)); n != 1 { + t.Fatalf("chunk %d read %d times, want once", idx, n) + } + } + // One named snapshot works the same way. + res = fx.verify("v1", VerifyOptions{Depth: VerifyBindings, Snapshot: "s2"}) + if len(res.Snapshots) != 1 || !strings.HasPrefix(res.Snapshots[0], "s2/") || res.ChunksChecked != 4 { + t.Fatalf("named snapshot: %+v", res) + } + if _, err := fx.c.Verify(context.Background(), "v1", VerifyOptions{Snapshot: "nope"}); CodeOf(err) != CodeSnapshotNotFound { + t.Fatalf("missing snapshot: %v", err) + } +} + +// A fork's qualified keys are checked in the owner volume's keys/, and its +// fork record against the parent snapshot. +func TestVerify_ForkQualifiedKeysAndRecord(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "snap"}, h); err != nil { + t.Fatal(err) + } + if _, err := fx.c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); err != nil { + t.Fatal(err) + } + for _, d := range allDepths() { + wantClasses(t, "clean fork "+string(d), fx.verify("v2", VerifyOptions{Depth: d})) + } + // The fork wrote no binding of its own: every chunk resolves to v1. + fx.deleteBinding(h.Chunks[1].Key) + res := fx.verify("v2", VerifyOptions{}) + wantClasses(t, "fork, parent binding gone", res, "BINDING_MISSING@1") + if res.Findings[0].Owner != "v1" || res.Findings[0].Volume != "v2" { + t.Fatalf("finding %+v, want owner v1 in volume v2", res.Findings[0]) + } + + // A fork record whose digest is not the parent snapshot's. + e, err := fx.f.LookupEntry(ctx, path.Join(catBase, "v2"), volumeName) + if err != nil { + t.Fatal(err) + } + var vi VolumeInfo + if err := json.Unmarshal(e.Content, &vi); err != nil { + t.Fatal(err) + } + vi.Fork.HeadSHA256 = strings.Repeat("0", 64) + if e.Content, err = json.Marshal(vi); err != nil { + t.Fatal(err) + } + if err := fx.f.UpdateEntry(ctx, path.Join(catBase, "v2"), e, nil); err != nil { + t.Fatal(err) + } + res = fx.verify("v2", VerifyOptions{Depth: VerifyMeta}) + wantClasses(t, "tampered fork record", res, "FORK_RECORD_MISMATCH") + if res.Findings[0].Owner != "v1" || !strings.Contains(res.Findings[0].Detail, "s1") { + t.Fatalf("finding %+v", res.Findings[0]) + } +} + +// A fork whose source volume was deleted afterwards has nothing to compare +// its fork record with. That is not damage: no finding, and the result +// says the source is gone. While the source volume still exists, a missing +// parent snapshot attempt is a finding. +func TestVerify_ForkSourceVolumeDeleted(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1)}, false) + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "snap"}, h); err != nil { + t.Fatal(err) + } + if _, err := fx.c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); err != nil { + t.Fatal(err) + } + // The parent's snapshot attempts vanish, the source volume remains. + dir := path.Join(catBase, "v1", snapsDir, "s1") + es, err := fx.f.ListEntries(ctx, dir, "", "", 100) + if err != nil || len(es) == 0 { + t.Fatalf("attempts of s1: %d, %v", len(es), err) + } + for _, e := range es { + if err := fx.f.DeleteEntry(ctx, dir, e.GetName(), nil); err != nil { + t.Fatal(err) + } + } + res := fx.verify("v2", VerifyOptions{Depth: VerifyMeta}) + wantClasses(t, "attempts gone, source present", res, "FORK_RECORD_MISMATCH") + if res.ForkSourceGone { + t.Fatal("ForkSourceGone set while the source volume exists") + } + // Now the source volume record goes too. + if err := fx.f.DeleteEntry(ctx, path.Join(catBase, "v1"), volumeName, nil); err != nil { + t.Fatal(err) + } + res = fx.verify("v2", VerifyOptions{Depth: VerifyMeta}) + wantClasses(t, "source volume deleted", res) + if !res.ForkSourceGone { + t.Fatal("ForkSourceGone not set") + } +} + +// Intent bookkeeping: an old capture intent below HEAD's epoch naming keys +// HEAD does not reference is reported; one naming a key HEAD binds, a +// current one and a copy intent are not. +func TestVerify_IntentStale(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1)}, false) + root := path.Join(catBase, "v1") + headKey := strings.TrimPrefix(h.Chunks[0].Key, "@v1/") + stale, err := putIntent(ctx, fx.f, root, storage.ChunkIntent{Gen: 1, Epoch: 0, Holder: "old/r1", Keys: []string{"chunks/lost/k"}}) + if err != nil { + t.Fatal(err) + } + for _, in := range []storage.ChunkIntent{ + {Gen: 1, Epoch: 0, Holder: "old/r1", Keys: []string{headKey}}, // HEAD binds its key + {Gen: 2, Epoch: 1, Holder: "h1", Keys: []string{"chunks/next/k"}}, // the current epoch + {Gen: 0, Epoch: 0, Holder: "snapshot:v1/s9/1-0000000000000000", Keys: []string{"x/y"}}, // a copy intent + } { + if _, err := putIntent(ctx, fx.f, root, in); err != nil { + t.Fatal(err) + } + } + wantClasses(t, "young intents", fx.verify("v1", VerifyOptions{})) + fx.c.SetClock(func() time.Time { return time.Now().Add(2 * time.Hour) }) + res := fx.verify("v1", VerifyOptions{Depth: VerifyMeta}) + wantClasses(t, "old intents", res, "INTENT_STALE") + if res.Findings[0].Root != "intent "+stale { + t.Fatalf("stale intent finding %+v, want intent %s", res.Findings[0], stale) + } +} + +// recordingStore counts every write the catalog makes through it. +type recordingStore struct { + Filer + blobs *countingBlobs + mu sync.Mutex + creates, updates, deletes int + blobPuts, blobDeletes, reads int +} + +func (r *recordingStore) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, o bool) error { + r.mu.Lock() + r.creates++ + r.mu.Unlock() + return r.Filer.CreateEntry(ctx, dir, e, o) +} +func (r *recordingStore) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, x map[string][]byte) error { + r.mu.Lock() + r.updates++ + r.mu.Unlock() + return r.Filer.UpdateEntry(ctx, dir, e, x) +} +func (r *recordingStore) DeleteEntry(ctx context.Context, dir, name string, x map[string][]byte) error { + r.mu.Lock() + r.deletes++ + r.mu.Unlock() + return r.Filer.DeleteEntry(ctx, dir, name, x) +} +func (r *recordingStore) Put(ctx context.Context, d []byte) (string, error) { + r.mu.Lock() + r.blobPuts++ + r.mu.Unlock() + return r.blobs.Put(ctx, d) +} +func (r *recordingStore) Get(ctx context.Context, fid string) ([]byte, error) { + r.mu.Lock() + r.reads++ + r.mu.Unlock() + return r.blobs.Get(ctx, fid) +} +func (r *recordingStore) DeleteBlob(ctx context.Context, fid string) error { + r.mu.Lock() + r.blobDeletes++ + r.mu.Unlock() + return r.blobs.DeleteBlob(ctx, fid) +} + +// Verify writes nothing, at any depth, also on the miss, superseded and +// refresh paths and for a fork. +func TestVerify_ReadOnlyAtEveryDepth(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2), verifyPer: verifyData(3)}, false) + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "snap"}, h); err != nil { + t.Fatal(err) + } + if _, err := fx.c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); err != nil { + t.Fatal(err) + } + if _, err := putIntent(ctx, fx.f, path.Join(catBase, "v1"), storage.ChunkIntent{Gen: 1, Holder: "old", Keys: []string{"k/old"}}); err != nil { + t.Fatal(err) + } + fx.needle(fx.fid(h.Chunks[1].Key), flipByte) + rec := &recordingStore{Filer: fx.f, blobs: fx.cb} + cat, err := NewCatalog(rec, catBase) + if err != nil { + t.Fatal(err) + } + cat.SetClock(func() time.Time { return time.Now().Add(2 * time.Hour) }) + for _, d := range allDepths() { + for _, vol := range []string{"v1", "v2"} { + opts := VerifyOptions{Depth: d, AllSnapshots: true, RefreshInterval: time.Millisecond} + opts.hook = func(stage string) { + if vol == "v1" && stage == verifyHookHeadWalked { + // Writes by the owner (through the fixture, not the + // recorder): a new HEAD, and the old chunk 0 collected. + r, _ := NewChunkRemote(fx.f, fx.b, path.Join(catBase, "v1")) + cur, err := r.GetHead(ctx) + if err != nil { + t.Error(err) + return + } + oldFid := fx.fid(cur.Chunks[0].Key) + fx.publish("v1", map[uint64][]byte{0: verifyData(byte(10 + len(d)))}, true) + fx.needle(oldFid, dropNeedle) + time.Sleep(3 * time.Millisecond) + } + } + res, err := cat.Verify(ctx, vol, opts) + if err != nil || !res.Complete { + t.Fatalf("%s %s: %v", d, vol, err) + } + if d == VerifyData && rec.reads == 0 { + t.Fatalf("%s %s: no blob reads recorded; the recorder is not in the path", d, vol) + } + } + } + if rec.creates+rec.updates+rec.deletes+rec.blobPuts+rec.blobDeletes != 0 { + t.Fatalf("verify wrote: %d creates, %d updates, %d deletes, %d blob puts, %d blob deletes", + rec.creates, rec.updates, rec.deletes, rec.blobPuts, rec.blobDeletes) + } +} + +// A chunk index past the end of VOLUME's geometry is a GEOMETRY finding. +func TestVerify_GeometryOutsideVolume(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + fx.publish("v1", map[uint64][]byte{0: verifyData(1), 2 * verifyPer: verifyData(2)}, false) + e, err := fx.f.LookupEntry(ctx, path.Join(catBase, "v1"), volumeName) + if err != nil { + t.Fatal(err) + } + var vi VolumeInfo + if err := json.Unmarshal(e.Content, &vi); err != nil { + t.Fatal(err) + } + vi.NumBlocks = 2 * verifyPer * 8 + if e.Content, err = json.Marshal(vi); err != nil { + t.Fatal(err) + } + if err := fx.f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil { + t.Fatal(err) + } + wantClasses(t, "meta", fx.verify("v1", VerifyOptions{Depth: VerifyMeta}), fmt.Sprintf("GEOMETRY@%d", 2*verifyPer)) +} + +// A HEAD that does not decode is a finding, not a failure to run. +func TestVerify_InvalidHeadRoot(t *testing.T) { + fx := newVerifyFixture(t, "v1") + fx.publish("v1", map[uint64][]byte{0: verifyData(1)}, false) + fx.f.bumpExtended(path.Join(catBase, "v1", headName), extGen, "999") + res := fx.verify("v1", VerifyOptions{}) + wantClasses(t, "bad HEAD", res, "ROOT_INVALID") + if len(res.HeadGens) != 0 { + t.Fatalf("covered gens %v of an invalid HEAD", res.HeadGens) + } +} + +// Only an inability to continue stops the pass: the result then says it is +// incomplete and keeps what was covered. +func TestVerify_ContextEndedIsIncomplete(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + opts := VerifyOptions{Depth: VerifyData} + opts.hook = func(stage string) { cancel() } + res, err := fx.c.Verify(ctx, "v1", opts) + if !errors.Is(err, context.Canceled) || res.Complete || len(res.HeadGens) != 1 || res.HeadGens[0] != h.Gen { + t.Fatalf("cancelled pass: %v, %+v", err, res) + } + if _, err := fx.c.Verify(context.Background(), "nope", VerifyOptions{}); CodeOf(err) != CodeNotChunkVolume { + t.Fatalf("missing volume: %v", err) + } +} From f3c84c4d815a0c016be69dffe8bec6d5d99327c0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 20:09:16 -0800 Subject: [PATCH 06/34] docs(invariants): rows for verify and the ops chunk single-filer check Co-Authored-By: Claude Fable 5.2 --- seaweed-block/docs/design/invariants.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index aa90753dcb..a9eb9eb8be 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -275,6 +275,10 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | `deleting` | `purging` | commit point, bound to the same delete incarnation | `core/frontend/chunkstore/volume_delete.go` `commitHeadPurging` | `INV-VOLDEL-COMMIT-001` | | `purging` | `deleted` | chunks dropped and `VOLUME` marked deleted | `core/frontend/chunkstore/volume_delete.go` `finishHeadDeleted`, `markVolumeDeleted` | `INV-VOL-ID-NO-REUSE-001` | | `deleting`, `purging`, `deleted` | — | no claim or cut moves HEAD; only the delete's own transitions | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-HEAD-DELETE-FROZEN-001` | +| `INV-VERIFY-READONLY-001` | Verify writes nothing to the filer or the blob store at any depth: no intent, mark, tombstone, binding or needle. | M6 (reader; no transition) | `core/frontend/chunkstore/verify.go` `Catalog.Verify` | `TestVerify_ReadOnlyAtEveryDepth` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-RECHECK-001` | Verify reports a miss only if its root still names the chunk when it is rechecked: a miss under HEAD is a finding only if the current HEAD still names the key at that index, and a miss under a snapshot only if that attempt is still published and not deleting. A reader that can outlive GC's grace holds no claim, so it rechecks its root. | M6 (reader beside GC mark) | `core/frontend/chunkstore/verify.go` `Catalog.Verify` | `TestVerify_SupersededDuringPass`, `TestVerify_SnapshotDeletedDuringPass`, `TestVerify_SharedChunkReportedUnderStillNamingRoot` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-NOTFOUND-001` | Verify reports `NEEDLE_MISSING` only when the blob store answers that the needle does not exist; any other read failure is retried and then reported as `READ_ERROR`, which means not verified. | M6 (reader) | `core/frontend/chunkstore/verify.go` `Catalog.Verify`; `core/frontend/chunkstore/swfs.go` `Get` (`ErrBlobNotFound`) | `TestVerify_PersistentReadErrorIsNotAMissingNeedle`, `TestVerify_TransientReadIsRetried`, `TestSWFS_GetNotFoundIsErrBlobNotFound` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-CHUNK-CLI-SINGLE-FILER-001` | Every `sw-block ops chunk` command, gc included, runs the single-filer check of `INV-WS-SINGLE-FILER-001` before its first catalog read or write, and refuses otherwise. | M4 (startup) → Refused, for the offline commands | `cmd/sw-block/chunk.go` `dialChunkFiler`; `cmd/sw-block/chunk_gc.go` `chunkGC` | `TestOpsChunk_RefusesMultiFiler` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE | | — | `aborted` | a GC copy sweep settles a dead fork by an exclusive create of an aborted HEAD tombstone, so the fork can never publish | `core/frontend/chunkstore/catalog.go` `AbortFork`; `core/frontend/chunkstore/gc_copy.go` `SweepCopies` | — | **Snapshots and forks.** From d563741b68629c29d77e7e7f866cf29c5487948d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 20:35:21 -0800 Subject: [PATCH 07/34] docs(invariants): rows for rules the code already keeps Add rows, each with its enforcing function and test checked against the code, for: the bounded guest wait and the logical read path during a cut; the named snapshot's point and durability; fork from a published snapshot; GC deleting the exact recorded fid; the grace restart; strict journal isolation on move and placement targets. The WAL flusher sync row is a STUB (no test yet). Clauses enforced only by reading are listed in the notes. Also: M7 in the contents, the row count recounted from the tables, Part A protects columns. Co-Authored-By: Claude Fable 5.2 --- seaweed-block/docs/design/invariants.md | 37 +++++++++++++++++++------ 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index aa90753dcb..92b1329d77 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -25,6 +25,7 @@ The design is described in three documents, and this one collects their machines - [M4 Workspace HEAD holder and takeover](#m4-workspace-head-holder-and-takeover) - [M5 The cut pipeline](#m5-the-cut-pipeline) - [M6 Chunk lifecycle](#m6-chunk-lifecycle) + - [M7. Host background-cut admission](#m7-host-background-cut-admission) - [Part B. Invariant ledger](#part-b-invariant-ledger) - [Part C. Change rules](#part-c-change-rules) @@ -58,7 +59,7 @@ stateDiagram-v2 | Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001` | | Serving | Serving | each `Read`, `Write`, `Sync` passes the operational, chunk-fence and lineage checks; write admission samples the active writer's native pressure before waiting; a write is durable only when a covering `Sync` returns | `core/frontend/durable/storage_adapter.go` `gate`; `core/storage/walstore.go` `WALStore.Sync` | `INV-FE-LINEAGE-GATE-001`, `INV-WAL-SYNC-FRONTIER-001`, `INV-FE-FUA-SYNC-001`, `INV-FE-FLUSH-SYNC-001`, `INV-WAL-V3-ADMISSION-001` | -| Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse | `core/storage/flusher.go` `flushOnceInternal`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001` | +| Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse | `core/storage/flusher.go` `flushOnceInternal`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001`, `INV-WAL-FLUSH-SYNC-COVERS-WAL-001` | | Serving | FaultLatched | the first failed `fsync` of the store file, or a WAL append whose write failed | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`; `core/storage/walstore_v3.go` `appendWriteV3` | `INV-WAL-FSYNC-STICKY-001`, `INV-WAL-APPEND-STICKY-001` | | FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` | | any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — | @@ -93,7 +94,7 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | | Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | -| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node other than the source, and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding; each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001` | +| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node other than the source, and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding, and, under strict journal isolation, a target node whose durable root does not share the authority store's file system (the retry of an issued move excepted); each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`; `core/host/master/journal_isolation.go` `colocatedTargetRefused` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-MASTER-JOURNAL-ISOLATION-001` | | Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | | Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` | | Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001` | @@ -240,7 +241,7 @@ stateDiagram-v2 |---|---|---|---| | Admit | optional Budget admitted before staging/barrier; not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease) | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `INV-WS-LEASE-001` | | Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` | -| Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; each new key is intent-rooted first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001` | +| Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; each new key is intent-rooted first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001`, `INV-CUT-READ-LOGICAL-001` | | Plain detach | explicit `plain=true` bypasses pre-copy cost admission only after exclusive frontend I/O admission succeeds immediately; busy requests change no frontend/pause/HEAD state. It then uses the ordinary StopIO, final cut and outcome settlement. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-001` | | Pre-copy admission | opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts reopen before ordinary uploads | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` | | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | @@ -248,7 +249,7 @@ stateDiagram-v2 | Guest-frozen detach | `frozen=true` carries a non-future guest freeze origin; forecast before staging, recheck authoritative candidates after Sync, and perform at most one cut. Ordinary frozen refusal issues no staging/payload upload and retains dirty bytes. Explicit `allowOverBudget=true` records `over_budget` and retains authority, drain and CAS settlement checks; actual whole-guest elapsed still reports a five-second violation. | `chunk_frozen_budget.go`; `chunk_precopy.go`; `captureLocked`; `DetachVolumeFrozen`; `/chunk/detach` | `INV-CUT-PRECOPY-001` | | Checkpoint tail | successful cuts sample remaining candidates and transfer cost from one rate observation after publication; zero bytes is known zero, insufficient history for a nonzero tail is unknown. This is advisory; frozen admission rechecks its own candidates. | `chunk_precopy.go` `candidateTail`; `chunk_control.go` `ChunkCutResponse` | `INV-CUT-PRECOPY-001` | | Pre-copy host drain | a committed freeze keeps commands held while host storage admission closes; transport teardown cancels held commands before joining the session, without issuing their storage work | `storage_adapter.go` `setOperationalLocked`; `nvme/session.go` `serve` | `INV-CUT-PRECOPY-001` | -| Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt) is read by a bounded upload worker at upload time; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001` | +| Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt) is read by a bounded upload worker at upload time; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001`, `INV-CUT-READ-LOGICAL-001`, `INV-CUT-GUEST-BOUNDED-WAIT-001` | | LSN guard | refuse when H is below HEAD's `RemoteLSN` (`lsn_behind`) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-MONOTONE-001` | | Upload | upload only chunks whose SHA-256 differs from HEAD, under fresh write-once keys, after one durable intent per cut or staging round names all candidate keys; an immutable slot retries through transient failures until cancellation or its object deadline | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | | Manifest | rewrite only segments whose references changed; new segments are covered by an intent | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-SEGMENT-REUSE-001`, `INV-CUT-INTENT-FIRST-001` | @@ -282,9 +283,9 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| | — | name held | exclusive name record `{request, attempt}`; a retry with the same request id gets its own attempt back | `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `claimName` | `INV-SNAP-EXPLICIT-DELETE-001` | -| name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001` | +| name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001`, `INV-SNAP-SEAL-POINT-001`, `INV-SNAP-SEAL-DURABLE-001` | | published | deleting | `DeleteSnapshot` or retention for this attempt, never while a fork claim is live | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001` | -| published | fork | claim the parent snapshot, check the source is not being deleted, write the target `VOLUME`, then its HEAD; no chunk is copied | `core/frontend/chunkstore/catalog.go` `Fork`, `claimForkParent` | `INV-GC-REACHABLE-001` | +| published | fork | claim the parent snapshot, check the source is not being deleted, write the target `VOLUME`, then its HEAD; no chunk is copied | `core/frontend/chunkstore/catalog.go` `Fork`, `claimForkParent` | `INV-GC-REACHABLE-001`, `INV-FORK-FROM-SEALED-001` | **Intents and key bindings.** @@ -294,7 +295,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | intent live | removed | the CAS outcome is known (success or a definite refusal) | `core/storage/chunk_layer.go` `captureLocked`, `dropIntents` | `INV-CUT-INTENT-FIRST-001`, `INV-WS-CAS-UNKNOWN-001` | | intent live | expired | older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has a higher epoch | `core/frontend/chunkstore/gc.go` `Collector.run` | `INV-GC-INTENT-EXPIRY-001` | | — | bound | exclusive create of the key; a key that exists or once existed is refused | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | -| bound | tombstoned, needle deleted | unrooted in two complete marks at least one grace period apart, older than the grace period, binding unchanged; an unreadable segment aborts the pass; the collector requires grace greater than the operation deadline | `core/frontend/chunkstore/gc.go` `Collector.run`, `NewCollector` | `INV-GC-REACHABLE-001`, `INV-GC-UNREADABLE-SEGMENT-001`, `INV-GC-GRACE-DEADLINE-001` | +| bound | tombstoned, needle deleted | unrooted in two complete marks at least one grace period apart, older than the grace period, binding unchanged; an unreadable segment aborts the pass; the collector requires grace greater than the operation deadline | `core/frontend/chunkstore/gc.go` `Collector.run`, `NewCollector` | `INV-GC-REACHABLE-001`, `INV-GC-UNREADABLE-SEGMENT-001`, `INV-GC-GRACE-DEADLINE-001`, `INV-GC-DELETE-EXACT-FID-001`, `INV-GC-GRACE-RESTART-001` | | tombstoned | (never rebound) | bindings are never removed | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | --- @@ -347,7 +348,7 @@ snapshot lifetime; local persistence does not bypass it. ## Part B. Invariant ledger -118 rows: 99 ACTIVE, 19 STUB; 15 kept from the internal ledger, 103 new. +131 rows: 110 ACTIVE, 19 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 116 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -426,6 +427,7 @@ Notes: | `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | | `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | | `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | +| `INV-MASTER-JOURNAL-ISOLATION-001` | With strict journal isolation, blockmaster refuses with FailedPrecondition a heartbeat from a node whose durable root shares the authority store's file system and that serves no volume, a new workspace placement on such a node, a new product-loop placement on it, and a move whose target is such a node; a node that already serves by durable state, a repeated identical placement and the retry of an issued move are not refused, and without strict mode co-location only raises an alarm. | M2 workspace move: Acked or Expired → (move refused, nothing written); workspace placement admission; node heartbeat | `core/host/master/journal_isolation.go` `refuseColocatedHeartbeat`, `colocatedTargetRefused`, `reconcilePlacements`, `nodeServesVolumes`; `core/host/master/workspace_service.go` `MoveWorkspace`; `core/host/master/workspace_binding.go` `PlaceWorkspace` | `TestColocatedNodeIsAlarmedButAcceptedByDefault`, `TestStrictRefusesColocatedNodeWithoutVolumes`, `TestStrictAcceptsColocatedNodeThatAlreadyServes`, `TestStrictRefusesPlacementAndMoveOntoColocatedNode`, `TestStrictProductLoopSkipsColocatedNodeForNewPlacement` (`core/host/master/journal_isolation_test.go`); `TestStrictReplaysAnIssuedMoveToANowColocatedTarget`, `TestStrictKeepsAnIdempotentPlacementOnANowColocatedNode` (`core/host/master/journal_isolation_fold_test.go`) | — | ACTIVE | Notes: @@ -496,10 +498,12 @@ Notes: | `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`) | — | ACTIVE | | `INV-CUT-UPLOAD-FROM-BUFFER` | CopyFinish owns an immutable at-H slot. Every PUT retry sends that slot, without rereading local bytes; transient failures keep the point until the caller deadline, window abort or 30-second object deadline. Guest writes to a copied chunk need no save. | M5 Copy -> Upload | `chunk_cut_cow.go` `copyCOWEntry`; `chunk_upload.go` `putCaptured` | `TestCutUploadRetriesPastThreeAttemptsAtSamePoint`, `TestChunkCutUploadDeadlineBoundRetainsDirt`, `TestCutCOWV3_PutRetryUsesFrozenSlot` (`core/storage/chunk_cut_alignment_test.go`) | CutCOW2 BufFrozen; separate upload action extension pending | ACTIVE | | `INV-CUT-NO-WAL-PIN` | A cut window pins no WAL space and does not defer the flusher. Logical readers validate their resolved record and retry against the dirty map/extent after retirement and reuse. | M1 Checkpoint / M5 Copy | `walstore_v3.go` `readDirtyV3`; `flusher.go` `flushOnceInternal` | `TestCutCOWV3_CaptureDoesNotPinWAL` (`core/storage/chunk_cut_alignment_test.go`) | CutFlush refinement; native real ring-reuse control | ACTIVE | +| `INV-CUT-READ-LOGICAL-001` | Every cut read of a chunk (COW copy, COW save and pre-copy staging) resolves each block through the dirty map first, validates the whole WAL record it read and re-resolves on a mismatch, and reads the extent only for a block with no dirty entry; no cut path reads the extent region directly. | M5 Stage / Copy | `core/storage/chunk_cut_cow.go` `readCOWChunk`, `readLocalBlock`; `core/storage/chunk_layer.go` `readChunk`; `core/storage/walstore_v3.go` `readDirtyV3Into` | `TestCutCOWV3_CaptureDoesNotPinWAL` (`core/storage/chunk_cut_alignment_test.go`); `TestCutCOWV3_SaverUsesValidatedWALBatchAndLazyHEAD` (`core/storage/chunk_cut_cow_lifetime_test.go`) | — | ACTIVE | | `INV-CUT-HOOK-BEFORE-APPEND` | The COW hook owns/saves the at-H image before a read-visible WAL mutation, under shared capture admission. | M1 Write / M5 Save | `walstore.go` `Write`, `WriteBatch`; `chunk_cut_cow.go` `beforeChunkMutation` | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 SaveStart before Write | ACTIVE | | `INV-CUT-FILL-FROM-BASE` | Lazily absent blocks are filled from this cut's fixed base HEAD, never a newer remote HEAD. Remote fetch runs after releasing local ownership. | M5 Copy / lazy fill | `chunk_cut_cow.go` `readCOWChunk`, `fillMissing` | `TestCutCOWV3_LazySaverSpillImageIsExact`, `TestCutCOWV3_SaverUsesValidatedWALBatchAndLazyHEAD` | Remote fill not modelled; native byte-image controls | ACTIVE | +| `INV-CUT-GUEST-BOUNDED-WAIT-001` | Inside an open cut window, a guest write to a candidate chunk waits only for local work: a saver slot for at most 250 ms (then only the cut aborts) and one local capture of that chunk's at-H image, its own or that of the chunk's current copier or saver; lazily absent blocks are left to the copier to fill from the base HEAD after it releases the entry, so a guest write never waits for a remote fetch or upload. | M5 OpenWindow → Copy (guest write during Copy / Upload) | `core/storage/chunk_cut_cow.go` `beforeCOWMutation`, `claim`, `acquireSaver`, `readCOWChunk`, `fillMissing` | `TestCutCOWV3_SaverUsesValidatedWALBatchAndLazyHEAD`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_RemoteUploadDoesNotParkCopiedChunk`, `TestCutCOWV3_SaverBurstWaitsAndPublishes` (`core/storage/chunk_cut_cow_spillcap_test.go`); `TestCutCOWV3_HeldFillIsCancelledByAbortAndDrained` (`core/storage/chunk_cut_cow_fill_test.go`) | `CutCOW2` `Blocked` defines which writes wait; remote I/O is not modelled | ACTIVE | | `PROGRESS-DESTRUCTIVE` | Supported guest zero-data writes use ordinary COW and do not abort every update. Unsupported DSM/discard/write-zeroes opcodes reach no storage mutation. Administrative Recover/reset/BASE still invalidate and drain; progress assumes these lifecycle transitions eventually stop. | M1 Write / M5 Save | `chunk_cut_cow.go` `beforeCOWMutation`; frontend dispatch | `TestCutCOWV3_ZeroWritesDoNotAbortUpdates` (`core/storage/chunk_cut_alignment_test.go`); `TestDispatch_UnsupportedOperations` (`core/frontend/ublk/dispatch_test.go`); `TestT2Batch11a_IdentifyController_ONCSAllZero` (`core/frontend/nvme/identify_test.go`) | Guest/lifecycle distinction not modelled; native controls | ACTIVE | -| `INV-CUT-PAYLOAD-BOUNDED-001` | Saver-slot admission waits at most 250 ms without a window lock or remote call before aborting only the cut; physical local I/O remains joined. Upload workers, active savers and cached saves share a configurable per-volume payload byte bound independent of candidate count; an explicit budget below six chunks is refused. An optional Budget admits before staging/barrier and accounts each COW save without a window lock; revocation aborts only the cut and its ticket is released after worker joins. Host-wide policy is a separate limiter module. WAL batch validation uses block-sized scratch even when a record spans many chunks. Pre-copy streams one chunk per worker; native at-H reads protect unsent candidates with COW. Only guest overwrites consume side-file bytes. A full side-file cap aborts the update, retains its dirty set and allows guest writes to proceed. Uploads join before cleanup. | M5 Stage / Copy / Upload | `chunk_cut_payload.go`; `chunk_cut_cow.go`; `chunk_upload.go` | `TestCutBudgetRefusesBeforeBarrier`, `TestCutBudgetCOWRefusalAbortsOnlyCut`, `TestCutBudgetRevocationJoinsBeforeRelease` (`core/storage/chunk_cut_budget_test.go`); `TestV3ReadLargeBatchScratchIsBlockBounded`, `TestCutCOWV3_SaverBurstWaitsAndPublishes`; `TestStatusServer_ChunkErrorBodyIsTyped` (local cut abort wins over its cancelled upload; uncertain CAS, fencing and terminal Closed/Detached keep precedence), `TestCutAbortReasonsAreCountedAndCopied`, `TestCutPayloadBudgetBoundsSlots`, `TestChunkLayerPayloadBudgetRejectsUndersized` (`core/storage/chunk_cut_payload_budget_test.go`); `TestWALStoreChunk_InitialWriteAnonymousMemory` (isolated Linux RSS arms, `core/frontend/durable/provider_initial_memory_linux_test.go`); `TestCutCOWV3_ChangedImageExceedsSpillCap`, `TestChunkStageV3_ChangedImageExceedsSpillCap`, `TestCutCOWV3_OverwriteStormAbortsAndRetries`, `TestCutCOWV3_RemoteUploadDoesNotParkCopiedChunk` (`core/storage/chunk_cut_cow_spillcap_test.go`); `TestChunkUploads_FailureJoinsBeforeIntentCleanup` (`core/storage/chunk_upload_parallel_test.go`) | `CutPipeline` `AbortPoint` covers refused-point stutter; byte counts and filesystem/transport resource costs are not modelled | ACTIVE | +| `INV-CUT-PAYLOAD-BOUNDED-001` | Saver-slot admission waits at most 250 ms without a window lock or remote call before aborting only the cut; physical local I/O remains joined. Upload workers, active savers and cached saves share a configurable per-volume payload byte bound independent of candidate count; an explicit budget below six chunks is refused. An optional Budget admits before staging/barrier and accounts each COW save without a window lock; revocation aborts only the cut and its ticket is released after worker joins. Host-wide policy is a separate limiter module. WAL batch validation uses block-sized scratch even when a record spans many chunks. Pre-copy streams one chunk per worker; native at-H reads protect unsent candidates with COW. Only guest overwrites consume side-file bytes. A full side-file cap aborts the update, retains its dirty set and allows guest writes to proceed. Uploads join before cleanup. | M5 Stage / Copy / Upload | `chunk_cut_payload.go`; `chunk_cut_cow.go`; `chunk_upload.go` | `TestCutBudgetRefusesBeforeBarrier`, `TestCutBudgetCOWRefusalAbortsOnlyCut`, `TestCutBudgetRevocationJoinsBeforeRelease` (`core/storage/chunk_cut_budget_test.go`); `TestV3ReadLargeBatchScratchIsBlockBounded`, `TestCutCOWV3_SaverBurstWaitsAndPublishes`; `TestStatusServer_ChunkErrorBodyIsTyped` (local cut abort wins over its cancelled upload; uncertain CAS, fencing and terminal Closed/Detached keep precedence), `TestCutAbortReasonsAreCountedAndCopied`, `TestCutPayloadBudgetBoundsSlots`, `TestChunkLayerPayloadBudgetRejectsUndersized` (`core/storage/chunk_cut_payload_budget_test.go`); `TestWALStoreChunk_InitialWriteAnonymousMemory` (isolated Linux RSS arms, `core/frontend/durable/provider_initial_memory_linux_test.go`); `TestCutCOWV3_ChangedImageExceedsSpillCap`, `TestChunkStageV3_ChangedImageExceedsSpillCap`, `TestCutCOWV3_OverwriteStormAbortsAndRetries`, `TestCutCOWV3_RemoteUploadDoesNotParkCopiedChunk`, `TestCutCOWV3_SpillCapAbortsTheCut` (`core/storage/chunk_cut_cow_spillcap_test.go`); `TestChunkUploads_FailureJoinsBeforeIntentCleanup` (`core/storage/chunk_upload_parallel_test.go`) | `CutPipeline` `AbortPoint` covers refused-point stutter; byte counts and filesystem/transport resource costs are not modelled | ACTIVE | | `INV-HOST-CUT-BUDGET-001` | Cooperating cut processes hold an OS slot before staging/barrier; payload and side caps are reserved per slot, including urgent slots. Cancellation never frees a slot before actual worker settlement. Active coordinated reservations exclude retained crash spill, fallback and RSS. Unavailable pools refuse ordinary background work; urgent/named fallback is explicitly degraded and cannot claim a host resource/rate bound. Pacing debt persists within one process, not across process turnover. | M7 admission/drain/release | `core/hostlimit`; durable `ChunkBudget`; blockvolume host-limit flags | `TestSlotsUrgentAndJoinedRelease`, `TestCOWAbortHoldsSlotUntilWorkerSettlement`, `TestHoldExpiryAndCloseDoNotSteal`, `TestKilledProcessReleasesButLiveHolderDoesNot`, `TestHostCutLimitDoesNotGateGuestIO`, `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin`, `TestCutPolicy_StaggerPreservesExplicitTimerReset`, `TestKilledInitializerDoesNotPublishPartialConfiguration`, `TestUnusablePoolClassPolicy`, `TestPacingDebtSurvivesOwnLeaseTurnover`, `TestPacingFreshProcessesDoNotShareDebt`, `TestChunkControl_NamedSnapshotUsesUrgentFallback`, `TestLastFallbackReleaseClearsActiveStatus`, `TestConfigurationLockFailurePreservesPoolPolicy`, `TestConfigurationLockContentionRefusesAllClasses` | `HostBudget` HeldUntilJoined/PayloadBound/SpillBound (bounded OS-lock abstraction; fallback excluded) | ACTIVE | | `INV-HOST-POOL-CONFIG-001` | A pool configuration is invisible until its complete synced temporary file is atomically renamed under the OS configuration lock. A killed initializer cannot leave a partial visible configuration that strands successors. | M7 configuration preparation/publication | `core/hostlimit` `publishConfig` | `TestKilledInitializerDoesNotPublishPartialConfiguration` | `HostBudget` NoPartialConfig/ConfigBeforeAdmission (filesystem atomicity checked natively) | ACTIVE | | `INV-CUT-INTENT-FIRST-001` | Before the first upload of a cut or staging round, one intent names every preallocated candidate key (unused keys are harmless), independent of upload wave count. Known-aborted reusable roots are removed at clean Close; unresolved CAS roots remain protected. Intent removal follows a known CAS outcome. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestCutPayloadReadsOverlapEarlierUploadsWithinBudget`, `TestCutPayloadIntentCountIndependentOfCandidates`, `TestChunkCloseDropsReusableButKeepsUnknownCASRoots`, `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | @@ -513,6 +517,7 @@ A guest read has a cooperative arrival budget; internal contextless readers keep Notes: - `INV-CUT-STAGED-REUSE-001`: `captureLocked` also requires HEAD's generation to be the one the stage was compared against (code reading; not asserted by these tests). +- `INV-CUT-READ-LOGICAL-001`: the staging clause (`readChunk` through `WALStore.Read`) is enforced by reading; no test captures WAL-only bytes through a staging round. ### B.6 Workspace: chunk lifecycle, GC and delete @@ -523,7 +528,12 @@ Notes: | `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE | | `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE | | `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | — | `RetentionGCTiming` `NoLiveDelete` | STUB | +| `INV-GC-DELETE-EXACT-FID-001` | GC deletes a needle only after tombstoning its key binding, and only by the exact fid recorded in that binding (volume id, needle key and cookie, never rebuilt); a delete response other than 200, 202, 204 or 404 from any replica is an error that fails the pass and leaves the binding tombstoned for a later retry. | M6 key: Bound → Tombstoned, needle deleted | `core/frontend/chunkstore/gc.go` `Collector.run`; `core/frontend/chunkstore/swfs.go` `SWFS.DeleteBlob` | `TestSWFS_DeleteBlobStatusesAndExactPath` (`core/frontend/chunkstore/gc_test.go`) | — | ACTIVE | +| `INV-GC-GRACE-RESTART-001` | A binding's grace counts from the first complete mark that finds it unrooted and restarts whenever a mark finds it rooted or changed; a deleted snapshot's attempt stays a root until its deleting time is older than the grace, after which the two-mark rule needs another full grace. | M6 key: Bound → Tombstoned; M6 snapshot: Deleting | `core/frontend/chunkstore/gc.go` `Collector.run`; `core/frontend/chunkstore/gc_copy.go` `snapshotAttemptHeads`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestGC_PublishedUnnamedAttemptRootsUntilDeletingGrace` (`core/frontend/chunkstore/gc_copy_test.go`) | `RetentionGCTiming` `NoLiveDelete` | ACTIVE | | `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt, and never while a fork claim on it is live. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | +| `INV-SNAP-SEAL-POINT-001` | A named snapshot request for a free name runs exactly one cut and stores the HEAD that cut installed as the snapshot; a retry of a recorded request replays that snapshot without cutting; if the cut fails (including a COW window abort) the request fails with that error and records no snapshot. | M5 Admit → Settled, then M6 snapshot: name held → published | `core/host/volume/chunk_control.go` `chunkControl.Snapshot`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestNamedSnapshotWindowAbortNeverSubstitutesPoint` (`core/host/volume/chunk_review271_test.go`); `TestChunkControl_SnapshotStoresTheCutHead` (`core/host/volume/chunk_control_adapter_test.go`) | — | ACTIVE | +| `INV-SNAP-SEAL-DURABLE-001` | A named snapshot is reported done only after its cut's HEAD CAS is confirmed (every referenced chunk uploaded first) and its attempt entry is confirmed by its exclusive create or a read-back; an unknown outcome of either reports failure, and an unknown create keeps the snapshot's intent. | M5 CAS → Settled; M6 snapshot: name held → published | `core/host/volume/chunk_control.go` `chunkControl.Snapshot`; `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `createResolved` | `TestCatalog_SnapshotUncertainCreateKeepsIntent`, `TestCatalog_SnapshotAppliedResponseLostIsConfirmed` (`core/frontend/chunkstore/catalog_settle_test.go`); `TestNamedSnapshotWindowAbortNeverSubstitutesPoint` (`core/host/volume/chunk_review271_test.go`) | — | ACTIVE | +| `INV-FORK-FROM-SEALED-001` | A fork reads only a published, active snapshot: a name with no published attempt or an aborted one is `snapshot_not_found`, a deleting one is `snapshot_deleting`, and the parent claim is conditioned on the attempt still being active. | M6 snapshot: published → fork | `core/frontend/chunkstore/catalog.go` `Fork`, `claimForkParent`, `resolveSnap` | `TestFork_RefusalsAndDeadline` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_SweepTombstonesADeadSnapshotAttempt` (`core/frontend/chunkstore/catalog_held_create_test.go`); `TestCatalog_ForkAfterTheMarkRefuses` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` models the snapshot as a name record plus an attempt path; no fork-from-unpublished property | ACTIVE | | `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | | `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | @@ -531,6 +541,10 @@ Notes: Notes: - `INV-GC-GRACE-DEADLINE-001`: The check is in `NewCollector`; no Go test constructs a collector with a too-short grace. +- `INV-GC-DELETE-EXACT-FID-001`: the tombstone written before the delete and the retry after a failed delete are enforced by reading; no test fails a GC delete. The cookie check itself is done by the SeaweedFS volume server, not by this repository. +- `INV-GC-GRACE-RESTART-001`: the restart on a rooted mark is enforced by reading; no test re-roots a candidate between marks. A deleted fork volume's keys get only the ordinary two-mark grace from their first unrooted mark, with no deleting-time root and no dedicated test. +- `INV-SNAP-SEAL-DURABLE-001`: whether a confirmed filer write has reached disk (filer fsync) is a deployment setting of the SeaweedFS filer, not checked by the code. +- `INV-FORK-FROM-SEALED-001`: the case of a name whose attempt is still in flight (name record present, attempt entry absent) is enforced by reading; no test forks during a held snapshot create. ### B.7 Rows kept from the internal ledger: Kubernetes line and replica fencing @@ -581,6 +595,11 @@ Notes: | ID | Invariant | Machine / transition | Enforced in | Tests | TLA+ | Status | |---|---|---|---|---|---|---| | `INV-WAL-DATA-SYNC-001` | `SWBLOCK_SYNC=auto` is the default. Once at volume open, Linux WAL/extent sync selects fdatasync only when every resolved non-partition node, including dm/md nodes and all slaves, advertises write through; write back or unknown/unreadable device policy selects fsync. `SWBLOCK_SYNC=fsync|fdatasync` explicitly overrides detection (other platforms retain fsync). The selected mode and reason are logged and exposed in durable status without mid-life reselection. Descriptor/map/create/directory durability still uses fsync. `SWBLOCK_ALLOCATION=sparse|prezero` selects allocation at create; sparse is the default and fallocate is refused. `SWBLOCK_PREZERO=1` aliases prezero, which explicitly writes every byte only at create, fsyncs, then refuses holes/unwritten FIEMAP mappings. Existing files are never prezeroed. | M1 Create / Sync / Checkpoint | `data_sync.go`, `device_sync_linux.go`; `walstore_v3.go` Create; `walstore.go` data sync seams; `core/frontend/durable/storage_adapter.go` status | `TestDurableProvider_DataSyncStatus` (`core/frontend/durable/data_sync_status_test.go`), `TestExplicitAutoDataSyncPolicy`, `TestDeviceDataSyncStackNodePolicy`, `TestDeviceDataSyncMalformedTopology`, `TestDeviceDataSyncPolicy`, `TestExplicitDataSyncPolicyDoesNotInspectDevice` (`core/storage/device_sync_linux_test.go`; positive cache fixtures witness empty-stack/cycle guards), `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten`, `TestFallocateAllocationIsRefused`, `TestDefaultCreatedVolumeStaysSparse`, `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE | +| `INV-WAL-FLUSH-SYNC-COVERS-WAL-001` | WAL and extent data live in one store file, and the WAL sync and the flusher's extent sync are the same whole-file fsync or fdatasync of that one descriptor, never a range sync, so every flusher sync also makes the WAL durable. | M1 Serving → Serving (checkpoint) | `core/storage/walstore.go` `openInitializedV3`; `core/storage/data_sync.go` `bindDataFileSync`; `core/storage/flusher.go` `flushOnceInternal` | — | — | STUB | + +Notes: + +- `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`: the one-file, one-descriptor, no-range-sync clause is enforced by reading; no test asserts it yet. Fault-injection tests replace the WAL sync and the extent sync separately and do not check that they are the same call. ## Part C. Change rules From 4ae53120aa009ab92511bc7fda5e5f88891bbcf7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 20:51:05 -0800 Subject: [PATCH 08/34] docs(invariants): count the INV rows as the tables have them Co-Authored-By: Claude Fable 5.2 --- seaweed-block/docs/design/invariants.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 92b1329d77..37415d38a6 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -348,7 +348,7 @@ snapshot lifetime; local persistence does not bypass it. ## Part B. Invariant ledger -131 rows: 110 ACTIVE, 19 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 116 new. +130 `INV-` rows: 109 ACTIVE, 19 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 115 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. From 3073d4e134b61f32f52bfd580278bfaeeb67cb1b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 21:56:02 -0800 Subject: [PATCH 09/34] storage, chunkstore: #324 fold: periodic cut reports through unlockCap; failure-safe joins and a causal Close witness; Begin and Finish refusal controls; ledger rows, wait-site row and hook contract docs Co-Authored-By: Claude Opus 5.5 --- .../frontend/chunkstore/share_guard_test.go | 40 ++++ .../core/frontend/durable/provider.go | 10 +- .../host/volume/chunk_control_order_test.go | 20 ++ seaweed-block/core/storage/chunk_layer.go | 6 + .../core/storage/chunk_periodic_cut.go | 2 +- .../core/storage/chunk_publish_settled.go | 8 + .../storage/chunk_publish_settled_test.go | 189 +++++++++++------- seaweed-block/core/storage/chunk_seam.go | 19 +- seaweed-block/docs/design/invariants.md | 13 +- 9 files changed, 225 insertions(+), 82 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/share_guard_test.go b/seaweed-block/core/frontend/chunkstore/share_guard_test.go index 42b839a9d1..a0f7661520 100644 --- a/seaweed-block/core/frontend/chunkstore/share_guard_test.go +++ b/seaweed-block/core/frontend/chunkstore/share_guard_test.go @@ -17,6 +17,7 @@ type recGuard struct { events []string n int finishErr error + beginErr error onFinish func() } @@ -25,6 +26,9 @@ func (g *recGuard) Begin(_ context.Context, vol string) (string, error) { defer g.mu.Unlock() g.n++ g.events = append(g.events, "begin:"+vol) + if g.beginErr != nil { + return "", g.beginErr + } return fmt.Sprintf("tok-%d", g.n), nil } @@ -161,4 +165,40 @@ func TestShareGuard_Fork(t *testing.T) { if countUnder(f, catBase+"/v3/HEAD") != 0 { t.Fatal("child HEAD written after a refused Finish") } + if n := countUnder(f, catBase+"/v3/intents/"); n != 0 { + t.Fatalf("%d intents left for the refused fork; want its new intent dropped", n) + } +} + +// A refused Begin stops the snapshot and the fork before anything is +// written: no Finish, no snapshot entry, no child HEAD, no intent left. +func TestShareGuard_BeginRefused(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s0", RequestID: "r0"}, h); err != nil { + t.Fatal(err) + } + intents := countUnder(f, catBase+"/v1/intents/") + g := &recGuard{beginErr: errors.New("share refused")} + c.SetShareGuard(g) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err == nil { + t.Fatal("snapshot after a refused Begin") + } + if n := countUnder(f, catBase+"/v1/snaps/s1/"); n != 0 { + t.Fatalf("%d snapshot entries after a refused Begin", n) + } + if n := countUnder(f, catBase+"/v1/intents/"); n != intents { + t.Fatalf("intents %d -> %d after a refused Begin", intents, n) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s0", Target: "v4", RequestID: "fork-b"}); err == nil { + t.Fatal("fork after a refused Begin") + } + if countUnder(f, catBase+"/v4/HEAD") != 0 || countUnder(f, catBase+"/v4/intents/") != 0 { + t.Fatal("a fork refused at Begin wrote a child HEAD or an intent") + } + for _, e := range g.list() { + if strings.HasPrefix(e, "finish:") { + t.Fatalf("Finish after a refused Begin: %v", g.list()) + } + } } diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index af6a417c34..6d6e5c0b70 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -194,9 +194,13 @@ type ProviderConfig struct { OnChunkDetachResumed func(volumeID string, attempt uint64) // ChunkOnPublishSettled, optional, is called once per confirmed // publication of a chunk volume's HEAD, with the HEAD before and after it - // (storage.ChunkLayerConfig.OnPublishSettled). It runs on the publishing - // caller after the capture lock is released; ctx ends when the volume's - // layer closes. + // (storage.ChunkLayerConfig.OnPublishSettled): serialized, in publication + // order, outside the capture lock, by the volume's one registered drainer + // (whichever publishing caller is draining; a publisher may return before + // its own report is delivered). ctx ends when the volume's layer closes; + // after that no report is dequeued, though one already dequeued may still + // be delivered. It must return without blocking and without remote calls: + // enqueue work to your own worker (it is a guest-visible wait on detach). ChunkOnPublishSettled func(ctx context.Context, volumeID string, prev, next storage.ChunkHead) // ChunkDirtyThreshold is the number of candidate chunks above which // a cut pre-copies (stages) chunks before its barrier, in rounds of diff --git a/seaweed-block/core/host/volume/chunk_control_order_test.go b/seaweed-block/core/host/volume/chunk_control_order_test.go index 46d9c288fd..71a16b3e89 100644 --- a/seaweed-block/core/host/volume/chunk_control_order_test.go +++ b/seaweed-block/core/host/volume/chunk_control_order_test.go @@ -6,6 +6,7 @@ package volume import ( "context" + "errors" "testing" "github.com/seaweedfs/seaweed-block/core/frontend" @@ -102,10 +103,14 @@ type ownerGuard struct { cutsAtBegin []int finishes []string fp *fakeChunkProvider + beginErr error } func (g *ownerGuard) Begin(context.Context, string) (string, error) { g.cutsAtBegin = append(g.cutsAtBegin, g.fp.cuts) + if g.beginErr != nil { + return "", g.beginErr + } return "owner", nil } @@ -131,3 +136,18 @@ func TestChunkControl_SnapshotBeginsShareBeforeTheCut(t *testing.T) { t.Fatalf("finishes %v; want one Finish with the owner's token", g.finishes) } } + +// A refused Begin stops the owner's seal before its cut: no cut, no Finish, +// no snapshot. +func TestChunkControl_SnapshotBeginRefusedCutsNothing(t *testing.T) { + ctx := context.Background() + fp, ctl := adapterFixture(t) + g := &ownerGuard{fp: fp, beginErr: errors.New("share refused")} + ctl.(*chunkControl).cat.SetShareGuard(g) + if _, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r"}); err == nil { + t.Fatal("snapshot after a refused Begin") + } + if fp.cuts != 0 || len(g.finishes) != 0 { + t.Fatalf("cuts %d finishes %v after a refused Begin; want none", fp.cuts, g.finishes) + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 6b87408ad3..ad4f45955a 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1864,7 +1864,13 @@ func (l *chunkLayerImpl) Close() error { if w != nil { w.join() } + if h := testCloseJoinHook; h != nil { + h() // tests: Close has cancelled the layer and now joins its owners, the drainer among them + } l.wg.Wait() + if h := testCloseJoinedHook; h != nil { + h() // tests: the join returned + } l.stMu.Lock() protected := make(map[string]bool, len(l.pendingIntents)) for _, id := range l.pendingIntents { diff --git a/seaweed-block/core/storage/chunk_periodic_cut.go b/seaweed-block/core/storage/chunk_periodic_cut.go index 49822ee959..7803020e59 100644 --- a/seaweed-block/core/storage/chunk_periodic_cut.go +++ b/seaweed-block/core/storage/chunk_periodic_cut.go @@ -17,7 +17,7 @@ var _ ChunkPeriodicCutter = (*chunkLayerImpl)(nil) func (l *chunkLayerImpl) CutUnlessCutSince(ctx context.Context, lastCutNs int64) (chunkCutResult, bool, error) { l.capMu.Lock() - defer l.capMu.Unlock() + defer l.unlockCap() // delivers the cut's OnPublishSettled report after the lock l.stMu.Lock() last := l.stats.LastCutNs l.stMu.Unlock() diff --git a/seaweed-block/core/storage/chunk_publish_settled.go b/seaweed-block/core/storage/chunk_publish_settled.go index fe41e34512..2f2c0b905a 100644 --- a/seaweed-block/core/storage/chunk_publish_settled.go +++ b/seaweed-block/core/storage/chunk_publish_settled.go @@ -61,3 +61,11 @@ func (l *chunkLayerImpl) runPublishSettled() { hook(l.ctx, t.prev, t.next) } } + +// testCloseJoinHook, set only by tests, runs in Close after the layer is +// cancelled and before it joins its owners (the active drainer among them). +var testCloseJoinHook func() + +// testCloseJoinedHook, set only by tests, runs in Close when that join has +// returned. +var testCloseJoinedHook func() diff --git a/seaweed-block/core/storage/chunk_publish_settled_test.go b/seaweed-block/core/storage/chunk_publish_settled_test.go index 2e03073d42..51171e81e2 100644 --- a/seaweed-block/core/storage/chunk_publish_settled_test.go +++ b/seaweed-block/core/storage/chunk_publish_settled_test.go @@ -141,6 +141,58 @@ func waitClosed(t *testing.T, ch <-chan struct{}, what string) { } } +// worker is a goroutine a test launches. Its bounded join (after release, +// if given) is registered as cleanup before it starts, so a failing test +// never leaves it running; the result is read once and kept. +type worker struct { + name string + done chan error + once sync.Once + err error + ok bool +} + +func launch(t *testing.T, name string, release func(), f func() error) *worker { + t.Helper() + w := &worker{name: name, done: make(chan error, 1)} + t.Cleanup(func() { + if release != nil { + release() + } + if _, ok := w.result(10 * time.Second); !ok { + t.Errorf("%s never returned", name) + } + }) + go func() { w.done <- f() }() + return w +} + +// result waits up to d for the worker; ok is false on timeout. +func (w *worker) result(d time.Duration) (error, bool) { + w.once.Do(func() { + select { + case w.err = <-w.done: + w.ok = true + case <-time.After(d): + } + }) + if !w.ok { + w.once = sync.Once{} // a timed-out wait may be retried + } + return w.err, w.ok +} + +func (w *worker) mustReturn(t *testing.T) { + t.Helper() + err, ok := w.result(10 * time.Second) + if !ok { + t.Fatalf("%s did not return", w.name) + } + if err != nil { + t.Fatalf("%s: %v", w.name, err) + } +} + // Overlapping publishers: while the first report's hook is held, a second // publisher's cut completes and returns; its report is delivered after the // first, never concurrently with it. @@ -150,7 +202,7 @@ func TestChunkPublishSettled_OverlappingPublishersStayOrdered(t *testing.T) { layer := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl) entered, release := make(chan struct{}), make(chan struct{}) var once, rel sync.Once - t.Cleanup(func() { rel.Do(func() { close(release) }) }) + releaseHook := func() { rel.Do(func() { close(release) }) } var mu sync.Mutex var got [][2]uint64 active, maxActive := 0, 0 @@ -171,27 +223,14 @@ func TestChunkPublishSettled_OverlappingPublishersStayOrdered(t *testing.T) { } w := newWriteLog() w.write(t, s, 2, 0x22) - aDone := make(chan error, 1) - go func() { _, err := layer.Cut(context.Background()); aDone <- err }() - t.Cleanup(func() { - rel.Do(func() { close(release) }) - select { - case <-aDone: - case <-time.After(10 * time.Second): - t.Error("the first publisher never returned") - } - }) + a := launch(t, "the first publisher", releaseHook, func() error { _, err := layer.Cut(context.Background()); return err }) waitClosed(t, entered, "the first report") w.write(t, s, 9, 0x29) - bDone := make(chan error, 1) - go func() { _, err := layer.Cut(context.Background()); bDone <- err }() - select { - case err := <-bDone: - if err != nil { - t.Fatal(err) - } - case <-time.After(10 * time.Second): + b := launch(t, "the second publisher", releaseHook, func() error { _, err := layer.Cut(context.Background()); return err }) + if err, ok := b.result(10 * time.Second); !ok { t.Fatal("the second publisher waited on the first report's hook") + } else if err != nil { + t.Fatal(err) } mu.Lock() n := len(got) @@ -199,16 +238,8 @@ func TestChunkPublishSettled_OverlappingPublishersStayOrdered(t *testing.T) { if n != 1 { t.Fatalf("%d reports delivered while the first was held; want 1", n) } - rel.Do(func() { close(release) }) - select { - case err := <-aDone: - aDone <- err - if err != nil { - t.Fatal(err) - } - case <-time.After(10 * time.Second): - t.Fatal("the first publisher did not finish") - } + releaseHook() + a.mustReturn(t) mu.Lock() defer mu.Unlock() if len(got) != 2 || got[0] != [2]uint64{0, 1} || got[1] != [2]uint64{1, 2} || maxActive != 1 { @@ -217,14 +248,23 @@ func TestChunkPublishSettled_OverlappingPublishersStayOrdered(t *testing.T) { } // Close during the first of two queued reports: the first hook sees its -// context end, Close waits for it, and the second report is never delivered. +// context end, Close reaches its join of the active drainer and waits there +// (witnessed, not timed), and the second report is never delivered. func TestChunkPublishSettled_CloseDropsUnstartedReports(t *testing.T) { f := newFakeChunkRemote() s, _ := newChunkTestStore(t) layer := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl) entered, release := make(chan struct{}), make(chan struct{}) var rel sync.Once - t.Cleanup(func() { rel.Do(func() { close(release) }) }) + releaseHook := func() { rel.Do(func() { close(release) }) } + joining := make(chan struct{}) + var joinOnce sync.Once + var order []string // "hook returned" and "Close joined", in the order they happened + var orderMu sync.Mutex + note := func(e string) { orderMu.Lock(); order = append(order, e); orderMu.Unlock() } + testCloseJoinHook = func() { joinOnce.Do(func() { close(joining) }) } + testCloseJoinedHook = func() { note("Close joined") } + t.Cleanup(func() { testCloseJoinHook, testCloseJoinedHook = nil, nil }) var hookCtx context.Context var mu sync.Mutex calls := 0 @@ -232,46 +272,35 @@ func TestChunkPublishSettled_CloseDropsUnstartedReports(t *testing.T) { mu.Lock() calls++ n := calls - mu.Unlock() if n == 1 { hookCtx = ctx + } + mu.Unlock() + if n == 1 { close(entered) <-release + note("hook returned") } } layer.stMu.Lock() layer.settled = append(layer.settled, headTransition{prev: chunkHead{Gen: 0}, next: chunkHead{Gen: 1}}, headTransition{prev: chunkHead{Gen: 1}, next: chunkHead{Gen: 2}}) layer.stMu.Unlock() - drained := make(chan struct{}) - go func() { layer.runPublishSettled(); close(drained) }() + drainer := launch(t, "the drainer", releaseHook, func() error { layer.runPublishSettled(); return nil }) waitClosed(t, entered, "the first report") - closeDone := make(chan error, 1) - go func() { closeDone <- layer.Close() }() - t.Cleanup(func() { - rel.Do(func() { close(release) }) - select { - case <-closeDone: - case <-time.After(10 * time.Second): - t.Error("Close never returned") - } - }) - waitClosed(t, hookCtx.Done(), "Close cancelling the hook's context") - select { - case err := <-closeDone: - closeDone <- err - t.Fatal("Close returned while a report hook was running") - case <-time.After(200 * time.Millisecond): - } - rel.Do(func() { close(release) }) - waitClosed(t, drained, "the drain to end") - select { - case err := <-closeDone: - closeDone <- err - if err != nil { - t.Fatal(err) - } - case <-time.After(10 * time.Second): - t.Fatal("Close did not return") + closer := launch(t, "Close", releaseHook, layer.Close) + mu.Lock() + ctx := hookCtx + mu.Unlock() + waitClosed(t, ctx.Done(), "Close cancelling the hook's context") + waitClosed(t, joining, "Close reaching its join of the drainer") + releaseHook() + drainer.mustReturn(t) + closer.mustReturn(t) + orderMu.Lock() + seq := append([]string(nil), order...) + orderMu.Unlock() + if len(seq) != 2 || seq[0] != "hook returned" || seq[1] != "Close joined" { + t.Fatalf("order %v; want the running hook to return before Close's join does", seq) } mu.Lock() defer mu.Unlock() @@ -287,12 +316,16 @@ func TestChunkPublishSettled_HookThatPublishes(t *testing.T) { s, _ := newChunkTestStore(t) layer := mustAttach(t, s, f, ctConfig(1)).(*chunkLayerImpl) w := newWriteLog() + var mu sync.Mutex var got [][2]uint64 nested := false layer.cfg.OnPublishSettled = func(ctx context.Context, prev, next ChunkHead) { + mu.Lock() got = append(got, [2]uint64{prev.Gen, next.Gen}) - if !nested { - nested = true + again := !nested + nested = true + mu.Unlock() + if again { w.write(t, s, 9, 0x29) if _, err := layer.Cut(ctx); err != nil { t.Errorf("cut from the hook: %v", err) @@ -300,17 +333,31 @@ func TestChunkPublishSettled_HookThatPublishes(t *testing.T) { } } w.write(t, s, 2, 0x22) - done := make(chan error, 1) - go func() { _, err := layer.Cut(context.Background()); done <- err }() - select { - case err := <-done: - if err != nil { - t.Fatal(err) - } - case <-time.After(10 * time.Second): + cut := launch(t, "a cut whose hook publishes", nil, func() error { _, err := layer.Cut(context.Background()); return err }) + if err, ok := cut.result(10 * time.Second); !ok { t.Fatal("a hook that publishes deadlocked") + } else if err != nil { + t.Fatal(err) } + mu.Lock() + defer mu.Unlock() if len(got) != 2 || got[0] != [2]uint64{0, 1} || got[1] != [2]uint64{1, 2} { t.Fatalf("reports %v; want [0->1 1->2]", got) } } + +// A periodic cut (CutUnlessCutSince) reports its publication like any other +// cut, after the capture lock is released, before it returns. +func TestChunkPublishSettled_PeriodicCutReports(t *testing.T) { + f := newFakeChunkRemote() + s, layer, log := attachWithSettled(t, f) + w := newWriteLog() + w.write(t, s, 3, 0x33) + if _, skipped, err := layer.CutUnlessCutSince(ctTimeout(t), 0); err != nil || skipped { + t.Fatalf("periodic cut: skipped=%v err=%v", skipped, err) + } + got, free := log.snapshot() + if len(got) != 1 || got[0] != [2]uint64{0, 1} || !free[0] { + t.Fatalf("periodic cut reports %v (capture lock free %v); want one report 0->1 with the lock free", got, free) + } +} diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 9706888146..7be66e2e10 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -312,12 +312,19 @@ func validChunkIntentID(id string) bool { type chunkLayerConfig struct { // OnPublishSettled, when set, is called once per confirmed publication // (a cut, a detach, or an earlier unresolved CAS found applied), with the - // HEAD before and after it. Calls are serialized and in publication - // order, outside the capture lock, on whichever publishing caller is - // draining the reports (a publisher may return before its own report is - // delivered by the drainer). The drainer is registered with Close; ctx - // ends with Close, and once Close has begun no further report is - // delivered. A hook may publish again (its report is delivered after). + // HEAD before and after it (INV-PUBLISH-SETTLED-001). Calls are + // serialized and in publication order, outside the capture lock, on + // whichever publishing caller is draining the reports (a publisher may + // return before its own report is delivered by the drainer). The drainer + // is registered with Close; ctx ends with Close. Once Close has begun no + // further report is dequeued; a report already dequeued may still reach + // the hook after Close began (Close then waits for it). + // + // The hook MUST return without blocking and without remote calls; enqueue + // work to your own worker. It runs on the cut or detach caller's + // goroutine, before a detach returns: its duration is a guest-visible wait + // (Part C wait sites). While a hook stalls, later reports queue without a + // bound. A hook may publish again (its report is delivered after). OnPublishSettled func(ctx context.Context, prev, next ChunkHead) // ChunkBlocks is the number of consecutive blocks per chunk (1024 for // 4 KiB blocks and 4 MiB chunks). diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index aa90753dcb..b6ed420d15 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -347,7 +347,7 @@ snapshot lifetime; local persistence does not bypass it. ## Part B. Invariant ledger -118 rows: 99 ACTIVE, 19 STUB; 15 kept from the internal ledger, 103 new. +120 rows: 101 ACTIVE, 19 STUB; 15 kept from the internal ledger, 105 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -527,10 +527,13 @@ Notes: | `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | | `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | +| `INV-SHARE-ACTIVATION-001` | With a `ShareGuard` installed, a snapshot activates (writes its snapshot entry) and a fork activates (writes the child HEAD) only after `Finish` accepted the share for that HEAD; a refused `Begin` or `Finish` aborts before activation and drops the new intent, and the owner's seal calls `Begin` before the cut that produces the sealed HEAD (a refused `Begin` cuts nothing). With no guard, no call and no check is added. | M6 snapshot: Pending → Published; fork: child HEAD create | `core/frontend/chunkstore/share_guard.go` `beginShare`, `finishShare`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `Fork`; `core/host/volume/chunk_control.go` `chunkControl.Snapshot` | `TestShareGuard_SnapshotFinishesBeforeActivation`, `TestShareGuard_RefusedFinishAbortsTheSnapshot`, `TestShareGuard_StaleHeadIsRefused`, `TestShareGuard_CallerToken`, `TestShareGuard_Fork`, `TestShareGuard_BeginRefused` (`core/frontend/chunkstore/share_guard_test.go`); `TestChunkControl_SnapshotBeginsShareBeforeTheCut`, `TestChunkControl_SnapshotBeginRefusedCutsNothing` (`core/host/volume/chunk_control_order_test.go`) | — (the enterprise policy's protocol is modelled in `ShareMarker`) | ACTIVE | +| `INV-PUBLISH-SETTLED-001` | With `OnPublishSettled` set, each confirmed publication (HEAD prev → next with a new generation: a cut, a detach, or an earlier unresolved CAS found applied) is delivered once, in publication order, one at a time, outside the capture and state locks, by one registered drainer. Once Close has begun no report is dequeued; a report already dequeued may still reach the hook. A no-op cut reports nothing; with no hook nothing is queued. | M5 CAS → Settled; M6 HEAD: published | `core/storage/chunk_publish_settled.go` `noteSettled`, `unlockCap`, `runPublishSettled`; `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince` | `TestChunkPublishSettled_ReportsEachPublication`, `TestChunkPublishSettled_ReportsALatePublication`, `TestChunkPublishSettled_ClosedAndUnset`, `TestChunkPublishSettled_OverlappingPublishersStayOrdered`, `TestChunkPublishSettled_CloseDropsUnstartedReports`, `TestChunkPublishSettled_HookThatPublishes`, `TestChunkPublishSettled_PeriodicCutReports` (`core/storage/chunk_publish_settled_test.go`); `TestWALStoreChunk_PublishSettledHook` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE | Notes: - `INV-GC-GRACE-DEADLINE-001`: The check is in `NewCollector`; no Go test constructs a collector with a too-short grace. +- `ChunkRemote.ReclaimKey` is the Collector's per-key step (`reclaimBinding`) exported, not a new admission: `INV-GC-REACHABLE-001` (reachability and the two-mark grace) stays the Collector's, and a `ReclaimKey` caller must itself know nothing references the key. The step keeps `INV-CHUNK-WRITE-ONCE-001`: the binding is tombstoned, its exact fid deleted, and the binding kept for ever, never rebound; owner-qualified keys are refused. ### B.7 Rows kept from the internal ledger: Kubernetes line and replica fencing @@ -593,6 +596,14 @@ How a fix or a feature is calibrated against this model: 5. **Rows are stable.** IDs are never reused or renumbered. A retired row stays with status `ARCHIVED` and a reason. A narrowed statement says what was dropped in a note. 6. **STUB rows block claims.** A release note or a design document must not claim a property backed only by a `STUB` row. Turning a `STUB` into `ACTIVE` is the test plus the status change. +### C.W Wait sites (SYSTEM-MATH Part C) + +One row per wait in the data and control paths. Guest-visible rows on one path must sum to at most 5 s. + +| Site | Waits for | Bound | Owner that ends it | On expiry | Lock held while waiting | Guest-visible | +|---|---|---|---|---|---|---| +| `core/storage/chunk_publish_settled.go` `runPublishSettled` (from `unlockCap`, on the cut or detach caller's goroutine) | the `OnPublishSettled` hook to return | the hook's duration: the hook must return without blocking and without remote calls, enqueueing its work to its own worker | the hook implementer | none: a stalled hook stalls its caller, and later reports queue without a bound (a nil hook queues nothing) | none (`capMu` and `stMu` released) | yes on detach (the detach caller delivers before returning) | + Format v3 row 4 remains dark. Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The later W/BASE/fence owner must check R < W*, fence and publish bounds before readiness or append admission; neither codec nor scan success is readiness. The installed scan begins at max(BaseCursor, retainedTail). No ACTIVE v2 machine/guard is replaced by this step. ### Dark v3 offline reader (row12a) From e8f325dedc1334421e7f8b09ba5f64392608b279 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 21:59:34 -0800 Subject: [PATCH 10/34] chunkstore, sw-block: verify: bind rechecks to the lookup identity, confirm absence freshly, bound the start check - A failed refresh cancels reads in progress before joining them and is the error returned. - A reference to a chunk already read is compared with that content; two references to one key that disagree are a finding. - A snapshot is identified by the name it was looked up by; a document naming another snapshot or volume is ROOT_INVALID and excuses no miss. - The single-filer check of every ops chunk command runs within the command's --timeout. - SWFS.Get reports not found only after a fresh volume lookup whose every location answers 404; a warm, correct cache costs no extra lookup. - The verify rows move to Part B of the invariant document. Co-Authored-By: Claude Fable 5.2 --- seaweed-block/cmd/sw-block/chunk.go | 40 +- seaweed-block/cmd/sw-block/chunk_gc.go | 7 +- seaweed-block/cmd/sw-block/chunk_gc_test.go | 14 +- .../cmd/sw-block/chunk_output_test.go | 4 +- seaweed-block/cmd/sw-block/chunk_retain.go | 12 +- .../cmd/sw-block/chunk_retain_partial_test.go | 4 +- .../cmd/sw-block/chunk_retain_test.go | 4 +- seaweed-block/cmd/sw-block/chunk_show_test.go | 4 +- seaweed-block/cmd/sw-block/chunk_test.go | 10 +- seaweed-block/cmd/sw-block/chunk_verify.go | 7 +- .../cmd/sw-block/chunk_verify_test.go | 59 +- .../cmd/sw-block/chunk_volume_delete.go | 6 +- .../cmd/sw-block/chunk_volume_delete_test.go | 4 +- seaweed-block/core/frontend/chunkstore/GC.md | 20 +- .../core/frontend/chunkstore/swfs.go | 61 ++- .../core/frontend/chunkstore/swfs_test.go | 2 + .../core/frontend/chunkstore/verify.go | 173 ++++-- .../core/frontend/chunkstore/verify_test.go | 513 +++++++++++++++++- seaweed-block/docs/design/invariants.md | 13 +- 19 files changed, 840 insertions(+), 117 deletions(-) diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go index 9f2fcb8374..2d2e2bd401 100644 --- a/seaweed-block/cmd/sw-block/chunk.go +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -38,13 +38,14 @@ const ( // dialChunkFiler opens the filer for the direct commands and refuses unless // it is the only filer of its group, the same start check blockvolume makes // (chunkstore.CheckSingleFiler): a compare-and-swap on one of several -// filers does not exclude a writer on another. Tests replace it. -var dialChunkFiler = func(addr string) (chunkstore.Filer, func() error, error) { +// filers does not exclude a writer on another. The check runs within ctx, +// the command's own bound (and within its own). Tests replace it. +var dialChunkFiler = func(ctx context.Context, addr string) (chunkstore.Filer, func() error, error) { c, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{FilerGRPC: addr}) if err != nil { return nil, nil, err } - if err := c.CheckSingleFiler(context.Background()); err != nil { + if err := c.CheckSingleFiler(ctx); err != nil { _ = c.Close() return nil, nil, err } @@ -280,13 +281,14 @@ func chunkDetach(args []string, stdout, stderr io.Writer) int { return chunkPost("detach", statusAddr, "/chunk/detach", timeout, body, stdout, stderr) } -// chunkCatalog opens the catalog under --chunk-path on --chunk-filer. -// It returns exit -1 on success, else the exit code after reporting. -func chunkCatalog(name, filer, base string, stdout, stderr io.Writer) (*chunkstore.Catalog, func() error, int) { +// chunkCatalog opens the catalog under --chunk-path on --chunk-filer, its +// single-filer check bounded by ctx (the command's --timeout). It returns +// exit -1 on success, else the exit code after reporting. +func chunkCatalog(ctx context.Context, name, filer, base string, stdout, stderr io.Writer) (*chunkstore.Catalog, func() error, int) { if filer == "" { return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer is required", false) } - f, closeFn, err := dialChunkFiler(filer) + f, closeFn, err := dialChunkFiler(ctx, filer) if err != nil { return nil, nil, chunkDialFail(name, err, stdout, stderr) } @@ -387,13 +389,13 @@ func chunkSnapshots(args []string, stdout, stderr io.Writer) int { if volumeID == "" { return chunkFail("snapshots", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false) } - cat, closeFn, exit := chunkCatalog("snapshots", filer, base, stdout, stderr) + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + cat, closeFn, exit := chunkCatalog(ctx, "snapshots", filer, base, stdout, stderr) if exit >= 0 { return exit } defer closeFn() - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() list, next, err := cat.ListSnapshots(ctx, volumeID, chunkstore.ListOptions{Prefix: prefix, StartAfter: startAfter, Limit: limit, IncludeDeleting: includeDeleting}) return chunkResult("snapshots", chunkstore.NewSnapshotListBody(volumeID, list, next), err, stdout, stderr) } @@ -415,13 +417,13 @@ func chunkSnapshotDelete(args []string, stdout, stderr io.Writer) int { if volumeID == "" || name == "" { return chunkFail("snapshot-delete", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --name are required", false) } - cat, closeFn, exit := chunkCatalog("snapshot-delete", filer, base, stdout, stderr) + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + cat, closeFn, exit := chunkCatalog(ctx, "snapshot-delete", filer, base, stdout, stderr) if exit >= 0 { return exit } defer closeFn() - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() state, err := cat.DeleteSnapshot(ctx, volumeID, name) return chunkResult("snapshot-delete", chunkstore.SnapshotDeleteBody{VolumeID: volumeID, Name: name, State: state}, err, stdout, stderr) } @@ -451,13 +453,13 @@ func chunkFork(args []string, stdout, stderr io.Writer) int { requestID = newRequestID() fmt.Fprintf(stderr, "sw-block ops chunk fork: request id %s (reuse it to retry)\n", requestID) } - cat, closeFn, exit := chunkCatalog("fork", filer, base, stdout, stderr) + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + cat, closeFn, exit := chunkCatalog(ctx, "fork", filer, base, stdout, stderr) if exit >= 0 { return exit } defer closeFn() - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() res, err := cat.Fork(ctx, chunkstore.ForkRequest{Source: source, Snapshot: snapshot, Target: target, RequestID: requestID, Labels: map[string]string(labels)}) return chunkResult("fork", res, err, stdout, stderr) } @@ -479,13 +481,13 @@ func chunkShow(args []string, stdout, stderr io.Writer) int { if volumeID == "" { return chunkFail("show", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false) } - cat, closeFn, exit := chunkCatalog("show", filer, base, stdout, stderr) + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + cat, closeFn, exit := chunkCatalog(ctx, "show", filer, base, stdout, stderr) if exit >= 0 { return exit } defer closeFn() - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() v, hasVolume, err := cat.ReadVolume(ctx, volumeID) if err != nil { return chunkResult("show", nil, err, stdout, stderr) diff --git a/seaweed-block/cmd/sw-block/chunk_gc.go b/seaweed-block/cmd/sw-block/chunk_gc.go index 4615ff18ee..179b441fe3 100644 --- a/seaweed-block/cmd/sw-block/chunk_gc.go +++ b/seaweed-block/cmd/sw-block/chunk_gc.go @@ -36,7 +36,10 @@ func chunkGC(args []string, stdout, stderr io.Writer) int { if fs.NArg() != 0 || filer == "" || master == "" || timeout <= 0 || ttl <= 0 || grace <= chunkstore.DefaultOpDeadline { return chunkFail("gc", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer and --master are required; durations must be positive and grace must exceed the operation deadline", false) } - f, closeFn, e := dialChunkFiler(filer) + // One bound for the pass, the single-filer check included. + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + f, closeFn, e := dialChunkFiler(ctx, filer) if errors.Is(e, chunkstore.ErrNotSingleFiler) { return chunkDialFail("gc", e, stdout, stderr) } @@ -67,8 +70,6 @@ func chunkGC(args []string, stdout, stderr io.Writer) int { } return reply.Epoch, nil } - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() out, e := cat.ExecuteGC(ctx, blobs, chunkstore.GCConfig{Grace: grace, IntentTTL: ttl, Now: chunkGCNow, IssuedEpoch: issuedEpoch}, apply) return chunkGCResult(out, e, stdout, stderr) } diff --git a/seaweed-block/cmd/sw-block/chunk_gc_test.go b/seaweed-block/cmd/sw-block/chunk_gc_test.go index aaf158c4cf..2c121f13bb 100644 --- a/seaweed-block/cmd/sw-block/chunk_gc_test.go +++ b/seaweed-block/cmd/sw-block/chunk_gc_test.go @@ -63,7 +63,9 @@ func TestOpsChunkGC_DefaultIsReadOnly(t *testing.T) { store := &gcCLIStore{MemFiler: chunkstore.NewMemFiler()} old := dialChunkFiler defer func() { dialChunkFiler = old }() - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return store, func() error { return nil }, nil } + dialChunkFiler = func(context.Context, string) (chunkstore.Filer, func() error, error) { + return store, func() error { return nil }, nil + } code, out, errs := runChunk("gc", "--master", h.Addr(), "--chunk-filer", "local-test", "--chunk-path", "/gc-test") if code != 0 { t.Fatalf("missing safe GC entrypoint: exit=%d out=%s stderr=%s", code, out, errs) @@ -105,7 +107,7 @@ func TestOpsChunkGC_InvalidAdmissionHasNoStoreEffects(t *testing.T) { old := dialChunkFiler defer func() { dialChunkFiler = old }() calls := 0 - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + dialChunkFiler = func(context.Context, string) (chunkstore.Filer, func() error, error) { calls++ t.Fatal("invalid request reached store") return nil, nil, nil @@ -132,7 +134,9 @@ func gcPartialFixture(t *testing.T) (*gcCLIStore, *time.Time) { store := &gcCLIStore{MemFiler: chunkstore.NewMemFiler()} oldDial, oldClock := dialChunkFiler, chunkGCNow t.Cleanup(func() { dialChunkFiler = oldDial; chunkGCNow = oldClock }) - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return store, func() error { return nil }, nil } + dialChunkFiler = func(context.Context, string) (chunkstore.Filer, func() error, error) { + return store, func() error { return nil }, nil + } now := time.Now().Add(2 * time.Hour) chunkGCNow = func() time.Time { return now } ctx := context.Background() @@ -245,7 +249,9 @@ func TestOpsChunkGC_FailedMarkLookupPreservesUnknownUnbound(t *testing.T) { store := &gcFailedMarkLookup{gcCLIStore: &gcCLIStore{MemFiler: chunkstore.NewMemFiler()}} old := dialChunkFiler t.Cleanup(func() { dialChunkFiler = old }) - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return store, func() error { return nil }, nil } + dialChunkFiler = func(context.Context, string) (chunkstore.Filer, func() error, error) { + return store, func() error { return nil }, nil + } args := []string{"gc", "--master", "127.0.0.1:1", "--chunk-filer", "local", "--chunk-path", "/gc-lookup"} if apply { args = append(args, "--apply") diff --git a/seaweed-block/cmd/sw-block/chunk_output_test.go b/seaweed-block/cmd/sw-block/chunk_output_test.go index 47844a5ff8..65ad0eb087 100644 --- a/seaweed-block/cmd/sw-block/chunk_output_test.go +++ b/seaweed-block/cmd/sw-block/chunk_output_test.go @@ -62,7 +62,9 @@ func TestOpsChunk_LostResultFailsTheCommand(t *testing.T) { srv, _ := chunkServer(t, 200, `{"volumeID":"v1","cutLSN":9}`) mem := chunkstore.NewMemFiler() prev := dialChunkFiler - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + dialChunkFiler = func(context.Context, string) (chunkstore.Filer, func() error, error) { + return mem, func() error { return nil }, nil + } t.Cleanup(func() { dialChunkFiler = prev }) cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI) if err != nil { diff --git a/seaweed-block/cmd/sw-block/chunk_retain.go b/seaweed-block/cmd/sw-block/chunk_retain.go index 7b9702672c..16b3b7a3a1 100644 --- a/seaweed-block/cmd/sw-block/chunk_retain.go +++ b/seaweed-block/cmd/sw-block/chunk_retain.go @@ -31,13 +31,13 @@ func chunkUsage(args []string, stdout, stderr io.Writer) int { if volumeID == "" { return chunkFail("usage", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false) } - cat, closeFn, exit := chunkCatalog("usage", filer, base, stdout, stderr) + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + cat, closeFn, exit := chunkCatalog(ctx, "usage", filer, base, stdout, stderr) if exit >= 0 { return exit } defer closeFn() - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() u, err := cat.Usage(ctx, volumeID) return chunkResult("usage", u, err, stdout, stderr) } @@ -74,13 +74,13 @@ func chunkRetain(args []string, stdout, stderr io.Writer) int { if setPolicy && dryRun { return chunkFail("retain", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--set-policy and --dry-run do not combine", false) } - cat, closeFn, exit := chunkCatalog("retain", filer, base, stdout, stderr) + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + cat, closeFn, exit := chunkCatalog(ctx, "retain", filer, base, stdout, stderr) if exit >= 0 { return exit } defer closeFn() - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() if setPolicy { p := chunkstore.RetentionPolicy{KeepNewest: keepNewest, KeepYoungerNs: int64(keepYounger), KeepHourly: keepHourly, KeepDaily: keepDaily, KeepWeekly: keepWeekly} if err := cat.SetRetentionPolicy(ctx, volumeID, p); err != nil { diff --git a/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go b/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go index b40b03134e..0be4c05680 100644 --- a/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go +++ b/seaweed-block/cmd/sw-block/chunk_retain_partial_test.go @@ -43,7 +43,9 @@ func TestOpsChunk_RetainReportsPartialProgress(t *testing.T) { ff := &failingFiler{MemFiler: chunkstore.NewMemFiler()} fm := newManifestFixtureFiler(ff) prev := dialChunkFiler - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return fm, func() error { return nil }, nil } + dialChunkFiler = func(context.Context, string) (chunkstore.Filer, func() error, error) { + return fm, func() error { return nil }, nil + } t.Cleanup(func() { dialChunkFiler = prev }) cat, err := chunkstore.NewCatalog(fm, defaultChunkPathCLI) if err != nil { diff --git a/seaweed-block/cmd/sw-block/chunk_retain_test.go b/seaweed-block/cmd/sw-block/chunk_retain_test.go index 0dd4633cfd..3381d87358 100644 --- a/seaweed-block/cmd/sw-block/chunk_retain_test.go +++ b/seaweed-block/cmd/sw-block/chunk_retain_test.go @@ -46,7 +46,9 @@ func TestOpsChunk_UsageAndRetain(t *testing.T) { ctx := context.Background() mem := newManifestFixtureFiler(chunkstore.NewMemFiler()) prev := dialChunkFiler - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + dialChunkFiler = func(context.Context, string) (chunkstore.Filer, func() error, error) { + return mem, func() error { return nil }, nil + } t.Cleanup(func() { dialChunkFiler = prev }) cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI) if err != nil { diff --git a/seaweed-block/cmd/sw-block/chunk_show_test.go b/seaweed-block/cmd/sw-block/chunk_show_test.go index 6a36ac02a5..c5a2bd15ee 100644 --- a/seaweed-block/cmd/sw-block/chunk_show_test.go +++ b/seaweed-block/cmd/sw-block/chunk_show_test.go @@ -15,7 +15,9 @@ func TestOpsChunk_Show(t *testing.T) { ctx := context.Background() mem := newManifestFixtureFiler(chunkstore.NewMemFiler()) prev := dialChunkFiler - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + dialChunkFiler = func(context.Context, string) (chunkstore.Filer, func() error, error) { + return mem, func() error { return nil }, nil + } t.Cleanup(func() { dialChunkFiler = prev }) cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI) if err != nil { diff --git a/seaweed-block/cmd/sw-block/chunk_test.go b/seaweed-block/cmd/sw-block/chunk_test.go index 39347d09fa..4f04e24b89 100644 --- a/seaweed-block/cmd/sw-block/chunk_test.go +++ b/seaweed-block/cmd/sw-block/chunk_test.go @@ -132,7 +132,9 @@ func TestOpsChunk_ErrorsAreJSONOnStdout(t *testing.T) { mem := chunkstore.NewMemFiler() prev := dialChunkFiler - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + dialChunkFiler = func(context.Context, string) (chunkstore.Filer, func() error, error) { + return mem, func() error { return nil }, nil + } t.Cleanup(func() { dialChunkFiler = prev }) if code, out, _ := runChunk("fork", "--chunk-filer", "f:1", "--source", "v1", "--snapshot", "s9", "--target", "v2", "--request-id", "r"); code != chunkExitFailed { t.Fatalf("fork of a missing snapshot: exit %d %q", code, out) @@ -146,7 +148,9 @@ func TestOpsChunk_FilerCommands(t *testing.T) { ctx := context.Background() mem := chunkstore.NewMemFiler() prev := dialChunkFiler - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + dialChunkFiler = func(context.Context, string) (chunkstore.Filer, func() error, error) { + return mem, func() error { return nil }, nil + } t.Cleanup(func() { dialChunkFiler = prev }) cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI) if err != nil { @@ -162,7 +166,7 @@ func TestOpsChunk_FilerCommands(t *testing.T) { if err != nil { t.Fatal(err) } - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + dialChunkFiler = func(context.Context, string) (chunkstore.Filer, func() error, error) { return manifestMem, func() error { return nil }, nil } head = prepareFixtureHead(t, manifestMem, head) diff --git a/seaweed-block/cmd/sw-block/chunk_verify.go b/seaweed-block/cmd/sw-block/chunk_verify.go index af5fc66dcd..30e95f0c44 100644 --- a/seaweed-block/cmd/sw-block/chunk_verify.go +++ b/seaweed-block/cmd/sw-block/chunk_verify.go @@ -64,7 +64,10 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int { case timeout <= 0 || concurrency <= 0 || bytesPerSec < 0: return usage("--timeout and --concurrency must be positive and --bytes-per-sec not negative") } - cat, closeFn, exit := chunkCatalog("verify", filer, base, stdout, stderr) + // One bound for the whole pass, the single-filer check included. + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + cat, closeFn, exit := chunkCatalog(ctx, "verify", filer, base, stdout, stderr) if exit >= 0 { return exit } @@ -72,8 +75,6 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int { if bytesPerSec == 0 { bytesPerSec = -1 // the library's "unpaced" } - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() res, err := cat.Verify(ctx, volumeID, chunkstore.VerifyOptions{Depth: d, Snapshot: snapshot, AllSnapshots: allSnapshots, Concurrency: concurrency, BytesPerSecond: bytesPerSec}) if err != nil { diff --git a/seaweed-block/cmd/sw-block/chunk_verify_test.go b/seaweed-block/cmd/sw-block/chunk_verify_test.go index 0037cd8587..0a8be963c4 100644 --- a/seaweed-block/cmd/sw-block/chunk_verify_test.go +++ b/seaweed-block/cmd/sw-block/chunk_verify_test.go @@ -11,6 +11,7 @@ import ( "path" "strings" "testing" + "time" "google.golang.org/grpc" @@ -27,7 +28,9 @@ func verifyCLIFixture(t *testing.T) (*manifestFixtureFiler, storage.ChunkHead) { ctx := context.Background() mem := newManifestFixtureFiler(chunkstore.NewMemFiler()) prev := dialChunkFiler - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + dialChunkFiler = func(context.Context, string) (chunkstore.Filer, func() error, error) { + return mem, func() error { return nil }, nil + } t.Cleanup(func() { dialChunkFiler = prev }) cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI) if err != nil { @@ -161,7 +164,9 @@ func TestOpsChunk_VerifyReadErrorExits3(t *testing.T) { t.Fatal(err) } store := unreadableStore{mem, string(e.Extended["swb.fid"])} - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return store, func() error { return nil }, nil } + dialChunkFiler = func(context.Context, string) (chunkstore.Filer, func() error, error) { + return store, func() error { return nil }, nil + } code, out, errs := runChunk("verify", "--volume", "v1", "--chunk-filer", "filer:18888", "--depth", "data", "--timeout", "10s") res := decodeVerify(t, out) if code != chunkExitFindings || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != chunkstore.FindingReadError || @@ -243,3 +248,53 @@ func TestOpsChunk_RefusesMultiFiler(t *testing.T) { t.Fatalf("verify against the only filer: exit %d %q %q; want past the check", code, out, errs) } } + +// stalledConfigFiler never answers GetFilerConfiguration: the call returns +// only when its context ends. It reports the deadline the call carried and +// the context error it ended with. +type stalledConfigFiler struct { + filerpb.UnimplementedSeaweedFilerServer + deadline chan time.Time // zero: the call had no deadline + ended chan error +} + +func (f *stalledConfigFiler) GetFilerConfiguration(ctx context.Context, _ *filerpb.GetFilerConfigurationRequest) (*filerpb.GetFilerConfigurationResponse, error) { + dl, _ := ctx.Deadline() + f.deadline <- dl + <-ctx.Done() + f.ended <- ctx.Err() + return nil, ctx.Err() +} + +// The single-filer check runs within the command's --timeout: a filer that +// never answers holds the check only until that bound, which the call +// carries as its deadline and then observes as its cancellation. The +// command fails closed (exit 1). +func TestOpsChunk_SingleFilerCheckWithinTimeout(t *testing.T) { + const timeout = 2 * time.Second + for _, args := range [][]string{ + {"verify", "--volume", "v1"}, + {"gc", "--master", "127.0.0.1:1"}, + {"snapshots", "--volume", "v1"}, + } { + t.Run(args[0], func(t *testing.T) { + f := &stalledConfigFiler{deadline: make(chan time.Time, 1), ended: make(chan error, 1)} + addr := serveGRPC(t, func(s *grpc.Server) { filerpb.RegisterSeaweedFilerServer(s, f) }) + start := time.Now() + code, out, errs := runChunk(append(args, "--chunk-filer", addr, "--timeout", timeout.String())...) + dl := <-f.deadline + ended := <-f.ended + if e := chunkErrorOut(t, out); code != chunkExitFailed || e.Code != codeNotSingleFilerCLI || !strings.Contains(e.Message, "deadline") { + t.Fatalf("%s with a stalled filer: exit %d %q %q; want 1, not_single_filer, the deadline", args[0], code, out, errs) + } + // The call's deadline is the command's: start + timeout, plus + // the time to start the command; far below the check's own 60 s. + if dl.IsZero() || dl.After(start.Add(timeout+20*time.Second)) { + t.Fatalf("%s: the check's call carried deadline %v (start %v); want the command's %s", args[0], dl, start, timeout) + } + if ended == nil { + t.Fatalf("%s: the check's call did not observe the cancellation", args[0]) + } + }) + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_volume_delete.go b/seaweed-block/cmd/sw-block/chunk_volume_delete.go index 52e05da0cc..e482cbd99b 100644 --- a/seaweed-block/cmd/sw-block/chunk_volume_delete.go +++ b/seaweed-block/cmd/sw-block/chunk_volume_delete.go @@ -46,7 +46,9 @@ func chunkVolumeDelete(args []string, stdout, stderr io.Writer) int { if volumeID == "" || master == "" || requestID == "" || timeout <= 0 { return chunkFail("volume-delete", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "a volume, --master and --request-id are required; --timeout must be positive", false) } - cat, closeFn, exit := chunkCatalog("volume-delete", filer, base, stdout, stderr) + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + cat, closeFn, exit := chunkCatalog(ctx, "volume-delete", filer, base, stdout, stderr) if exit >= 0 { return exit } @@ -57,8 +59,6 @@ func chunkVolumeDelete(args []string, stdout, stderr io.Writer) int { } defer conn.Close() admit := &masterAdmission{lc: control.NewLifecycleServiceClient(conn), token: requestID} - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() res, err := cat.DeleteVolume(ctx, volumeID, admit) if err != nil { return volumeDeletePartial(res, err, stdout, stderr) diff --git a/seaweed-block/cmd/sw-block/chunk_volume_delete_test.go b/seaweed-block/cmd/sw-block/chunk_volume_delete_test.go index 535811e3a3..440b66159c 100644 --- a/seaweed-block/cmd/sw-block/chunk_volume_delete_test.go +++ b/seaweed-block/cmd/sw-block/chunk_volume_delete_test.go @@ -56,7 +56,9 @@ func TestOpsChunk_VolumeDelete(t *testing.T) { ctx := context.Background() mem := chunkstore.NewMemFiler() prev := dialChunkFiler - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + dialChunkFiler = func(context.Context, string) (chunkstore.Filer, func() error, error) { + return mem, func() error { return nil }, nil + } t.Cleanup(func() { dialChunkFiler = prev }) cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI) if err != nil { diff --git a/seaweed-block/core/frontend/chunkstore/GC.md b/seaweed-block/core/frontend/chunkstore/GC.md index 4a7ff80102..c835c539dc 100644 --- a/seaweed-block/core/frontend/chunkstore/GC.md +++ b/seaweed-block/core/frontend/chunkstore/GC.md @@ -111,7 +111,9 @@ Every catalog command (`verify`, `usage`, `show`, `snapshots`, check as blockvolume: it asks the filer for its masters and filer group, and refuses unless a master lists exactly one filer in that group and it is the `--chunk-filer` given. The refusal exits 1 with code `not_single_filer`. The -masters the filer reports must be reachable from where the command runs. +check runs within the command's `--timeout`; a check that cannot finish within +it refuses. The masters the filer reports must be reachable from where the +command runs. ## Verify @@ -133,8 +135,12 @@ one before it: - `meta`: the HEAD root decodes and is self-consistent; its chunk size and chunk indices fit the VOLUME geometry; every segment a checked root names is readable, matches its SHA-256 and decodes strictly; the same for each checked - snapshot's embedded HEAD; for a fork, its fork record's digest matches an - attempt of the parent snapshot at the recorded generation. + snapshot's embedded HEAD; a snapshot's document names the volume and the + snapshot it was found under (else `ROOT_INVALID`; the snapshot is still + checked, and rechecked, under the name it was found under); references to one + chunk with different SHA-256s disagree (`CONTENT_MISMATCH`); for a fork, its + fork record's digest matches an attempt of the parent snapshot at the + recorded generation. - `bindings` (the default): also, every chunk key a checked root references has a binding in its owner's `keys/` (a fork's `@owner/key` resolves to the owner volume), of the right kind, with a fid, without filer chunks, and not @@ -160,7 +166,9 @@ class and a detail. Classes: `ROOT_INVALID`, `GEOMETRY`, `SEGMENT_UNREADABLE`, `SIZE_MISMATCH`, `FORK_RECORD_MISMATCH`, `INTENT_STALE`, `READ_ERROR`. `NEEDLE_MISSING` means the blob store answered that the needle does not exist -(for SeaweedFS: HTTP 404 from every location). Any other read failure, such as a +(for SeaweedFS: HTTP 404 from every location of a fresh volume lookup; when the +cached locations all answer 404, the volume is looked up again, since it may +have moved). Any other read failure, such as a timeout, a refused or reset connection, or another HTTP status, is retried twice with a short backoff. If it still fails, the chunk or segment is reported as `READ_ERROR`, with the error in the detail. `READ_ERROR` is not evidence of @@ -196,7 +204,9 @@ finding against the current roots. A chunk that several checked roots name is reported once, under the first root that still names it (HEAD first). The HEAD view is also refreshed at least every 2 minutes during a long pass; only segments whose key changed are read again, -and chunks the pass has not seen are added. The result therefore states "every +and chunks the pass has not seen are added. A changed reference to a chunk +already seen is compared with that chunk's content (at depth `data`; the chunk +is not read again) or with its other references. The result therefore states "every chunk named by the listed HEAD generations at the time it was checked", not "the image at one instant". diff --git a/seaweed-block/core/frontend/chunkstore/swfs.go b/seaweed-block/core/frontend/chunkstore/swfs.go index 8426bfb456..4bbf6a72b4 100644 --- a/seaweed-block/core/frontend/chunkstore/swfs.go +++ b/seaweed-block/core/frontend/chunkstore/swfs.go @@ -224,22 +224,51 @@ func (c *SWFS) Put(ctx context.Context, data []byte) (string, error) { } // Get implements Blobs: resolve the fid's volume through the filer, then GET -// the needle from each location until one answers. +// the needle from each location until one answers. The needle is reported +// absent (ErrBlobNotFound) only when every location of a fresh lookup +// answers 404: cached locations can be stale after a volume moves, so their +// 404s are followed by one fresh lookup. func (c *SWFS) Get(ctx context.Context, fid string) ([]byte, error) { vid, _, ok := strings.Cut(fid, ",") if !ok { return nil, fmt.Errorf("chunkstore: bad fid %q", fid) } - urls, err := c.lookupVolume(ctx, vid) + urls, cached, err := c.lookupVolume(ctx, vid) if err != nil { return nil, err } - var lastErr error - allNotFound := true + b, allNotFound, lastErr := c.getFromAll(ctx, urls, fid) + if lastErr == nil { + return b, nil + } + c.mu.Lock() + delete(c.vidCache, vid) + c.mu.Unlock() + if allNotFound && cached { + if urls, _, err = c.lookupVolume(ctx, vid); err != nil { + return nil, err + } + if b, allNotFound, lastErr = c.getFromAll(ctx, urls, fid); lastErr == nil { + return b, nil + } + c.mu.Lock() + delete(c.vidCache, vid) + c.mu.Unlock() + } + if allNotFound { + lastErr = &blobNotFoundError{lastErr} + } + return nil, fmt.Errorf("chunkstore: read %s: %w", fid, lastErr) +} + +// getFromAll tries each location in turn. On failure lastErr is the last +// location's error and allNotFound whether every location answered 404. +func (c *SWFS) getFromAll(ctx context.Context, urls []string, fid string) (b []byte, allNotFound bool, lastErr error) { + allNotFound = true for _, host := range urls { b, err := c.getFrom(ctx, host, fid) if err == nil { - return b, nil + return b, false, nil } lastErr = err var se *blobStatusError @@ -247,13 +276,7 @@ func (c *SWFS) Get(ctx context.Context, fid string) ([]byte, error) { allNotFound = false } } - c.mu.Lock() - delete(c.vidCache, vid) - c.mu.Unlock() - if allNotFound && lastErr != nil { - lastErr = &blobNotFoundError{lastErr} - } - return nil, fmt.Errorf("chunkstore: read %s: %w", fid, lastErr) + return nil, allNotFound && lastErr != nil, lastErr } // blobStatusError is a volume server's non-200 answer to a needle GET. @@ -288,16 +311,18 @@ func (c *SWFS) getFrom(ctx context.Context, host, fid string) ([]byte, error) { return io.ReadAll(resp.Body) } -func (c *SWFS) lookupVolume(ctx context.Context, vid string) ([]string, error) { +// lookupVolume returns vid's locations; cached reports that they came from +// the cache rather than a lookup made now. +func (c *SWFS) lookupVolume(ctx context.Context, vid string) (urls []string, cached bool, err error) { c.mu.Lock() urls, ok := c.vidCache[vid] c.mu.Unlock() if ok && len(urls) > 0 { - return urls, nil + return urls, true, nil } resp, err := c.fc.LookupVolume(ctx, &filerpb.LookupVolumeRequest{VolumeIds: []string{vid}}) if err != nil { - return nil, fmt.Errorf("chunkstore: lookup volume %s: %w", vid, err) + return nil, false, fmt.Errorf("chunkstore: lookup volume %s: %w", vid, err) } for _, l := range resp.GetLocationsMap()[vid].GetLocations() { if l.GetUrl() != "" { @@ -305,12 +330,12 @@ func (c *SWFS) lookupVolume(ctx context.Context, vid string) ([]string, error) { } } if len(urls) == 0 { - return nil, fmt.Errorf("chunkstore: volume %s has no locations", vid) + return nil, false, fmt.Errorf("chunkstore: volume %s has no locations", vid) } c.mu.Lock() c.vidCache[vid] = urls c.mu.Unlock() - return urls, nil + return urls, false, nil } var ( @@ -327,7 +352,7 @@ func (c *SWFS) DeleteBlob(ctx context.Context, fid string) error { if !ok || vid == "" || needle == "" || strings.ContainsAny(fid, "/\\?#% \r\n") { return fmt.Errorf("chunkstore: bad deletion fid %q", fid) } - urls, err := c.lookupVolume(ctx, vid) + urls, _, err := c.lookupVolume(ctx, vid) if err != nil { return err } diff --git a/seaweed-block/core/frontend/chunkstore/swfs_test.go b/seaweed-block/core/frontend/chunkstore/swfs_test.go index 748681e3a8..b26eedeafa 100644 --- a/seaweed-block/core/frontend/chunkstore/swfs_test.go +++ b/seaweed-block/core/frontend/chunkstore/swfs_test.go @@ -32,6 +32,7 @@ type fakeFilerGRPC struct { lookupErr error assignResp *filerpb.AssignVolumeResponse lookupVol *filerpb.LookupVolumeResponse + volLookups int // LookupVolume calls lastCreate *filerpb.CreateEntryRequest lastUpdate *filerpb.UpdateEntryRequest @@ -80,6 +81,7 @@ func (f *fakeFilerGRPC) AssignVolume(_ context.Context, r *filerpb.AssignVolumeR func (f *fakeFilerGRPC) LookupVolume(_ context.Context, r *filerpb.LookupVolumeRequest) (*filerpb.LookupVolumeResponse, error) { f.mu.Lock() defer f.mu.Unlock() + f.volLookups++ return f.lookupVol, nil } diff --git a/seaweed-block/core/frontend/chunkstore/verify.go b/seaweed-block/core/frontend/chunkstore/verify.go index 77b35066a9..d5652770d4 100644 --- a/seaweed-block/core/frontend/chunkstore/verify.go +++ b/seaweed-block/core/frontend/chunkstore/verify.go @@ -7,15 +7,19 @@ package chunkstore // Depths, each including the one before: // // - meta: the HEAD root decodes and is self-consistent; its geometry -// matches VOLUME; every segment a selected root names is readable and -// passes its SHA-256 and strict decode; a fork's record matches the -// parent snapshot it was made from. +// matches VOLUME; a snapshot's document names the volume and the +// snapshot it was found under; every segment a selected root names is +// readable and passes its SHA-256 and strict decode; a fork's record +// matches the parent snapshot it was made from. References to one +// chunk with different SHA-256s disagree (CONTENT_MISMATCH). // - bindings (the default): every chunk key a selected root references // has a sound binding in its owner's keys/ (one listing per owner), // not tombstoned by GC. // - data: every distinct chunk (owner + key, across all selected roots) -// is fetched once; its SHA-256 must equal the reference and its length -// the chunk size (the rule the chunk layer applies on a read miss). +// is fetched once; its SHA-256 must equal each reference and its length +// the chunk size (the rule the chunk layer applies on a read miss). A +// reference added later (a refreshed HEAD) is compared with the content +// already read; the chunk is not read again. // // Running beside a live owner and beside GC: segments and chunks are // immutable and written before the root that names them, so a root read @@ -280,6 +284,36 @@ type verifyChunk struct { uses []verifyUse fid string bound bool // a sound, untombstoned binding was found + + // Under the verifier's lock. read is set once the needle was read + // (depth data), with its length and SHA-256: a later reference is + // compared with them, the chunk is not read again. late are the + // references refreshed HEADs added; the reader compares those added + // before it read the chunk, addUses the ones added after. + read bool + length int + digest [32]byte + late []verifyUse +} + +// repeats reports whether u repeats a reference already recorded for w +// (same index and SHA-256): comparing it again finds nothing new. +func (w *verifyChunk) repeats(u verifyUse) bool { + for _, list := range [][]verifyUse{w.uses, w.late} { + for _, o := range list { + if o.idx == u.idx && o.sha == u.sha { + return true + } + } + } + return false +} + +// verifyRef is a reference to a chunk already seen, to compare without +// reading the chunk (see addUses). +type verifyRef struct { + w *verifyChunk + u verifyUse } type verifier struct { @@ -435,14 +469,16 @@ func (v *verifier) run(ctx context.Context) error { v.finding(VerifyFinding{Root: "HEAD", Class: FindingRootInvalid, Detail: derr.Error()}) break } - v.head, v.hasHead, v.lastRefresh = h, true, time.Now() + v.head, v.hasHead, v.lastRefresh = h, true, v.c.now() hr := verifyRoot{label: headLabel(h.Gen), head: true} v.res.HeadGens = append(v.res.HeadGens, h.Gen) chunks, err := v.walk(ctx, hr, h) if err != nil { return err } - v.addUses(hr, chunks, false) + if err := v.compareRefs(ctx, v.addUses(hr, chunks, false)); err != nil { + return err + } if err := v.intents(ctx, h, chunks); err != nil { return err } @@ -804,28 +840,69 @@ func (v *verifier) names(ctx context.Context, h storage.ChunkHead, idx uint64, i return has && chunkIdentity(v.vol, ref.Key) == id, nil } -// addUses records r's chunk references. onlyNew (a refreshed HEAD) -// adds only chunks this pass has not seen: an unchanged key was already -// checked, and its content cannot have changed. -func (v *verifier) addUses(r verifyRoot, chunks map[uint64]storage.ChunkRef, onlyNew bool) { +// addUses records r's chunk references, queueing the chunks this pass has +// not seen, and returns the references to compare once the lock is +// released. A chunk is immutable, but a new reference to it can be wrong, +// so a reference to a chunk already seen is compared, never by reading the +// chunk again: with its content once it was read, and below depth data +// with the chunk's first reference. A refreshed HEAD's references (refreshed +// set) to chunks already seen are not counted as checked again; one that +// repeats a recorded reference adds nothing, and one the reader has yet to +// read is left for it to compare. +func (v *verifier) addUses(r verifyRoot, chunks map[uint64]storage.ChunkRef, refreshed bool) []verifyRef { v.mu.Lock() defer v.mu.Unlock() + var check []verifyRef for _, idx := range sortedIndexes(chunks) { ref := chunks[idx] id := chunkIdentity(v.vol, ref.Key) + u := verifyUse{root: r, idx: idx, sha: ref.SHA256} w := v.chunks[id] - if w != nil && onlyNew { - continue - } if w == nil { owner, key := splitIdentity(id) w = &verifyChunk{id: id, owner: owner, key: key} v.chunks[id] = w v.pending = append(v.pending, w) + } else { + if refreshed { + if w.repeats(u) { + continue + } + w.late = append(w.late, u) + } + if w.read || (v.opts.Depth != VerifyData && u.sha != w.uses[0].sha) { + check = append(check, verifyRef{w, u}) + } + if refreshed { + continue + } } - w.uses = append(w.uses, verifyUse{root: r, idx: idx, sha: ref.SHA256}) + w.uses = append(w.uses, u) v.res.ChunksChecked++ } + return check +} + +// compareRefs compares references to chunks already seen (see addUses). +func (v *verifier) compareRefs(ctx context.Context, refs []verifyRef) error { + for _, c := range refs { + v.mu.Lock() + read, n, sum, first := c.w.read, c.w.length, c.w.digest, c.w.uses[0] + v.mu.Unlock() + var err error + if read { + err = v.compareContent(ctx, c.w, n, sum, []verifyUse{c.u}) + } else { + err = v.missUses(ctx, c.w, []verifyUse{c.u}, FindingContentMismatch, func(u verifyUse) string { + return fmt.Sprintf("references to this chunk disagree: SHA-256 %s here, %s under %s at index %d (depth data reads the chunk)", + hex.EncodeToString(u.sha[:]), hex.EncodeToString(first.sha[:]), first.root.label, first.idx) + }) + } + if err != nil { + return err + } + } + return nil } func sortedIndexes(m map[uint64]storage.ChunkRef) []uint64 { @@ -861,7 +938,7 @@ func (v *verifier) snapshots(ctx context.Context) error { if ref.info.State == SnapDeleting { return catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted; GC may already reclaim its chunks", v.vol, v.opts.Snapshot) } - return v.snapshot(ctx, ref.info) + return v.snapshot(ctx, v.opts.Snapshot, ref) } if !v.opts.AllSnapshots { return nil @@ -889,7 +966,7 @@ func (v *verifier) snapshots(ctx context.Context) error { if !ok || ref.entry == nil || ref.info.State == SnapAborted || ref.info.State == SnapDeleting { continue } - if err := v.snapshot(ctx, ref.info); err != nil { + if err := v.snapshot(ctx, e.GetName(), ref); err != nil { return err } } @@ -899,10 +976,19 @@ func (v *verifier) snapshots(ctx context.Context) error { } } -func (v *verifier) snapshot(ctx context.Context, s SnapshotInfo) error { - r := verifyRoot{label: "snapshot " + s.Name + "/" + s.attempt, name: s.Name, attempt: s.attempt} - v.res.Snapshots = append(v.res.Snapshots, s.Name+"/"+s.attempt) +// snapshot checks the snapshot found under name, at the attempt its name +// record names. That path is the snapshot's identity, for its label and +// every recheck; a document naming another volume or snapshot is +// ROOT_INVALID, and its chunks are still checked under that path. +func (v *verifier) snapshot(ctx context.Context, name string, ref snapRef) error { + s, attempt := ref.info, ref.rec.Attempt + r := verifyRoot{label: "snapshot " + name + "/" + attempt, name: name, attempt: attempt} + v.res.Snapshots = append(v.res.Snapshots, name+"/"+attempt) v.snapRoots = append(v.snapRoots, r) + if s.VolumeID != v.vol || s.Name != name { + v.finding(VerifyFinding{Root: r.label, Class: FindingRootInvalid, + Detail: fmt.Sprintf("snapshot document names %s/%s, found as %s/%s", s.VolumeID, s.Name, v.vol, name)}) + } if s.geo != (Geometry{}) && s.geo != v.geo { v.finding(VerifyFinding{Root: r.label, Class: FindingGeometry, Detail: fmt.Sprintf("snapshot geometry %+v, VOLUME %+v", s.geo, v.geo)}) } @@ -910,8 +996,7 @@ func (v *verifier) snapshot(ctx context.Context, s SnapshotInfo) error { if err != nil { return err } - v.addUses(r, chunks, false) - return nil + return v.compareRefs(ctx, v.addUses(r, chunks, false)) } // forkRecord checks a fork's record against the parent snapshot it names: @@ -1036,12 +1121,14 @@ func (v *verifier) intents(ctx context.Context, h storage.ChunkHead, chunks map[ // maybeRefresh reads HEAD again once RefreshInterval has passed since the // last view. A new generation is walked (only segments whose reference -// changed are read) and its chunks this pass has not seen are queued. +// changed are read); its chunks this pass has not seen are queued, and its +// changed references to chunks already seen are compared (addUses). func (v *verifier) maybeRefresh(ctx context.Context) error { - if !v.hasHead || time.Since(v.lastRefresh) < v.opts.RefreshInterval { + now := v.c.now() + if !v.hasHead || now.Sub(v.lastRefresh) < v.opts.RefreshInterval { return nil } - v.lastRefresh = time.Now() + v.lastRefresh = now e, err := v.c.f.LookupEntry(ctx, v.root, headName) if errors.Is(err, ErrNotFound) { return nil @@ -1066,9 +1153,8 @@ func (v *verifier) maybeRefresh(ctx context.Context) error { if err != nil { return err } - v.addUses(hr, chunks, true) v.head = h - return nil + return v.compareRefs(ctx, v.addUses(hr, chunks, true)) } // ---- bindings ---- @@ -1266,13 +1352,17 @@ func (v *verifier) checkData(ctx context.Context, batch []*verifyChunk) error { } return nil } - derr := dispatch() + if err := dispatch(); err != nil { + // Stop the reads in flight before waiting for them, so a known + // failure is not held up by a read that would end only with the + // caller's deadline. The failure that stopped the pass is the one + // returned, not the cancellation it caused in the readers. + setErr(err) + cancel() + } close(jobs) wg.Wait() - if err := getErr(); err != nil { - return err - } - return derr + return getErr() } func (v *verifier) readChunk(ctx context.Context, w *verifyChunk) error { @@ -1286,16 +1376,27 @@ func (v *verifier) readChunk(ctx context.Context, w *verifyChunk) error { default: return v.miss(ctx, w, FindingReadError, readErrorDetail(err)) } + sum := sha256.Sum256(data) v.mu.Lock() v.res.DistinctChunksRead++ v.res.BytesRead += int64(len(data)) + w.read, w.length, w.digest = true, len(data), sum + uses := append(append([]verifyUse(nil), w.uses...), w.late...) v.mu.Unlock() - if uint64(len(data)) != v.chunkBytes { - return v.miss(ctx, w, FindingSizeMismatch, fmt.Sprintf("needle holds %d bytes, chunk size %d", len(data), v.chunkBytes)) + return v.compareContent(ctx, w, len(data), sum, uses) +} + +// compareContent checks uses against a chunk's content, n bytes with +// SHA-256 sum: the length must be the chunk size and the hash each +// reference's. +func (v *verifier) compareContent(ctx context.Context, w *verifyChunk, n int, sum [32]byte, uses []verifyUse) error { + if uint64(n) != v.chunkBytes { + return v.missUses(ctx, w, uses, FindingSizeMismatch, func(verifyUse) string { + return fmt.Sprintf("needle holds %d bytes, chunk size %d", n, v.chunkBytes) + }) } - sum := sha256.Sum256(data) var mismatched []verifyUse - for _, u := range w.uses { + for _, u := range uses { if sum != u.sha { mismatched = append(mismatched, u) } diff --git a/seaweed-block/core/frontend/chunkstore/verify_test.go b/seaweed-block/core/frontend/chunkstore/verify_test.go index f9d19030fa..6722481eee 100644 --- a/seaweed-block/core/frontend/chunkstore/verify_test.go +++ b/seaweed-block/core/frontend/chunkstore/verify_test.go @@ -387,6 +387,18 @@ func TestSWFS_GetNotFoundIsErrBlobNotFound(t *testing.T) { return strings.TrimPrefix(s.URL, "http://") } missing, broken := server(http.StatusNotFound), server(http.StatusInternalServerError) + // dropped closes every connection without an answer: a transport error. + dropped := func() string { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + conn, _, err := w.(http.Hijacker).Hijack() + if err == nil { + _ = conn.Close() + } + })) + t.Cleanup(s.Close) + return strings.TrimPrefix(s.URL, "http://") + }() + statusOf := map[string]int{missing: http.StatusNotFound, broken: http.StatusInternalServerError} for _, tc := range []struct { name string hosts []string @@ -395,6 +407,9 @@ func TestSWFS_GetNotFoundIsErrBlobNotFound(t *testing.T) { {"every location 404", []string{missing, missing}, true}, {"one location 500", []string{missing, broken}, false}, {"only 500", []string{broken}, false}, + // Only the last answer is 404: still not proof of absence. + {"500 then 404", []string{broken, missing}, false}, + {"transport error then 404", []string{dropped, missing}, false}, } { t.Run(tc.name, func(t *testing.T) { var locs []*filerpb.Location @@ -404,10 +419,7 @@ func TestSWFS_GetNotFoundIsErrBlobNotFound(t *testing.T) { c := startFakeFiler(t, &fakeFilerGRPC{lookupVol: &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{"7": {Locations: locs}}}}) _, err := c.Get(context.Background(), "7,0000dead") last := tc.hosts[len(tc.hosts)-1] - status := 404 - if last == broken { - status = 500 - } + status := statusOf[last] if err == nil || errors.Is(err, ErrBlobNotFound) != tc.notFound || err.Error() != fmt.Sprintf("chunkstore: read 7,0000dead: http %d from %s", status, last) { t.Fatalf("Get: %v (not found %v), want not found %v", err, errors.Is(err, ErrBlobNotFound), tc.notFound) } @@ -415,6 +427,130 @@ func TestSWFS_GetNotFoundIsErrBlobNotFound(t *testing.T) { } } +// volumeAt is a LookupVolume answer placing volume vid at hosts. +func volumeAt(vid string, hosts ...string) *filerpb.LookupVolumeResponse { + var locs []*filerpb.Location + for _, h := range hosts { + locs = append(locs, &filerpb.Location{Url: h}) + } + return &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{vid: {Locations: locs}}} +} + +func (f *fakeFilerGRPC) volumeLookups() int { + f.mu.Lock() + defer f.mu.Unlock() + return f.volLookups +} + +// Cached locations can be stale (the volume moved): 404 from every cached +// location is not proof of absence. Get looks the volume up again and reads +// from the fresh locations; only 404 from every fresh location is +// ErrBlobNotFound. A read the cache serves makes no lookup. +func TestSWFS_GetStaleCachedLocationLooksUpAgain(t *testing.T) { + body := []byte("needle bytes") + server := func(status int) string { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(status) + if status == http.StatusOK { + _, _ = w.Write(body) + } + })) + t.Cleanup(s.Close) + return strings.TrimPrefix(s.URL, "http://") + } + oldLoc, newLoc, alsoMissing := server(http.StatusNotFound), server(http.StatusOK), server(http.StatusNotFound) + const fid = "7,0000dead" + for _, tc := range []struct { + name string + cached []string // nil: nothing cached + fresh string + wantBody bool + wantLookups int + }{ + {"cached location 404, fresh location has it", []string{oldLoc}, newLoc, true, 1}, + {"cached and fresh locations 404", []string{oldLoc}, alsoMissing, false, 1}, + {"warm cache", []string{newLoc}, newLoc, true, 0}, + {"nothing cached, fresh location 404", nil, alsoMissing, false, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + f := &fakeFilerGRPC{lookupVol: volumeAt("7", tc.fresh)} + c := startFakeFiler(t, f) + if tc.cached != nil { + c.mu.Lock() + c.vidCache["7"] = tc.cached + c.mu.Unlock() + } + b, err := c.Get(context.Background(), fid) + if n := f.volumeLookups(); n != tc.wantLookups { + t.Fatalf("Get made %d volume lookups, want %d (err %v)", n, tc.wantLookups, err) + } + if tc.wantBody { + if err != nil || string(b) != string(body) { + t.Fatalf("Get: %q, %v; want the needle from %s", b, err, tc.fresh) + } + return + } + if !errors.Is(err, ErrBlobNotFound) || err.Error() != "chunkstore: read "+fid+": http 404 from "+tc.fresh { + t.Fatalf("Get: %v (not found %v); want ErrBlobNotFound from the fresh location %s", err, errors.Is(err, ErrBlobNotFound), tc.fresh) + } + }) + } +} + +// A volume that moved after its location was cached is not missing: depth +// data through SWFS reads every needle from the new location, no finding. +func TestVerify_MovedVolumeIsNotAMissingNeedle(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + var mu sync.Mutex + moved := false + serve := func(old bool) string { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + gone := old && moved + mu.Unlock() + fx.b.mu.Lock() + d, ok := fx.b.data[strings.TrimPrefix(r.URL.Path, "/")] + fx.b.mu.Unlock() + if gone || !ok { + w.WriteHeader(http.StatusNotFound) + return + } + _, _ = w.Write(d) + })) + t.Cleanup(s.Close) + return strings.TrimPrefix(s.URL, "http://") + } + oldLoc, newLoc := serve(true), serve(false) + vid, _, _ := strings.Cut(fx.fid(h.Chunks[0].Key), ",") + f := &fakeFilerGRPC{lookupVol: volumeAt(vid, oldLoc)} + sw := startFakeFiler(t, f) + ctx := context.Background() + // Warm the location cache at the old location, then move the volume. + if _, err := sw.Get(ctx, fx.fid(h.Chunks[0].Key)); err != nil { + t.Fatal(err) + } + mu.Lock() + moved = true + mu.Unlock() + f.mu.Lock() + f.lookupVol = volumeAt(vid, newLoc) + f.mu.Unlock() + + cat, err := NewCatalog(manifestFilerBlobs{fx.f, sw}, catBase) + if err != nil { + t.Fatal(err) + } + res, err := cat.Verify(ctx, "v1", VerifyOptions{Depth: VerifyData, BytesPerSecond: -1}) + if err != nil || !res.Complete { + t.Fatalf("verify: %v, %+v", err, res) + } + wantClasses(t, "moved volume", res) + if res.DistinctChunksRead != 2 || res.SegmentReads != 1 { + t.Fatalf("read %d chunks, %d segments; want 2, 1", res.DistinctChunksRead, res.SegmentReads) + } +} + // A root that names a binding GC tombstoned: the chunk is gone or going. func TestVerify_TombstonedBinding(t *testing.T) { fx := newVerifyFixture(t, "v1") @@ -940,3 +1076,372 @@ func TestVerify_ContextEndedIsIncomplete(t *testing.T) { t.Fatalf("missing volume: %v", err) } } + +// heldReads holds the read of one needle open until the reader's context +// ends, and counts the reads in progress. +type heldReads struct { + Blobs + fid string + onEnter func() // runs once, when the held read has started + entered chan struct{} // closed when the held read has started + once sync.Once + + mu sync.Mutex + active int + ended error // the held read's context error, once it ended +} + +func newHeldReads(b Blobs, fid string) *heldReads { + return &heldReads{Blobs: b, fid: fid, entered: make(chan struct{})} +} + +func (h *heldReads) Get(ctx context.Context, fid string) ([]byte, error) { + h.mu.Lock() + h.active++ + h.mu.Unlock() + defer func() { + h.mu.Lock() + h.active-- + h.mu.Unlock() + }() + if fid != h.fid { + return h.Blobs.Get(ctx, fid) + } + h.once.Do(func() { + close(h.entered) + if h.onEnter != nil { + h.onEnter() + } + }) + <-ctx.Done() + h.mu.Lock() + h.ended = ctx.Err() + h.mu.Unlock() + return nil, fmt.Errorf("chunkstore: read %s: %w", fid, ctx.Err()) +} + +func (h *heldReads) state() (active int, ended error) { + h.mu.Lock() + defer h.mu.Unlock() + return h.active, h.ended +} + +var errFilerDown = errors.New("filer: connection refused") + +// tickingClock advances by step at every reading: with a refresh interval +// of step, a pass refreshes HEAD at every opportunity, without waiting. +func tickingClock(step time.Duration) func() time.Time { + var mu sync.Mutex + now := time.Now() + return func() time.Time { + mu.Lock() + defer mu.Unlock() + now = now.Add(step) + return now + } +} + +// headFailsDuringRead fails HEAD reads made while the held read is in +// progress. The first HEAD read after the chunk key listing passes (it is +// the refresh before the first chunk, the held one, is handed to a reader); +// later ones wait until the held read has started, then fail. +type headFailsDuringRead struct { + Filer + root, keys string + entered <-chan struct{} + + mu sync.Mutex + listed bool + after int // HEAD reads since the listing +} + +func (f *headFailsDuringRead) ListEntries(ctx context.Context, dir, prefix, after string, limit uint32) ([]*filerpb.Entry, error) { + if dir == f.keys { + f.mu.Lock() + f.listed = true + f.mu.Unlock() + } + return f.Filer.ListEntries(ctx, dir, prefix, after, limit) +} + +func (f *headFailsDuringRead) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if dir == f.root && name == headName { + f.mu.Lock() + n := 0 + if f.listed { + f.after++ + n = f.after + } + f.mu.Unlock() + if n >= 2 { + select { + case <-f.entered: + return nil, errFilerDown + case <-ctx.Done(): + return nil, ctx.Err() + } + } + } + return f.Filer.LookupEntry(ctx, dir, name) +} + +// A HEAD refresh that fails while a chunk read is in progress stops that +// read at once: Verify returns the filer's error (not the cancellation it +// caused in the reader), incomplete, with no read left running, and long +// before the caller's own deadline. +func TestVerify_FailedRefreshCancelsReadInProgress(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + held := newHeldReads(fx.cb, fx.fid(h.Chunks[0].Key)) + filer := &headFailsDuringRead{Filer: fx.f, root: path.Join(catBase, "v1"), keys: path.Join(catBase, "v1", keysDir), entered: held.entered} + cat, err := NewCatalog(manifestFilerBlobs{filer, held}, catBase) + if err != nil { + t.Fatal(err) + } + cat.SetClock(tickingClock(time.Minute)) + // The caller's deadline only guards the test: Verify must end well before it. + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + res, err := cat.Verify(ctx, "v1", VerifyOptions{Depth: VerifyData, RefreshInterval: time.Minute, BytesPerSecond: -1}) + active, ended := held.state() + if !errors.Is(err, errFilerDown) || !strings.Contains(err.Error(), "refresh HEAD") { + t.Fatalf("verify: %v; want the HEAD refresh error", err) + } + if ctx.Err() != nil || !errors.Is(ended, context.Canceled) { + t.Fatalf("held read ended with %v (caller context %v); want cancelled by the failed refresh", ended, ctx.Err()) + } + if res.Complete || active != 0 { + t.Fatalf("complete %v, %d reads still running; want incomplete, none", res.Complete, active) + } +} + +// Cancelling the caller's context while a chunk read is in progress ends +// that read and the pass: incomplete, the cancellation reported, no read +// left running. +func TestVerify_CancelDuringReadJoinsReaders(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + held := newHeldReads(fx.cb, fx.fid(h.Chunks[0].Key)) + cat, err := NewCatalog(manifestFilerBlobs{fx.f, held}, catBase) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + held.onEnter = cancel + res, err := cat.Verify(ctx, "v1", VerifyOptions{Depth: VerifyData, BytesPerSecond: -1}) + active, ended := held.state() + select { + case <-held.entered: + default: + t.Fatal("the held read never started") + } + if !errors.Is(err, context.Canceled) || res.Complete || !errors.Is(ended, context.Canceled) || active != 0 { + t.Fatalf("verify: %v, complete %v; held read ended with %v, %d reads still running", err, res.Complete, ended, active) + } + if len(res.HeadGens) != 1 || res.HeadGens[0] != h.Gen { + t.Fatalf("covered gens %v, want [%d]", res.HeadGens, h.Gen) + } +} + +// republish installs a new HEAD for vol with the current chunk references +// as edit leaves them (keys are not uploaded again). +func (fx *verifyFixture) republish(vol string, edit func(map[uint64]storage.ChunkRef)) storage.ChunkHead { + fx.t.Helper() + ctx := context.Background() + r, err := NewChunkRemote(fx.f, fx.b, path.Join(catBase, vol)) + if err != nil { + fx.t.Fatal(err) + } + cur, err := r.GetHead(ctx) + if err != nil { + fx.t.Fatal(err) + } + next := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: cur.RemoteLSN + 1, Chunks: map[uint64]storage.ChunkRef{}} + for idx, ref := range cur.Chunks { + next.Chunks[idx] = ref + } + edit(next.Chunks) + next, ids, err := r.PrepareManifest(ctx, cur, next, verifyChunkBytes) + if err != nil { + fx.t.Fatal(err) + } + gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, next) + if err != nil { + fx.t.Fatal(err) + } + next.Gen = gen + for _, id := range ids { + if err := r.DeleteIntent(ctx, id); err != nil { + fx.t.Fatal(err) + } + } + return next +} + +// wrongHash flips the reference SHA-256 of chunk idx, keeping its key. +func wrongHash(idx uint64) func(map[uint64]storage.ChunkRef) { + return func(c map[uint64]storage.ChunkRef) { + ref := c[idx] + ref.SHA256[0] ^= 0xff + c[idx] = ref + } +} + +// beforeRead runs fn once, before the first read of fid. +type beforeRead struct { + Blobs + fid string + fn func() + once sync.Once +} + +func (b *beforeRead) Get(ctx context.Context, fid string) ([]byte, error) { + if fid == b.fid { + b.once.Do(b.fn) + } + return b.Blobs.Get(ctx, fid) +} + +// A reference to a chunk already checked, under the same key but with +// another SHA-256, is a finding: at depth data it is compared with the +// content read once for that chunk (the chunk is not read again), below +// data with the other reference. This holds for a HEAD refreshed during +// the pass and for a snapshot. +func TestVerify_SameKeyWithAnotherHashIsAFinding(t *testing.T) { + for _, tc := range []struct { + name string + depth VerifyDepth + when string // "walked": HEAD changes once the first view is walked; "read": once chunk 0 was read; "snapshot": before the pass + detail string + }{ + {"refreshed HEAD, data, before the read", VerifyData, "walked", "needle SHA-256"}, + {"refreshed HEAD, data, after the read", VerifyData, "read", "needle SHA-256"}, + {"refreshed HEAD, bindings", VerifyBindings, "walked", "disagree"}, + {"snapshot, data", VerifyData, "snapshot", "needle SHA-256"}, + {"snapshot, bindings", VerifyBindings, "snapshot", "disagree"}, + } { + t.Run(tc.name, func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fid0 := fx.fid(h1.Chunks[0].Key) + var h2 storage.ChunkHead + opts := VerifyOptions{Depth: tc.depth, BytesPerSecond: -1, RefreshInterval: time.Minute, Concurrency: 1} + cat := fx.c + switch tc.when { + case "walked": + opts.hook = func(stage string) { + if stage == verifyHookHeadWalked { + h2 = fx.republish("v1", wrongHash(0)) + } + } + case "read": + // One reader: chunk 0 is read completely before chunk 1 is + // handed out, so its content is known when HEAD changes. + br := &beforeRead{Blobs: fx.cb, fid: fx.fid(h1.Chunks[1].Key), fn: func() { h2 = fx.republish("v1", wrongHash(0)) }} + var err error + if cat, err = NewCatalog(manifestFilerBlobs{fx.f, br}, catBase); err != nil { + t.Fatal(err) + } + case "snapshot": + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h1); err != nil { + t.Fatal(err) + } + h2 = fx.republish("v1", wrongHash(0)) + opts.AllSnapshots = true + } + cat.SetClock(tickingClock(time.Minute)) + res, err := cat.Verify(ctx, "v1", opts) + if err != nil || !res.Complete { + t.Fatalf("verify: %v, %+v", err, res) + } + wantClasses(t, tc.name, res, "CONTENT_MISMATCH@0") + f := res.Findings[0] + wantRoot := headLabel(h2.Gen) + if tc.when == "snapshot" && tc.depth != VerifyData { + // HEAD is walked first; the snapshot's reference is the one + // that disagrees with it. + wantRoot = "snapshot s1/" + } + if !strings.HasPrefix(f.Root, wantRoot) || !strings.Contains(f.Detail, tc.detail) || f.Key == "" { + t.Fatalf("finding %+v; want under %q, detail with %q", f, wantRoot, tc.detail) + } + if tc.when != "snapshot" && (len(res.HeadGens) != 2 || res.HeadGens[0] != h1.Gen || res.HeadGens[1] != h2.Gen) { + t.Fatalf("covered gens %v, want [%d %d]", res.HeadGens, h1.Gen, h2.Gen) + } + if tc.depth == VerifyData && (res.DistinctChunksRead != 2 || fx.cb.reads(fid0) != 1) { + t.Fatalf("read %d chunks, chunk 0 %d times; want 2, chunk 0 once", res.DistinctChunksRead, fx.cb.reads(fid0)) + } + }) + } +} + +// retagSnapshot rewrites one field of the document of the attempt snapshot +// name resolves to, leaving it otherwise valid. +func (fx *verifyFixture) retagSnapshot(vol, name, field, value string) string { + fx.t.Helper() + ctx := context.Background() + ref, ok, err := fx.c.resolveSnap(ctx, vol, name) + if err != nil || !ok || ref.entry == nil { + fx.t.Fatalf("snapshot %s/%s: %v %v", vol, name, ok, err) + } + dir := path.Join(catBase, vol, snapsDir, name) + e, err := fx.f.LookupEntry(ctx, dir, ref.rec.Attempt) + if err != nil { + fx.t.Fatal(err) + } + var doc map[string]json.RawMessage + if err := json.Unmarshal(e.Content, &doc); err != nil { + fx.t.Fatal(err) + } + if doc[field], err = json.Marshal(value); err != nil { + fx.t.Fatal(err) + } + if e.Content, err = json.Marshal(doc); err != nil { + fx.t.Fatal(err) + } + if err := fx.f.UpdateEntry(ctx, dir, e, nil); err != nil { + fx.t.Fatal(err) + } + return ref.rec.Attempt +} + +// A snapshot is checked under the name and volume it was found at. A +// document that names another snapshot or volume is ROOT_INVALID, and a +// miss under that still published attempt is reported under the name it +// was found at, never excused as a snapshot deleted during the pass. +func TestVerify_SnapshotDocumentNamingAnotherSnapshot(t *testing.T) { + for _, tc := range []struct { + name, field, value string + opts VerifyOptions + }{ + {"named, another name", "name", "s2", VerifyOptions{Snapshot: "s1"}}, + {"all, another name", "name", "s2", VerifyOptions{AllSnapshots: true}}, + {"named, another volume", "volume_id", "v9", VerifyOptions{Snapshot: "s1"}}, + {"all, another volume", "volume_id", "v9", VerifyOptions{AllSnapshots: true}}, + } { + t.Run(tc.name, func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { + t.Fatal(err) + } + // HEAD moves on: only the snapshot names the old chunk 0, whose binding goes. + fx.publish("v1", map[uint64][]byte{0: verifyData(9)}, true) + attempt := fx.retagSnapshot("v1", "s1", tc.field, tc.value) + fx.deleteBinding(h.Chunks[0].Key) + res := fx.verify("v1", tc.opts) + wantClasses(t, tc.name, res, "ROOT_INVALID", "BINDING_MISSING@0") + label := "snapshot s1/" + attempt + if res.Findings[0].Root != label || res.Findings[1].Root != label || !strings.Contains(res.Findings[0].Detail, tc.value) { + t.Fatalf("findings %+v; want both under %q", res.Findings, label) + } + if len(res.Snapshots) != 1 || res.Snapshots[0] != "s1/"+attempt || res.RootDeletedDuringVerify != 0 || len(res.SnapshotsDeletedDuringVerify) != 0 { + t.Fatalf("snapshots %v, root deleted %d, deleted %v; want [s1/%s], 0, none", + res.Snapshots, res.RootDeletedDuringVerify, res.SnapshotsDeletedDuringVerify, attempt) + } + }) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index a9eb9eb8be..d22a981882 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -189,7 +189,7 @@ stateDiagram-v2 | StopPending | Valid | only the latest detach attempt, provably not applied, with serving resumed; an applied, fenced or unknown outcome, or an older attempt's resume, leaves StopPending | `core/frontend/durable/provider_chunk.go` `resumeAfterDetach`; `core/host/volume/workspace_runtime.go` `WorkspaceStopResumed`; `core/host/volume/workspace_lease.go` `ClearStopPending` | `INV-WS-STOP-PENDING-001` | | Fenced | Drained, Acked | the stop callback succeeded; only then, and only when revoked, the acknowledgement is sent | `core/host/volume/workspace_lease.go` `drain` | `INV-WS-REVOKE-ACK-001` | | Attaching | Refused | an existing local root whose HEAD another holder has published (`ErrChunkStaleLocalRoot`) | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-STALE-LOCAL-ROOT-001` | -| (startup) | Refused | `--chunk-filer` is not the only filer of its group: a master lists another filer or several, or no master lists it within 60 s (`ErrNotSingleFiler`) | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring` | `INV-WS-SINGLE-FILER-001` | +| (startup) | Refused | `--chunk-filer` is not the only filer of its group: a master lists another filer or several, or no master lists it within 60 s (`ErrNotSingleFiler`) | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring` | `INV-WS-SINGLE-FILER-001`, `INV-CHUNK-CLI-SINGLE-FILER-001` | | Claiming | Holder | HEAD epoch not above the master-issued epoch, no other holder at the same epoch; the local frontier is seeded from HEAD before the CAS; I/O opens only after the configured cooling window (zero at one serialization point) and an exact generation/epoch/holder readback | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-WS-HEAD-CAS-001` | | Claiming | Holder, or not installed | unknown CAS outcome: success only if a re-read shows the exact proposal; never a blind replay | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CAS-UNKNOWN-001` | | Holder | Holder | every publish is a cut (M5) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | @@ -275,10 +275,6 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | `deleting` | `purging` | commit point, bound to the same delete incarnation | `core/frontend/chunkstore/volume_delete.go` `commitHeadPurging` | `INV-VOLDEL-COMMIT-001` | | `purging` | `deleted` | chunks dropped and `VOLUME` marked deleted | `core/frontend/chunkstore/volume_delete.go` `finishHeadDeleted`, `markVolumeDeleted` | `INV-VOL-ID-NO-REUSE-001` | | `deleting`, `purging`, `deleted` | — | no claim or cut moves HEAD; only the delete's own transitions | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-HEAD-DELETE-FROZEN-001` | -| `INV-VERIFY-READONLY-001` | Verify writes nothing to the filer or the blob store at any depth: no intent, mark, tombstone, binding or needle. | M6 (reader; no transition) | `core/frontend/chunkstore/verify.go` `Catalog.Verify` | `TestVerify_ReadOnlyAtEveryDepth` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-RECHECK-001` | Verify reports a miss only if its root still names the chunk when it is rechecked: a miss under HEAD is a finding only if the current HEAD still names the key at that index, and a miss under a snapshot only if that attempt is still published and not deleting. A reader that can outlive GC's grace holds no claim, so it rechecks its root. | M6 (reader beside GC mark) | `core/frontend/chunkstore/verify.go` `Catalog.Verify` | `TestVerify_SupersededDuringPass`, `TestVerify_SnapshotDeletedDuringPass`, `TestVerify_SharedChunkReportedUnderStillNamingRoot` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-NOTFOUND-001` | Verify reports `NEEDLE_MISSING` only when the blob store answers that the needle does not exist; any other read failure is retried and then reported as `READ_ERROR`, which means not verified. | M6 (reader) | `core/frontend/chunkstore/verify.go` `Catalog.Verify`; `core/frontend/chunkstore/swfs.go` `Get` (`ErrBlobNotFound`) | `TestVerify_PersistentReadErrorIsNotAMissingNeedle`, `TestVerify_TransientReadIsRetried`, `TestSWFS_GetNotFoundIsErrBlobNotFound` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-CHUNK-CLI-SINGLE-FILER-001` | Every `sw-block ops chunk` command, gc included, runs the single-filer check of `INV-WS-SINGLE-FILER-001` before its first catalog read or write, and refuses otherwise. | M4 (startup) → Refused, for the offline commands | `cmd/sw-block/chunk.go` `dialChunkFiler`; `cmd/sw-block/chunk_gc.go` `chunkGC` | `TestOpsChunk_RefusesMultiFiler` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE | | — | `aborted` | a GC copy sweep settles a dead fork by an exclusive create of an aborted HEAD tombstone, so the fork can never publish | `core/frontend/chunkstore/catalog.go` `AbortFork`; `core/frontend/chunkstore/gc_copy.go` `SweepCopies` | — | **Snapshots and forks.** @@ -351,7 +347,7 @@ snapshot lifetime; local persistence does not bypass it. ## Part B. Invariant ledger -118 rows: 99 ACTIVE, 19 STUB; 15 kept from the internal ledger, 103 new. +127 rows: 107 ACTIVE, 18 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 112 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -471,6 +467,7 @@ Notes: | `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE | | `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | | `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`) | — | ACTIVE | +| `INV-CHUNK-CLI-SINGLE-FILER-001` | Every `sw-block ops chunk` command, gc included, runs the single-filer check of `INV-WS-SINGLE-FILER-001` within its own `--timeout` before its first catalog read or write, and refuses otherwise. | M4 (startup) → Refused, for the offline commands | `cmd/sw-block/chunk.go` `dialChunkFiler`, `chunkCatalog`; `cmd/sw-block/chunk_gc.go` `chunkGC` | `TestOpsChunk_RefusesMultiFiler`, `TestOpsChunk_SingleFilerCheckWithinTimeout` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE | | `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | | `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | | `INV-WS-STOP-PENDING-001` | Stop-pending changes only when the lease guard renews, never what it admits or acknowledges: from the start of a chunk detach until the guard fences, its sleep after a completed renewal is at most 250 ms; it returns to the normal renewal delay only when that same (latest) detach attempt provably did not happen and serving resumed. It bounds scheduling, not the time from a revocation to its acknowledgement. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/frontend/durable/provider_chunk.go` `DetachVolume`, `resumeAfterDetach`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay` | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE | @@ -531,6 +528,10 @@ Notes: | `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | | `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | +| `INV-VERIFY-READONLY-001` | Verify writes nothing to the filer or the blob store at any depth: no intent, mark, tombstone, binding or needle. | M6 (reader; no transition) | `core/frontend/chunkstore/verify.go` `Catalog.Verify` | `TestVerify_ReadOnlyAtEveryDepth` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-RECHECK-001` | Verify reports a miss only if its root still names the chunk at the recheck: under HEAD, the current HEAD names the key at that index; under a snapshot, the attempt its name record names is published and not deleting. A root is identified by the name it was looked up by, not by its document. | M6 (reader beside GC mark) | `core/frontend/chunkstore/verify.go` `Catalog.Verify` | `TestVerify_SupersededDuringPass`, `TestVerify_SnapshotDeletedDuringPass`, `TestVerify_SharedChunkReportedUnderStillNamingRoot`, `TestVerify_SnapshotDocumentNamingAnotherSnapshot` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-NOTFOUND-001` | Verify reports `NEEDLE_MISSING` only when the blob store answers that the needle does not exist (for SeaweedFS, every location of a fresh volume lookup answers 404); any other read failure is retried and then reported as `READ_ERROR`, which means not verified. | M6 (reader) | `core/frontend/chunkstore/verify.go` `Catalog.Verify`; `core/frontend/chunkstore/swfs.go` `Get` (`ErrBlobNotFound`) | `TestVerify_PersistentReadErrorIsNotAMissingNeedle`, `TestVerify_TransientReadIsRetried`, `TestSWFS_GetNotFoundIsErrBlobNotFound`, `TestSWFS_GetStaleCachedLocationLooksUpAgain`, `TestVerify_MovedVolumeIsNotAMissingNeedle` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-COVERAGE-001` | Every chunk reference of every root the result lists, HEAD generations found by a refresh included, is checked at the pass's depth: each distinct chunk is read at most once, and a reference to a chunk already read is compared with that content (below depth `data`, with the chunk's other references). | M6 (reader) | `core/frontend/chunkstore/verify.go` `addUses`, `compareRefs`, `readChunk` | `TestVerify_SameKeyWithAnotherHashIsAFinding`, `TestVerify_HeadRefreshRewalksChangedSegments`, `TestVerify_DedupSharedChunkReadOnce` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | Notes: From 3fed158179b6560dc0d2c1e77da6fed77d89d068 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 22:17:31 -0800 Subject: [PATCH 11/34] chunkstore: verify: a chunk's outcome applies to every reference to it A miss or a read error was reported against the references known when the chunk was queued. A reference added by a HEAD refresh, before or after the read ended, is now given the same outcome under the usual recheck, without reading the chunk again. Tests that hold a call open get an independent bound so a broken implementation fails instead of hanging. Co-Authored-By: Claude Fable 5.2 --- .../cmd/sw-block/chunk_verify_test.go | 69 +++++-- seaweed-block/core/frontend/chunkstore/GC.md | 6 +- .../core/frontend/chunkstore/verify.go | 55 +++--- .../core/frontend/chunkstore/verify_test.go | 168 +++++++++++++++++- seaweed-block/docs/design/invariants.md | 5 +- 5 files changed, 258 insertions(+), 45 deletions(-) diff --git a/seaweed-block/cmd/sw-block/chunk_verify_test.go b/seaweed-block/cmd/sw-block/chunk_verify_test.go index 0a8be963c4..4314ca658d 100644 --- a/seaweed-block/cmd/sw-block/chunk_verify_test.go +++ b/seaweed-block/cmd/sw-block/chunk_verify_test.go @@ -5,6 +5,7 @@ import ( "context" "crypto/sha256" "encoding/json" + "errors" "fmt" "net" "net/url" @@ -250,20 +251,47 @@ func TestOpsChunk_RefusesMultiFiler(t *testing.T) { } // stalledConfigFiler never answers GetFilerConfiguration: the call returns -// only when its context ends. It reports the deadline the call carried and -// the context error it ended with. +// only when its context ends (or the test releases it). It reports the +// deadline the call carried and the context error it ended with. type stalledConfigFiler struct { filerpb.UnimplementedSeaweedFilerServer deadline chan time.Time // zero: the call had no deadline ended chan error + release chan struct{} // the test's escape, closed in its cleanup } func (f *stalledConfigFiler) GetFilerConfiguration(ctx context.Context, _ *filerpb.GetFilerConfigurationRequest) (*filerpb.GetFilerConfigurationResponse, error) { dl, _ := ctx.Deadline() f.deadline <- dl - <-ctx.Done() - f.ended <- ctx.Err() - return nil, ctx.Err() + select { + case <-ctx.Done(): + f.ended <- ctx.Err() + return nil, ctx.Err() + case <-f.release: + return nil, errors.New("released by the test") + } +} + +// chunkTestEscape bounds a wait for something that should happen promptly; +// it only turns a hang into a failure, it is not a success criterion. +const chunkTestEscape = 30 * time.Second + +// within receives from ch, or fails the test naming what was not exercised. +func within[T any](t *testing.T, ch <-chan T, what string) T { + t.Helper() + select { + case v := <-ch: + return v + case <-time.After(chunkTestEscape): + t.Fatalf("not exercised within %s: %s", chunkTestEscape, what) + var zero T + return zero + } +} + +type chunkRun struct { + code int + out, errs string } // The single-filer check runs within the command's --timeout: a filer that @@ -278,23 +306,40 @@ func TestOpsChunk_SingleFilerCheckWithinTimeout(t *testing.T) { {"snapshots", "--volume", "v1"}, } { t.Run(args[0], func(t *testing.T) { - f := &stalledConfigFiler{deadline: make(chan time.Time, 1), ended: make(chan error, 1)} + f := &stalledConfigFiler{deadline: make(chan time.Time, 1), ended: make(chan error, 1), release: make(chan struct{})} addr := serveGRPC(t, func(s *grpc.Server) { filerpb.RegisterSeaweedFilerServer(s, f) }) + done := make(chan chunkRun, 1) + // Registered before the launch (and run before the server stops): + // release a call still held, then join the command. + t.Cleanup(func() { + close(f.release) + select { + case r := <-done: + done <- r + case <-time.After(chunkTestEscape): + t.Errorf("%s did not return even after the held call was released", args[0]) + } + }) start := time.Now() - code, out, errs := runChunk(append(args, "--chunk-filer", addr, "--timeout", timeout.String())...) - dl := <-f.deadline - ended := <-f.ended - if e := chunkErrorOut(t, out); code != chunkExitFailed || e.Code != codeNotSingleFilerCLI || !strings.Contains(e.Message, "deadline") { - t.Fatalf("%s with a stalled filer: exit %d %q %q; want 1, not_single_filer, the deadline", args[0], code, out, errs) - } + go func() { + code, out, errs := runChunk(append(args, "--chunk-filer", addr, "--timeout", timeout.String())...) + done <- chunkRun{code, out, errs} + }() + dl := within(t, f.deadline, args[0]+": the start check never called GetFilerConfiguration") // The call's deadline is the command's: start + timeout, plus // the time to start the command; far below the check's own 60 s. if dl.IsZero() || dl.After(start.Add(timeout+20*time.Second)) { t.Fatalf("%s: the check's call carried deadline %v (start %v); want the command's %s", args[0], dl, start, timeout) } + ended := within(t, f.ended, args[0]+": the start check's call never observed the end of its context") + r := within(t, done, args[0]+": the command did not return after the check's call ended") + done <- r // for the cleanup's join if ended == nil { t.Fatalf("%s: the check's call did not observe the cancellation", args[0]) } + if e := chunkErrorOut(t, r.out); r.code != chunkExitFailed || e.Code != codeNotSingleFilerCLI || !strings.Contains(e.Message, "deadline") { + t.Fatalf("%s with a stalled filer: exit %d %q %q; want 1, not_single_filer, the deadline", args[0], r.code, r.out, r.errs) + } }) } } diff --git a/seaweed-block/core/frontend/chunkstore/GC.md b/seaweed-block/core/frontend/chunkstore/GC.md index c835c539dc..d019f78cde 100644 --- a/seaweed-block/core/frontend/chunkstore/GC.md +++ b/seaweed-block/core/frontend/chunkstore/GC.md @@ -205,8 +205,10 @@ A chunk that several checked roots name is reported once, under the first root that still names it (HEAD first). The HEAD view is also refreshed at least every 2 minutes during a long pass; only segments whose key changed are read again, and chunks the pass has not seen are added. A changed reference to a chunk -already seen is compared with that chunk's content (at depth `data`; the chunk -is not read again) or with its other references. The result therefore states "every +already seen gets that chunk's outcome: it is compared with the chunk's content +(at depth `data`; the chunk is not read again) or its other references, and a +miss already found for the chunk is reported under it if its root still names +the chunk there. The result therefore states "every chunk named by the listed HEAD generations at the time it was checked", not "the image at one instant". diff --git a/seaweed-block/core/frontend/chunkstore/verify.go b/seaweed-block/core/frontend/chunkstore/verify.go index d5652770d4..ccef67364d 100644 --- a/seaweed-block/core/frontend/chunkstore/verify.go +++ b/seaweed-block/core/frontend/chunkstore/verify.go @@ -18,8 +18,9 @@ package chunkstore // - data: every distinct chunk (owner + key, across all selected roots) // is fetched once; its SHA-256 must equal each reference and its length // the chunk size (the rule the chunk layer applies on a read miss). A -// reference added later (a refreshed HEAD) is compared with the content -// already read; the chunk is not read again. +// chunk's outcome (the content read, or its miss) applies to every +// reference to it, also one a refreshed HEAD adds later; the chunk is +// not read again. // // Running beside a live owner and beside GC: segments and chunks are // immutable and written before the root that names them, so a root read @@ -285,15 +286,18 @@ type verifyChunk struct { fid string bound bool // a sound, untombstoned binding was found - // Under the verifier's lock. read is set once the needle was read - // (depth data), with its length and SHA-256: a later reference is - // compared with them, the chunk is not read again. late are the - // references refreshed HEADs added; the reader compares those added - // before it read the chunk, addUses the ones added after. - read bool - length int - digest [32]byte - late []verifyUse + // Under the verifier's lock: the chunk's outcome, which applies to every + // reference to it. read is set once the needle was read (depth data), + // with its length and SHA-256; missClass and missDetail once a miss + // settled it (binding missing or tombstoned, needle missing, read + // error). The chunk is not read again. late are the references + // refreshed HEADs added: the outcome applies to those present when it + // is settled, and addUses applies it to the ones added after. + read bool + length int + digest [32]byte + missClass, missDetail string + late []verifyUse } // repeats reports whether u repeats a reference already recorded for w @@ -844,11 +848,11 @@ func (v *verifier) names(ctx context.Context, h storage.ChunkHead, idx uint64, i // not seen, and returns the references to compare once the lock is // released. A chunk is immutable, but a new reference to it can be wrong, // so a reference to a chunk already seen is compared, never by reading the -// chunk again: with its content once it was read, and below depth data -// with the chunk's first reference. A refreshed HEAD's references (refreshed -// set) to chunks already seen are not counted as checked again; one that -// repeats a recorded reference adds nothing, and one the reader has yet to -// read is left for it to compare. +// chunk again: with its outcome once settled (its content, or its miss), +// and below depth data with the chunk's first reference. A refreshed HEAD's +// references (refreshed set) to chunks already seen are not counted as +// checked again; one that repeats a recorded reference adds nothing, and +// one to a chunk not yet settled is left for its outcome. func (v *verifier) addUses(r verifyRoot, chunks map[uint64]storage.ChunkRef, refreshed bool) []verifyRef { v.mu.Lock() defer v.mu.Unlock() @@ -870,7 +874,7 @@ func (v *verifier) addUses(r verifyRoot, chunks map[uint64]storage.ChunkRef, ref } w.late = append(w.late, u) } - if w.read || (v.opts.Depth != VerifyData && u.sha != w.uses[0].sha) { + if w.read || w.missClass != "" || (v.opts.Depth != VerifyData && u.sha != w.uses[0].sha) { check = append(check, verifyRef{w, u}) } if refreshed { @@ -888,11 +892,15 @@ func (v *verifier) compareRefs(ctx context.Context, refs []verifyRef) error { for _, c := range refs { v.mu.Lock() read, n, sum, first := c.w.read, c.w.length, c.w.digest, c.w.uses[0] + missClass, missDetail := c.w.missClass, c.w.missDetail v.mu.Unlock() var err error - if read { + switch { + case read: err = v.compareContent(ctx, c.w, n, sum, []verifyUse{c.u}) - } else { + case missClass != "": + err = v.missUses(ctx, c.w, []verifyUse{c.u}, missClass, func(verifyUse) string { return missDetail }) + default: err = v.missUses(ctx, c.w, []verifyUse{c.u}, FindingContentMismatch, func(u verifyUse) string { return fmt.Sprintf("references to this chunk disagree: SHA-256 %s here, %s under %s at index %d (depth data reads the chunk)", hex.EncodeToString(u.sha[:]), hex.EncodeToString(first.sha[:]), first.root.label, first.idx) @@ -1259,9 +1267,14 @@ func (v *verifier) evaluateBinding(ctx context.Context, w *verifyChunk, e *filer return nil } -// miss reports a miss of w under all of its roots. +// miss settles w with a miss and reports it under all of its references, +// those refreshed HEADs added included; addUses applies it to later ones. func (v *verifier) miss(ctx context.Context, w *verifyChunk, class, detail string) error { - return v.missUses(ctx, w, w.uses, class, func(verifyUse) string { return detail }) + v.mu.Lock() + w.missClass, w.missDetail = class, detail + uses := append(append([]verifyUse(nil), w.uses...), w.late...) + v.mu.Unlock() + return v.missUses(ctx, w, uses, class, func(verifyUse) string { return detail }) } // missUses reports a miss of w as at most one finding: under the first of diff --git a/seaweed-block/core/frontend/chunkstore/verify_test.go b/seaweed-block/core/frontend/chunkstore/verify_test.go index 6722481eee..c85aa6ea42 100644 --- a/seaweed-block/core/frontend/chunkstore/verify_test.go +++ b/seaweed-block/core/frontend/chunkstore/verify_test.go @@ -1078,7 +1078,7 @@ func TestVerify_ContextEndedIsIncomplete(t *testing.T) { } // heldReads holds the read of one needle open until the reader's context -// ends, and counts the reads in progress. +// ends (or the test releases it), and counts the reads in progress. type heldReads struct { Blobs fid string @@ -1086,13 +1086,56 @@ type heldReads struct { entered chan struct{} // closed when the held read has started once sync.Once + released chan struct{} // closed by release: the escape when cancellation fails + releaseOnce sync.Once + mu sync.Mutex active int - ended error // the held read's context error, once it ended + ended error // the held read's context error, once its context ended } func newHeldReads(b Blobs, fid string) *heldReads { - return &heldReads{Blobs: b, fid: fid, entered: make(chan struct{})} + return &heldReads{Blobs: b, fid: fid, entered: make(chan struct{}), released: make(chan struct{})} +} + +func (h *heldReads) release() { h.releaseOnce.Do(func() { close(h.released) }) } + +// verifyEscape bounds a test's wait for a Verify that should return at +// once; it only turns a hang into a failure, it is not a success criterion. +const verifyEscape = 30 * time.Second + +type verifyOutcome struct { + res VerifyResult + err error +} + +// verifyBounded runs cat.Verify in a goroutine and returns its result, or +// fails the test when it has not returned within verifyEscape. The cleanup, +// registered before the launch, releases the held read and joins the call. +func verifyBounded(t *testing.T, cat *Catalog, ctx context.Context, opts VerifyOptions, held *heldReads) (VerifyResult, error) { + t.Helper() + done := make(chan verifyOutcome, 1) + t.Cleanup(func() { + held.release() + select { + case out := <-done: + done <- out + case <-time.After(verifyEscape): + t.Error("Verify did not return even after its held read was released") + } + }) + go func() { + res, err := cat.Verify(ctx, "v1", opts) + done <- verifyOutcome{res, err} + }() + select { + case out := <-done: + done <- out // for the cleanup's join + return out.res, out.err + case <-time.After(verifyEscape): + t.Fatalf("Verify did not return within %s: the read in progress was not cancelled and joined", verifyEscape) + return VerifyResult{}, nil + } } func (h *heldReads) Get(ctx context.Context, fid string) ([]byte, error) { @@ -1113,7 +1156,11 @@ func (h *heldReads) Get(ctx context.Context, fid string) ([]byte, error) { h.onEnter() } }) - <-ctx.Done() + select { + case <-ctx.Done(): + case <-h.released: + return nil, fmt.Errorf("chunkstore: read %s: released by the test", fid) + } h.mu.Lock() h.ended = ctx.Err() h.mu.Unlock() @@ -1149,6 +1196,7 @@ type headFailsDuringRead struct { Filer root, keys string entered <-chan struct{} + released <-chan struct{} // the test's escape mu sync.Mutex listed bool @@ -1179,6 +1227,8 @@ func (f *headFailsDuringRead) LookupEntry(ctx context.Context, dir, name string) return nil, errFilerDown case <-ctx.Done(): return nil, ctx.Err() + case <-f.released: + return nil, errors.New("released by the test") } } } @@ -1193,16 +1243,18 @@ func TestVerify_FailedRefreshCancelsReadInProgress(t *testing.T) { fx := newVerifyFixture(t, "v1") h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) held := newHeldReads(fx.cb, fx.fid(h.Chunks[0].Key)) - filer := &headFailsDuringRead{Filer: fx.f, root: path.Join(catBase, "v1"), keys: path.Join(catBase, "v1", keysDir), entered: held.entered} + filer := &headFailsDuringRead{Filer: fx.f, root: path.Join(catBase, "v1"), keys: path.Join(catBase, "v1", keysDir), + entered: held.entered, released: held.released} cat, err := NewCatalog(manifestFilerBlobs{filer, held}, catBase) if err != nil { t.Fatal(err) } cat.SetClock(tickingClock(time.Minute)) - // The caller's deadline only guards the test: Verify must end well before it. + // The caller's deadline tells a read cancelled by the failed refresh + // from one that ran into it: Verify must end well before it. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - res, err := cat.Verify(ctx, "v1", VerifyOptions{Depth: VerifyData, RefreshInterval: time.Minute, BytesPerSecond: -1}) + res, err := verifyBounded(t, cat, ctx, VerifyOptions{Depth: VerifyData, RefreshInterval: time.Minute, BytesPerSecond: -1}, held) active, ended := held.state() if !errors.Is(err, errFilerDown) || !strings.Contains(err.Error(), "refresh HEAD") { t.Fatalf("verify: %v; want the HEAD refresh error", err) @@ -1229,7 +1281,7 @@ func TestVerify_CancelDuringReadJoinsReaders(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() held.onEnter = cancel - res, err := cat.Verify(ctx, "v1", VerifyOptions{Depth: VerifyData, BytesPerSecond: -1}) + res, err := verifyBounded(t, cat, ctx, VerifyOptions{Depth: VerifyData, BytesPerSecond: -1}, held) active, ended := held.state() select { case <-held.entered: @@ -1377,6 +1429,106 @@ func TestVerify_SameKeyWithAnotherHashIsAFinding(t *testing.T) { } } +// manualClock stands still until advanced. +type manualClock struct { + mu sync.Mutex + now time.Time +} + +func (c *manualClock) read() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.now +} + +func (c *manualClock) advance(d time.Duration) { + c.mu.Lock() + c.now = c.now.Add(d) + c.mu.Unlock() +} + +// A chunk's outcome (needle missing, read error, binding missing) applies +// to every reference to it, also to those a refreshed HEAD added before or +// after that outcome: a reference whose root still names the chunk there is +// a finding, under that root. The chunk is not read again. +func TestVerify_OutcomeAppliesToRefreshedReferences(t *testing.T) { + dropK := func(fx *verifyFixture, k string) { fx.needle(fx.fid(k), dropNeedle) } + failK := func(fx *verifyFixture, k string) { fx.cb.failReads(fx.fid(k), -1) } + unbindK := func(fx *verifyFixture, k string) { fx.deleteBinding(k) } + for _, tc := range []struct { + name string + depth VerifyDepth + after bool // the refresh comes after the outcome, not before + damage func(fx *verifyFixture, qkey string) + want string + reads int // reads of the damaged chunk + }{ + {"refresh before, needle missing", VerifyData, false, dropK, "NEEDLE_MISSING@1", 1}, + {"refresh before, read error", VerifyData, false, failK, "READ_ERROR@1", verifyReadAttempts}, + {"refresh before, binding missing", VerifyBindings, false, unbindK, "BINDING_MISSING@1", 0}, + {"refresh after, needle missing", VerifyData, true, dropK, "NEEDLE_MISSING@1", 1}, + {"refresh after, read error", VerifyData, true, failK, "READ_ERROR@1", verifyReadAttempts}, + } { + t.Run(tc.name, func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + k := h1.Chunks[0].Key + fidK := fx.fid(k) + var h2 storage.ChunkHead + // The owner moves chunk K from index 0 to index 1 (index 0 and + // the old chunk 1 leave HEAD), and K is damaged. + move := func() { + h2 = fx.republish("v1", func(c map[uint64]storage.ChunkRef) { + c[1] = c[0] + delete(c, 0) + }) + tc.damage(fx, k) + } + opts := VerifyOptions{Depth: tc.depth, BytesPerSecond: -1, RefreshInterval: time.Minute, Concurrency: 1} + cat := fx.c + if !tc.after { + // Refreshed at every opportunity: the bindings phase sees + // the move before K is checked. + cat.SetClock(tickingClock(time.Minute)) + opts.hook = func(stage string) { + if stage == verifyHookHeadWalked { + move() + } + } + } else { + // No refresh until K's read has failed (one reader: K, at + // index 0, is read completely before the old chunk 1), then + // time passes and the pass refreshes after that batch. + clock := &manualClock{now: time.Now()} + moveFirst := &beforeRead{Blobs: fx.cb, fid: fidK, fn: move} + thenAdvance := &beforeRead{Blobs: moveFirst, fid: fx.fid(h1.Chunks[1].Key), fn: func() { clock.advance(time.Hour) }} + var err error + if cat, err = NewCatalog(manifestFilerBlobs{fx.f, thenAdvance}, catBase); err != nil { + t.Fatal(err) + } + cat.SetClock(clock.read) + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + res, err := cat.Verify(ctx, "v1", opts) + if err != nil || !res.Complete { + t.Fatalf("verify: %v, %+v", err, res) + } + wantClasses(t, tc.name, res, tc.want) + if res.Findings[0].Root != headLabel(h2.Gen) || res.SupersededDuringVerify != 1 { + t.Fatalf("finding under %q, superseded %d; want under %q (the index 0 reference superseded)", + res.Findings[0].Root, res.SupersededDuringVerify, headLabel(h2.Gen)) + } + if len(res.HeadGens) != 2 || res.HeadGens[0] != h1.Gen || res.HeadGens[1] != h2.Gen { + t.Fatalf("covered gens %v, want [%d %d]", res.HeadGens, h1.Gen, h2.Gen) + } + if n := fx.cb.reads(fidK); n != tc.reads { + t.Fatalf("chunk K read %d times, want %d", n, tc.reads) + } + }) + } +} + // retagSnapshot rewrites one field of the document of the attempt snapshot // name resolves to, leaving it otherwise valid. func (fx *verifyFixture) retagSnapshot(vol, name, field, value string) string { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d22a981882..dc62753b39 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -347,7 +347,7 @@ snapshot lifetime; local persistence does not bypass it. ## Part B. Invariant ledger -127 rows: 107 ACTIVE, 18 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 112 new. +127 `INV-` rows: 107 ACTIVE, 18 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 112 new. One further row, `PROGRESS-DESTRUCTIVE`, has no `INV-` ID. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -531,7 +531,8 @@ Notes: | `INV-VERIFY-READONLY-001` | Verify writes nothing to the filer or the blob store at any depth: no intent, mark, tombstone, binding or needle. | M6 (reader; no transition) | `core/frontend/chunkstore/verify.go` `Catalog.Verify` | `TestVerify_ReadOnlyAtEveryDepth` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | | `INV-VERIFY-RECHECK-001` | Verify reports a miss only if its root still names the chunk at the recheck: under HEAD, the current HEAD names the key at that index; under a snapshot, the attempt its name record names is published and not deleting. A root is identified by the name it was looked up by, not by its document. | M6 (reader beside GC mark) | `core/frontend/chunkstore/verify.go` `Catalog.Verify` | `TestVerify_SupersededDuringPass`, `TestVerify_SnapshotDeletedDuringPass`, `TestVerify_SharedChunkReportedUnderStillNamingRoot`, `TestVerify_SnapshotDocumentNamingAnotherSnapshot` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | | `INV-VERIFY-NOTFOUND-001` | Verify reports `NEEDLE_MISSING` only when the blob store answers that the needle does not exist (for SeaweedFS, every location of a fresh volume lookup answers 404); any other read failure is retried and then reported as `READ_ERROR`, which means not verified. | M6 (reader) | `core/frontend/chunkstore/verify.go` `Catalog.Verify`; `core/frontend/chunkstore/swfs.go` `Get` (`ErrBlobNotFound`) | `TestVerify_PersistentReadErrorIsNotAMissingNeedle`, `TestVerify_TransientReadIsRetried`, `TestSWFS_GetNotFoundIsErrBlobNotFound`, `TestSWFS_GetStaleCachedLocationLooksUpAgain`, `TestVerify_MovedVolumeIsNotAMissingNeedle` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-COVERAGE-001` | Every chunk reference of every root the result lists, HEAD generations found by a refresh included, is checked at the pass's depth: each distinct chunk is read at most once, and a reference to a chunk already read is compared with that content (below depth `data`, with the chunk's other references). | M6 (reader) | `core/frontend/chunkstore/verify.go` `addUses`, `compareRefs`, `readChunk` | `TestVerify_SameKeyWithAnotherHashIsAFinding`, `TestVerify_HeadRefreshRewalksChangedSegments`, `TestVerify_DedupSharedChunkReadOnce` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-COVERAGE-001` | Every chunk reference of every root the result lists, refreshed HEADs included, is checked at the pass's depth: each distinct chunk is read at most once, and its outcome (content, miss or read error) applies to every reference to it, later ones included. | M6 (reader) | `core/frontend/chunkstore/verify.go` `addUses`, `compareRefs`, `readChunk`, `miss` | `TestVerify_SameKeyWithAnotherHashIsAFinding`, `TestVerify_OutcomeAppliesToRefreshedReferences`, `TestVerify_HeadRefreshRewalksChangedSegments`, `TestVerify_DedupSharedChunkReadOnce` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-CANCEL-001` | A failed dispatch of chunk reads (a filer error, or the caller's context ending) cancels the reads in progress before joining them, and Verify returns the originating error. | M6 (reader) | `core/frontend/chunkstore/verify.go` `checkData` | `TestVerify_FailedRefreshCancelsReadInProgress`, `TestVerify_CancelDuringReadJoinsReaders` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | Notes: From a4c0ccbdde907b1f07312488d3f0c4c634ed183d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:16:15 -0800 Subject: [PATCH 12/34] chunkstore: verify: compute findings once, from chunk outcomes and the final view The pass kept three kinds of state: a chunk (unseen, queued, settled with one outcome, never re-checked), the HEAD view (replaced by each refresh) and each selected snapshot's view. Settling a chunk records its outcome and reports nothing. The pass closes on a read of HEAD and of the snapshots' state that names no unseen key; that same read is the final view. Findings are computed once, from the outcomes and the final view: at most one per chunk key and class, under the first root that names the key; a bad chunk that no root names is counted, not reported. A key the pass saw named, then not named, then named again is reported. If the closing rounds run out the result is incomplete, never clean. This replaces the reporting done as reads settled and as refreshes arrived, together with the late-reference list and the per-finding rechecks. Co-Authored-By: Claude Fable 5.2 --- .../cmd/sw-block/chunk_verify_test.go | 7 +- seaweed-block/core/frontend/chunkstore/GC.md | 70 +- .../core/frontend/chunkstore/verify.go | 1066 +++++++++-------- .../core/frontend/chunkstore/verify_test.go | 345 ++++-- seaweed-block/docs/design/invariants.md | 12 +- 5 files changed, 820 insertions(+), 680 deletions(-) diff --git a/seaweed-block/cmd/sw-block/chunk_verify_test.go b/seaweed-block/cmd/sw-block/chunk_verify_test.go index 4314ca658d..ffd7c0414a 100644 --- a/seaweed-block/cmd/sw-block/chunk_verify_test.go +++ b/seaweed-block/cmd/sw-block/chunk_verify_test.go @@ -116,7 +116,8 @@ func TestOpsChunk_VerifyExitCodes(t *testing.T) { // Could not complete: the error body, with what was covered. code, out, _ = runChunk("verify", "--volume", "nope", "--chunk-filer", "filer:18888") - if e := chunkErrorOut(t, out); code != chunkExitFailed || e.Code != chunkstore.CodeNotChunkVolume || !strings.Contains(out, `"verify":{`) { + if e := chunkErrorOut(t, out); code != chunkExitFailed || e.Code != chunkstore.CodeNotChunkVolume || !strings.Contains(out, `"verify":{`) || + !strings.Contains(out, `"incomplete":"error"`) { t.Fatalf("verify of a missing volume: %d %q", code, out) } @@ -337,7 +338,9 @@ func TestOpsChunk_SingleFilerCheckWithinTimeout(t *testing.T) { if ended == nil { t.Fatalf("%s: the check's call did not observe the cancellation", args[0]) } - if e := chunkErrorOut(t, r.out); r.code != chunkExitFailed || e.Code != codeNotSingleFilerCLI || !strings.Contains(e.Message, "deadline") { + // gRPC words a deadline either way ("context deadline exceeded", + // or code DeadlineExceeded with a stream reset). + if e := chunkErrorOut(t, r.out); r.code != chunkExitFailed || e.Code != codeNotSingleFilerCLI || !strings.Contains(strings.ToLower(e.Message), "deadline") { t.Fatalf("%s with a stalled filer: exit %d %q %q; want 1, not_single_filer, the deadline", args[0], r.code, r.out, r.errs) } }) diff --git a/seaweed-block/core/frontend/chunkstore/GC.md b/seaweed-block/core/frontend/chunkstore/GC.md index d019f78cde..39cedf3764 100644 --- a/seaweed-block/core/frontend/chunkstore/GC.md +++ b/seaweed-block/core/frontend/chunkstore/GC.md @@ -137,7 +137,7 @@ one before it: readable, matches its SHA-256 and decodes strictly; the same for each checked snapshot's embedded HEAD; a snapshot's document names the volume and the snapshot it was found under (else `ROOT_INVALID`; the snapshot is still - checked, and rechecked, under the name it was found under); references to one + checked under the name it was found under); references to one chunk with different SHA-256s disagree (`CONTENT_MISMATCH`); for a fork, its fork record's digest matches an attempt of the parent snapshot at the recorded generation. @@ -157,8 +157,8 @@ reported as `INTENT_STALE`. This is a hint only: whether GC may expire an intent remains GC's decision, with blockmaster authority. The output is one JSON object: the HEAD generations and snapshots covered, -segments and chunks checked, distinct chunks and bytes read, the two recheck -counters below, findings by class, and the findings, one per line. Each finding +segments and chunks checked, distinct chunks and bytes read, the two counters +below, findings by class, and the findings, one per line. Each finding names the volume, the root (`HEAD gen N`, `snapshot name/attempt`, an intent or the VOLUME fork record), the chunk index or segment, the owner, key and fid, a class and a detail. Classes: `ROOT_INVALID`, `GEOMETRY`, `SEGMENT_UNREADABLE`, @@ -174,43 +174,43 @@ with a short backoff. If it still fails, the chunk or segment is reported as `READ_ERROR`, with the error in the detail. `READ_ERROR` is not evidence of damage: it means that object was **not verified**. Re-run verify, after fixing the store's reachability if needed. The summary counts these objects separately -in `chunksNotRead`, and `readRetries` counts the retried reads. Both rechecks -below apply to `READ_ERROR` as they do to a miss. +in `chunksNotRead`, and `readRetries` counts the retried reads. The rule below +applies to `READ_ERROR` as to any other bad outcome. ### Running beside a live owner and beside GC Segments and chunks are immutable and written before the root that names them, so a root read once and the segments it names are a consistent view. But nothing registers a reader with GC: a chunk that leaves a root can be collected once -GC's grace has passed, and a long pass can outlive that. Two rechecks keep such -a chunk from being reported: +GC's grace has passed, and a long pass can outlive that. So verify checks each +chunk once, records its outcome, and computes the findings only at the end, from +those outcomes and the roots at its final read: -- **Superseded during verify.** A miss under a HEAD root is a finding only if the - current HEAD still names that key at that index. On a miss, verify reads HEAD - again (the root and the one segment covering the index); if the key is gone, - the miss is counted in `supersededDuringVerify`, not reported. -- **Root deleted during verify.** A miss under a snapshot is a finding only if - that exact snapshot attempt still exists and is active. On a miss, verify reads - the snapshot's name record and attempt entry again; if the attempt is gone, - aborted or marked deleting, the miss is counted in `rootDeletedDuringVerify`, - not reported, and the snapshot is listed in `snapshotsDeletedDuringVerify` as - not fully covered. +- HEAD is read again at least every 2 minutes during a long pass (a newer + generation replaces the view; only segments whose key changed are read again; + chunks it names that the pass has not seen are added and checked). +- When every chunk is checked, verify reads HEAD and each checked snapshot's state + once more. If that read names a chunk not seen, verify checks it and reads + again, at most 3 times; the read that names nothing new is the final read. +- A bad chunk is one finding, under the first root that names it at the final + read (HEAD, then the snapshots still active, in order), at that root's first + index for it. A bad chunk no root names then is not reported: it is counted in + `rootDeletedDuringVerify` when a checked snapshot that was deleted during the + pass names it, otherwise in `supersededDuringVerify`. Deleted snapshots are + listed in `snapshotsDeletedDuringVerify` as not fully covered. +- A key that an earlier HEAD read named, a later one did not, and the final HEAD + names again is a `ROOT_INVALID` finding ("HEAD names a key it had dropped"), + whatever its chunk's state: a key that left every root may have been collected, + and must not come back. -A finding describes the image at the time of its recheck: the recheck and the -report are two steps, so a root that is superseded or deleted right after the -recheck can still appear in the findings. Run verify again to confirm a -finding against the current roots. +A finding describes each chunk as it was when checked, for the roots at the final +read; a chunk damaged after its check is the next pass's finding. -A chunk that several checked roots name is reported once, under the first root -that still names it (HEAD first). The HEAD view is also refreshed at least every -2 minutes during a long pass; only segments whose key changed are read again, -and chunks the pass has not seen are added. A changed reference to a chunk -already seen gets that chunk's outcome: it is compared with the chunk's content -(at depth `data`; the chunk is not read again) or its other references, and a -miss already found for the chunk is reported under it if its root still names -the chunk there. The result therefore states "every -chunk named by the listed HEAD generations at the time it was checked", not "the -image at one instant". +A pass that cannot finish is **incomplete**, never clean: `complete` is false and +`incomplete` gives the reason: `deadline`, `cancelled`, `error` (a filer or blob +store failure, or a refused request) or `closing_rounds_exhausted` (each of the 3 +final reads named new chunks: the volume is too busy; re-run). Its findings are +those computed from the chunks it did check. ### What verify cannot check @@ -230,8 +230,8 @@ image at one instant". - `0`: the pass completed with no finding. - `3`: the pass completed with findings. This includes `READ_ERROR`: the pass did not verify everything. -- `1`: the pass could not complete (the deadline passed, the filer failed, the - volume or snapshot does not exist, or the filer is not the only one of its - group). The error body `{code,message,retryable}` is printed with the partial - result under `verify`. +- `1`: the pass could not complete (the deadline passed, the filer failed, HEAD + kept naming new chunks, the volume or snapshot does not exist, or the filer is + not the only one of its group). The error body `{code,message,retryable}` is + printed with the partial result, and its `incomplete` reason, under `verify`. - `2`: usage error. diff --git a/seaweed-block/core/frontend/chunkstore/verify.go b/seaweed-block/core/frontend/chunkstore/verify.go index ccef67364d..5eab39156c 100644 --- a/seaweed-block/core/frontend/chunkstore/verify.go +++ b/seaweed-block/core/frontend/chunkstore/verify.go @@ -16,37 +16,45 @@ package chunkstore // has a sound binding in its owner's keys/ (one listing per owner), // not tombstoned by GC. // - data: every distinct chunk (owner + key, across all selected roots) -// is fetched once; its SHA-256 must equal each reference and its length -// the chunk size (the rule the chunk layer applies on a read miss). A -// chunk's outcome (the content read, or its miss) applies to every -// reference to it, also one a refreshed HEAD adds later; the chunk is -// not read again. +// is fetched once; its length must be the chunk size and its SHA-256 +// each reference's (the rule the chunk layer applies on a read miss). // -// Running beside a live owner and beside GC: segments and chunks are -// immutable and written before the root that names them, so a root read -// once and the segments it names are a consistent view. A chunk that leaves -// HEAD can be collected after GC's grace, so a miss under a HEAD root is a -// finding only if the current HEAD still names that key at that index: on a -// miss, HEAD is read again (the root and the one segment), and a key it no -// longer names is counted as superseded during verify. A snapshot can be -// deleted during the pass, and its chunks are then kept only for the grace, -// so a miss under a snapshot is a finding only if that exact attempt still -// exists and is active (its name record and attempt entry are read again); -// otherwise it is counted as root deleted during verify, and the snapshot is -// listed as not fully covered. A chunk several selected roots name is one -// finding, reported under the first of them that still names it. The HEAD view is -// refreshed at least every RefreshInterval during the binding and data -// phases; only segments whose key changed are read again, and the result -// lists every HEAD generation the pass covered. +// The pass runs beside a live owner and beside GC, so what it reports about +// chunks comes from a small automaton (the V.* names on the functions): +// +// - V.Discover: a chunk (owner, key) a root view names that the pass has +// not seen is queued for one check. +// - V.Settle: the check records the chunk's outcome and reports nothing; +// a settled chunk is never checked again. +// - V.Refresh: HEAD is read again at least every RefreshInterval; a newer +// generation replaces the HEAD view (an older one is ignored), the keys +// the old view named and the new one does not are marked dropped, and +// its new keys are discovered. +// - V.Round: once every queued chunk is settled, one closing read of HEAD +// and of each selected snapshot's state; if it names a chunk not seen, +// the pass checks it and reads again, at most ClosingRounds times +// (V.GiveUp: then the pass is incomplete). +// - V.Close: a closing read that names no chunk not seen is the final view. +// - V.Reconcile: the findings about chunks and segments are computed from +// the outcomes and the final view alone, nowhere else: a bad chunk is +// one finding under the first final root naming its key (HEAD, then the +// snapshots not gone, in order) at that root's first index; a key HEAD +// dropped and names again is ROOT_INVALID, whatever its outcome. +// +// The pass therefore reports the state of each named chunk at its check, +// for the roots at the final read; a chunk damaged after its check is the +// next pass's finding. A chunk that left HEAD can be collected after GC's +// grace, and a deleted snapshot's chunks are kept only for the grace, so a +// bad chunk that no root names at the final read is not a finding. // // A needle is NEEDLE_MISSING only when the store reports it absent // (ErrBlobNotFound). Any other read failure is retried; if it persists it is -// READ_ERROR, which means "not verified", not "damaged". Both rechecks above -// apply to it. +// READ_ERROR, which means "not verified", not "damaged". // // A finding never stops the pass. Only an inability to continue does (the -// context ended, the filer failed): Verify then returns the partial result, -// with Complete false, and the error. +// context ended, the filer failed) or a HEAD that keeps naming new chunks: +// Verify then returns the result with Complete false and the reason in +// Incomplete, the findings computed from what was checked, and the error. import ( "context" @@ -85,6 +93,8 @@ const ( // DefaultVerifyIntentStaleAge is the age past which a capture intent // below HEAD's epoch is reported as stale (the gc --intent-ttl default). DefaultVerifyIntentStaleAge = time.Hour + // DefaultVerifyClosingRounds is the default ClosingRounds. + DefaultVerifyClosingRounds = 3 ) // Finding classes. @@ -130,6 +140,9 @@ type VerifyOptions struct { // IntentStaleAge is the age past which a capture intent below HEAD's // epoch that names no key HEAD references is reported (a hint only). IntentStaleAge time.Duration + // ClosingRounds bounds the closing reads that may name chunks not seen + // before; past it the pass is incomplete. + ClosingRounds int // hook, when set, runs at the named stages of a pass (a test seam). hook func(stage string) @@ -137,10 +150,25 @@ type VerifyOptions struct { // Verify stages passed to the hook. const ( - verifyHookHeadWalked = "head-walked" // the first HEAD view has been read and walked - verifyHookRootsWalked = "roots-walked" // the selected snapshots have been read and walked too + verifyHookHeadWalked = "head-walked" // the first HEAD view has been read and walked + verifyHookRootsWalked = "roots-walked" // the selected snapshots have been read and walked too + verifyHookBatchChecked = "batch-checked" // a batch of checks has settled + verifyHookClosingRead = "closing-read" // a closing read is about to be made ) +// VerifyIncomplete is why a pass did not complete. +type VerifyIncomplete string + +const ( + VerifyIncompleteDeadline VerifyIncomplete = "deadline" // the caller's deadline passed + VerifyIncompleteCancelled VerifyIncomplete = "cancelled" // the caller cancelled + VerifyIncompleteRounds VerifyIncomplete = "closing_rounds_exhausted" // every closing read named new chunks + VerifyIncompleteError VerifyIncomplete = "error" // a filer or blob store failure, or a refused request +) + +// CodeVerifyIncomplete: every closing read named chunks not seen before. +const CodeVerifyIncomplete = "verify_incomplete" + // VerifyFinding is one problem found. Segment is set for a segment's own // problem, Index for a chunk's. type VerifyFinding struct { @@ -156,35 +184,37 @@ type VerifyFinding struct { } // VerifyResult is a pass's summary and findings. Complete is false when the -// pass could not finish; the counters then cover what it did. +// pass could not finish (Incomplete says why); the counters and findings +// then cover what it checked. type VerifyResult struct { VolumeID string `json:"volumeID"` Depth VerifyDepth `json:"depth"` Complete bool `json:"complete"` - // HeadGens are the HEAD generations the pass covered, in order. + // Incomplete is why the pass did not complete ("" when it did). + Incomplete VerifyIncomplete `json:"incomplete,omitempty"` + // HeadGens are the HEAD generations the pass read, in order; the last + // is the final view's. HeadGens []uint64 `json:"headGens"` // Snapshots are the snapshots checked, as name/attempt. Snapshots []string `json:"snapshots"` - // SegmentsChecked counts segment references checked (per root); + // SegmentsChecked counts segment references checked (per root walked); // SegmentReads the segment objects actually read. SegmentsChecked int `json:"segmentsChecked"` SegmentReads int `json:"segmentReads"` - // ChunksChecked counts chunk references checked (root, index); - // DistinctChunks the distinct chunks (owner, key) among them. + // ChunksChecked counts the chunk references (root, index) of the final + // view; DistinctChunks the distinct chunks (owner, key) the pass saw. ChunksChecked int `json:"chunksChecked"` DistinctChunks int `json:"distinctChunks"` // DistinctChunksRead and BytesRead count the chunk data read. DistinctChunksRead int `json:"distinctChunksRead"` BytesRead int64 `json:"bytesRead"` - // SupersededDuringVerify counts misses under a HEAD root whose key the - // current HEAD no longer names (not findings). - SupersededDuringVerify int `json:"supersededDuringVerify"` - // RootDeletedDuringVerify counts misses under a snapshot whose attempt - // was deleted (or aborted, or is gone) by the time of the report (not - // findings). + // SupersededDuringVerify counts bad chunks and segments no root names + // at the final read (not findings); RootDeletedDuringVerify those of + // them that a selected snapshot deleted during the pass names. + SupersededDuringVerify int `json:"supersededDuringVerify"` RootDeletedDuringVerify int `json:"rootDeletedDuringVerify"` // SnapshotsDeletedDuringVerify lists, as name/attempt, the checked - // snapshots deleted during the pass: they are not fully covered. + // snapshots gone at the final read: they are not fully covered. SnapshotsDeletedDuringVerify []string `json:"snapshotsDeletedDuringVerify"` // ForkSourceGone: this volume is a fork whose source volume no longer // exists, so its fork record could not be compared with the parent @@ -203,19 +233,23 @@ type VerifyResult struct { func (c *Catalog) Verify(ctx context.Context, vol string, opts VerifyOptions) (VerifyResult, error) { res := VerifyResult{VolumeID: vol, HeadGens: []uint64{}, Snapshots: []string{}, SnapshotsDeletedDuringVerify: []string{}, FindingsByClass: map[string]int{}, Findings: []VerifyFinding{}} + refuse := func(err error) (VerifyResult, error) { + res.Incomplete = VerifyIncompleteError + return res, err + } if opts.Depth == "" { opts.Depth = VerifyBindings } res.Depth = opts.Depth if opts.Depth != VerifyMeta && opts.Depth != VerifyBindings && opts.Depth != VerifyData { - return res, catErr(CodeInvalidName, false, nil, "verify depth %q: meta, bindings or data", opts.Depth) + return refuse(catErr(CodeInvalidName, false, nil, "verify depth %q: meta, bindings or data", opts.Depth)) } if opts.Snapshot != "" && opts.AllSnapshots { - return res, catErr(CodeInvalidName, false, nil, "verify: a named snapshot and all snapshots do not combine") + return refuse(catErr(CodeInvalidName, false, nil, "verify: a named snapshot and all snapshots do not combine")) } if opts.Snapshot != "" { if err := CheckSnapshotName(opts.Snapshot); err != nil { - return res, err + return refuse(err) } } if opts.Concurrency <= 0 { @@ -230,20 +264,34 @@ func (c *Catalog) Verify(ctx context.Context, vol string, opts VerifyOptions) (V if opts.IntentStaleAge <= 0 { opts.IntentStaleAge = DefaultVerifyIntentStaleAge } + if opts.ClosingRounds <= 0 { + opts.ClosingRounds = DefaultVerifyClosingRounds + } root, err := c.volRoot(vol) if err != nil { - return res, err + return refuse(err) } v := &verifier{c: c, vol: vol, root: root, opts: opts, res: &res, blobs: c.blobs, - segs: map[verifySegKey]verifiedSegment{}, chunks: map[string]*verifyChunk{}, deletedSnaps: map[verifyRoot]bool{}, + segs: map[verifySegKey]*verifiedSegment{}, chunks: map[string]*verifyChunk{}, dropped: map[string]bool{}, pacer: &verifyPacer{rate: opts.BytesPerSecond}} err = v.run(ctx) + v.reconcile() sort.SliceStable(res.Findings, func(i, j int) bool { return findingLess(res.Findings[i], res.Findings[j]) }) for _, f := range res.Findings { res.FindingsByClass[f.Class]++ } res.DistinctChunks = len(v.chunks) if err != nil { + switch { + case CodeOf(err) == CodeVerifyIncomplete: + res.Incomplete = VerifyIncompleteRounds + case errors.Is(err, context.DeadlineExceeded): + res.Incomplete = VerifyIncompleteDeadline + case errors.Is(err, context.Canceled): + res.Incomplete = VerifyIncompleteCancelled + default: + res.Incomplete = VerifyIncompleteError + } return res, err } res.Complete = true @@ -251,73 +299,54 @@ func (c *Catalog) Verify(ctx context.Context, vol string, opts VerifyOptions) (V } // verifySegKey names a segment reference: a segment object is immutable, so -// one verified under the same reference needs no second read. +// one read under the same reference needs no second read. type verifySegKey struct { group, chunkBytes uint64 ref storage.ChunkSegment } +// verifiedSegment is a segment as read once: its chunks, or the problems +// that make it unusable (issue) or doomed (tombstoned binding). type verifiedSegment struct { chunks map[uint64]storage.ChunkRef fid string tombstoned bool + issue *segIssue } -// verifyRoot names a root a pass checks: HEAD (head set) or one snapshot -// attempt (name and attempt). -type verifyRoot struct { - label string - head bool - name, attempt string +// segIssue is why a segment could not be used. +type segIssue struct { + class, fid, detail string } -// verifyUse is one root's reference to a chunk. -type verifyUse struct { - root verifyRoot - idx uint64 - sha [32]byte -} - -// verifyChunk is one distinct chunk (owner volume + the owner's own key). +// verifyChunk is one distinct chunk (owner volume + the owner's own key): +// unseen while absent from the verifier's map, then queued, then settled. type verifyChunk struct { id string owner, key string - uses []verifyUse fid string bound bool // a sound, untombstoned binding was found - // Under the verifier's lock: the chunk's outcome, which applies to every - // reference to it. read is set once the needle was read (depth data), - // with its length and SHA-256; missClass and missDetail once a miss - // settled it (binding missing or tombstoned, needle missing, read - // error). The chunk is not read again. late are the references - // refreshed HEADs added: the outcome applies to those present when it - // is settled, and addUses applies it to the ones added after. - read bool - length int - digest [32]byte - missClass, missDetail string - late []verifyUse + // The outcome, under the verifier's lock until the checks are joined: + // class and detail of a bad outcome (binding missing or tombstoned, + // needle missing, read error, size mismatch), or the SHA-256 of the + // content read (read). + settled bool + class, detail string + read bool + digest [32]byte } -// repeats reports whether u repeats a reference already recorded for w -// (same index and SHA-256): comparing it again finds nothing new. -func (w *verifyChunk) repeats(u verifyUse) bool { - for _, list := range [][]verifyUse{w.uses, w.late} { - for _, o := range list { - if o.idx == u.idx && o.sha == u.sha { - return true - } - } - } - return false -} - -// verifyRef is a reference to a chunk already seen, to compare without -// reading the chunk (see addUses). -type verifyRef struct { - w *verifyChunk - u verifyUse +// verifyView is one root as last read: its references by index, and its +// root document (for the segments it names). +type verifyView struct { + label string + h storage.ChunkHead + chunks map[uint64]storage.ChunkRef + // snapshots only: the identity they were found under, and whether the + // final round read them gone. + name, attempt string + gone bool } type verifier struct { @@ -334,15 +363,14 @@ type verifier struct { mu sync.Mutex res *VerifyResult - segs map[verifySegKey]verifiedSegment // verified segments, by reference - chunks map[string]*verifyChunk // by identity - pending []*verifyChunk // not yet checked at depth bindings/data + segs map[verifySegKey]*verifiedSegment // segments read, by reference + chunks map[string]*verifyChunk // the chunks seen, by identity + pending []*verifyChunk // queued, not yet checked + listed bool // the owners' keys/ were listed once - snapRoots []verifyRoot // the snapshots checked - deletedSnaps map[verifyRoot]bool // snapshots found deleted during the pass (permanent) - - head storage.ChunkHead // the current HEAD view (root only) - hasHead bool + head *verifyView // the HEAD view; nil without a decodable HEAD + dropped map[string]bool // keys a HEAD view named and a later one did not + snaps []*verifyView // the selected snapshots, in order lastRefresh time.Time badRefresh bool } @@ -412,12 +440,6 @@ func (p verifyPrefetched) Get(_ context.Context, fid string) ([]byte, error) { return p.body, nil } -func (v *verifier) superseded() { - v.mu.Lock() - v.res.SupersededDuringVerify++ - v.mu.Unlock() -} - // abortErr turns a failure that stops the pass into its error: a context // error stays one (the CLI reports deadline_exceeded), anything else from // the filer is remote_unavailable. @@ -473,17 +495,11 @@ func (v *verifier) run(ctx context.Context) error { v.finding(VerifyFinding{Root: "HEAD", Class: FindingRootInvalid, Detail: derr.Error()}) break } - v.head, v.hasHead, v.lastRefresh = h, true, v.c.now() - hr := verifyRoot{label: headLabel(h.Gen), head: true} - v.res.HeadGens = append(v.res.HeadGens, h.Gen) - chunks, err := v.walk(ctx, hr, h) - if err != nil { + v.lastRefresh = v.c.now() + if _, err := v.refresh(ctx, h); err != nil { return err } - if err := v.compareRefs(ctx, v.addUses(hr, chunks, false)); err != nil { - return err - } - if err := v.intents(ctx, h, chunks); err != nil { + if err := v.intents(ctx, h, v.head.chunks); err != nil { return err } } @@ -493,112 +509,141 @@ func (v *verifier) run(ctx context.Context) error { return err } v.hook(verifyHookRootsWalked) - if v.opts.Depth != VerifyMeta { - for first := true; len(v.pending) > 0; first = false { - batch := v.pending - v.pending = nil - if err := v.checkBindings(ctx, batch, first); err != nil { - return err - } - if v.opts.Depth == VerifyData { - if err := v.checkData(ctx, batch); err != nil { - return err - } - } - if err := v.maybeRefresh(ctx); err != nil { - return err - } - } - } - // Name the snapshots deleted during the pass: not fully covered. - for _, s := range v.snapRoots { - if _, _, err := v.snapshotActive(ctx, s); err != nil { + for rounds := 0; ; { + if err := v.drain(ctx); err != nil { return err } + named, err := v.round(ctx) + if err != nil { + return err + } + if !named { + return nil // V.Close: this read is the final view + } + if rounds++; rounds == v.opts.ClosingRounds { + return catErr(CodeVerifyIncomplete, true, nil, // V.GiveUp + "verify of %s: each of %d closing reads of HEAD named chunks not seen before; the pass is incomplete (re-run when the volume is quieter)", + v.vol, rounds) + } } - for _, s := range v.snapRoots { - if v.deletedSnaps[s] { - v.res.SnapshotsDeletedDuringVerify = append(v.res.SnapshotsDeletedDuringVerify, s.name+"/"+s.attempt) +} + +// drain checks every queued chunk, batch by batch, refreshing HEAD between +// batches (a refresh can queue more). +func (v *verifier) drain(ctx context.Context) error { + for len(v.pending) > 0 { + batch := v.pending + v.pending = nil + if err := v.checkBindings(ctx, batch, !v.listed); err != nil { + return err + } + v.listed = true + if v.opts.Depth == VerifyData { + if err := v.checkData(ctx, batch); err != nil { + return err + } + } + v.hook(verifyHookBatchChecked) + if err := v.maybeRefresh(ctx); err != nil { + return err } } return nil } -// ---- roots and segments ---- - -// segIssue is why a segment could not be used. -type segIssue struct { - class, fid, detail string +// V.Round: once every queued chunk is settled, read HEAD and each selected snapshot's state once; report whether HEAD named a chunk not seen. +func (v *verifier) round(ctx context.Context) (bool, error) { + v.hook(verifyHookClosingRead) + named := false + if v.head != nil { + var err error + if named, err = v.readHead(ctx); err != nil { + return false, err + } + } + for _, s := range v.snaps { + active, err := v.snapshotActive(ctx, s) + if err != nil { + return false, err + } + s.gone = !active + } + return named, nil } -// segment returns the verified chunks of h's segment group (keys -// owner-qualified), reading it unless this pass already verified the same -// reference. A non-nil issue is a problem with the segment; an error stops -// the pass. tombstoned reports a segment binding GC has tombstoned. -func (v *verifier) segment(ctx context.Context, h storage.ChunkHead, group uint64) (chunks map[uint64]storage.ChunkRef, fid string, tombstoned bool, issue *segIssue, err error) { +// ---- roots and segments ---- + +// segment returns h's segment group as read once by this pass (keys +// owner-qualified, verified through the decoder GC and the chunk layer +// use), reading it the first time. An error stops the pass. +func (v *verifier) segment(ctx context.Context, h storage.ChunkHead, group uint64) (*verifiedSegment, error) { ref := h.Segments[group] k := verifySegKey{group: group, chunkBytes: h.ChunkBytes, ref: ref} - v.mu.Lock() - cached, ok := v.segs[k] - v.mu.Unlock() - if ok { - return cached.chunks, cached.fid, cached.tombstoned, nil, nil + if s := v.segs[k]; s != nil { + return s, nil } + s, err := v.readSegment(ctx, h, group, ref) + if err != nil { + return nil, err + } + v.segs[k] = s + return s, nil +} + +func (v *verifier) readSegment(ctx context.Context, h storage.ChunkHead, group uint64, ref storage.ChunkSegment) (*verifiedSegment, error) { if v.blobs == nil { - return nil, "", false, nil, errors.New("chunkstore: verify needs a blob reader for segmented roots") + return nil, errors.New("chunkstore: verify needs a blob reader for segmented roots") } r, err := NewChunkRemote(v.c.f, v.blobs, v.root) if err != nil { - return nil, "", false, nil, err + return nil, err } dir, name, err := r.keyLocation(ref.Key) if err != nil { - return nil, "", false, &segIssue{FindingSegmentUnreadable, "", err.Error()}, nil + return &verifiedSegment{issue: &segIssue{FindingSegmentUnreadable, "", err.Error()}}, nil } e, err := v.c.f.LookupEntry(ctx, dir, name) if errors.Is(err, ErrNotFound) { - return nil, "", false, &segIssue{FindingSegmentUnreadable, "", "segment binding not found"}, nil + return &verifiedSegment{issue: &segIssue{FindingSegmentUnreadable, "", "segment binding not found"}}, nil } if err != nil { - return nil, "", false, nil, abortErr(ctx, err, "read segment binding %s/%s", dir, name) + return nil, abortErr(ctx, err, "read segment binding %s/%s", dir, name) } if bad := bindingProblem(e); bad != "" { - return nil, "", false, &segIssue{FindingSegmentUnreadable, string(e.Extended[extFid]), "segment binding: " + bad}, nil + return &verifiedSegment{issue: &segIssue{FindingSegmentUnreadable, string(e.Extended[extFid]), "segment binding: " + bad}}, nil } - fid = string(e.Extended[extFid]) - tombstoned = len(e.Extended[extGCDeleted]) != 0 + s := &verifiedSegment{fid: string(e.Extended[extFid]), tombstoned: len(e.Extended[extGCDeleted]) != 0} v.mu.Lock() v.res.SegmentReads++ v.mu.Unlock() - body, err := v.fetch(ctx, fid) + body, err := v.fetch(ctx, s.fid) switch { case err == nil: case isContextErr(ctx, err): - return nil, "", false, nil, abortErr(ctx, err, "read segment %s", ref.Key) + return nil, abortErr(ctx, err, "read segment %s", ref.Key) case errors.Is(err, ErrBlobNotFound): - return nil, fid, tombstoned, &segIssue{FindingSegmentUnreadable, fid, "segment needle not found: " + err.Error()}, nil + s.issue = &segIssue{FindingSegmentUnreadable, s.fid, "segment needle not found: " + err.Error()} + return s, nil default: - return nil, fid, tombstoned, &segIssue{FindingReadError, fid, readErrorDetail(err)}, nil + s.issue = &segIssue{FindingReadError, s.fid, readErrorDetail(err)} + return s, nil } - // Verify the bytes read through the same decoder GC and the chunk - // layer use (hash, size bound, strict decode, contents). - r, err = NewChunkRemote(v.c.f, verifyPrefetched{fid, body}, v.root) + r, err = NewChunkRemote(v.c.f, verifyPrefetched{s.fid, body}, v.root) if err != nil { - return nil, "", false, nil, err + return nil, err } r.mu.Lock() - r.fids[ref.Key] = fid + r.fids[ref.Key] = s.fid r.mu.Unlock() one := storage.ChunkHead{Segments: map[uint64]storage.ChunkSegment{group: ref}, ChunkBytes: h.ChunkBytes, ManifestChunkCount: ref.Count, RemoteLSN: h.RemoteLSN, State: storage.ChunkHeadActive} resolved, err := r.resolveManifest(ctx, one) if err != nil { - return nil, fid, tombstoned, &segIssue{FindingSegmentUnreadable, fid, err.Error()}, nil + s.issue = &segIssue{FindingSegmentUnreadable, s.fid, err.Error()} + return s, nil } - v.mu.Lock() - v.segs[k] = verifiedSegment{resolved.Chunks, fid, tombstoned} - v.mu.Unlock() - return resolved.Chunks, fid, tombstoned, nil, nil + s.chunks = resolved.Chunks + return s, nil } // bindingProblem is what makes e unusable as a chunk key binding, or "". @@ -616,301 +661,109 @@ func bindingProblem(e *filerpb.Entry) string { return "" } -// walk checks one root (meta depth) and returns its chunk map. -func (v *verifier) walk(ctx context.Context, r verifyRoot, h storage.ChunkHead) (map[uint64]storage.ChunkRef, error) { - label := r.label +// walk reads the segments root h names and returns its chunk references by +// index, and the segment groups it could not use (their chunks are unknown). +func (v *verifier) walk(ctx context.Context, h storage.ChunkHead) (map[uint64]storage.ChunkRef, map[uint64]bool, error) { out := map[uint64]storage.ChunkRef{} + unusable := map[uint64]bool{} if h.Segments == nil { for idx, ref := range h.Chunks { out[idx] = ref } - } else { - if h.ChunkBytes != v.chunkBytes { - v.finding(VerifyFinding{Root: label, Class: FindingGeometry, - Detail: fmt.Sprintf("root chunk_bytes %d, VOLUME chunk size %d", h.ChunkBytes, v.chunkBytes)}) + return out, unusable, nil + } + groups := make([]uint64, 0, len(h.Segments)) + for g := range h.Segments { + groups = append(groups, g) + } + sort.Slice(groups, func(i, j int) bool { return groups[i] < groups[j] }) + for _, g := range groups { + v.mu.Lock() + v.res.SegmentsChecked++ + v.mu.Unlock() + s, err := v.segment(ctx, h, g) + if err != nil { + return out, unusable, err } - groups := make([]uint64, 0, len(h.Segments)) - for g := range h.Segments { - groups = append(groups, g) + if s.issue != nil { + unusable[g] = true + continue } - sort.Slice(groups, func(i, j int) bool { return groups[i] < groups[j] }) - for _, g := range groups { - ref := h.Segments[g] - v.mu.Lock() - v.res.SegmentsChecked++ - v.mu.Unlock() - chunks, fid, tomb, issue, err := v.segment(ctx, h, g) - if err != nil { - return out, err - } - group := g - if tomb && v.opts.Depth != VerifyMeta { - if err := v.segmentMiss(ctx, r, group, ref, VerifyFinding{Class: FindingBindingTombstoned, FID: fid, Detail: "segment binding tombstoned by GC"}); err != nil { - return out, err - } - } - if issue != nil { - if err := v.segmentMiss(ctx, r, group, ref, VerifyFinding{Class: issue.class, FID: issue.fid, Detail: issue.detail}); err != nil { - return out, err - } - continue - } - for idx, cr := range chunks { - out[idx] = cr - } + for idx, cr := range s.chunks { + out[idx] = cr } } - idxs := sortedIndexes(out) - for _, idx := range idxs { + return out, unusable, nil +} + +// geometry reports a root's chunk size and chunk indices against VOLUME. +func (v *verifier) geometry(label string, h storage.ChunkHead, chunks map[uint64]storage.ChunkRef) { + if h.Segments != nil && h.ChunkBytes != v.chunkBytes { + v.finding(VerifyFinding{Root: label, Class: FindingGeometry, + Detail: fmt.Sprintf("root chunk_bytes %d, VOLUME chunk size %d", h.ChunkBytes, v.chunkBytes)}) + } + for _, idx := range sortedIndexes(chunks) { if idx >= v.nChunks { i := idx - owner, key := splitIdentity(chunkIdentity(v.vol, out[idx].Key)) + owner, key := splitIdentity(chunkIdentity(v.vol, chunks[idx].Key)) v.finding(VerifyFinding{Root: label, Index: &i, Owner: owner, Key: key, Class: FindingGeometry, Detail: fmt.Sprintf("chunk index %d outside the volume (%d chunks)", idx, v.nChunks)}) } } - return out, nil } -// segmentMiss reports a segment problem, unless it is under a HEAD root -// that no longer names that segment, or under a snapshot deleted since. -func (v *verifier) segmentMiss(ctx context.Context, r verifyRoot, group uint64, ref storage.ChunkSegment, f VerifyFinding) error { - if r.head { - h, ok, err := v.readHeadRoot(ctx) - switch { - case errors.Is(err, errUndecodableHead): - // cannot excuse the miss: report it - case err != nil: - return err - case !ok || h.Segments[group] != ref: - v.superseded() - return nil +// V.Discover: queue one check of each chunk the references name that this pass has not seen; report whether there was one. +func (v *verifier) discover(chunks map[uint64]storage.ChunkRef) bool { + found := false + for _, idx := range sortedIndexes(chunks) { + id := chunkIdentity(v.vol, chunks[idx].Key) + if v.chunks[id] != nil { + continue } - } else { - active, _, err := v.snapshotActive(ctx, r) - if err != nil { - return err - } - if !active { - v.rootDeleted() - return nil + owner, key := splitIdentity(id) + w := &verifyChunk{id: id, owner: owner, key: key} + v.chunks[id] = w + found = true + if v.opts.Depth == VerifyMeta { + w.settled = true // nothing to check at this depth + continue } + v.pending = append(v.pending, w) } - f.Root, f.Segment, f.Owner, f.Key = r.label, &group, ref.Owner, ref.Key - v.finding(f) - return nil + return found } -func (v *verifier) rootDeleted() { +// V.Settle: record w's outcome (a bad outcome's class and detail, or none); report nothing. +func (v *verifier) settle(w *verifyChunk, class, detail string) { v.mu.Lock() - v.res.RootDeletedDuringVerify++ + w.settled, w.class, w.detail = true, class, detail v.mu.Unlock() } -// snapshotActive reads snapshot r again: its name record must still name -// r's attempt, and the attempt entry must still exist, active. A name -// record that is gone or names another attempt, or an attempt entry that is -// gone, aborted or marked deleting, means r was deleted (permanently: the -// attempt path is never reused). An entry that does not decode cannot -// excuse a miss: it counts as active, with a nil head. -func (v *verifier) snapshotActive(ctx context.Context, r verifyRoot) (active bool, head *storage.ChunkHead, err error) { - v.mu.Lock() - gone := v.deletedSnaps[r] - v.mu.Unlock() - if gone { - return false, nil, nil - } - deleted := func() (bool, *storage.ChunkHead, error) { - v.mu.Lock() - v.deletedSnaps[r] = true - v.mu.Unlock() - return false, nil, nil - } - ne, err := v.c.f.LookupEntry(ctx, path.Join(v.root, snapNamesDir), r.name) +// snapshotActive reads snapshot s's state again (part of V.Round): its name +// record must still name s's attempt, and the attempt entry must still +// exist, neither aborted nor marked deleting (the attempt path is never +// reused, so a snapshot read gone stays gone). +func (v *verifier) snapshotActive(ctx context.Context, s *verifyView) (bool, error) { + ne, err := v.c.f.LookupEntry(ctx, path.Join(v.root, snapNamesDir), s.name) if errors.Is(err, ErrNotFound) { - return deleted() - } - if err != nil { - return false, nil, abortErr(ctx, err, "re-read snapshot name %s/%s", v.vol, r.name) - } - rec, err := decodeNameRecord(path.Join(v.root, snapNamesDir, r.name), ne) - if err == nil && rec.Attempt != r.attempt { - return deleted() - } - dir := path.Join(v.root, snapsDir, r.name) - e, err := v.c.f.LookupEntry(ctx, dir, r.attempt) - if errors.Is(err, ErrNotFound) { - return deleted() - } - if err != nil { - return false, nil, abortErr(ctx, err, "re-read snapshot %s/%s/%s", v.vol, r.name, r.attempt) - } - if st := string(e.Extended[extSnapState]); st == SnapAborted || st == SnapDeleting || len(e.Extended[extSnapDeletedNs]) != 0 { - return deleted() - } - info, _, err := decodeSnap(path.Join(dir, r.attempt), e) - if err != nil { - return true, nil, nil - } - h := info.Head() - return true, &h, nil -} - -// readHeadRoot reads the current HEAD root. ok is false when there is none; -// a HEAD that does not decode is errUndecodableHead. -func (v *verifier) readHeadRoot(ctx context.Context) (storage.ChunkHead, bool, error) { - e, err := v.c.f.LookupEntry(ctx, v.root, headName) - if errors.Is(err, ErrNotFound) { - return storage.ChunkHead{}, false, nil - } - if err != nil { - return storage.ChunkHead{}, false, abortErr(ctx, err, "re-read HEAD of %s", v.vol) - } - h, err := decodeHead(path.Join(v.root, headName), e) - if err != nil { - return storage.ChunkHead{}, false, errUndecodableHead - } - return h, true, nil -} - -// errUndecodableHead: a re-read HEAD that does not decode cannot excuse a -// miss; the caller reports it. -var errUndecodableHead = errors.New("chunkstore: verify: HEAD does not decode") - -// stillNamed reports whether root r still names chunk identity id at index -// idx at report time, and counts why when it does not. For HEAD it reads -// the root again and, for a segmented root, the one segment covering idx -// (superseded during verify when the key is gone). For a snapshot it reads -// the name record and the attempt again (root deleted during verify when -// the attempt is no longer active). Anything it cannot read or decode -// counts as still naming the chunk: a miss is never excused on a guess. -func (v *verifier) stillNamed(ctx context.Context, r verifyRoot, idx uint64, id string) (bool, error) { - var h storage.ChunkHead - if r.head { - cur, ok, err := v.readHeadRoot(ctx) - if errors.Is(err, errUndecodableHead) { - return true, nil - } - if err != nil { - return false, err - } - if !ok { - v.superseded() - return false, nil - } - h = cur - } else { - active, head, err := v.snapshotActive(ctx, r) - if err != nil { - return false, err - } - if !active { - v.rootDeleted() - return false, nil - } - if head == nil { - return true, nil - } - h = *head - } - named, err := v.names(ctx, h, idx, id) - if err == nil && !named { - v.superseded() - } - return named, err -} - -// names reports whether root h names chunk identity id at index idx. -func (v *verifier) names(ctx context.Context, h storage.ChunkHead, idx uint64, id string) (bool, error) { - if h.Segments == nil { - ref, has := h.Chunks[idx] - return has && chunkIdentity(v.vol, ref.Key) == id, nil - } - if h.ChunkBytes == 0 { - return true, nil - } - group := idx / (manifestSegmentBytes / h.ChunkBytes) - if _, has := h.Segments[group]; !has { return false, nil } - chunks, _, _, issue, err := v.segment(ctx, h, group) if err != nil { - return false, err + return false, abortErr(ctx, err, "re-read snapshot name %s/%s", v.vol, s.name) } - if issue != nil { - return true, nil + if rec, err := decodeNameRecord(path.Join(v.root, snapNamesDir, s.name), ne); err == nil && rec.Attempt != s.attempt { + return false, nil } - ref, has := chunks[idx] - return has && chunkIdentity(v.vol, ref.Key) == id, nil -} - -// addUses records r's chunk references, queueing the chunks this pass has -// not seen, and returns the references to compare once the lock is -// released. A chunk is immutable, but a new reference to it can be wrong, -// so a reference to a chunk already seen is compared, never by reading the -// chunk again: with its outcome once settled (its content, or its miss), -// and below depth data with the chunk's first reference. A refreshed HEAD's -// references (refreshed set) to chunks already seen are not counted as -// checked again; one that repeats a recorded reference adds nothing, and -// one to a chunk not yet settled is left for its outcome. -func (v *verifier) addUses(r verifyRoot, chunks map[uint64]storage.ChunkRef, refreshed bool) []verifyRef { - v.mu.Lock() - defer v.mu.Unlock() - var check []verifyRef - for _, idx := range sortedIndexes(chunks) { - ref := chunks[idx] - id := chunkIdentity(v.vol, ref.Key) - u := verifyUse{root: r, idx: idx, sha: ref.SHA256} - w := v.chunks[id] - if w == nil { - owner, key := splitIdentity(id) - w = &verifyChunk{id: id, owner: owner, key: key} - v.chunks[id] = w - v.pending = append(v.pending, w) - } else { - if refreshed { - if w.repeats(u) { - continue - } - w.late = append(w.late, u) - } - if w.read || w.missClass != "" || (v.opts.Depth != VerifyData && u.sha != w.uses[0].sha) { - check = append(check, verifyRef{w, u}) - } - if refreshed { - continue - } - } - w.uses = append(w.uses, u) - v.res.ChunksChecked++ + e, err := v.c.f.LookupEntry(ctx, path.Join(v.root, snapsDir, s.name), s.attempt) + if errors.Is(err, ErrNotFound) { + return false, nil } - return check -} - -// compareRefs compares references to chunks already seen (see addUses). -func (v *verifier) compareRefs(ctx context.Context, refs []verifyRef) error { - for _, c := range refs { - v.mu.Lock() - read, n, sum, first := c.w.read, c.w.length, c.w.digest, c.w.uses[0] - missClass, missDetail := c.w.missClass, c.w.missDetail - v.mu.Unlock() - var err error - switch { - case read: - err = v.compareContent(ctx, c.w, n, sum, []verifyUse{c.u}) - case missClass != "": - err = v.missUses(ctx, c.w, []verifyUse{c.u}, missClass, func(verifyUse) string { return missDetail }) - default: - err = v.missUses(ctx, c.w, []verifyUse{c.u}, FindingContentMismatch, func(u verifyUse) string { - return fmt.Sprintf("references to this chunk disagree: SHA-256 %s here, %s under %s at index %d (depth data reads the chunk)", - hex.EncodeToString(u.sha[:]), hex.EncodeToString(first.sha[:]), first.root.label, first.idx) - }) - } - if err != nil { - return err - } + if err != nil { + return false, abortErr(ctx, err, "re-read snapshot %s/%s/%s", v.vol, s.name, s.attempt) } - return nil + st := string(e.Extended[extSnapState]) + return st != SnapAborted && st != SnapDeleting && len(e.Extended[extSnapDeletedNs]) == 0, nil } func sortedIndexes(m map[uint64]storage.ChunkRef) []uint64 { @@ -984,27 +837,29 @@ func (v *verifier) snapshots(ctx context.Context) error { } } -// snapshot checks the snapshot found under name, at the attempt its name -// record names. That path is the snapshot's identity, for its label and -// every recheck; a document naming another volume or snapshot is -// ROOT_INVALID, and its chunks are still checked under that path. +// snapshot selects the snapshot found under name, at the attempt its name +// record names: that path is its identity (label, state reads), and a +// document naming another volume or snapshot is ROOT_INVALID. Its +// references are fixed; its chunks are discovered (V.Discover). func (v *verifier) snapshot(ctx context.Context, name string, ref snapRef) error { - s, attempt := ref.info, ref.rec.Attempt - r := verifyRoot{label: "snapshot " + name + "/" + attempt, name: name, attempt: attempt} - v.res.Snapshots = append(v.res.Snapshots, name+"/"+attempt) - v.snapRoots = append(v.snapRoots, r) - if s.VolumeID != v.vol || s.Name != name { - v.finding(VerifyFinding{Root: r.label, Class: FindingRootInvalid, - Detail: fmt.Sprintf("snapshot document names %s/%s, found as %s/%s", s.VolumeID, s.Name, v.vol, name)}) + s := &verifyView{label: "snapshot " + name + "/" + ref.rec.Attempt, h: ref.info.Head(), name: name, attempt: ref.rec.Attempt} + v.res.Snapshots = append(v.res.Snapshots, name+"/"+s.attempt) + v.snaps = append(v.snaps, s) + if ref.info.VolumeID != v.vol || ref.info.Name != name { + v.finding(VerifyFinding{Root: s.label, Class: FindingRootInvalid, + Detail: fmt.Sprintf("snapshot document names %s/%s, found as %s/%s", ref.info.VolumeID, ref.info.Name, v.vol, name)}) } - if s.geo != (Geometry{}) && s.geo != v.geo { - v.finding(VerifyFinding{Root: r.label, Class: FindingGeometry, Detail: fmt.Sprintf("snapshot geometry %+v, VOLUME %+v", s.geo, v.geo)}) + if ref.info.geo != (Geometry{}) && ref.info.geo != v.geo { + v.finding(VerifyFinding{Root: s.label, Class: FindingGeometry, Detail: fmt.Sprintf("snapshot geometry %+v, VOLUME %+v", ref.info.geo, v.geo)}) } - chunks, err := v.walk(ctx, r, s.Head()) + chunks, _, err := v.walk(ctx, s.h) if err != nil { return err } - return v.compareRefs(ctx, v.addUses(r, chunks, false)) + s.chunks = chunks + v.geometry(s.label, s.h, chunks) + v.discover(chunks) + return nil } // forkRecord checks a fork's record against the parent snapshot it names: @@ -1127,22 +982,26 @@ func (v *verifier) intents(ctx context.Context, h storage.ChunkHead, chunks map[ // ---- refresh ---- -// maybeRefresh reads HEAD again once RefreshInterval has passed since the -// last view. A new generation is walked (only segments whose reference -// changed are read); its chunks this pass has not seen are queued, and its -// changed references to chunks already seen are compared (addUses). +// maybeRefresh reads HEAD again (V.Refresh) once RefreshInterval has passed since the last read. func (v *verifier) maybeRefresh(ctx context.Context) error { - now := v.c.now() - if !v.hasHead || now.Sub(v.lastRefresh) < v.opts.RefreshInterval { + if v.head == nil || v.c.now().Sub(v.lastRefresh) < v.opts.RefreshInterval { return nil } - v.lastRefresh = now + _, err := v.readHead(ctx) + return err +} + +// readHead reads HEAD and applies it (V.Refresh); a HEAD that is gone, or does +// not decode (reported once), changes nothing. It reports whether HEAD named +// a chunk not seen. +func (v *verifier) readHead(ctx context.Context) (bool, error) { + v.lastRefresh = v.c.now() e, err := v.c.f.LookupEntry(ctx, v.root, headName) if errors.Is(err, ErrNotFound) { - return nil + return false, nil } if err != nil { - return abortErr(ctx, err, "refresh HEAD of %s", v.vol) + return false, abortErr(ctx, err, "refresh HEAD of %s", v.vol) } h, err := decodeHead(path.Join(v.root, headName), e) if err != nil { @@ -1150,19 +1009,40 @@ func (v *verifier) maybeRefresh(ctx context.Context) error { v.badRefresh = true v.finding(VerifyFinding{Root: "HEAD", Class: FindingRootInvalid, Detail: "refreshed HEAD: " + err.Error()}) } - return nil + return false, nil } - if h.Gen == v.head.Gen && h.Epoch == v.head.Epoch { - return nil + return v.refresh(ctx, h) +} + +// V.Refresh: replace the HEAD view with h unless h is older (or the same); mark the keys it drops; discover its new keys. +func (v *verifier) refresh(ctx context.Context, h storage.ChunkHead) (bool, error) { + if v.head != nil && (h.Gen < v.head.h.Gen || h.Gen == v.head.h.Gen && h.Epoch == v.head.h.Epoch) { + return false, nil } - hr := verifyRoot{label: headLabel(h.Gen), head: true} - v.res.HeadGens = append(v.res.HeadGens, h.Gen) - chunks, err := v.walk(ctx, hr, h) + chunks, unusable, err := v.walk(ctx, h) if err != nil { - return err + return false, err } - v.head = h - return v.compareRefs(ctx, v.addUses(hr, chunks, true)) + if v.head != nil { + // A key the old view named that h does not is dropped, unless its + // old index lies in a segment of h that could not be read. + perSeg := uint64(0) + if h.ChunkBytes > 0 { + perSeg = manifestSegmentBytes / h.ChunkBytes + } + now := map[string]bool{} + for _, ref := range chunks { + now[chunkIdentity(v.vol, ref.Key)] = true + } + for idx, ref := range v.head.chunks { + if id := chunkIdentity(v.vol, ref.Key); !now[id] && (perSeg == 0 || !unusable[idx/perSeg]) { + v.dropped[id] = true + } + } + } + v.head = &verifyView{label: headLabel(h.Gen), h: h, chunks: chunks} + v.res.HeadGens = append(v.res.HeadGens, h.Gen) + return v.discover(chunks), nil } // ---- bindings ---- @@ -1225,9 +1105,7 @@ func (v *verifier) checkBindings(ctx context.Context, batch []*verifyChunk, list return err } } - if err := v.evaluateBinding(ctx, w, e); err != nil { - return err - } + v.evaluateBinding(w, e) } return nil } @@ -1252,55 +1130,30 @@ func (v *verifier) lookupBinding(ctx context.Context, w *verifyChunk) (*filerpb. return e, nil } -func (v *verifier) evaluateBinding(ctx context.Context, w *verifyChunk, e *filerpb.Entry) error { +// V.Settle (bindings): a missing, invalid or tombstoned binding is w's outcome; a sound one settles it at depth bindings. +func (v *verifier) evaluateBinding(w *verifyChunk, e *filerpb.Entry) { if e == nil { - return v.miss(ctx, w, FindingBindingMissing, fmt.Sprintf("no binding in %s/keys", w.owner)) + v.settle(w, FindingBindingMissing, fmt.Sprintf("no binding in %s/keys", w.owner)) + return } w.fid = string(e.Extended[extFid]) - if bad := bindingProblem(e); bad != "" { - return v.miss(ctx, w, FindingBindingMissing, "invalid binding: "+bad) - } - if t := e.Extended[extGCDeleted]; len(t) != 0 { - return v.miss(ctx, w, FindingBindingTombstoned, fmt.Sprintf("binding tombstoned by GC (%s=%s)", extGCDeleted, t)) - } - w.bound = true - return nil -} - -// miss settles w with a miss and reports it under all of its references, -// those refreshed HEADs added included; addUses applies it to later ones. -func (v *verifier) miss(ctx context.Context, w *verifyChunk, class, detail string) error { - v.mu.Lock() - w.missClass, w.missDetail = class, detail - uses := append(append([]verifyUse(nil), w.uses...), w.late...) - v.mu.Unlock() - return v.missUses(ctx, w, uses, class, func(verifyUse) string { return detail }) -} - -// missUses reports a miss of w as at most one finding: under the first of -// uses whose root still names w at that index at report time (HEAD first, -// then snapshots in the order checked). A root that no longer names it is -// counted (superseded, or root deleted, during verify) and not reported. -func (v *verifier) missUses(ctx context.Context, w *verifyChunk, uses []verifyUse, class string, detail func(verifyUse) string) error { - for _, u := range uses { - still, err := v.stillNamed(ctx, u.root, u.idx, w.id) - if err != nil { - return err + switch bad := bindingProblem(e); { + case bad != "": + v.settle(w, FindingBindingMissing, "invalid binding: "+bad) + case len(e.Extended[extGCDeleted]) != 0: + v.settle(w, FindingBindingTombstoned, fmt.Sprintf("binding tombstoned by GC (%s=%s)", extGCDeleted, e.Extended[extGCDeleted])) + default: + w.bound = true + if v.opts.Depth != VerifyData { + v.settle(w, "", "") } - if !still { - continue - } - idx := u.idx - v.finding(VerifyFinding{Root: u.root.label, Index: &idx, Owner: w.owner, Key: w.key, FID: w.fid, Class: class, Detail: detail(u)}) - return nil } - return nil } // ---- data ---- // checkData fetches every bound chunk of batch once, at bounded concurrency -// and paced, and checks it against each reference. +// and paced. func (v *verifier) checkData(ctx context.Context, batch []*verifyChunk) error { if v.blobs == nil { return errors.New("chunkstore: verify needs a blob reader for depth data") @@ -1378,6 +1231,7 @@ func (v *verifier) checkData(ctx context.Context, batch []*verifyChunk) error { return getErr() } +// V.Settle (data): read w's needle once and record the outcome (missing, read error, wrong size, or the content's SHA-256). func (v *verifier) readChunk(ctx context.Context, w *verifyChunk) error { data, err := v.fetch(ctx, w.fid) switch { @@ -1385,38 +1239,190 @@ func (v *verifier) readChunk(ctx context.Context, w *verifyChunk) error { case isContextErr(ctx, err): return abortErr(ctx, err, "read chunk %s", w.fid) case errors.Is(err, ErrBlobNotFound): - return v.miss(ctx, w, FindingNeedleMissing, err.Error()) + v.settle(w, FindingNeedleMissing, err.Error()) + return nil default: - return v.miss(ctx, w, FindingReadError, readErrorDetail(err)) + v.settle(w, FindingReadError, readErrorDetail(err)) + return nil } sum := sha256.Sum256(data) v.mu.Lock() + defer v.mu.Unlock() v.res.DistinctChunksRead++ v.res.BytesRead += int64(len(data)) - w.read, w.length, w.digest = true, len(data), sum - uses := append(append([]verifyUse(nil), w.uses...), w.late...) - v.mu.Unlock() - return v.compareContent(ctx, w, len(data), sum, uses) + w.settled, w.read, w.digest = true, true, sum + if uint64(len(data)) != v.chunkBytes { + w.class, w.detail = FindingSizeMismatch, fmt.Sprintf("needle holds %d bytes, chunk size %d", len(data), v.chunkBytes) + } + return nil } -// compareContent checks uses against a chunk's content, n bytes with -// SHA-256 sum: the length must be the chunk size and the hash each -// reference's. -func (v *verifier) compareContent(ctx context.Context, w *verifyChunk, n int, sum [32]byte, uses []verifyUse) error { - if uint64(n) != v.chunkBytes { - return v.missUses(ctx, w, uses, FindingSizeMismatch, func(verifyUse) string { - return fmt.Sprintf("needle holds %d bytes, chunk size %d", n, v.chunkBytes) - }) +// ---- reconcile ---- + +// verifyRef is a final-view reference: the root (its position among the +// final roots), the index and the SHA-256. +type verifyRef struct { + root int + idx uint64 + sha [32]byte +} + +// V.Reconcile: compute every chunk and segment finding from the outcomes and the final view alone; an unnamed bad chunk counts as root deleted if a gone selected snapshot names it, else as superseded. +func (v *verifier) reconcile() { + // The final roots are the HEAD view, then each selected snapshot not + // gone, in order. A chunk with a bad outcome: one finding under the + // first final root that names its key, at that root's first index; if + // none does, no finding, counted once (root deleted takes precedence + // over superseded). A chunk read and verified: one CONTENT_MISMATCH, + // under the first final reference that differs from the content, its + // detail counting the others (and naming the next root carrying one). + // At most one finding per key and class. Below depth data, final + // references to one chunk with different SHA-256s are one + // CONTENT_MISMATCH. A key HEAD + // dropped earlier in the pass and names again is one ROOT_INVALID. A + // segment problem follows the bad-chunk rule over the final roots that + // name that segment. Chunks never settled (an incomplete pass) are not + // judged. + var roots []*verifyView + if v.head != nil { + roots = append(roots, v.head) + v.geometry(v.head.label, v.head.h, v.head.chunks) } - var mismatched []verifyUse - for _, u := range uses { - if sum != u.sha { - mismatched = append(mismatched, u) + for _, s := range v.snaps { + if s.gone { + v.res.SnapshotsDeletedDuringVerify = append(v.res.SnapshotsDeletedDuringVerify, s.name+"/"+s.attempt) + } else { + roots = append(roots, s) } } - return v.missUses(ctx, w, mismatched, FindingContentMismatch, func(u verifyUse) string { - return fmt.Sprintf("needle SHA-256 %s, reference %s", hex.EncodeToString(sum[:]), hex.EncodeToString(u.sha[:])) - }) + named := map[string][]verifyRef{} + for ri, r := range roots { + for _, idx := range sortedIndexes(r.chunks) { + ref := r.chunks[idx] + id := chunkIdentity(v.vol, ref.Key) + named[id] = append(named[id], verifyRef{root: ri, idx: idx, sha: ref.SHA256}) + v.res.ChunksChecked++ + } + } + ids := make([]string, 0, len(v.chunks)) + for id := range v.chunks { + ids = append(ids, id) + } + sort.Strings(ids) + for _, id := range ids { + w, refs := v.chunks[id], named[id] + report := func(at verifyRef, class, detail string) { + idx := at.idx + v.finding(VerifyFinding{Root: roots[at.root].label, Index: &idx, Owner: w.owner, Key: w.key, FID: w.fid, Class: class, Detail: detail}) + } + switch { + case !w.settled: + case w.class != "" && len(refs) == 0: + v.unnamed(func(s *verifyView) bool { return s.namesChunk(v.vol, id) }) + case w.class != "": + report(refs[0], w.class, w.detail) + case w.read: + var differ []verifyRef + for _, r := range refs { + if r.sha != w.digest { + differ = append(differ, r) + } + } + if len(differ) == 0 { + break + } + detail := fmt.Sprintf("needle SHA-256 %s, reference %s", hex.EncodeToString(w.digest[:]), hex.EncodeToString(differ[0].sha[:])) + if more := differ[1:]; len(more) > 0 { + detail += fmt.Sprintf("; %d more final reference(s) differ", len(more)) + for _, r := range more { + if r.root != differ[0].root { + detail += ", next under " + roots[r.root].label + break + } + } + } + report(differ[0], FindingContentMismatch, detail) + } + if v.opts.Depth != VerifyData { + for _, r := range refs[min(1, len(refs)):] { + if r.sha != refs[0].sha { + report(r, FindingContentMismatch, fmt.Sprintf("references to this chunk disagree: SHA-256 %s here, %s under %s at index %d (depth data reads the chunk)", + hex.EncodeToString(r.sha[:]), hex.EncodeToString(refs[0].sha[:]), roots[refs[0].root].label, refs[0].idx)) + break + } + } + } + } + if v.head != nil { + reported := map[string]bool{} + for _, idx := range sortedIndexes(v.head.chunks) { + id := chunkIdentity(v.vol, v.head.chunks[idx].Key) + if v.dropped[id] && !reported[id] { + reported[id] = true + i := idx + owner, key := splitIdentity(id) + fid := "" + if w := v.chunks[id]; w != nil { + fid = w.fid + } + v.finding(VerifyFinding{Root: v.head.label, Index: &i, Owner: owner, Key: key, FID: fid, Class: FindingRootInvalid, + Detail: "HEAD names a key it had dropped earlier in this pass; a key that left every root must not be named again"}) + } + } + } + for k, s := range v.segs { + var issues []segIssue + if s.tombstoned && v.opts.Depth != VerifyMeta { + issues = append(issues, segIssue{FindingBindingTombstoned, s.fid, "segment binding tombstoned by GC"}) + } + if s.issue != nil { + issues = append(issues, *s.issue) + } + if len(issues) == 0 { + continue + } + var at *verifyView + for _, r := range roots { + if r.namesSegment(k) { + at = r + break + } + } + if at == nil { + v.unnamed(func(s *verifyView) bool { return s.namesSegment(k) }) + continue + } + for _, is := range issues { + g := k.group + v.finding(VerifyFinding{Root: at.label, Segment: &g, Owner: k.ref.Owner, Key: k.ref.Key, FID: is.fid, Class: is.class, Detail: is.detail}) + } + } +} + +// unnamed counts a bad chunk or segment no final root names: root deleted +// when a selected snapshot that is gone names it, otherwise superseded. +func (v *verifier) unnamed(namedBy func(*verifyView) bool) { + for _, s := range v.snaps { + if s.gone && namedBy(s) { + v.res.RootDeletedDuringVerify++ + return + } + } + v.res.SupersededDuringVerify++ +} + +func (r *verifyView) namesChunk(vol, id string) bool { + for _, ref := range r.chunks { + if chunkIdentity(vol, ref.Key) == id { + return true + } + } + return false +} + +func (r *verifyView) namesSegment(k verifySegKey) bool { + ref, ok := r.h.Segments[k.group] + return ok && ref == k.ref && r.h.ChunkBytes == k.chunkBytes } // verifyPacer spaces reads so they average at most rate bytes per second. diff --git a/seaweed-block/core/frontend/chunkstore/verify_test.go b/seaweed-block/core/frontend/chunkstore/verify_test.go index c85aa6ea42..19b470d87e 100644 --- a/seaweed-block/core/frontend/chunkstore/verify_test.go +++ b/seaweed-block/core/frontend/chunkstore/verify_test.go @@ -585,8 +585,9 @@ func TestVerify_UnreadableSegmentContinues(t *testing.T) { } // A chunk that leaves HEAD and is collected while the pass runs is not a -// finding under HEAD (it is counted as superseded during verify); the same -// miss under a snapshot that still names it is one. +// finding when no root names it at the final read (a bad outcome is then +// counted as superseded during verify; read content has no reference left +// to compare with); under a snapshot that still names it, it is one. func TestVerify_SupersededDuringPass(t *testing.T) { type damage struct { name string @@ -640,8 +641,13 @@ func TestVerify_SupersededDuringPass(t *testing.T) { t.Fatalf("finding root %q, want the snapshot", res.Findings[0].Root) } } - if hooked != 1 || res.SupersededDuringVerify != 1 || len(res.HeadGens) != 1 || res.HeadGens[0] != h.Gen { - t.Fatalf("hooked %d, superseded %d, gens %v; want 1, 1, [%d]", hooked, res.SupersededDuringVerify, res.HeadGens, h.Gen) + superseded := 0 + if !withSnap && tc.class != FindingContentMismatch { + superseded = 1 + } + // The closing read sees the owner's new HEAD: it is the final view. + if hooked != 1 || res.SupersededDuringVerify != superseded || len(res.HeadGens) != 2 || res.HeadGens[0] != h.Gen { + t.Fatalf("hooked %d, superseded %d, gens %v; want 1, %d, [%d next]", hooked, res.SupersededDuringVerify, superseded, res.HeadGens, h.Gen) } }) } @@ -649,9 +655,9 @@ func TestVerify_SupersededDuringPass(t *testing.T) { } // A miss under a snapshot is a finding only while that attempt is still -// active: a snapshot deleted during the pass, whose chunk is then -// collected, is counted as root deleted during verify and listed as not -// fully covered, not reported. +// active at the final read: a snapshot deleted during the pass, whose chunk +// is then collected, is listed as not fully covered, its bad chunk counted +// as root deleted during verify, not reported. func TestVerify_SnapshotDeletedDuringPass(t *testing.T) { cases := []struct { name string @@ -705,7 +711,11 @@ func TestVerify_SnapshotDeletedDuringPass(t *testing.T) { return } wantClasses(t, "deleted snapshot", res) - if res.RootDeletedDuringVerify != 1 || res.SupersededDuringVerify != 0 || + rootDeleted := 1 // a bad outcome; read content has no reference left to compare with + if tc.class == FindingContentMismatch { + rootDeleted = 0 + } + if res.RootDeletedDuringVerify != rootDeleted || res.SupersededDuringVerify != 0 || len(res.SnapshotsDeletedDuringVerify) != 1 || res.SnapshotsDeletedDuringVerify[0] != res.Snapshots[0] { t.Fatalf("deleted snapshot: root deleted %d, superseded %d, deleted list %v (checked %v, created %+v)", res.RootDeletedDuringVerify, res.SupersededDuringVerify, res.SnapshotsDeletedDuringVerify, res.Snapshots, s.Name) @@ -716,7 +726,8 @@ func TestVerify_SnapshotDeletedDuringPass(t *testing.T) { } // A chunk named by HEAD (superseded during the pass) and by a snapshot that -// is still active is one finding, under the snapshot. +// is still active is one finding, under the snapshot (and not counted as +// superseded: a root still names it). func TestVerify_SharedChunkReportedUnderStillNamingRoot(t *testing.T) { fx := newVerifyFixture(t, "v1") ctx := context.Background() @@ -733,27 +744,28 @@ func TestVerify_SharedChunkReportedUnderStillNamingRoot(t *testing.T) { } res := fx.verify("v1", opts) wantClasses(t, "shared chunk", res, "NEEDLE_MISSING@0") - if !strings.HasPrefix(res.Findings[0].Root, "snapshot s1/") || res.SupersededDuringVerify != 1 || res.RootDeletedDuringVerify != 0 { - t.Fatalf("finding under %q, superseded %d, root deleted %d; want the snapshot, 1, 0", + if !strings.HasPrefix(res.Findings[0].Root, "snapshot s1/") || res.SupersededDuringVerify != 0 || res.RootDeletedDuringVerify != 0 { + t.Fatalf("finding under %q, superseded %d, root deleted %d; want the snapshot, 0, 0", res.Findings[0].Root, res.SupersededDuringVerify, res.RootDeletedDuringVerify) } } -// A HEAD that advances mid-pass: the result lists both generations, and -// only the segment whose key changed is read again. +// A HEAD that advances mid-pass: the result lists both generations, only +// the segment whose key changed is read again, and the references checked +// are the final view's. func TestVerify_HeadRefreshRewalksChangedSegments(t *testing.T) { for _, d := range []VerifyDepth{VerifyBindings, VerifyData} { t.Run(string(d), func(t *testing.T) { fx := newVerifyFixture(t, "v1") h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2), 2 * verifyPer: verifyData(3)}, false) var h2 storage.ChunkHead - opts := VerifyOptions{Depth: d, RefreshInterval: time.Millisecond} + opts := VerifyOptions{Depth: d, RefreshInterval: time.Minute} opts.hook = func(stage string) { if stage == verifyHookHeadWalked { h2 = fx.publish("v1", map[uint64][]byte{verifyPer: verifyData(7)}, true) - time.Sleep(3 * time.Millisecond) // past the refresh interval } } + fx.c.SetClock(tickingClock(time.Minute)) // past the refresh interval at every read res := fx.verify("v1", opts) wantClasses(t, "refresh", res) if len(res.HeadGens) != 2 || res.HeadGens[0] != h1.Gen || res.HeadGens[1] != h2.Gen { @@ -765,8 +777,8 @@ func TestVerify_HeadRefreshRewalksChangedSegments(t *testing.T) { if res.SegmentReads != 4 || res.SegmentsChecked != 6 { t.Fatalf("segment reads %d (checked %d); want 3 + 1 changed", res.SegmentReads, res.SegmentsChecked) } - if res.DistinctChunks != 4 || res.ChunksChecked != 4 { - t.Fatalf("chunks %d distinct, %d checked; want the 3 first and the 1 new", res.DistinctChunks, res.ChunksChecked) + if res.DistinctChunks != 4 || res.ChunksChecked != 3 { + t.Fatalf("chunks %d distinct, %d checked; want the 3 first and the 1 new, 3 final references", res.DistinctChunks, res.ChunksChecked) } if d == VerifyData && (res.DistinctChunksRead != 4 || fx.cb.reads(fx.fid(h2.Chunks[verifyPer].Key)) != 1) { t.Fatalf("read %d chunks; want 4, the new one included", res.DistinctChunksRead) @@ -1355,11 +1367,11 @@ func (b *beforeRead) Get(ctx context.Context, fid string) ([]byte, error) { return b.Blobs.Get(ctx, fid) } -// A reference to a chunk already checked, under the same key but with -// another SHA-256, is a finding: at depth data it is compared with the -// content read once for that chunk (the chunk is not read again), below -// data with the other reference. This holds for a HEAD refreshed during -// the pass and for a snapshot. +// A final reference to a chunk under the same key but with another SHA-256 +// is a finding: at depth data it is compared with the content read once for +// that chunk (the chunk is not read again), below data with the other final +// references. A reference only an earlier HEAD view carried is not compared +// (detail "": no finding). func TestVerify_SameKeyWithAnotherHashIsAFinding(t *testing.T) { for _, tc := range []struct { name string @@ -1369,7 +1381,7 @@ func TestVerify_SameKeyWithAnotherHashIsAFinding(t *testing.T) { }{ {"refreshed HEAD, data, before the read", VerifyData, "walked", "needle SHA-256"}, {"refreshed HEAD, data, after the read", VerifyData, "read", "needle SHA-256"}, - {"refreshed HEAD, bindings", VerifyBindings, "walked", "disagree"}, + {"refreshed HEAD, bindings", VerifyBindings, "walked", ""}, {"snapshot, data", VerifyData, "snapshot", "needle SHA-256"}, {"snapshot, bindings", VerifyBindings, "snapshot", "disagree"}, } { @@ -1408,6 +1420,10 @@ func TestVerify_SameKeyWithAnotherHashIsAFinding(t *testing.T) { if err != nil || !res.Complete { t.Fatalf("verify: %v, %+v", err, res) } + if tc.detail == "" { + wantClasses(t, tc.name, res) + return + } wantClasses(t, tc.name, res, "CONTENT_MISMATCH@0") f := res.Findings[0] wantRoot := headLabel(h2.Gen) @@ -1429,106 +1445,215 @@ func TestVerify_SameKeyWithAnotherHashIsAFinding(t *testing.T) { } } -// manualClock stands still until advanced. -type manualClock struct { - mu sync.Mutex - now time.Time +// A chunk read once whose final references (HEAD and an active snapshot) +// carry two different wrong SHA-256s is one CONTENT_MISMATCH, under HEAD, +// whose detail counts the other differing reference and names its root. +func TestVerify_TwoWrongReferencesAreOneFinding(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + h2 := fx.republish("v1", wrongHash(0)) // the snapshot keeps this wrong hash + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h2); err != nil { + t.Fatal(err) + } + h3 := fx.republish("v1", func(c map[uint64]storage.ChunkRef) { // HEAD: another wrong hash, same key + ref := c[0] + ref.SHA256[1] ^= 0xff + c[0] = ref + }) + if h3.Chunks[0].Key != h1.Chunks[0].Key || h3.Chunks[0].SHA256 == h2.Chunks[0].SHA256 || h2.Chunks[0].SHA256 == h1.Chunks[0].SHA256 { + t.Fatal("fixture: one key, three different reference hashes") + } + res := fx.verify("v1", VerifyOptions{Depth: VerifyData, AllSnapshots: true, BytesPerSecond: -1}) + wantClasses(t, "two wrong references", res, "CONTENT_MISMATCH@0") + f := res.Findings[0] + if f.Root != headLabel(h3.Gen) || !strings.Contains(f.Detail, "1 more") || !strings.Contains(f.Detail, "snapshot s1/") { + t.Fatalf("finding %+v; want under %q, detail counting 1 more differing reference under the snapshot", f, headLabel(h3.Gen)) + } + if n := fx.cb.reads(fx.fid(h1.Chunks[0].Key)); n != 1 { + t.Fatalf("chunk read %d times, want once", n) + } } -func (c *manualClock) read() time.Time { - c.mu.Lock() - defer c.mu.Unlock() - return c.now +// A schedule point: where a world event lands relative to the pass. +type schedPoint string + +const ( + atWalked schedPoint = "walked" // after the first HEAD view, before any check + atChecked schedPoint = "checked" // after the first batch of checks has settled + atClosing schedPoint = "closing" // just before the first closing read + atDuring schedPoint = "during" // while chunk K's read is in progress +) + +// verifyFixture.schedule runs a data-depth pass over v1 whose owner applies +// steps[i] at points[i] (several steps at one point run in order). HEAD is +// re-read at every opportunity; fidK is the chunk whose read is "during". +func (fx *verifyFixture) schedule(fidK string, steps []func(), points []schedPoint) VerifyResult { + fx.t.Helper() + var mu sync.Mutex + pending := map[schedPoint][]func(){} + for i, p := range points { + pending[p] = append(pending[p], steps[i]) + } + fire := func(p schedPoint) { + mu.Lock() + fs := pending[p] + delete(pending, p) + mu.Unlock() + for _, f := range fs { + f() + } + } + opts := VerifyOptions{Depth: VerifyData, BytesPerSecond: -1, RefreshInterval: time.Minute, Concurrency: 1} + opts.hook = func(stage string) { + switch stage { + case verifyHookHeadWalked: + fire(atWalked) + case verifyHookBatchChecked: + fire(atChecked) + case verifyHookClosingRead: + fire(atClosing) + } + } + during := &beforeRead{Blobs: fx.cb, fid: fidK, fn: func() { fire(atDuring) }} + cat, err := NewCatalog(manifestFilerBlobs{fx.f, during}, catBase) + if err != nil { + fx.t.Fatal(err) + } + cat.SetClock(tickingClock(time.Minute)) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + res, err := cat.Verify(ctx, "v1", opts) + if err != nil || !res.Complete { + fx.t.Fatalf("verify: %v, %+v", err, res) + } + if len(pending) != 0 { + fx.t.Fatalf("schedule points never reached: %v", pending) + } + return res } -func (c *manualClock) advance(d time.Duration) { - c.mu.Lock() - c.now = c.now.Add(d) - c.mu.Unlock() -} - -// A chunk's outcome (needle missing, read error, binding missing) applies -// to every reference to it, also to those a refreshed HEAD added before or -// after that outcome: a reference whose root still names the chunk there is -// a finding, under that root. The chunk is not read again. -func TestVerify_OutcomeAppliesToRefreshedReferences(t *testing.T) { - dropK := func(fx *verifyFixture, k string) { fx.needle(fx.fid(k), dropNeedle) } - failK := func(fx *verifyFixture, k string) { fx.cb.failReads(fx.fid(k), -1) } - unbindK := func(fx *verifyFixture, k string) { fx.deleteBinding(k) } +// The same owner events in different interleavings with the pass's checks +// and HEAD reads give the same findings: the findings are computed at the +// end, from each chunk's one outcome and the roots at the final read. K is +// chunk 0 (index 0), L chunk 1; "bad" means K's needle is missing. +func TestVerify_SchedulesGiveTheSameFindings(t *testing.T) { + moveK := func(c map[uint64]storage.ChunkRef) { c[1] = c[0]; delete(c, 0) } + addK1 := func(c map[uint64]storage.ChunkRef) { c[1] = c[0] } + dropK := func(c map[uint64]storage.ChunkRef) { delete(c, 0) } + type edit = func(c map[uint64]storage.ChunkRef) for _, tc := range []struct { - name string - depth VerifyDepth - after bool // the refresh comes after the outcome, not before - damage func(fx *verifyFixture, qkey string) - want string - reads int // reads of the damaged chunk + name string + bad bool + edits []edit // the owner's publishes, in order (nil: restore K at index 0) + interleave [][]schedPoint + want []string + superseded int + finalGenStep int // findings are under the HEAD this many publishes after the first (all of them) }{ - {"refresh before, needle missing", VerifyData, false, dropK, "NEEDLE_MISSING@1", 1}, - {"refresh before, read error", VerifyData, false, failK, "READ_ERROR@1", verifyReadAttempts}, - {"refresh before, binding missing", VerifyBindings, false, unbindK, "BINDING_MISSING@1", 0}, - {"refresh after, needle missing", VerifyData, true, dropK, "NEEDLE_MISSING@1", 1}, - {"refresh after, read error", VerifyData, true, failK, "READ_ERROR@1", verifyReadAttempts}, + {"K moves from index 0 to 1, its check fails", true, []edit{moveK}, + [][]schedPoint{{atWalked}, {atChecked}, {atClosing}}, []string{"NEEDLE_MISSING@1"}, 0, 1}, + {"a reference to K arrives after K settled bad", true, []edit{addK1, dropK}, + [][]schedPoint{{atWalked, atWalked}, {atWalked, atChecked}, {atChecked, atClosing}}, []string{"NEEDLE_MISSING@1"}, 0, 2}, + {"K is bad, a refresh keeps index 0 and adds index 1", true, []edit{addK1}, + [][]schedPoint{{atWalked}, {atChecked}, {atClosing}}, []string{"NEEDLE_MISSING@0"}, 0, 1}, + {"settlement and refresh overlap", true, []edit{moveK}, + [][]schedPoint{{atDuring}, {atWalked}}, []string{"NEEDLE_MISSING@1"}, 0, 1}, + {"K is named, not named, named again (bad)", true, []edit{dropK, nil}, + [][]schedPoint{{atWalked, atChecked}, {atChecked, atClosing}}, []string{"NEEDLE_MISSING@0", "ROOT_INVALID@0"}, 0, 2}, + {"K is named, not named, named again (good)", false, []edit{dropK, nil}, + [][]schedPoint{{atWalked, atChecked}, {atChecked, atClosing}}, []string{"ROOT_INVALID@0"}, 0, 2}, + {"K is bad and the final view does not name it", true, []edit{dropK}, + [][]schedPoint{{atWalked}, {atChecked}, {atClosing}}, nil, 1, 1}, } { - t.Run(tc.name, func(t *testing.T) { - fx := newVerifyFixture(t, "v1") - h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) - k := h1.Chunks[0].Key - fidK := fx.fid(k) - var h2 storage.ChunkHead - // The owner moves chunk K from index 0 to index 1 (index 0 and - // the old chunk 1 leave HEAD), and K is damaged. - move := func() { - h2 = fx.republish("v1", func(c map[uint64]storage.ChunkRef) { - c[1] = c[0] - delete(c, 0) - }) - tc.damage(fx, k) - } - opts := VerifyOptions{Depth: tc.depth, BytesPerSecond: -1, RefreshInterval: time.Minute, Concurrency: 1} - cat := fx.c - if !tc.after { - // Refreshed at every opportunity: the bindings phase sees - // the move before K is checked. - cat.SetClock(tickingClock(time.Minute)) - opts.hook = func(stage string) { - if stage == verifyHookHeadWalked { - move() + for _, points := range tc.interleave { + t.Run(fmt.Sprintf("%s/%v", tc.name, points), func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + k := h1.Chunks[0] + fidK := fx.fid(k.Key) + if tc.bad { + fx.needle(fidK, dropNeedle) + } + var last storage.ChunkHead + steps := make([]func(), len(tc.edits)) + for i, e := range tc.edits { + if e == nil { + e = func(c map[uint64]storage.ChunkRef) { c[0] = k } + } + steps[i] = func() { last = fx.republish("v1", e) } + } + res := fx.schedule(fidK, steps, points) + wantClasses(t, tc.name, res, tc.want...) + for _, f := range res.Findings { + if f.Root != headLabel(last.Gen) || f.Key == "" { + t.Fatalf("finding %+v; want under %q (the final HEAD view)", f, headLabel(last.Gen)) } } - } else { - // No refresh until K's read has failed (one reader: K, at - // index 0, is read completely before the old chunk 1), then - // time passes and the pass refreshes after that batch. - clock := &manualClock{now: time.Now()} - moveFirst := &beforeRead{Blobs: fx.cb, fid: fidK, fn: move} - thenAdvance := &beforeRead{Blobs: moveFirst, fid: fx.fid(h1.Chunks[1].Key), fn: func() { clock.advance(time.Hour) }} - var err error - if cat, err = NewCatalog(manifestFilerBlobs{fx.f, thenAdvance}, catBase); err != nil { - t.Fatal(err) + if res.SupersededDuringVerify != tc.superseded || res.RootDeletedDuringVerify != 0 { + t.Fatalf("superseded %d, root deleted %d; want %d, 0", res.SupersededDuringVerify, res.RootDeletedDuringVerify, tc.superseded) } - cat.SetClock(clock.read) - } - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - defer cancel() - res, err := cat.Verify(ctx, "v1", opts) - if err != nil || !res.Complete { - t.Fatalf("verify: %v, %+v", err, res) - } - wantClasses(t, tc.name, res, tc.want) - if res.Findings[0].Root != headLabel(h2.Gen) || res.SupersededDuringVerify != 1 { - t.Fatalf("finding under %q, superseded %d; want under %q (the index 0 reference superseded)", - res.Findings[0].Root, res.SupersededDuringVerify, headLabel(h2.Gen)) - } - if len(res.HeadGens) != 2 || res.HeadGens[0] != h1.Gen || res.HeadGens[1] != h2.Gen { - t.Fatalf("covered gens %v, want [%d %d]", res.HeadGens, h1.Gen, h2.Gen) - } - if n := fx.cb.reads(fidK); n != tc.reads { - t.Fatalf("chunk K read %d times, want %d", n, tc.reads) - } - }) + if res.HeadGens[len(res.HeadGens)-1] != last.Gen { + t.Fatalf("covered gens %v; want the last one %d", res.HeadGens, last.Gen) + } + // One check per chunk, however often HEAD names it again. + if n := fx.cb.reads(fidK); n != 1 { + t.Fatalf("chunk K read %d times, want once", n) + } + }) + } } } +// A publish that lands while the pass makes its closing read is not missed: +// the read names a chunk not seen before, so the pass checks it and reads +// again; a bad new chunk is a finding, not a clean pass. +func TestVerify_PublishDuringClosingReadIsChecked(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h1 := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + var h2 storage.ChunkHead + steps := []func(){func() { + h2 = fx.publish("v1", map[uint64][]byte{2: verifyData(3)}, true) + fx.needle(fx.fid(h2.Chunks[2].Key), dropNeedle) + }} + res := fx.schedule(fx.fid(h1.Chunks[0].Key), steps, []schedPoint{atClosing}) + wantClasses(t, "publish during the closing read", res, "NEEDLE_MISSING@2") + if res.Findings[0].Root != headLabel(h2.Gen) || fx.cb.reads(fx.fid(h2.Chunks[2].Key)) != 1 { + t.Fatalf("finding %+v, new chunk read %d times; want under %q, read once", res.Findings[0], fx.cb.reads(fx.fid(h2.Chunks[2].Key)), headLabel(h2.Gen)) + } + if len(res.HeadGens) != 2 || res.HeadGens[1] != h2.Gen { + t.Fatalf("covered gens %v, want [%d %d]", res.HeadGens, h1.Gen, h2.Gen) + } +} + +// An owner that publishes a new chunk before every closing read keeps the +// pass from closing: after ClosingRounds such reads the result is +// incomplete (never clean), with its reason and the findings computed from +// what was checked. +func TestVerify_ClosingRoundsExhaustedIsIncomplete(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + fx.needle(fx.fid(h.Chunks[0].Key), dropNeedle) + reads := 0 + opts := VerifyOptions{Depth: VerifyData, BytesPerSecond: -1} + opts.hook = func(stage string) { + if stage == verifyHookClosingRead { + reads++ + fx.publish("v1", map[uint64][]byte{uint64(2 + reads): verifyData(byte(10 + reads))}, true) + } + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + res, err := fx.c.Verify(ctx, "v1", opts) + if CodeOf(err) != CodeVerifyIncomplete || res.Complete || res.Incomplete != VerifyIncompleteRounds { + t.Fatalf("verify: %v, complete %v, incomplete %q; want %s, incomplete for the closing rounds", err, res.Complete, res.Incomplete, CodeVerifyIncomplete) + } + if reads != DefaultVerifyClosingRounds { + t.Fatalf("%d closing reads, want %d", reads, DefaultVerifyClosingRounds) + } + wantClasses(t, "partial findings", res, "NEEDLE_MISSING@0") +} + // retagSnapshot rewrites one field of the document of the attempt snapshot // name resolves to, leaving it otherwise valid. func (fx *verifyFixture) retagSnapshot(vol, name, field, value string) string { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index f1bc754528..b434359129 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -362,7 +362,7 @@ with a separate scope/config-bound mark. Incomplete marks carry no coverage. ## Part B. Invariant ledger -132 `INV-` rows: 113 ACTIVE, 17 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 117 new. One further row, `PROGRESS-DESTRUCTIVE`, has no `INV-` ID. +137 `INV-` rows: 117 ACTIVE, 18 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 122 new. One further row, `PROGRESS-DESTRUCTIVE`, has no `INV-` ID. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -478,6 +478,7 @@ Notes: | `INV-WS-HEAD-BELT-001` | A takeover confirms its exact HEAD before serving. The supported single-serialization-point mode has W=0; explicit experimental cooling requires W >= the 2 s HEAD operation deadline plus 100 ms settling. Each CAS and confirmation has its own 2 s deadline. A successful cut CAS requires readback before remoteLSN/map settlement and intent cleanup. Unconfirmed roots remain protected through Close; an observed different publication owner fences without retry, even after epoch regression or when the original HEAD was empty. | M4 Claiming → Cooling → Holder; M5 CAS → Confirmed or Pending/Fenced | `core/storage/chunk_head_belt.go`; `chunk_restore.go` `ClaimChunkHead`; `chunk_layer.go` `captureLocked`, `resolvePending`, `SettleDetach`, `dropIntents`, `Close` | `TestHeadBeltTakeoverRefusesLateOldCAS`; `TestHeadBeltTakeoverWaitsBeforeConfirmation`; `TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier`; `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`; `TestHeadBeltEmptyBaseForeignPublicationFences`; `TestHeadBeltSinglePointHasNoCoolingDelay`; `TestHeadBeltOperationsHaveOwnDeadline`; `TestHeadBeltCoolingWindowCoversCASAndSettle` (`core/storage/chunk_head_belt_test.go`) | `WorkspaceTakeover` belt extension pending | ACTIVE | | `INV-WS-HEAD-CAS-001` | Every HEAD publish is conditional on `{gen, epoch}` at one serialization point. A conflicting observed owner fences the publisher. Multiple independent filer serialization points are not made atomic by readback. | M4 Holder → Fenced | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `supersededBy`, `captureLocked` | `TestChunkRemote_TakeoverRefusesOldHolder` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_FencedOnTakeover` (`core/storage/chunk_layer_contract_test.go`); `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`) | `WorkspaceTakeover` `NoOldCasAfterTakeover` | ACTIVE | | `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkRemote_EpochNeverLowers` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkCut_RemoteLSNNeverDecreases` (`core/storage/chunk_layer_lsn_order_test.go`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`); `TestNativeReplacementCutBehindHEADRefuses` (`core/storage/legacy_replacement_v3_test.go`) | `WorkspaceTakeover` `HeadMonotone` | ACTIVE | +| `INV-WS-HEAD-KEY-PROVENANCE-001` | Every key a HEAD names is named by its predecessor HEAD or was uploaded by this owner under an intent that rooted it until the CAS settled; a key that left every root is never named again. | M5 Manifest → CAS | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | — | — | STUB | | `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its intents stay. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestChunkRemote_UncertainCASIsNotPrecondition` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestClaimChunkHeadSettlesUnknownWithoutReplay` (`core/storage/chunk_restore_test.go`); `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | — | ACTIVE | | `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE | | `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | @@ -495,6 +496,7 @@ Notes: - `INV-WS-HEAD-CAS-001`: The integration test needs build tag `chunkstore_integration` and a pinned `weed` binary. - `INV-WS-CAS-UNKNOWN-001`: An unknown-outcome CAS is not in the TLA+ models (`docs/spec/README.md`, Limits). +- `INV-WS-HEAD-KEY-PROVENANCE-001`: No test asserts it yet in this change. Verify reports a violation it observes during a pass (a key HEAD named, then dropped, then named again is `ROOT_INVALID`): `TestVerify_SchedulesGiveTheSameFindings` (`core/frontend/chunkstore/verify_test.go`), the named-again cases. - `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model. Extended for a new holder that dies between its grant and its HEAD claim: the move issue starts its lease, admission uses that grant's lease, HEAD is read after admission, an older-epoch HEAD is accepted (its generation and remote LSN may have moved by an earlier holder's late claim), and a returning holder is refused by two fences, its lease-gated attach and the higher HEAD epoch. `WorkspaceTakeover` models one move from A to B and does not cover a second move away from an unclaimed grant; that model check is open and not claimed here. - `INV-WS-LOST-RANGE-READOUT-001`: The HEAD time is the HEAD filer entry's mtime from the filer's `Last-Modified` header on the same read as the HEAD content (1 s resolution). chunkstore writes that mtime from the clock of the host that wrote the entry (the cut); the readout labels it "(publishing host clock as recorded in the filer, 1 s resolution)", and it is not a master time; there is no HEAD format change. The HEAD times sit beside the v1 ranges in the lost-range file with their own checksum, so a binary that predates them still verifies the file; a record without one reads as unknown. The readout reads the ranges loaded at startup: damage after startup shows at the next load. The no-HEAD form ("no remote image exists") is defensive: the master refuses a forced move without a published HEAD. The header is checked against test HTTP servers only; the `chunkstore_integration` test does not assert it. Not in the TLA+ models. - `INV-WS-FORCED-CONFIRM-001`: A client-side rule: the master's own guards (explicit force, admission, expected epoch) are `INV-WS-FORCED-MOVE-001`. The holder's logical replica id is read from `QueryWorkspace` (the lease, or the journal on a rerun). @@ -551,9 +553,13 @@ Notes: | `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | | `INV-VERIFY-READONLY-001` | Verify writes nothing to the filer or the blob store at any depth: no intent, mark, tombstone, binding or needle. | M6 (reader; no transition) | `core/frontend/chunkstore/verify.go` `Catalog.Verify` | `TestVerify_ReadOnlyAtEveryDepth` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-RECHECK-001` | Verify reports a miss only if its root still names the chunk at the recheck: under HEAD, the current HEAD names the key at that index; under a snapshot, the attempt its name record names is published and not deleting. A root is identified by the name it was looked up by, not by its document. | M6 (reader beside GC mark) | `core/frontend/chunkstore/verify.go` `Catalog.Verify` | `TestVerify_SupersededDuringPass`, `TestVerify_SnapshotDeletedDuringPass`, `TestVerify_SharedChunkReportedUnderStillNamingRoot`, `TestVerify_SnapshotDocumentNamingAnotherSnapshot` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-RECHECK-001` | Verify reports a bad chunk only if a root names it at the final read (HEAD, then the selected snapshots still published under the name they were looked up by); a bad chunk no root names then is counted, not reported. | M6 (reader beside GC mark) | `core/frontend/chunkstore/verify.go` `round`, `reconcile` | `TestVerify_SupersededDuringPass`, `TestVerify_SnapshotDeletedDuringPass`, `TestVerify_SharedChunkReportedUnderStillNamingRoot`, `TestVerify_SnapshotDocumentNamingAnotherSnapshot`, `TestVerify_SchedulesGiveTheSameFindings` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-ONE-READ-001` | Verify checks each distinct chunk at most once per pass: a settled chunk is never checked again, however often a root names it again. | M6 (reader) | `core/frontend/chunkstore/verify.go` `discover`, `settle` | `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_DedupSharedChunkReadOnce`, `TestVerify_HeadRefreshRewalksChangedSegments` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-NAMED-HAVE-OUTCOME-001` | In a complete pass every chunk the final view names has a settled outcome: the final view is a closing read that names no chunk the pass had not seen. | M6 (reader) | `core/frontend/chunkstore/verify.go` `run`, `round` | `TestVerify_PublishDuringClosingReadIsChecked`, `TestVerify_SchedulesGiveTheSameFindings` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-REPORT-ONCE-001` | A complete pass yields at most one finding per chunk key and class, computed only at Reconcile from the chunk outcomes and the final view. | M6 (reader) | `core/frontend/chunkstore/verify.go` `reconcile` | `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_TwoWrongReferencesAreOneFinding`, `TestVerify_SameKeyWithAnotherHashIsAFinding` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-NO-FALSE-CLEAN-001` | In a complete pass, a chunk the final view names that was bad when checked, or whose key HEAD dropped earlier in the pass and names again, has a finding. | M6 (reader) | `core/frontend/chunkstore/verify.go` `refresh`, `reconcile` | `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_PublishDuringClosingReadIsChecked` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-CLOSE-BOUND-001` | A pass closes on a closing read that names no chunk it had not seen, within `ClosingRounds` such reads (default 3); otherwise its result is incomplete, with that reason, never clean. | M6 (reader) | `core/frontend/chunkstore/verify.go` `run`, `Catalog.Verify` | `TestVerify_ClosingRoundsExhaustedIsIncomplete` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | | `INV-VERIFY-NOTFOUND-001` | Verify reports `NEEDLE_MISSING` only when the blob store answers that the needle does not exist (for SeaweedFS, every location of a fresh volume lookup answers 404); any other read failure is retried and then reported as `READ_ERROR`, which means not verified. | M6 (reader) | `core/frontend/chunkstore/verify.go` `Catalog.Verify`; `core/frontend/chunkstore/swfs.go` `Get` (`ErrBlobNotFound`) | `TestVerify_PersistentReadErrorIsNotAMissingNeedle`, `TestVerify_TransientReadIsRetried`, `TestSWFS_GetNotFoundIsErrBlobNotFound`, `TestSWFS_GetStaleCachedLocationLooksUpAgain`, `TestVerify_MovedVolumeIsNotAMissingNeedle` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-COVERAGE-001` | Every chunk reference of every root the result lists, refreshed HEADs included, is checked at the pass's depth: each distinct chunk is read at most once, and its outcome (content, miss or read error) applies to every reference to it, later ones included. | M6 (reader) | `core/frontend/chunkstore/verify.go` `addUses`, `compareRefs`, `readChunk`, `miss` | `TestVerify_SameKeyWithAnotherHashIsAFinding`, `TestVerify_OutcomeAppliesToRefreshedReferences`, `TestVerify_HeadRefreshRewalksChangedSegments`, `TestVerify_DedupSharedChunkReadOnce` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | | `INV-VERIFY-CANCEL-001` | A failed dispatch of chunk reads (a filer error, or the caller's context ending) cancels the reads in progress before joining them, and Verify returns the originating error. | M6 (reader) | `core/frontend/chunkstore/verify.go` `checkData` | `TestVerify_FailedRefreshCancelsReadInProgress`, `TestVerify_CancelDuringReadJoinsReaders` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | Notes: From d49b5c5fca3f4c382d0a31f846bc1c6ad0a63b8f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:18:58 -0800 Subject: [PATCH 13/34] invariants: condense the two new statement cells to 300 characters; detail in the notes Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index b6ed420d15..27e557b315 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -527,11 +527,13 @@ Notes: | `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | | `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | -| `INV-SHARE-ACTIVATION-001` | With a `ShareGuard` installed, a snapshot activates (writes its snapshot entry) and a fork activates (writes the child HEAD) only after `Finish` accepted the share for that HEAD; a refused `Begin` or `Finish` aborts before activation and drops the new intent, and the owner's seal calls `Begin` before the cut that produces the sealed HEAD (a refused `Begin` cuts nothing). With no guard, no call and no check is added. | M6 snapshot: Pending → Published; fork: child HEAD create | `core/frontend/chunkstore/share_guard.go` `beginShare`, `finishShare`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `Fork`; `core/host/volume/chunk_control.go` `chunkControl.Snapshot` | `TestShareGuard_SnapshotFinishesBeforeActivation`, `TestShareGuard_RefusedFinishAbortsTheSnapshot`, `TestShareGuard_StaleHeadIsRefused`, `TestShareGuard_CallerToken`, `TestShareGuard_Fork`, `TestShareGuard_BeginRefused` (`core/frontend/chunkstore/share_guard_test.go`); `TestChunkControl_SnapshotBeginsShareBeforeTheCut`, `TestChunkControl_SnapshotBeginRefusedCutsNothing` (`core/host/volume/chunk_control_order_test.go`) | — (the enterprise policy's protocol is modelled in `ShareMarker`) | ACTIVE | -| `INV-PUBLISH-SETTLED-001` | With `OnPublishSettled` set, each confirmed publication (HEAD prev → next with a new generation: a cut, a detach, or an earlier unresolved CAS found applied) is delivered once, in publication order, one at a time, outside the capture and state locks, by one registered drainer. Once Close has begun no report is dequeued; a report already dequeued may still reach the hook. A no-op cut reports nothing; with no hook nothing is queued. | M5 CAS → Settled; M6 HEAD: published | `core/storage/chunk_publish_settled.go` `noteSettled`, `unlockCap`, `runPublishSettled`; `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince` | `TestChunkPublishSettled_ReportsEachPublication`, `TestChunkPublishSettled_ReportsALatePublication`, `TestChunkPublishSettled_ClosedAndUnset`, `TestChunkPublishSettled_OverlappingPublishersStayOrdered`, `TestChunkPublishSettled_CloseDropsUnstartedReports`, `TestChunkPublishSettled_HookThatPublishes`, `TestChunkPublishSettled_PeriodicCutReports` (`core/storage/chunk_publish_settled_test.go`); `TestWALStoreChunk_PublishSettledHook` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE | +| `INV-SHARE-ACTIVATION-001` | With a `ShareGuard` installed, a snapshot or fork activates (snapshot entry, child HEAD) only after `Finish` accepts the share; a refused `Begin` or `Finish` aborts before activation and drops the new intent. With no guard, nothing is called or checked. | M6 snapshot: Pending → Published; fork: child HEAD create | `core/frontend/chunkstore/share_guard.go` `beginShare`, `finishShare`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `Fork`; `core/host/volume/chunk_control.go` `chunkControl.Snapshot` | `TestShareGuard_SnapshotFinishesBeforeActivation`, `TestShareGuard_RefusedFinishAbortsTheSnapshot`, `TestShareGuard_StaleHeadIsRefused`, `TestShareGuard_CallerToken`, `TestShareGuard_Fork`, `TestShareGuard_BeginRefused` (`core/frontend/chunkstore/share_guard_test.go`); `TestChunkControl_SnapshotBeginsShareBeforeTheCut`, `TestChunkControl_SnapshotBeginRefusedCutsNothing` (`core/host/volume/chunk_control_order_test.go`) | — (the enterprise policy's protocol is modelled in `ShareMarker`) | ACTIVE | +| `INV-PUBLISH-SETTLED-001` | With `OnPublishSettled` set, each confirmed publication (a new HEAD generation) is delivered once, in publication order, one at a time, outside the capture and state locks. After Close begins, no report is dequeued. | M5 CAS → Settled; M6 HEAD: published | `core/storage/chunk_publish_settled.go` `noteSettled`, `unlockCap`, `runPublishSettled`; `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince` | `TestChunkPublishSettled_ReportsEachPublication`, `TestChunkPublishSettled_ReportsALatePublication`, `TestChunkPublishSettled_ClosedAndUnset`, `TestChunkPublishSettled_OverlappingPublishersStayOrdered`, `TestChunkPublishSettled_CloseDropsUnstartedReports`, `TestChunkPublishSettled_HookThatPublishes`, `TestChunkPublishSettled_PeriodicCutReports` (`core/storage/chunk_publish_settled_test.go`); `TestWALStoreChunk_PublishSettledHook` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE | Notes: +- `INV-SHARE-ACTIVATION-001`: the owner's seal calls `Begin` before the cut that produces the sealed HEAD, so a refused `Begin` cuts nothing. +- `INV-PUBLISH-SETTLED-001`: a publication is a cut, a detach, or an earlier unresolved CAS found applied; a no-op cut reports nothing, and with no hook nothing is queued. One registered drainer delivers; a report already dequeued when Close begins may still reach the hook, and Close waits for it. - `INV-GC-GRACE-DEADLINE-001`: The check is in `NewCollector`; no Go test constructs a collector with a too-short grace. - `ChunkRemote.ReclaimKey` is the Collector's per-key step (`reclaimBinding`) exported, not a new admission: `INV-GC-REACHABLE-001` (reachability and the two-mark grace) stays the Collector's, and a `ReclaimKey` caller must itself know nothing references the key. The step keeps `INV-CHUNK-WRITE-ONCE-001`: the binding is tombstoned, its exact fid deleted, and the binding kept for ever, never rebound; owner-qualified keys are refused. From 29c81a1dca5cf7db39bc59a0e6ee0bf44e88b139 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:23:16 -0800 Subject: [PATCH 14/34] storage: OwnBatch bounded re-own cut and a byte-paced walker (restore part B) OwnBatch(n, foreign) runs one ordinary cut whose candidates include up to n local chunks whose HEAD keys name another volume; streamCutPayloads uploads each under a new own key even when its bytes equal HEAD's, and the cut's one intent and HEAD CAS publish them (M6.Restore.Owning>Owning). An absent chunk is never fetched by a batch; with nothing to own no cut runs. HydrateAllAt paces the walker to a byte rate before admission (HydrateAll = unpaced). Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_cut_payload.go | 2 +- .../core/storage/chunk_hydrate_all.go | 25 +++++ .../core/storage/chunk_hydrate_all_test.go | 17 ++++ seaweed-block/core/storage/chunk_layer.go | 12 ++- seaweed-block/core/storage/chunk_own.go | 96 +++++++++++++++++++ seaweed-block/core/storage/chunk_own_test.go | 96 +++++++++++++++++++ 6 files changed, 246 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_own.go create mode 100644 seaweed-block/core/storage/chunk_own_test.go diff --git a/seaweed-block/core/storage/chunk_cut_payload.go b/seaweed-block/core/storage/chunk_cut_payload.go index 3cac8535be..6e66f07433 100644 --- a/seaweed-block/core/storage/chunk_cut_payload.go +++ b/seaweed-block/core/storage/chunk_cut_payload.go @@ -58,7 +58,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64, return err } ref, had := head.Chunks[c.idx] - if !c.zero && !(had && ref.SHA256 == c.sum) { + if !c.zero && !(had && ref.SHA256 == c.sum && !l.owning(c.idx)) { c.key, c.size = keys[i], len(c.data) once.Do(func() { intent, intentErr = l.remote.PutIntent(ctx, chunkIntent{Gen: head.Gen, Epoch: l.cfg.Epoch, Holder: l.cfg.Holder, Keys: keys}) diff --git a/seaweed-block/core/storage/chunk_hydrate_all.go b/seaweed-block/core/storage/chunk_hydrate_all.go index 5655491ec5..17fae0e4b3 100644 --- a/seaweed-block/core/storage/chunk_hydrate_all.go +++ b/seaweed-block/core/storage/chunk_hydrate_all.go @@ -47,7 +47,16 @@ var ( // or on a fill error that is not a retryable pending state; the caller may // call it again. func (l *chunkLayerImpl) HydrateAll(ctx context.Context) (HydrateProgress, error) { + return l.HydrateAllAt(ctx, 0) +} + +// HydrateAllAt is HydrateAll paced to at most bytesPerSecond of fill payload +// (one chunk per fill), counted from its start; 0 means unpaced. The pace +// applies before admission, so a paced walker holds no permit while it waits. +func (l *chunkLayerImpl) HydrateAllAt(ctx context.Context, bytesPerSecond int64) (HydrateProgress, error) { var p HydrateProgress + start := time.Now() + started := int64(0) // fills started, for the pace walk, stop := context.WithCancelCause(ctx) defer stop(nil) backoff := hydrateAllMinBackoff @@ -89,6 +98,21 @@ func (l *chunkLayerImpl) HydrateAll(ctx context.Context) (HydrateProgress, error } continue } + if bytesPerSecond > 0 && started > 0 { + due := start.Add(time.Duration(float64(started*int64(l.chunkBlocks)*int64(l.blockSize)) / float64(bytesPerSecond) * float64(time.Second))) + if d := time.Until(due); d > 0 { + t := time.NewTimer(d) + select { + case <-t.C: + case <-walk.Done(): + t.Stop() + return quit(context.Cause(walk)) + case <-l.ctx.Done(): + t.Stop() + return quit(errChunkLayerClosed) + } + } + } release, err := l.admitFill(walk, stop) if err != nil { p.Deferred++ @@ -110,6 +134,7 @@ func (l *chunkLayerImpl) HydrateAll(ctx context.Context) (HydrateProgress, error if f == nil { continue // resolved meanwhile } + started++ select { case <-f.done: case <-walk.Done(): diff --git a/seaweed-block/core/storage/chunk_hydrate_all_test.go b/seaweed-block/core/storage/chunk_hydrate_all_test.go index b184105503..34e981ea67 100644 --- a/seaweed-block/core/storage/chunk_hydrate_all_test.go +++ b/seaweed-block/core/storage/chunk_hydrate_all_test.go @@ -406,3 +406,20 @@ func TestHydrateAll_StatsReportAbsentChunks(t *testing.T) { t.Fatalf("absent after the walk: %d, want 0", n) } } + +// The walker's byte pace bounds the fill rate: 8 chunks at 4 chunks/s take +// at least (8-1)/4 s. +func TestHydrateAll_PacedByByteRate(t *testing.T) { + fastWalker(t) + _, layer, _, _ := hydrationFixture(t, 2, 64) + rate := int64(4 * ctChunkBytes) + start := time.Now() + p, err := layer.HydrateAllAt(boundedCtx(t, context.Background()), rate) + took := time.Since(start) + if err != nil || p.Remaining != 0 { + t.Fatalf("paced walk: %+v %v", p, err) + } + if min := time.Duration(p.Filled-1) * time.Second / 4; took < min { + t.Fatalf("%d fills at %d B/s took %v, want at least %v", p.Filled, rate, took, min) + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 3ed9ec97b5..f98da1e83f 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -116,6 +116,9 @@ type chunkLayerImpl struct { dirty map[uint64]bool // chunks dirtied since the cut in progress or the last HEAD inflight map[uint64]bool // chunks captured by a cut whose HEAD is not yet installed allDirty bool // a BASE block landed: every chunk is dirty + // own names the chunks OwnBatch re-uploads under this layer's own keys in + // the cut it runs (set and cleared under capMu, read under stMu). + own map[uint64]bool cutLSN uint64 // H of the latest cut taken (in flight or installed) // chunkMut counts the mutations of each chunk: every dirty-map insert @@ -850,6 +853,11 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch candidates[i] = true } } + for idx := range l.own { + if !l.absent[idx] { // a re-own reads the local copy, never fetches + candidates[idx] = true + } + } // A staged chunk stands for the barrier copy while no write reached // it since staging (its version is unchanged) and HEAD is the one it // was compared against. @@ -973,7 +981,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch c.birth = births[c.idx] ref, had := baseHead.Chunks[c.idx] switch { - case c.zero && !had, had && !c.zero && ref.SHA256 == c.sum: + case c.zero && !had, had && !c.zero && ref.SHA256 == c.sum && c.key == "": + // A chunk equal to HEAD is skipped unless streamCutPayloads + // uploaded it under a new key: a re-owned chunk (OwnBatch). st.UnchangedChunks++ continue case c.zero: diff --git a/seaweed-block/core/storage/chunk_own.go b/seaweed-block/core/storage/chunk_own.go new file mode 100644 index 0000000000..e86ebd408a --- /dev/null +++ b/seaweed-block/core/storage/chunk_own.go @@ -0,0 +1,96 @@ +package storage + +import ( + "context" + "sort" +) + +// OwnProgress reports one OwnBatch call. +// - Owned: foreign chunks this call's cut re-uploaded under own keys. +// - Remaining: chunks HEAD still names with a foreign key after the call. +// - NotLocal: of those, chunks not local yet (the hydrate walker fills them). +type OwnProgress struct { + Owned int + Remaining int + NotLocal int +} + +// OwnBatch runs one bounded cut (M6.Restore.Owning>Owning): it picks up to n +// chunks, lowest index first, whose HEAD key is foreign (foreign reports +// whether a key names another volume's object) and that are local, and cuts +// with them as candidates: each is uploaded under a new own key under the +// cut's intent and published by the cut's one HEAD CAS, even when its bytes +// equal HEAD's. Absent chunks are skipped (never fetched by the cut). The cut +// is an ordinary cut, so guest writes since the last HEAD go with it. With +// nothing to own it runs no cut. A failed cut leaves HEAD as it was; the next +// call picks again from the current HEAD. +func (l *chunkLayerImpl) OwnBatch(ctx context.Context, n int, foreign func(key string) bool) (OwnProgress, error) { + l.capMu.Lock() + defer l.capMu.Unlock() + l.stMu.Lock() + var picked []uint64 + for _, idx := range sortedForeign(l.head.Chunks, foreign) { + if len(picked) < n && !l.absent[idx] { + picked = append(picked, idx) + } + } + if len(picked) == 0 { + p := l.ownProgressLocked(foreign) + l.stMu.Unlock() + return p.OwnProgress, nil + } + l.own = make(map[uint64]bool, len(picked)) + for _, idx := range picked { + l.own[idx] = true + } + l.stMu.Unlock() + _, err := l.captureLocked(ctx, false) + l.stMu.Lock() + l.own = nil + p := l.ownProgressLocked(foreign) + l.stMu.Unlock() + if err == nil { + for _, idx := range picked { + if ref, ok := p.head[idx]; !ok || !foreign(ref.Key) { + p.Owned++ + } + } + } + return p.OwnProgress, err +} + +type ownCount struct { + OwnProgress + head map[uint64]chunkRef +} + +// ownProgressLocked counts HEAD's foreign chunks. Caller holds stMu. +func (l *chunkLayerImpl) ownProgressLocked(foreign func(string) bool) ownCount { + c := ownCount{head: l.head.Chunks} + for _, idx := range sortedForeign(l.head.Chunks, foreign) { + c.Remaining++ + if l.absent[idx] { + c.NotLocal++ + } + } + return c +} + +func sortedForeign(chunks map[uint64]chunkRef, foreign func(string) bool) []uint64 { + var out []uint64 + for idx, ref := range chunks { + if foreign(ref.Key) { + out = append(out, idx) + } + } + sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) + return out +} + +// owning reports whether chunk idx is re-owned by the running OwnBatch cut: +// it is uploaded under a new own key even when its bytes equal HEAD's. +func (l *chunkLayerImpl) owning(idx uint64) bool { + l.stMu.Lock() + defer l.stMu.Unlock() + return l.own[idx] +} diff --git a/seaweed-block/core/storage/chunk_own_test.go b/seaweed-block/core/storage/chunk_own_test.go new file mode 100644 index 0000000000..fa986a0df5 --- /dev/null +++ b/seaweed-block/core/storage/chunk_own_test.go @@ -0,0 +1,96 @@ +package storage + +import ( + "bytes" + "context" + "strings" + "testing" +) + +func seedForeign(key string) bool { return strings.HasPrefix(key, "seed/") } + +func ownCtx(t *testing.T) context.Context { return boundedCtx(t, context.Background()) } + +// M6.Restore.Owning>Owning: each batch is one cut that re-uploads at most n +// foreign chunks under own keys, the image unchanged, until none is left. +func TestOwnBatch_BoundedBatchesReplaceEveryForeignKey(t *testing.T) { + fastWalker(t) + _, layer, remote, _ := hydrationFixture(t, 2, 64) + before := remote.stats() + want := remote.imageOf(t, before.head) + if p, err := layer.HydrateAll(ownCtx(t)); err != nil || p.Remaining != 0 { + t.Fatalf("hydrate: %+v %v", p, err) + } + total := ctNumBlocks / ctChunkBlocks + left := total + for left > 0 { + puts := remote.stats().puts + cas := remote.stats().cas + p, err := layer.OwnBatch(ownCtx(t), 3, seedForeign) + if err != nil { + t.Fatal(err) + } + step := min(3, left) + if p.Owned != step || p.Remaining != left-step || p.NotLocal != 0 { + t.Fatalf("batch: %+v, want %d owned and %d remaining", p, step, left-step) + } + if got := remote.stats().puts - puts; got != step { + t.Fatalf("batch uploaded %d chunks, want exactly %d (bounded)", got, step) + } + if got := remote.stats().cas - cas; got != 1 { + t.Fatalf("batch made %d HEAD CAS, want one", got) + } + left -= step + } + after := remote.stats().head + for idx, ref := range after.Chunks { + if seedForeign(ref.Key) { + t.Fatalf("chunk %d still foreign after the last batch: %s", idx, ref.Key) + } + } + if !bytes.Equal(remote.imageOf(t, after), want) { + t.Fatal("owning changed the volume image") + } + cas := remote.stats().cas + if p, err := layer.OwnBatch(ownCtx(t), 3, seedForeign); err != nil || p != (OwnProgress{}) || remote.stats().cas != cas { + t.Fatalf("nothing left to own must run no cut: %+v %v", p, err) + } +} + +// A chunk not local yet is never fetched by a batch: it waits for the walker. +func TestOwnBatch_SkipsChunksNotLocal(t *testing.T) { + _, layer, remote, _ := hydrationFixture(t, 2, 64) + before := remote.stats() + p, err := layer.OwnBatch(ownCtx(t), 3, seedForeign) + total := ctNumBlocks / ctChunkBlocks + if err != nil || p.Owned != 0 || p.Remaining != total || p.NotLocal != total { + t.Fatalf("batch before any hydration: %+v %v", p, err) + } + after := remote.stats() + if after.cas != before.cas || after.gets != before.gets { + t.Fatalf("a batch with nothing local cut or fetched: cas %d->%d gets %d->%d", before.cas, after.cas, before.gets, after.gets) + } +} + +// A batch is an ordinary cut: a guest write since the last HEAD goes with it. +func TestOwnBatch_CarriesGuestWrites(t *testing.T) { + fastWalker(t) + s, layer, remote, _ := hydrationFixture(t, 2, 64) + if _, err := layer.HydrateAll(ownCtx(t)); err != nil { + t.Fatal(err) + } + if _, err := s.Write(ctChunkBlocks*6+1, makeBlock(ctBlockSize, 0xAB)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if _, err := layer.OwnBatch(ownCtx(t), 2, seedForeign); err != nil { + t.Fatal(err) + } + img := remote.imageOf(t, remote.stats().head) + off := (ctChunkBlocks*6 + 1) * ctBlockSize + if !bytes.Equal(img[off:off+ctBlockSize], makeBlock(ctBlockSize, 0xAB)) { + t.Fatal("the guest write did not reach HEAD with the batch") + } +} From 8a886ff6da58ef7b255022f02898a089ddce3bed Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:23:16 -0800 Subject: [PATCH 15/34] restore: driver, /chunk/restore and sw-block ops chunk restore (part B) The driver walks (64 MiB/s, BackgroundFill), cuts bounded batches (64 chunks) until no foreign ref is left, then writes RESTORE-INDEPENDENT (M6.Restore Restoring>Hydrating>Owning>Owning>Independent). It decides only from the target's VOLUME, HEAD and marker, so a rerun resumes from the remote state and a deleted source is a normal state. POST /chunk/restore starts or joins one background run per volume and returns its status; GET (or statusOnly) reports it; sw-block ops chunk restore calls it. Docs: M6 restore rows, INV-RESTORE-OWN-BATCH-001 and INV-RESTORE-DRIVER-001, the restore quantities, the workspace design diagram. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/chunk.go | 4 +- seaweed-block/cmd/sw-block/chunk_restore.go | 30 ++ .../cmd/sw-block/chunk_restore_test.go | 39 +++ .../core/frontend/durable/provider_restore.go | 51 ++++ .../core/host/volume/chunk_control.go | 6 +- .../core/host/volume/chunk_restore.go | 234 ++++++++++++++ .../core/host/volume/chunk_restore_test.go | 287 ++++++++++++++++++ .../docs/design/agent-workspace-design.md | 8 +- seaweed-block/docs/design/invariants.md | 12 +- 9 files changed, 662 insertions(+), 9 deletions(-) create mode 100644 seaweed-block/cmd/sw-block/chunk_restore.go create mode 100644 seaweed-block/cmd/sw-block/chunk_restore_test.go create mode 100644 seaweed-block/core/frontend/durable/provider_restore.go create mode 100644 seaweed-block/core/host/volume/chunk_restore.go create mode 100644 seaweed-block/core/host/volume/chunk_restore_test.go diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go index 80cc5f67ad..9b604371f0 100644 --- a/seaweed-block/cmd/sw-block/chunk.go +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -44,7 +44,7 @@ var dialChunkFiler = func(addr string) (chunkstore.Filer, func() error, error) { func runOpsChunk(args []string, stdout, stderr io.Writer) int { if len(args) == 0 { - return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show|gc|usage|retain|volume-delete", false) + return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show|gc|usage|retain|volume-delete|restore", false) } switch args[0] { case "gc": @@ -69,6 +69,8 @@ func runOpsChunk(args []string, stdout, stderr io.Writer) int { return chunkRetain(args[1:], stdout, stderr) case "volume-delete": return chunkVolumeDelete(args[1:], stdout, stderr) + case "restore": + return chunkRestore(args[1:], stdout, stderr) default: return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, fmt.Sprintf("unknown subcommand %q", args[0]), false) } diff --git a/seaweed-block/cmd/sw-block/chunk_restore.go b/seaweed-block/cmd/sw-block/chunk_restore.go new file mode 100644 index 0000000000..4a94e2f456 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_restore.go @@ -0,0 +1,30 @@ +package main + +import ( + "io" + "time" + + "github.com/seaweedfs/seaweed-block/core/ops" +) + +// chunkRestore starts (or joins) the independent-restore driver of a volume +// restored from a snapshot and prints its status; with --status it only +// prints the status. The driver runs in blockvolume and outlives this call. +func chunkRestore(args []string, stdout, stderr io.Writer) int { + fs := chunkFlagSet("restore", stderr) + var ( + volumeID, statusAddr string + statusOnly bool + ) + fs.StringVar(&volumeID, "volume", "", "restored volume id") + fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL (with --chunk-control-endpoint)") + fs.BoolVar(&statusOnly, "status", false, "print the restore status without starting a run") + if err := fs.Parse(args); err != nil { + return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + } + if volumeID == "" || statusAddr == "" { + return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --status-addr are required", false) + } + body := map[string]any{"volumeID": volumeID, "statusOnly": statusOnly} + return chunkPost("restore", statusAddr, "/chunk/restore", 30*time.Second, body, stdout, stderr) +} diff --git a/seaweed-block/cmd/sw-block/chunk_restore_test.go b/seaweed-block/cmd/sw-block/chunk_restore_test.go new file mode 100644 index 0000000000..2c9c32f1c2 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_restore_test.go @@ -0,0 +1,39 @@ +package main + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestOpsChunk_RestoreStartsAndReportsStatus(t *testing.T) { + var got []map[string]any + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/chunk/restore" || r.Method != http.MethodPost { + http.Error(w, "unexpected "+r.Method+" "+r.URL.Path, http.StatusNotFound) + return + } + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + got = append(got, body) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"volumeID":"v2","phase":"owning","running":true,"foreign":3}`)) + })) + defer srv.Close() + for _, args := range [][]string{{"restore", "--volume", "v2", "--status-addr", srv.URL}, {"restore", "--volume", "v2", "--status-addr", srv.URL, "--status"}} { + var out, errb bytes.Buffer + if code := runOpsChunk(args, &out, &errb); code != 0 || !strings.Contains(out.String(), `"phase":"owning"`) { + t.Fatalf("%v: exit %d out %q err %q", args, code, out.String(), errb.String()) + } + } + if len(got) != 2 || got[0]["volumeID"] != "v2" || got[0]["statusOnly"] != false || got[1]["statusOnly"] != true { + t.Fatalf("requests %v: want a start, then a status-only call", got) + } + var out, errb bytes.Buffer + if code := runOpsChunk([]string{"restore", "--status-addr", srv.URL}, &out, &errb); code == 0 { + t.Fatal("restore without --volume must be refused") + } +} diff --git a/seaweed-block/core/frontend/durable/provider_restore.go b/seaweed-block/core/frontend/durable/provider_restore.go new file mode 100644 index 0000000000..fde0c680aa --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_restore.go @@ -0,0 +1,51 @@ +package durable + +import ( + "context" + "fmt" + + "github.com/seaweedfs/seaweed-block/core/hostlimit" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// chunkRestorer is the chunk layer's independent-restore surface. +type chunkRestorer interface { + HydrateAllAt(ctx context.Context, bytesPerSecond int64) (storage.HydrateProgress, error) + OwnBatch(ctx context.Context, n int, foreign func(key string) bool) (storage.OwnProgress, error) +} + +func (p *DurableProvider) restorer(volumeID string) (chunkRestorer, error) { + _, layer, err := p.chunkHandle(volumeID) + if err != nil { + return nil, err + } + r, ok := layer.(chunkRestorer) + if !ok { + return nil, fmt.Errorf("durable: volume %s: chunk layer has no restore surface: %w", volumeID, ErrNotChunkVolume) + } + return r, nil +} + +// HydrateVolume makes every HEAD-named absent chunk of volumeID local +// (M6.Restore.Restoring>Hydrating), paced to bytesPerSecond, under the +// host limiter's BackgroundFill class. +func (p *DurableProvider) HydrateVolume(ctx context.Context, volumeID string, bytesPerSecond int64) (storage.HydrateProgress, error) { + r, err := p.restorer(volumeID) + if err != nil { + return storage.HydrateProgress{}, err + } + return r.HydrateAllAt(hostlimit.WithClass(ctx, hostlimit.BackgroundFill), bytesPerSecond) +} + +// OwnVolumeBatch runs one bounded cut of volumeID that re-uploads up to n +// local chunks with foreign HEAD keys under own keys +// (M6.Restore.Owning>Owning). +func (p *DurableProvider) OwnVolumeBatch(ctx context.Context, volumeID string, n int, foreign func(string) bool) (storage.OwnProgress, error) { + r, err := p.restorer(volumeID) + if err != nil { + return storage.OwnProgress{}, err + } + ctx, cancel := p.chunkCutContext(ctx) + defer cancel() + return r.OwnBatch(ctx, n, foreign) +} diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index c1e4029609..ab9dfb6499 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -231,6 +231,7 @@ func (s *StatusServer) chunkMux() http.Handler { mux.HandleFunc("/chunk/snapshots", s.handleChunkSnapshots) mux.HandleFunc("/chunk/snapshot/delete", s.handleChunkSnapshotDelete) mux.HandleFunc("/chunk/detach", s.handleChunkDetach) + mux.HandleFunc("/chunk/restore", s.handleChunkRestore) // Any other /chunk path: a typed JSON 404, like every other /chunk // error, not net/http's plain-text page. mux.HandleFunc("/chunk/", func(w http.ResponseWriter, r *http.Request) { @@ -589,8 +590,9 @@ type ChunkProvider interface { var errFrozenDetachUnsupported = errors.New("frozen detach unsupported by provider") type chunkControl struct { - p ChunkProvider - cat *chunkstore.Catalog + p ChunkProvider + cat *chunkstore.Catalog + restores restoreRuns } // NewChunkControl serves the routes from a durable provider (cut, detach) diff --git a/seaweed-block/core/host/volume/chunk_restore.go b/seaweed-block/core/host/volume/chunk_restore.go new file mode 100644 index 0000000000..eb334788df --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_restore.go @@ -0,0 +1,234 @@ +package volume + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + "sync" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Independent restore driver (M6.Restore). A restored volume serves at once; +// the driver then makes every chunk local (Restoring>Hydrating), re-uploads +// the chunks whose HEAD keys name another volume under the volume's own keys +// in bounded batch cuts (Hydrating>Owning, Owning>Owning; the walker and the +// batches may overlap), and writes the independence marker once HEAD holds +// no foreign ref (Owning>Independent). Every decision is read from the +// target's own facts (its VOLUME, HEAD and marker), never from the source, so +// a rerun after a crash resumes where the remote state is, and a deleted +// source snapshot or volume is a normal state. + +// Restore quantities (invariants.md Part E). +const ( + DefaultRestoreBatchChunks = 64 + DefaultRestoreBytesPerSecond = 64 << 20 +) + +// RestoreProvider is the chunk layer's restore surface for an attached volume. +type RestoreProvider interface { + HydrateVolume(ctx context.Context, volumeID string, bytesPerSecond int64) (storage.HydrateProgress, error) + OwnVolumeBatch(ctx context.Context, volumeID string, n int, foreign func(string) bool) (storage.OwnProgress, error) +} + +// RestoreConfig bounds one restore run; zero fields take the defaults. +type RestoreConfig struct { + BatchChunks int + BytesPerSecond int64 +} + +// Restore phases. +const ( + RestoreHydrating = "hydrating" + RestoreOwning = "owning" + RestoreIndependent = "independent" + RestoreFailed = "failed" +) + +// RestoreStatus is the body of /chunk/restore. +type RestoreStatus struct { + VolumeID string `json:"volumeID"` + Phase string `json:"phase"` + Running bool `json:"running"` + Filled int `json:"filled"` // chunks the walker made local + Owned int `json:"owned"` // chunks re-uploaded under own keys + Foreign int `json:"foreign"` // HEAD chunks still naming another volume + NotLocal int `json:"notLocal"` // of those, not local yet + Batches int `json:"batches"` // batch cuts run + MarkedGen uint64 `json:"markedGen"` // HEAD gen the marker names (independent) + ErrorCode string `json:"errorCode,omitempty"` + ErrorText string `json:"error,omitempty"` +} + +// foreignKey reports whether key names another volume's object: an +// owner-qualified key whose owner is not vol. +func foreignKey(vol string) func(string) bool { + own := "@" + vol + "/" + return func(key string) bool { return strings.HasPrefix(key, "@") && !strings.HasPrefix(key, own) } +} + +var ( + errRestoreStuck = errors.New("restore: foreign chunks remain but none is local and the walker fills none") + errNotRestore = errors.New("restore: not a restore") +) + +// runRestore drives one restore of vol to independence, reporting progress. +func runRestore(ctx context.Context, cat *chunkstore.Catalog, p RestoreProvider, vol string, cfg RestoreConfig, report func(RestoreStatus)) (RestoreStatus, error) { + if cfg.BatchChunks <= 0 { + cfg.BatchChunks = DefaultRestoreBatchChunks + } + if cfg.BytesPerSecond <= 0 { + cfg.BytesPerSecond = DefaultRestoreBytesPerSecond + } + st := RestoreStatus{VolumeID: vol, Phase: RestoreHydrating, Running: true} + if m, ok, err := cat.ReadIndependence(ctx, vol); err != nil { + return st, err + } else if ok { + st.Phase, st.MarkedGen = RestoreIndependent, m.HeadGen + return st, nil + } + v, ok, err := cat.ReadVolume(ctx, vol) + if err != nil { + return st, err + } + if !ok || v.Origin != chunkstore.OriginRestore { + return st, fmt.Errorf("volume %s was not made by restore: %w", vol, errNotRestore) + } + foreign := foreignKey(vol) + for stalls := 0; ; { + h, err := p.HydrateVolume(ctx, vol, cfg.BytesPerSecond) + st.Filled += h.Filled + report(st) + if err != nil { + return st, err + } + st.Phase = RestoreOwning + progressed := h.Filled > 0 + for { + o, err := p.OwnVolumeBatch(ctx, vol, cfg.BatchChunks, foreign) + st.Owned, st.Foreign, st.NotLocal = st.Owned+o.Owned, o.Remaining, o.NotLocal + if o.Owned > 0 { + st.Batches++ + progressed = true + } + report(st) + if err != nil { + return st, err + } + if o.Remaining == 0 { + m, err := cat.MarkIndependent(ctx, vol) + if err != nil { + return st, err + } + st.Phase, st.MarkedGen, st.Running = RestoreIndependent, m.HeadGen, false + report(st) + return st, nil + } + if o.Owned == 0 { + break // what is left is not local: walk again + } + } + if !progressed { + if stalls++; stalls > 2 { + return st, errRestoreStuck + } + } else { + stalls = 0 + } + } +} + +// restoreRuns holds at most one running restore per volume and the last +// status of each. +type restoreRuns struct { + mu sync.Mutex + runs map[string]*RestoreStatus +} + +// Restore reports vol's restore status and, with start, starts a run unless +// one is running (POST /chunk/restore). A run outlives the request; it ends +// independent, or failed with the error (a later start resumes from the +// target's remote facts). +func (c *chunkControl) Restore(ctx context.Context, vol string, start bool) (RestoreStatus, error) { + p, ok := c.p.(RestoreProvider) + if !ok { + return RestoreStatus{}, fmt.Errorf("restore: provider has no restore surface: %w", errNotRestore) + } + c.restores.mu.Lock() + defer c.restores.mu.Unlock() + if c.restores.runs == nil { + c.restores.runs = map[string]*RestoreStatus{} + } + cur := c.restores.runs[vol] + if cur != nil && (cur.Running || !start) { + return *cur, nil + } + if !start { + return RestoreStatus{VolumeID: vol}, nil + } + st := &RestoreStatus{VolumeID: vol, Phase: RestoreHydrating, Running: true} + c.restores.runs[vol] = st + report := func(s RestoreStatus) { + c.restores.mu.Lock() + *st = s + c.restores.mu.Unlock() + } + go func() { + final, err := runRestore(context.Background(), c.cat, p, vol, RestoreConfig{}, report) + final.Running = false + if err != nil { + _, code, _ := chunkErrorCode(err) + final.Phase, final.ErrorCode, final.ErrorText = RestoreFailed, code, err.Error() + } + report(final) + }() + return *st, nil +} + +// handleChunkRestore serves GET /chunk/restore?volume=V (status) and +// POST /chunk/restore {"volumeID": V} (start or join a run; with +// "statusOnly": true, status only). Both answer 200 with the status. +func (s *StatusServer) handleChunkRestore(w http.ResponseWriter, r *http.Request) { + method := http.MethodGet + if r.Method == http.MethodPost { + method = http.MethodPost + } + if !s.chunkAdmit(w, r, method) { + return + } + vol := r.URL.Query().Get("volume") + if method == http.MethodPost { + var req struct { + VolumeID string `json:"volumeID"` + StatusOnly bool `json:"statusOnly"` + TimeoutMs int64 `json:"timeoutMs"` + } + if !decodeChunkBody(w, r, &req) { + return + } + vol = req.VolumeID + if req.StatusOnly { + method = http.MethodGet + } + } + ctl := s.chunkTarget(w, vol) + if ctl == nil { + return + } + rc, ok := ctl.(interface { + Restore(context.Context, string, bool) (RestoreStatus, error) + }) + if !ok { + writeChunkErr(w, http.StatusNotFound, codeNotFound, false, "restore is not served here") + return + } + st, err := rc.Restore(r.Context(), vol, method == http.MethodPost) + if err != nil { + writeChunkFailure(w, err) + return + } + writeChunkJSON(w, http.StatusOK, st) +} diff --git a/seaweed-block/core/host/volume/chunk_restore_test.go b/seaweed-block/core/host/volume/chunk_restore_test.go new file mode 100644 index 0000000000..b4eebd880c --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_restore_test.go @@ -0,0 +1,287 @@ +package volume + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "path" + "sort" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +const restoreBase = "/swblock/chunks" + +var restoreGeo = chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8} + +// sourceReadGuard fails every catalog read of the source volume's own +// entries (VOLUME, HEAD, snapshots) once armed; chunk bindings stay readable +// (hydration reads the source's chunks through T's qualified refs). +type sourceReadGuard struct { + *adapterManifestFiler + armed bool + reads []string +} + +func (g *sourceReadGuard) denied(dir string) bool { + src := path.Join(restoreBase, "v1") + return g.armed && (dir == src || strings.HasPrefix(dir, src+"/snap")) +} + +func (g *sourceReadGuard) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if g.denied(dir) { + g.reads = append(g.reads, path.Join(dir, name)) + return nil, errors.New("test: the restore driver read the source") + } + return g.adapterManifestFiler.LookupEntry(ctx, dir, name) +} + +func (g *sourceReadGuard) ListEntries(ctx context.Context, dir, prefix, after string, limit uint32) ([]*filerpb.Entry, error) { + if g.denied(dir) { + g.reads = append(g.reads, dir) + return nil, errors.New("test: the restore driver listed the source") + } + return g.adapterManifestFiler.ListEntries(ctx, dir, prefix, after, limit) +} + +// fakeRestoreProvider stands in for the chunk layer: the walk makes every +// chunk local, and a batch is one HEAD CAS replacing up to n foreign keys. +type fakeRestoreProvider struct { + r *chunkstore.ChunkRemote + local bool + hydrations int + batches int + failAtBatch int // a batch with this 1-based number fails (0: never) +} + +func (p *fakeRestoreProvider) HydrateVolume(ctx context.Context, vol string, bps int64) (storage.HydrateProgress, error) { + p.hydrations++ + if bps != DefaultRestoreBytesPerSecond { + return storage.HydrateProgress{}, fmt.Errorf("walker pace %d, want the default %d", bps, DefaultRestoreBytesPerSecond) + } + if p.local { + return storage.HydrateProgress{}, nil + } + h, err := p.r.GetHead(ctx) + if err != nil { + return storage.HydrateProgress{}, err + } + p.local = true + return storage.HydrateProgress{Filled: len(h.Chunks)}, nil +} + +func (p *fakeRestoreProvider) OwnVolumeBatch(ctx context.Context, vol string, n int, foreign func(string) bool) (storage.OwnProgress, error) { + h, err := p.r.GetHead(ctx) + if err != nil { + return storage.OwnProgress{}, err + } + var todo []uint64 + for idx, ref := range h.Chunks { + if foreign(ref.Key) { + todo = append(todo, idx) + } + } + sort.Slice(todo, func(i, j int) bool { return todo[i] < todo[j] }) + if !p.local || len(todo) == 0 { + nl := 0 + if !p.local { + nl = len(todo) + } + return storage.OwnProgress{Remaining: len(todo), NotLocal: nl}, nil + } + p.batches++ + if p.batches == p.failAtBatch { + return storage.OwnProgress{Remaining: len(todo)}, errors.New("test: batch cut failed") + } + next := storage.ChunkHead{Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Chunks: map[uint64]storage.ChunkRef{}} + for idx, ref := range h.Chunks { + next.Chunks[idx] = ref + } + owned := 0 + for _, idx := range todo { + if owned == n { + break + } + data, err := p.r.Get(ctx, h.Chunks[idx].Key) + if err != nil { + return storage.OwnProgress{}, err + } + key := fmt.Sprintf("chunks/e3/c%d/b%d", idx, p.batches) + if err := p.r.Put(ctx, key, data); err != nil { + return storage.OwnProgress{}, err + } + next.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + owned++ + } + next, intents, err := p.r.PrepareManifest(ctx, h, next, uint64(restoreGeo.BlockSize)*uint64(restoreGeo.ChunkBlocks)) + if err != nil { + return storage.OwnProgress{}, err + } + if _, err := p.r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, next); err != nil { + return storage.OwnProgress{}, err + } + for _, id := range intents { + _ = p.r.DeleteIntent(ctx, id) + } + return storage.OwnProgress{Owned: owned, Remaining: len(todo) - owned}, nil +} + +// restoreFixtureHost publishes source v1 (chunks), snapshots it and restores +// it into v2; it returns the guard filer, the catalog and v2's provider. +func restoreFixtureHost(t *testing.T, chunks int) (*sourceReadGuard, *chunkstore.Catalog, *fakeRestoreProvider) { + t.Helper() + ctx := context.Background() + f := &sourceReadGuard{adapterManifestFiler: &adapterManifestFiler{Filer: chunkstore.NewMemFiler(), blobs: map[string][]byte{}}} + cat, err := chunkstore.NewCatalog(f, restoreBase) + if err != nil { + t.Fatal(err) + } + if _, err := cat.EnsureVolume(ctx, "v1", restoreGeo); err != nil { + t.Fatal(err) + } + r1, err := chunkstore.NewChunkRemote(f, f, path.Join(restoreBase, "v1")) + if err != nil { + t.Fatal(err) + } + cur, err := r1.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + h := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 42, Chunks: map[uint64]storage.ChunkRef{}} + for idx := 0; idx < chunks; idx++ { + data := make([]byte, int(restoreGeo.BlockSize)*int(restoreGeo.ChunkBlocks)) + data[0] = byte(0x60 + idx) + key := fmt.Sprintf("chunks/e1/c%d/k", idx) + if err := r1.Put(ctx, key, data); err != nil { + t.Fatal(err) + } + h.Chunks[uint64(idx)] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} + } + h, intents, err := r1.PrepareManifest(ctx, cur, h, uint64(restoreGeo.BlockSize)*uint64(restoreGeo.ChunkBlocks)) + if err != nil { + t.Fatal(err) + } + if h.Gen, err = r1.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h); err != nil { + t.Fatal(err) + } + for _, id := range intents { + _ = r1.DeleteIntent(ctx, id) + } + if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + if _, err := cat.Restore(ctx, chunkstore.ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "rs"}); err != nil { + t.Fatal(err) + } + r2, err := chunkstore.NewChunkRemote(f, f, path.Join(restoreBase, "v2")) + if err != nil { + t.Fatal(err) + } + return f, cat, &fakeRestoreProvider{r: r2} +} + +func noReport(RestoreStatus) {} + +// The driver walks, cuts bounded batches until no foreign ref is left and +// writes the marker, reading only the target's facts (Restoring>Hydrating> +// Owning>Owning>Independent). +func TestRestoreDriver_RunsToIndependenceFromTheTargetsFactsOnly(t *testing.T) { + f, cat, p := restoreFixtureHost(t, 5) + f.armed = true // from here, any read of the source's catalog entries fails + ctx := context.Background() + st, err := runRestore(ctx, cat, p, "v2", RestoreConfig{BatchChunks: 2}, noReport) + if err != nil { + t.Fatalf("restore: %+v %v (source reads %v)", st, err, f.reads) + } + if len(f.reads) != 0 { + t.Fatalf("the driver read the source: %v", f.reads) + } + if st.Phase != RestoreIndependent || st.Owned != 5 || st.Foreign != 0 || st.Batches != 3 || st.Filled != 5 { + t.Fatalf("status %+v, want independent after 3 batches of at most 2", st) + } + m, ok, err := cat.ReadIndependence(ctx, "v2") + if err != nil || !ok || m.HeadGen != st.MarkedGen { + t.Fatalf("marker: %+v ok=%v %v", m, ok, err) + } + again, err := runRestore(ctx, cat, p, "v2", RestoreConfig{}, noReport) + if err != nil || again.Phase != RestoreIndependent || p.batches != 3 { + t.Fatalf("a rerun of an independent restore must do nothing: %+v %v", again, err) + } +} + +// A failed batch leaves HEAD as it was; the next run resumes from the +// target's HEAD and finishes. +func TestRestoreDriver_ResumesAfterAFailedBatch(t *testing.T) { + _, cat, p := restoreFixtureHost(t, 5) + ctx := context.Background() + p.failAtBatch = 2 + st, err := runRestore(ctx, cat, p, "v2", RestoreConfig{BatchChunks: 2}, noReport) + if err == nil || st.Owned != 2 || st.Foreign != 3 { + t.Fatalf("first run: %+v %v, want the failure after 2 owned", st, err) + } + if _, ok, _ := cat.ReadIndependence(ctx, "v2"); ok { + t.Fatal("marker written with foreign refs left") + } + p.failAtBatch = 0 + st, err = runRestore(ctx, cat, p, "v2", RestoreConfig{BatchChunks: 2}, noReport) + if err != nil || st.Phase != RestoreIndependent || st.Owned != 3 { + t.Fatalf("resumed run: %+v %v, want the 3 left owned and the marker", st, err) + } +} + +// Only a restore volume is driven. +func TestRestoreDriver_RefusesAVolumeNotMadeByRestore(t *testing.T) { + _, cat, p := restoreFixtureHost(t, 1) + if _, err := runRestore(context.Background(), cat, p, "v1", RestoreConfig{}, noReport); !errors.Is(err, errNotRestore) { + t.Fatalf("driving the source volume: %v, want not a restore", err) + } +} + +// POST /chunk/restore starts one background run; GET reports it. +func TestRestoreDriver_ChunkControlStartsOneRunAndReportsIt(t *testing.T) { + _, cat, p := restoreFixtureHost(t, 3) + ctl := &chunkControl{p: restoreOnlyProvider{p}, cat: cat} + ctx := context.Background() + if st, err := ctl.Restore(ctx, "v2", false); err != nil || st.Phase != "" { + t.Fatalf("status before any run: %+v %v", st, err) + } + if _, err := ctl.Restore(ctx, "v2", true); err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(5 * time.Second) + for { + st, err := ctl.Restore(ctx, "v2", false) + if err != nil { + t.Fatal(err) + } + if !st.Running { + if st.Phase != RestoreIndependent || st.Owned != 3 { + t.Fatalf("final status %+v", st) + } + break + } + if time.Now().After(deadline) { + t.Fatalf("restore still running: %+v", st) + } + time.Sleep(time.Millisecond) + } +} + +// restoreOnlyProvider is a ChunkProvider whose cut and detach are unused. +type restoreOnlyProvider struct{ *fakeRestoreProvider } + +func (restoreOnlyProvider) CutVolume(context.Context, string, uint64) (storage.ChunkCutResult, error) { + return storage.ChunkCutResult{}, errors.New("unused") +} +func (restoreOnlyProvider) DetachVolume(context.Context, string) (storage.ChunkCutResult, uint64, error) { + return storage.ChunkCutResult{}, 0, errors.New("unused") +} + +var _ RestoreProvider = (*durable.DurableProvider)(nil) diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 480573c503..c537e968ec 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -243,13 +243,15 @@ stateDiagram-v2 [*] --> Claimed: claim parent snapshot, write VOLUME (origin restore) Claimed --> Restoring: first HEAD (parent's refs, owner-qualified); claim dropped Claimed --> Aborted: GC tombstones the HEAD (parent kept as fork_parent) - Restoring --> Restoring: walker fills; batch cut replaces foreign refs with own keys - Restoring --> Independent: no foreign ref in the resolved HEAD; RESTORE-INDEPENDENT created + Restoring --> Hydrating: driver starts the paced walker + Hydrating --> Owning: batch cuts start (the walker may still run) + Owning --> Owning: one bounded batch cut replaces up to N foreign refs with own keys + Owning --> Independent: no foreign ref in the resolved HEAD; RESTORE-INDEPENDENT created Independent --> [*] Aborted --> [*]: target deleted ``` -Snapshots of the target are refused in `Claimed` and `Restoring`. +Snapshots of the target are refused until `Independent`. The driver (`core/host/volume/chunk_restore.go`) runs these steps from the target's own facts; `POST /chunk/restore` starts it and `sw-block ops chunk restore` calls it. ### Attached-volume scheduling diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ba83dc3ba6..e94549d468 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -293,7 +293,10 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | published | deleting | `DeleteSnapshot` or retention for this attempt, never while a fork claim is live | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001` | | published | fork | claim the parent snapshot, check the source is not being deleted, write the target `VOLUME`, then its HEAD; no chunk is copied | `core/frontend/chunkstore/catalog.go` `Fork`, `claimForkParent` | `INV-GC-REACHABLE-001` | | published | restore | the fork steps with `VOLUME` origin `restore`: the claim is live until the target has a HEAD (the fork's semantics); after that the target's owner-qualified refs keep the source's chunks live through GC rooting by owner, with the source snapshot and the source volume both gone; a replay onto a volume of the other origin is refused | `core/frontend/chunkstore/catalog.go` `Restore`, `fork`, `checkForkRecord`; `core/frontend/chunkstore/gc.go` `Collector.run` (qualified refs rooted by owner) | `INV-GC-REACHABLE-001`, `INV-RESTORE-PARENT-HOLD-001` | -| restore | independent | the write-once `RESTORE-INDEPENDENT` entry is created only on a live HEAD whose resolved image (segments and every chunk ref inside) holds no ref owned by another volume | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`, `ForeignRefs` | `INV-RESTORE-INDEPENDENT-001` | +| restore (Restoring) | Hydrating | M6.Restore.Restoring>Hydrating: the driver starts the walker, paced at a byte rate under the BackgroundFill class | `core/host/volume/chunk_restore.go` `runRestore`; `core/frontend/durable/provider_restore.go` `HydrateVolume`; `core/storage/chunk_hydrate_all.go` `HydrateAllAt` | `INV-RESTORE-HYDRATE-001`, `INV-RESTORE-DRIVER-001` | +| restore (Hydrating) | Owning | M6.Restore.Hydrating>Owning: batch cuts start once chunks are local; the walker and the batches may overlap | `core/host/volume/chunk_restore.go` `runRestore` | `INV-RESTORE-DRIVER-001` | +| restore (Owning) | Owning | M6.Restore.Owning>Owning: one bounded batch cut re-uploads at most N local chunks with foreign keys under own keys (one intent, one HEAD CAS); absent chunks wait for the walker | `core/storage/chunk_own.go` `OwnBatch`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `INV-RESTORE-OWN-BATCH-001` | +| restore (Owning) | Independent | M6.Restore.Owning>Independent: the write-once `RESTORE-INDEPENDENT` entry is created only on a live HEAD whose resolved image (segments and every chunk ref inside) holds no ref owned by another volume | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`, `ForeignRefs`; `core/host/volume/chunk_restore.go` `runRestore` | `INV-RESTORE-INDEPENDENT-001`, `INV-RESTORE-DRIVER-001` | | restore (not independent) | name held | refused: `CreateSnapshot` on a restore volume needs the marker, and the supplied image itself must hold no foreign ref; a refused request leaves no name or attempt | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-RESTORE-SNAPSHOT-001` | **Intents and key bindings.** @@ -382,7 +385,7 @@ with a separate scope/config-bound mark. Incomplete marks carry no coverage. ## Part B. Invariant ledger -135 rows: 116 ACTIVE, 17 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 120 new. +137 rows: 118 ACTIVE, 17 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 122 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -576,11 +579,14 @@ Notes: | `INV-RESTORE-INDEPENDENT-001` | `RESTORE-INDEPENDENT` is written once, only for a restore volume with a live HEAD whose resolved image holds no ref owned by another volume; a restore without a live HEAD (absent or aborted) never attaches and is never marked. | M6 snapshot: restore → independent | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestRestore_MarkIndependentOnlyWithoutQualifiedRefs`, `TestRestore_WithoutLiveHeadNeverAttaches`, `TestRestore_SourceGoneIsNormal` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent`, `NoForeignList` | ACTIVE | | `INV-RESTORE-SNAPSHOT-001` | A snapshot of a restore volume is refused until it is independent, and the snapshot image itself must hold no ref owned by another volume (a cut saved before the marker is refused after it); a refused request leaves no name or attempt. | M6 snapshot: restore (not independent) → name held (refused) | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestRestore_SnapshotsRefusedUntilIndependent`, `TestRestore_SnapshotOfAStalePreIndependenceImageRefused` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent` (`red_snap_during_restore`) | ACTIVE | | `INV-RESTORE-PARENT-HOLD-001` | A restore target with an aborted first HEAD no longer has a live fork claim (any HEAD ends the claim), but retention still keeps the parent snapshot as `fork_parent` (the fork-record scan treats an aborted HEAD as no HEAD) until the target volume is deleted. | M6 snapshot: published (parent of an aborted restore) | `core/frontend/chunkstore/retention.go` `liveClaims`, `forkParentsNeeded` | `TestRestore_AbortedFirstHeadKeepsTheParentUntilTheTargetIsDeleted` (`core/frontend/chunkstore/restore_test.go`) | — (Go only: the model's `ClaimUntilHead` does not cover retention of an aborted target) | ACTIVE | -| `INV-RESTORE-HYDRATE-001` | The background hydrate walker fills only through the shared fill flights (one fetch per chunk, never over a local write), yields while a guest waits, and holds one host fill permit (no cut payload, the caller's class) per flight until that flight's I/O is over, also when it returns early on cancel or revocation. | M4 Holder (background hydrate) | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `startWalkerFill`, `admitFill` | `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld` (`core/storage/chunk_hydrate_all_test.go`) | — | ACTIVE | +| `INV-RESTORE-HYDRATE-001` | The background hydrate walker fills only through the shared fill flights (one fetch per chunk, never over a local write), yields while a guest waits, and holds one host fill permit (no cut payload, the caller's class) per flight until that flight's I/O is over, also when it returns early on cancel or revocation. | M4 Holder (background hydrate) | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `HydrateAllAt`, `startWalkerFill`, `admitFill` | `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld`, `TestHydrateAll_PacedByByteRate` (`core/storage/chunk_hydrate_all_test.go`) | — | ACTIVE | +| `INV-RESTORE-OWN-BATCH-001` | A batch cut re-uploads at most N local chunks whose HEAD keys name another volume under new own keys, even when their bytes equal HEAD's, in one ordinary cut (one intent, one HEAD CAS); it never fetches an absent chunk. | M6.Restore.Owning>Owning | `core/storage/chunk_own.go` `OwnBatch`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`, `TestOwnBatch_SkipsChunksNotLocal`, `TestOwnBatch_CarriesGuestWrites` (`core/storage/chunk_own_test.go`) | `RestoreIndependence` `NoGap` | ACTIVE | +| `INV-RESTORE-DRIVER-001` | The restore driver decides only from the target's VOLUME, HEAD and marker (never the source), writes the marker only after a batch leaves no foreign ref, and a rerun resumes from the target's remote state. | M6.Restore (all transitions) | `core/host/volume/chunk_restore.go` `runRestore`, `chunkControl.Restore` | `TestRestoreDriver_RunsToIndependenceFromTheTargetsFactsOnly`, `TestRestoreDriver_ResumesAfterAFailedBatch`, `TestRestoreDriver_RefusesAVolumeNotMadeByRestore` (`core/host/volume/chunk_restore_test.go`) | `RestoreIndependence` `Independent`, `StateRemote` | ACTIVE | | `INV-CAT-INTENT-DROP-BOUNDED-001` | Dropping an operation's intent outlives the caller's cancellation (cleanup after a refused or cancelled request) but is bounded by `dropIntentTimeout`; a failed or timed-out delete leaves the intent, which only over-protects. | M6 intent: Live → Removed | `core/frontend/chunkstore/catalog.go` `dropIntent` | `TestCatalog_DropIntentIsBoundedAfterTheCallerIsCancelled` (`core/frontend/chunkstore/restore_test.go`) | — | ACTIVE | Notes: +- Restore quantities: batch size N = `DefaultRestoreBatchChunks` (64 chunks per batch cut) and the walker pace = `DefaultRestoreBytesPerSecond` (64 MiB/s, plus the host limiter's BackgroundFill class), both in `core/host/volume/chunk_restore.go`. They move to the quantity table when it exists. ### B.7 Rows kept from the internal ledger: Kubernetes line and replica fencing From 5184b1c1196f1ae503910545cdba1f2e298007db Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:25:28 -0800 Subject: [PATCH 16/34] storage: keep the re-own decisions out of captureLocked The re-own candidates join through captureCandidates (addOwnCandidatesLocked) and the HEAD-equal skip is a predicate (unchangedFromHead) in chunk_own.go: captureLocked gains no branch. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_layer.go | 10 ++-------- seaweed-block/core/storage/chunk_own.go | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index f98da1e83f..7650cb3912 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -408,6 +408,7 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool { absent[idx] = true } } + l.addOwnCandidatesLocked(out) l.stMu.Unlock() l.s.mu.RLock() for idx, e := range l.s.v3.mapEntries { @@ -853,11 +854,6 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch candidates[i] = true } } - for idx := range l.own { - if !l.absent[idx] { // a re-own reads the local copy, never fetches - candidates[idx] = true - } - } // A staged chunk stands for the barrier copy while no write reached // it since staging (its version is unchanged) and HEAD is the one it // was compared against. @@ -981,9 +977,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch c.birth = births[c.idx] ref, had := baseHead.Chunks[c.idx] switch { - case c.zero && !had, had && !c.zero && ref.SHA256 == c.sum && c.key == "": - // A chunk equal to HEAD is skipped unless streamCutPayloads - // uploaded it under a new key: a re-owned chunk (OwnBatch). + case c.zero && !had, unchangedFromHead(c, ref, had): st.UnchangedChunks++ continue case c.zero: diff --git a/seaweed-block/core/storage/chunk_own.go b/seaweed-block/core/storage/chunk_own.go index e86ebd408a..5f9188f8b4 100644 --- a/seaweed-block/core/storage/chunk_own.go +++ b/seaweed-block/core/storage/chunk_own.go @@ -94,3 +94,22 @@ func (l *chunkLayerImpl) owning(idx uint64) bool { defer l.stMu.Unlock() return l.own[idx] } + +// addOwnCandidatesLocked adds the running OwnBatch's chunks to a cut's +// candidates: a re-own reads the local copy, so an absent chunk is left out. +// Caller holds stMu. +func (l *chunkLayerImpl) addOwnCandidatesLocked(out map[uint64]bool) { + for idx := range l.own { + if !l.absent[idx] { + out[idx] = true + } + } +} + +// unchangedFromHead reports whether a captured chunk equals HEAD's and was +// not uploaded: such a chunk keeps its HEAD ref. A re-owned chunk equal to +// HEAD was uploaded by streamCutPayloads under a new own key (c.key set), so +// it is published like a changed chunk. +func unchangedFromHead(c capturedChunk, ref chunkRef, had bool) bool { + return had && !c.zero && ref.SHA256 == c.sum && c.key == "" +} From 732941ff5a07a0a8f4289fd5668e0eef848c30da Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:40:31 -0800 Subject: [PATCH 17/34] chunkstore: verify: only a usable closing read completes a pass; one segment object per key A closing read of HEAD that finds no HEAD, or one that does not decode, leaves the final view without a HEAD root and the result incomplete (head_absent, head_invalid); it no longer keeps the earlier view. A manifest segment is checked once per owner and key with one outcome, like a chunk; a root whose reference does not match the content gets one mismatch, and segment findings follow the one-per-key-and-class rule under the first root that names the key. Co-Authored-By: Claude Fable 5.2 --- seaweed-block/core/frontend/chunkstore/GC.md | 26 +- .../core/frontend/chunkstore/verify.go | 343 +++++++++++++----- .../core/frontend/chunkstore/verify_test.go | 201 +++++++++- seaweed-block/docs/design/invariants.md | 10 +- 4 files changed, 469 insertions(+), 111 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/GC.md b/seaweed-block/core/frontend/chunkstore/GC.md index 39cedf3764..39d89aba90 100644 --- a/seaweed-block/core/frontend/chunkstore/GC.md +++ b/seaweed-block/core/frontend/chunkstore/GC.md @@ -191,10 +191,16 @@ those outcomes and the roots at its final read: chunks it names that the pass has not seen are added and checked). - When every chunk is checked, verify reads HEAD and each checked snapshot's state once more. If that read names a chunk not seen, verify checks it and reads - again, at most 3 times; the read that names nothing new is the final read. -- A bad chunk is one finding, under the first root that names it at the final - read (HEAD, then the snapshots still active, in order), at that root's first - index for it. A bad chunk no root names then is not reported: it is counted in + again, at most 3 times; the read that names nothing new is the final read, and + no read follows it. Only a HEAD that decodes can be part of it: if that read + finds no HEAD, or one that does not decode, the final view has no HEAD root and + the pass is incomplete. +- A segment is read once per key, whatever reference names it: a root whose + reference matches its content uses it; a root whose reference does not has a + `CONTENT_MISMATCH` for that segment. +- A bad chunk (or segment) is one finding per class, under the first root that + names it at the final read (HEAD, then the snapshots still active, in order), at + that root's first index for it. A bad one no root names then is not reported: it is counted in `rootDeletedDuringVerify` when a checked snapshot that was deleted during the pass names it, otherwise in `supersededDuringVerify`. Deleted snapshots are listed in `snapshotsDeletedDuringVerify` as not fully covered. @@ -208,9 +214,12 @@ read; a chunk damaged after its check is the next pass's finding. A pass that cannot finish is **incomplete**, never clean: `complete` is false and `incomplete` gives the reason: `deadline`, `cancelled`, `error` (a filer or blob -store failure, or a refused request) or `closing_rounds_exhausted` (each of the 3 -final reads named new chunks: the volume is too busy; re-run). Its findings are -those computed from the chunks it did check. +store failure, a refused request, or a final read that returned an older HEAD), +`closing_rounds_exhausted` (each of the 3 final reads named new chunks: the volume +is too busy; re-run), `head_absent` (the final read found no HEAD) or +`head_invalid` (the final read's HEAD does not decode; also a `ROOT_INVALID` +finding). Its findings are those computed from the chunks it did check, for the +roots of its last view (none for HEAD in the last two cases). ### What verify cannot check @@ -231,7 +240,8 @@ those computed from the chunks it did check. - `3`: the pass completed with findings. This includes `READ_ERROR`: the pass did not verify everything. - `1`: the pass could not complete (the deadline passed, the filer failed, HEAD - kept naming new chunks, the volume or snapshot does not exist, or the filer is + kept naming new chunks, HEAD was gone or did not decode at the final read, the + volume or snapshot does not exist, or the filer is not the only one of its group). The error body `{code,message,retryable}` is printed with the partial result, and its `incomplete` reason, under `verify`. - `2`: usage error. diff --git a/seaweed-block/core/frontend/chunkstore/verify.go b/seaweed-block/core/frontend/chunkstore/verify.go index 5eab39156c..50b9992857 100644 --- a/seaweed-block/core/frontend/chunkstore/verify.go +++ b/seaweed-block/core/frontend/chunkstore/verify.go @@ -35,12 +35,20 @@ package chunkstore // the pass checks it and reads again, at most ClosingRounds times // (V.GiveUp: then the pass is incomplete). // - V.Close: a closing read that names no chunk not seen is the final view. +// Only a decodable HEAD, not older than the view, can close a pass as +// complete: a closing read that finds no HEAD, or one that does not +// decode (ROOT_INVALID), leaves no HEAD root and the pass incomplete. // - V.Reconcile: the findings about chunks and segments are computed from // the outcomes and the final view alone, nowhere else: a bad chunk is // one finding under the first final root naming its key (HEAD, then the // snapshots not gone, in order) at that root's first index; a key HEAD // dropped and names again is ROOT_INVALID, whatever its outcome. // +// A segment is an object of the same automaton, keyed by (owner, key): read +// once, its outcome kept; a root whose reference matches its content gets its +// chunk references, a root whose reference does not has a mismatch; its +// problems are reported by the chunk rule. +// // The pass therefore reports the state of each named chunk at its check, // for the roots at the final read; a chunk damaged after its check is the // next pass's finding. A chunk that left HEAD can be collected after GC's @@ -154,19 +162,23 @@ const ( verifyHookRootsWalked = "roots-walked" // the selected snapshots have been read and walked too verifyHookBatchChecked = "batch-checked" // a batch of checks has settled verifyHookClosingRead = "closing-read" // a closing read is about to be made + verifyHookClosed = "closed" // the quiet closing read was made: the final view is fixed ) // VerifyIncomplete is why a pass did not complete. type VerifyIncomplete string const ( - VerifyIncompleteDeadline VerifyIncomplete = "deadline" // the caller's deadline passed - VerifyIncompleteCancelled VerifyIncomplete = "cancelled" // the caller cancelled - VerifyIncompleteRounds VerifyIncomplete = "closing_rounds_exhausted" // every closing read named new chunks - VerifyIncompleteError VerifyIncomplete = "error" // a filer or blob store failure, or a refused request + VerifyIncompleteDeadline VerifyIncomplete = "deadline" // the caller's deadline passed + VerifyIncompleteCancelled VerifyIncomplete = "cancelled" // the caller cancelled + VerifyIncompleteRounds VerifyIncomplete = "closing_rounds_exhausted" // every closing read named new chunks + VerifyIncompleteHeadAbsent VerifyIncomplete = "head_absent" // the closing read found no HEAD + VerifyIncompleteHeadInvalid VerifyIncomplete = "head_invalid" // the closing read's HEAD does not decode + VerifyIncompleteError VerifyIncomplete = "error" // a filer or blob store failure, or a refused request ) -// CodeVerifyIncomplete: every closing read named chunks not seen before. +// CodeVerifyIncomplete: the closing reads could not close the pass (each +// named chunks not seen before, or the last found no usable HEAD). const CodeVerifyIncomplete = "verify_incomplete" // VerifyFinding is one problem found. Segment is set for a segment's own @@ -272,7 +284,7 @@ func (c *Catalog) Verify(ctx context.Context, vol string, opts VerifyOptions) (V return refuse(err) } v := &verifier{c: c, vol: vol, root: root, opts: opts, res: &res, blobs: c.blobs, - segs: map[verifySegKey]*verifiedSegment{}, chunks: map[string]*verifyChunk{}, dropped: map[string]bool{}, + segs: map[string]*verifySegment{}, chunks: map[string]*verifyChunk{}, dropped: map[string]bool{}, pacer: &verifyPacer{rate: opts.BytesPerSecond}} err = v.run(ctx) v.reconcile() @@ -283,6 +295,10 @@ func (c *Catalog) Verify(ctx context.Context, vol string, opts VerifyOptions) (V res.DistinctChunks = len(v.chunks) if err != nil { switch { + case errors.Is(err, errVerifyHeadAbsent): + res.Incomplete = VerifyIncompleteHeadAbsent + case errors.Is(err, errVerifyHeadInvalid): + res.Incomplete = VerifyIncompleteHeadInvalid case CodeOf(err) == CodeVerifyIncomplete: res.Incomplete = VerifyIncompleteRounds case errors.Is(err, context.DeadlineExceeded): @@ -298,20 +314,39 @@ func (c *Catalog) Verify(ctx context.Context, vol string, opts VerifyOptions) (V return res, nil } -// verifySegKey names a segment reference: a segment object is immutable, so -// one read under the same reference needs no second read. -type verifySegKey struct { - group, chunkBytes uint64 - ref storage.ChunkSegment -} +// Why a closing read leaves no HEAD root (wrapped in CodeVerifyIncomplete). +var ( + errVerifyHeadAbsent = errors.New("chunkstore: verify: the closing read found no HEAD") + errVerifyHeadInvalid = errors.New("chunkstore: verify: the closing read's HEAD does not decode") +) -// verifiedSegment is a segment as read once: its chunks, or the problems -// that make it unusable (issue) or doomed (tombstoned binding). -type verifiedSegment struct { - chunks map[uint64]storage.ChunkRef +// verifySegment is one segment object (owner, key): read once, like a chunk +// (keys are never rebound), its outcome kept, and per root reference the +// result of using it. Its chunk references are decoded under the first +// reference that matches its content; the body is kept until then. +type verifySegment struct { + owner, key string fid string tombstoned bool - issue *segIssue + issue *segIssue // the object could not be read: its outcome + sum [32]byte // the content's SHA-256, once read + body []byte + decoded *segUse // the use that decoded it (with decodedBy) + decodedBy segRef + uses map[segRef]segUse +} + +// segRef is one root's reference to a segment, with what decoding it depends on. +type segRef struct { + group, chunkBytes, remoteLSN uint64 + ref storage.ChunkSegment +} + +// segUse is the result of using a segment under one reference: its chunk +// references, or the problem for that root (issue). +type segUse struct { + chunks map[uint64]storage.ChunkRef + issue *segIssue } // segIssue is why a segment could not be used. @@ -319,6 +354,9 @@ type segIssue struct { class, fid, detail string } +// segID is a segment's identity: its owner and key. +func segID(vol string, ref storage.ChunkSegment) string { return chunkIdentity(vol, ref.Key) } + // verifyChunk is one distinct chunk (owner volume + the owner's own key): // unseen while absent from the verifier's map, then queued, then settled. type verifyChunk struct { @@ -363,16 +401,15 @@ type verifier struct { mu sync.Mutex res *VerifyResult - segs map[verifySegKey]*verifiedSegment // segments read, by reference - chunks map[string]*verifyChunk // the chunks seen, by identity - pending []*verifyChunk // queued, not yet checked - listed bool // the owners' keys/ were listed once + segs map[string]*verifySegment // the segments read, by identity + chunks map[string]*verifyChunk // the chunks seen, by identity + pending []*verifyChunk // queued, not yet checked + listed bool // the owners' keys/ were listed once - head *verifyView // the HEAD view; nil without a decodable HEAD + head *verifyView // the HEAD view; nil without a usable HEAD dropped map[string]bool // keys a HEAD view named and a later one did not snaps []*verifyView // the selected snapshots, in order lastRefresh time.Time - badRefresh bool } func (v *verifier) hook(stage string) { @@ -518,6 +555,7 @@ func (v *verifier) run(ctx context.Context) error { return err } if !named { + v.hook(verifyHookClosed) return nil // V.Close: this read is the final view } if rounds++; rounds == v.opts.ClosingRounds { @@ -557,7 +595,7 @@ func (v *verifier) round(ctx context.Context) (bool, error) { named := false if v.head != nil { var err error - if named, err = v.readHead(ctx); err != nil { + if named, err = v.readHead(ctx, true); err != nil { return false, err } } @@ -573,24 +611,21 @@ func (v *verifier) round(ctx context.Context) (bool, error) { // ---- roots and segments ---- -// segment returns h's segment group as read once by this pass (keys -// owner-qualified, verified through the decoder GC and the chunk layer -// use), reading it the first time. An error stops the pass. -func (v *verifier) segment(ctx context.Context, h storage.ChunkHead, group uint64) (*verifiedSegment, error) { - ref := h.Segments[group] - k := verifySegKey{group: group, chunkBytes: h.ChunkBytes, ref: ref} - if s := v.segs[k]; s != nil { +// V.Discover and V.Settle (segments): the segment ref names, read once per (owner, key) by this pass, its outcome kept. An error stops the pass. +func (v *verifier) segment(ctx context.Context, ref storage.ChunkSegment) (*verifySegment, error) { + id := segID(v.vol, ref) + if s := v.segs[id]; s != nil { return s, nil } - s, err := v.readSegment(ctx, h, group, ref) + s, err := v.readSegment(ctx, ref) if err != nil { return nil, err } - v.segs[k] = s + v.segs[id] = s return s, nil } -func (v *verifier) readSegment(ctx context.Context, h storage.ChunkHead, group uint64, ref storage.ChunkSegment) (*verifiedSegment, error) { +func (v *verifier) readSegment(ctx context.Context, ref storage.ChunkSegment) (*verifySegment, error) { if v.blobs == nil { return nil, errors.New("chunkstore: verify needs a blob reader for segmented roots") } @@ -598,21 +633,26 @@ func (v *verifier) readSegment(ctx context.Context, h storage.ChunkHead, group u if err != nil { return nil, err } + s := &verifySegment{owner: ref.Owner, key: ref.Key, uses: map[segRef]segUse{}} dir, name, err := r.keyLocation(ref.Key) if err != nil { - return &verifiedSegment{issue: &segIssue{FindingSegmentUnreadable, "", err.Error()}}, nil + s.issue = &segIssue{FindingSegmentUnreadable, "", err.Error()} + return s, nil } e, err := v.c.f.LookupEntry(ctx, dir, name) if errors.Is(err, ErrNotFound) { - return &verifiedSegment{issue: &segIssue{FindingSegmentUnreadable, "", "segment binding not found"}}, nil + s.issue = &segIssue{FindingSegmentUnreadable, "", "segment binding not found"} + return s, nil } if err != nil { return nil, abortErr(ctx, err, "read segment binding %s/%s", dir, name) } + s.fid = string(e.Extended[extFid]) if bad := bindingProblem(e); bad != "" { - return &verifiedSegment{issue: &segIssue{FindingSegmentUnreadable, string(e.Extended[extFid]), "segment binding: " + bad}}, nil + s.issue = &segIssue{FindingSegmentUnreadable, s.fid, "segment binding: " + bad} + return s, nil } - s := &verifiedSegment{fid: string(e.Extended[extFid]), tombstoned: len(e.Extended[extGCDeleted]) != 0} + s.tombstoned = len(e.Extended[extGCDeleted]) != 0 v.mu.Lock() v.res.SegmentReads++ v.mu.Unlock() @@ -628,24 +668,60 @@ func (v *verifier) readSegment(ctx context.Context, h storage.ChunkHead, group u s.issue = &segIssue{FindingReadError, s.fid, readErrorDetail(err)} return s, nil } - r, err = NewChunkRemote(v.c.f, verifyPrefetched{s.fid, body}, v.root) - if err != nil { - return nil, err - } - r.mu.Lock() - r.fids[ref.Key] = s.fid - r.mu.Unlock() - one := storage.ChunkHead{Segments: map[uint64]storage.ChunkSegment{group: ref}, ChunkBytes: h.ChunkBytes, - ManifestChunkCount: ref.Count, RemoteLSN: h.RemoteLSN, State: storage.ChunkHeadActive} - resolved, err := r.resolveManifest(ctx, one) - if err != nil { - s.issue = &segIssue{FindingSegmentUnreadable, s.fid, err.Error()} + if len(body) > maxManifestBytes { + s.issue = &segIssue{FindingSegmentUnreadable, s.fid, fmt.Sprintf("segment holds %d bytes, above the %d byte bound", len(body), maxManifestBytes)} return s, nil } - s.chunks = resolved.Chunks + s.sum, s.body = sha256.Sum256(body), body return s, nil } +// use returns what root h gets from segment s at group: its chunk references +// when h's reference matches the content (decoded through the decoder GC +// and the chunk layer use), else the problem for h: a reference whose hash, +// or whose other fields, differ from the content's is a CONTENT_MISMATCH; +// content that does not decode under a matching reference is unreadable. +// Nothing is read: the body is kept until a reference decodes it. +func (v *verifier) use(ctx context.Context, s *verifySegment, h storage.ChunkHead, group uint64) segUse { + if s.issue != nil { + return segUse{issue: s.issue} + } + k := segRef{group: group, chunkBytes: h.ChunkBytes, remoteLSN: h.RemoteLSN, ref: h.Segments[group]} + if u, ok := s.uses[k]; ok { + return u + } + u := segUse{} + d := s.decodedBy + switch { + case k.ref.SHA256 != s.sum: + u.issue = &segIssue{FindingContentMismatch, s.fid, fmt.Sprintf("segment SHA-256 %s, reference %s", hex.EncodeToString(s.sum[:]), hex.EncodeToString(k.ref.SHA256[:]))} + case s.decoded != nil && d.ref == k.ref && d.group == k.group && d.chunkBytes == k.chunkBytes && (k.ref.SegFormat == 1 || k.ref.MaxBirthLSN <= k.remoteLSN): + u.chunks = s.decoded.chunks + case s.body == nil: + u.issue = &segIssue{FindingContentMismatch, s.fid, "the reference has the segment's SHA-256 but not the rest of the reference it was decoded under"} + default: + r, err := NewChunkRemote(v.c.f, verifyPrefetched{s.fid, s.body}, v.root) + if err != nil { + u.issue = &segIssue{FindingSegmentUnreadable, s.fid, err.Error()} + break + } + r.mu.Lock() + r.fids[k.ref.Key] = s.fid + r.mu.Unlock() + one := storage.ChunkHead{Segments: map[uint64]storage.ChunkSegment{group: k.ref}, ChunkBytes: h.ChunkBytes, + ManifestChunkCount: k.ref.Count, RemoteLSN: h.RemoteLSN, State: storage.ChunkHeadActive} + resolved, err := r.resolveManifest(ctx, one) + if err != nil { + u.issue = &segIssue{FindingSegmentUnreadable, s.fid, err.Error()} + break + } + u.chunks = resolved.Chunks + s.decoded, s.decodedBy, s.body = &u, k, nil + } + s.uses[k] = u + return u +} + // bindingProblem is what makes e unusable as a chunk key binding, or "". func bindingProblem(e *filerpb.Entry) string { switch { @@ -672,24 +748,20 @@ func (v *verifier) walk(ctx context.Context, h storage.ChunkHead) (map[uint64]st } return out, unusable, nil } - groups := make([]uint64, 0, len(h.Segments)) - for g := range h.Segments { - groups = append(groups, g) - } - sort.Slice(groups, func(i, j int) bool { return groups[i] < groups[j] }) - for _, g := range groups { + for _, g := range sortedGroups(h.Segments) { v.mu.Lock() v.res.SegmentsChecked++ v.mu.Unlock() - s, err := v.segment(ctx, h, g) + s, err := v.segment(ctx, h.Segments[g]) if err != nil { return out, unusable, err } - if s.issue != nil { + u := v.use(ctx, s, h, g) + if u.issue != nil { unusable[g] = true continue } - for idx, cr := range s.chunks { + for idx, cr := range u.chunks { out[idx] = cr } } @@ -987,29 +1059,42 @@ func (v *verifier) maybeRefresh(ctx context.Context) error { if v.head == nil || v.c.now().Sub(v.lastRefresh) < v.opts.RefreshInterval { return nil } - _, err := v.readHead(ctx) + _, err := v.readHead(ctx, false) return err } -// readHead reads HEAD and applies it (V.Refresh); a HEAD that is gone, or does -// not decode (reported once), changes nothing. It reports whether HEAD named -// a chunk not seen. -func (v *verifier) readHead(ctx context.Context) (bool, error) { +// readHead reads HEAD and applies it (V.Refresh); it reports whether HEAD +// named a chunk not seen. A periodic read that finds no HEAD, one that does +// not decode, or an older generation changes nothing: the closing read +// decides. At the closing read (closing set) every answer decides the final +// view: no HEAD leaves no HEAD root and the pass incomplete (HEAD absent); +// an undecodable one is ROOT_INVALID, no HEAD root, incomplete (HEAD +// invalid); an older generation than the view cannot be the final view and +// cannot keep the earlier one, so the pass is incomplete (an error). +func (v *verifier) readHead(ctx context.Context, closing bool) (bool, error) { v.lastRefresh = v.c.now() e, err := v.c.f.LookupEntry(ctx, v.root, headName) if errors.Is(err, ErrNotFound) { - return false, nil + if !closing { + return false, nil + } + v.head = nil + return false, catErr(CodeVerifyIncomplete, true, errVerifyHeadAbsent, "verify of %s: the closing read found no HEAD; the pass has no HEAD to report against", v.vol) } if err != nil { return false, abortErr(ctx, err, "refresh HEAD of %s", v.vol) } h, err := decodeHead(path.Join(v.root, headName), e) if err != nil { - if !v.badRefresh { - v.badRefresh = true - v.finding(VerifyFinding{Root: "HEAD", Class: FindingRootInvalid, Detail: "refreshed HEAD: " + err.Error()}) + if !closing { + return false, nil } - return false, nil + v.head = nil + v.finding(VerifyFinding{Root: "HEAD", Class: FindingRootInvalid, Detail: "HEAD at the closing read: " + err.Error()}) + return false, catErr(CodeVerifyIncomplete, true, errVerifyHeadInvalid, "verify of %s: the HEAD of the closing read does not decode", v.vol) + } + if closing && v.head != nil && h.Gen < v.head.h.Gen { + return false, remoteErr(nil, "verify of %s: the closing read returned HEAD gen %d, older than gen %d already read", v.vol, h.Gen, v.head.h.Gen) } return v.refresh(ctx, h) } @@ -1370,33 +1455,99 @@ func (v *verifier) reconcile() { } } } - for k, s := range v.segs { - var issues []segIssue - if s.tombstoned && v.opts.Depth != VerifyMeta { - issues = append(issues, segIssue{FindingBindingTombstoned, s.fid, "segment binding tombstoned by GC"}) - } - if s.issue != nil { - issues = append(issues, *s.issue) - } - if len(issues) == 0 { - continue - } - var at *verifyView - for _, r := range roots { - if r.namesSegment(k) { - at = r - break + segIDs := make([]string, 0, len(v.segs)) + for id := range v.segs { + segIDs = append(segIDs, id) + } + sort.Strings(segIDs) + for _, id := range segIDs { + v.reconcileSegment(roots, id, v.segs[id]) + } +} + +// reconcileSegment reports segment id by the chunk rule: its own problems +// (unreadable, read error, tombstoned binding) and each final reference's +// (mismatch, undecodable) at most once per class, under the first final root +// naming it at that root's first group; a problem no final root names is +// counted once. +func (v *verifier) reconcileSegment(roots []*verifyView, id string, s *verifySegment) { + type at struct { + root int + group uint64 + } + var naming []at + for ri, r := range roots { + for _, g := range sortedGroups(r.h.Segments) { + if segID(v.vol, r.h.Segments[g]) == id { + naming = append(naming, at{ri, g}) } } - if at == nil { - v.unnamed(func(s *verifyView) bool { return s.namesSegment(k) }) + } + var own []segIssue + if s.tombstoned && v.opts.Depth != VerifyMeta { + own = append(own, segIssue{FindingBindingTombstoned, s.fid, "segment binding tombstoned by GC"}) + } + if s.issue != nil { + own = append(own, *s.issue) + } + if len(naming) == 0 { + if len(own) != 0 { + v.unnamed(func(r *verifyView) bool { return r.namesSegment(v.vol, id) }) + } + return + } + report := func(a at, is segIssue) { + g := a.group + v.finding(VerifyFinding{Root: roots[a.root].label, Segment: &g, Owner: s.owner, Key: s.key, FID: is.fid, Class: is.class, Detail: is.detail}) + } + for _, is := range own { + report(naming[0], is) + } + if s.issue != nil { + return + } + type problem struct { + at at + issue segIssue + more int + next string + } + var problems []*problem + byClass := map[string]*problem{} + for _, a := range naming { + u := v.use(context.Background(), s, roots[a.root].h, a.group) + if u.issue == nil { continue } - for _, is := range issues { - g := k.group - v.finding(VerifyFinding{Root: at.label, Segment: &g, Owner: k.ref.Owner, Key: k.ref.Key, FID: is.fid, Class: is.class, Detail: is.detail}) + if p := byClass[u.issue.class]; p != nil { + p.more++ + if p.next == "" && a.root != p.at.root { + p.next = roots[a.root].label + } + continue } + p := &problem{at: a, issue: *u.issue} + byClass[u.issue.class] = p + problems = append(problems, p) } + for _, p := range problems { + if p.more > 0 { + p.issue.detail += fmt.Sprintf("; %d more final reference(s) with this problem", p.more) + if p.next != "" { + p.issue.detail += ", next under " + p.next + } + } + report(p.at, p.issue) + } +} + +func sortedGroups(m map[uint64]storage.ChunkSegment) []uint64 { + out := make([]uint64, 0, len(m)) + for g := range m { + out = append(out, g) + } + sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) + return out } // unnamed counts a bad chunk or segment no final root names: root deleted @@ -1420,9 +1571,13 @@ func (r *verifyView) namesChunk(vol, id string) bool { return false } -func (r *verifyView) namesSegment(k verifySegKey) bool { - ref, ok := r.h.Segments[k.group] - return ok && ref == k.ref && r.h.ChunkBytes == k.chunkBytes +func (r *verifyView) namesSegment(vol, id string) bool { + for _, ref := range r.h.Segments { + if segID(vol, ref) == id { + return true + } + } + return false } // verifyPacer spaces reads so they average at most rate bytes per second. diff --git a/seaweed-block/core/frontend/chunkstore/verify_test.go b/seaweed-block/core/frontend/chunkstore/verify_test.go index 19b470d87e..38b0e4b0d1 100644 --- a/seaweed-block/core/frontend/chunkstore/verify_test.go +++ b/seaweed-block/core/frontend/chunkstore/verify_test.go @@ -566,8 +566,9 @@ func TestVerify_TombstonedBinding(t *testing.T) { } } -// A corrupt segment and a segment whose binding is gone are each a finding; -// the pass goes on to the other segments and their chunks. +// A corrupt segment (its content no longer matches the root's reference: a +// mismatch for that root) and a segment whose binding is gone are each a +// finding; the pass goes on to the other segments and their chunks. func TestVerify_UnreadableSegmentContinues(t *testing.T) { fx := newVerifyFixture(t, "v1") h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2), 2 * verifyPer: verifyData(3)}, false) @@ -575,11 +576,11 @@ func TestVerify_UnreadableSegmentContinues(t *testing.T) { fx.deleteBinding(h.Segments[1].Key) fx.deleteBinding(h.Chunks[2*verifyPer].Key) res := fx.verify("v1", VerifyOptions{}) - wantClasses(t, "bindings", res, "SEGMENT_UNREADABLE@seg0", "SEGMENT_UNREADABLE@seg1", fmt.Sprintf("BINDING_MISSING@%d", 2*verifyPer)) + wantClasses(t, "bindings", res, "CONTENT_MISMATCH@seg0", "SEGMENT_UNREADABLE@seg1", fmt.Sprintf("BINDING_MISSING@%d", 2*verifyPer)) if res.SegmentsChecked != 3 || res.ChunksChecked != 1 { t.Fatalf("summary %+v", res) } - if !strings.Contains(res.Findings[0].Detail, "hash") || res.Findings[0].Key != h.Segments[0].Key { + if !strings.Contains(res.Findings[0].Detail, "SHA-256") || res.Findings[0].Key != h.Segments[0].Key { t.Fatalf("corrupt segment finding %+v", res.Findings[0]) } } @@ -1722,3 +1723,195 @@ func TestVerify_SnapshotDocumentNamingAnotherSnapshot(t *testing.T) { }) } } + +// The closing read decides the final view: a HEAD that is gone, or that +// does not decode, leaves no HEAD root and makes the pass incomplete; it +// never closes on an earlier view. A bad chunk only that HEAD named is then +// counted as superseded, not reported. +func TestVerify_ClosingReadWithoutUsableHeadIsIncomplete(t *testing.T) { + for _, tc := range []struct { + name string + bad bool // chunk 0's needle is missing + undecoded bool // the closing read finds a HEAD that does not decode (else none) + want []string + reason VerifyIncomplete + superseded int + }{ + {"HEAD gone, bad chunk", true, false, nil, VerifyIncompleteHeadAbsent, 1}, + {"HEAD gone, good chunks", false, false, nil, VerifyIncompleteHeadAbsent, 0}, + {"HEAD does not decode", true, true, []string{"ROOT_INVALID"}, VerifyIncompleteHeadInvalid, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + if tc.bad { + fx.needle(fx.fid(h.Chunks[0].Key), dropNeedle) + } + done := false + opts := VerifyOptions{Depth: VerifyData, BytesPerSecond: -1} + opts.hook = func(stage string) { + if stage != verifyHookClosingRead || done { + return + } + done = true + if tc.undecoded { + fx.f.bumpExtended(path.Join(catBase, "v1", headName), extGen, "999") + } else if err := fx.f.DeleteEntry(ctx, path.Join(catBase, "v1"), headName, nil); err != nil { + t.Error(err) + } + } + res, err := fx.c.Verify(ctx, "v1", opts) + if CodeOf(err) != CodeVerifyIncomplete || res.Complete || res.Incomplete != tc.reason { + t.Fatalf("verify: %v, complete %v, incomplete %q; want incomplete %q", err, res.Complete, res.Incomplete, tc.reason) + } + wantClasses(t, tc.name, res, tc.want...) + for _, f := range res.Findings { + if f.Root == headLabel(h.Gen) { + t.Fatalf("finding %+v under the HEAD the closing read no longer returned", f) + } + } + if res.SupersededDuringVerify != tc.superseded { + t.Fatalf("superseded %d, want %d", res.SupersededDuringVerify, tc.superseded) + } + }) + } +} + +// casHead installs a HEAD whose segment references edit changes, without +// writing segments (the chunk references stay those of the current HEAD). +func (fx *verifyFixture) casHead(vol string, edit func(segs map[uint64]storage.ChunkSegment)) storage.ChunkHead { + fx.t.Helper() + ctx := context.Background() + r, err := NewChunkRemote(fx.f, fx.b, path.Join(catBase, vol)) + if err != nil { + fx.t.Fatal(err) + } + cur, err := r.GetHead(ctx) + if err != nil { + fx.t.Fatal(err) + } + next := cur + next.Chunks = nil + next.RemoteLSN = cur.RemoteLSN + 1 + next.Segments = map[uint64]storage.ChunkSegment{} + for g, s := range cur.Segments { + next.Segments[g] = s + } + edit(next.Segments) + if next.Gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, next); err != nil { + fx.t.Fatal(err) + } + return next +} + +// A segment is one object per (owner, key), read once: HEAD and an active +// snapshot naming one segment key with different reference hashes share its +// one outcome. A failed read is one READ_ERROR, under HEAD, counted once; a +// readable segment is used by the root whose reference matches its content, +// and the other root gets one mismatch finding. +func TestVerify_SegmentIsOneObjectPerKey(t *testing.T) { + for _, readFails := range []bool{true, false} { + t.Run(fmt.Sprintf("read fails=%v", readFails), func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { + t.Fatal(err) + } + // HEAD names the same segment key with another reference hash. + h2 := fx.casHead("v1", func(segs map[uint64]storage.ChunkSegment) { + s := segs[0] + s.SHA256[0] ^= 0xff + segs[0] = s + }) + segFid := fx.fid(h.Segments[0].Key) + if readFails { + fx.cb.failReads(segFid, -1) + } + res := fx.verify("v1", VerifyOptions{Depth: VerifyBindings, AllSnapshots: true}) + wantReads := 1 + if readFails { + wantClasses(t, "segment read fails", res, "READ_ERROR@seg0") + wantReads = verifyReadAttempts // one read, with its retries + if res.ChunksNotRead != 1 { + t.Fatalf("chunksNotRead %d, want 1", res.ChunksNotRead) + } + } else { + wantClasses(t, "segment matches the snapshot only", res, "CONTENT_MISMATCH@seg0") + // The snapshot's reference matches: its chunks are walked and checked. + if res.ChunksChecked != 2 || res.DistinctChunks != 2 { + t.Fatalf("chunks checked %d, distinct %d; want the snapshot's 2", res.ChunksChecked, res.DistinctChunks) + } + } + if f := res.Findings[0]; f.Root != headLabel(h2.Gen) || f.Key != h.Segments[0].Key { + t.Fatalf("finding %+v; want under %q for the segment key", f, headLabel(h2.Gen)) + } + if n := fx.cb.reads(segFid); n != wantReads { + t.Fatalf("segment read %d times, want %d", n, wantReads) + } + }) + } +} + +// headLookups counts the HEAD reads a pass makes. +type headLookups struct { + Filer + root string + mu sync.Mutex + n int +} + +func (f *headLookups) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if dir == f.root && name == headName { + f.mu.Lock() + f.n++ + f.mu.Unlock() + } + return f.Filer.LookupEntry(ctx, dir, name) +} + +func (f *headLookups) count() int { + f.mu.Lock() + defer f.mu.Unlock() + return f.n +} + +// The quiet closing read is the final view: no HEAD read follows it, and a +// publication that lands right after it is not part of this pass. +func TestVerify_QuietClosingReadIsTheFinalView(t *testing.T) { + fx := newVerifyFixture(t, "v1") + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + filer := &headLookups{Filer: fx.f, root: path.Join(catBase, "v1")} + cat, err := NewCatalog(manifestFilerBlobs{filer, fx.cb}, catBase) + if err != nil { + t.Fatal(err) + } + atClose := -1 + var h2 storage.ChunkHead + opts := VerifyOptions{Depth: VerifyData, BytesPerSecond: -1} + opts.hook = func(stage string) { + if stage == verifyHookClosed { + atClose = filer.count() + h2 = fx.publish("v1", map[uint64][]byte{2: verifyData(3)}, true) + fx.needle(fx.fid(h2.Chunks[2].Key), dropNeedle) + } + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + res, err := cat.Verify(ctx, "v1", opts) + if err != nil || !res.Complete { + t.Fatalf("verify: %v, %+v", err, res) + } + if atClose < 0 { + t.Fatal("the quiet closing read was never reached") + } + if n := filer.count(); n != atClose { + t.Fatalf("%d HEAD reads after the quiet closing read, want none", n-atClose) + } + wantClasses(t, "publication after the quiet read", res) + if res.HeadGens[len(res.HeadGens)-1] != h.Gen || h2.Gen <= h.Gen { + t.Fatalf("covered gens %v (published %d after the close); want the quiet read's %d last", res.HeadGens, h2.Gen, h.Gen) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 929dd4d6ad..8529810c86 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -577,12 +577,12 @@ Notes: | `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | | `INV-VERIFY-READONLY-001` | Verify writes nothing to the filer or the blob store at any depth: no intent, mark, tombstone, binding or needle. | M6 (reader; no transition) | `core/frontend/chunkstore/verify.go` `Catalog.Verify` | `TestVerify_ReadOnlyAtEveryDepth` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-RECHECK-001` | Verify reports a bad chunk only if a root names it at the final read (HEAD, then the selected snapshots still published under the name they were looked up by); a bad chunk no root names then is counted, not reported. | M6 (reader beside GC mark) | `core/frontend/chunkstore/verify.go` `round`, `reconcile` | `TestVerify_SupersededDuringPass`, `TestVerify_SnapshotDeletedDuringPass`, `TestVerify_SharedChunkReportedUnderStillNamingRoot`, `TestVerify_SnapshotDocumentNamingAnotherSnapshot`, `TestVerify_SchedulesGiveTheSameFindings` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-ONE-READ-001` | Verify checks each distinct chunk at most once per pass: a settled chunk is never checked again, however often a root names it again. | M6 (reader) | `core/frontend/chunkstore/verify.go` `discover`, `settle` | `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_DedupSharedChunkReadOnce`, `TestVerify_HeadRefreshRewalksChangedSegments` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-NAMED-HAVE-OUTCOME-001` | In a complete pass every chunk the final view names has a settled outcome: the final view is a closing read that names no chunk the pass had not seen. | M6 (reader) | `core/frontend/chunkstore/verify.go` `run`, `round` | `TestVerify_PublishDuringClosingReadIsChecked`, `TestVerify_SchedulesGiveTheSameFindings` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-REPORT-ONCE-001` | A complete pass yields at most one finding per chunk key and class, computed only at Reconcile from the chunk outcomes and the final view. | M6 (reader) | `core/frontend/chunkstore/verify.go` `reconcile` | `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_TwoWrongReferencesAreOneFinding`, `TestVerify_SameKeyWithAnotherHashIsAFinding` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-RECHECK-001` | Verify reports a bad chunk or segment only if a root of the final view names it: the HEAD the closing read returned (none if it found none or could not decode it), then the selected snapshots still published; else it is counted, not reported. | M6 (reader beside GC mark) | `core/frontend/chunkstore/verify.go` `round`, `readHead`, `reconcile` | `TestVerify_SupersededDuringPass`, `TestVerify_SnapshotDeletedDuringPass`, `TestVerify_SharedChunkReportedUnderStillNamingRoot`, `TestVerify_SnapshotDocumentNamingAnotherSnapshot`, `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_ClosingReadWithoutUsableHeadIsIncomplete` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-ONE-READ-001` | Verify checks each distinct chunk and reads each segment key at most once per pass: a settled object is never checked again, however often or under whatever reference a root names it again. | M6 (reader) | `core/frontend/chunkstore/verify.go` `discover`, `settle`, `segment` | `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_DedupSharedChunkReadOnce`, `TestVerify_HeadRefreshRewalksChangedSegments`, `TestVerify_SegmentIsOneObjectPerKey` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-NAMED-HAVE-OUTCOME-001` | In a complete pass every chunk the final view names has a settled outcome: the final view is the closing read itself, one that names no chunk the pass had not seen, with no read after it. | M6 (reader) | `core/frontend/chunkstore/verify.go` `run`, `round` | `TestVerify_PublishDuringClosingReadIsChecked`, `TestVerify_QuietClosingReadIsTheFinalView`, `TestVerify_SchedulesGiveTheSameFindings` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-REPORT-ONCE-001` | A complete pass yields at most one finding per chunk or segment key and class, computed only at Reconcile from the outcomes and the final view. | M6 (reader) | `core/frontend/chunkstore/verify.go` `reconcile`, `reconcileSegment` | `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_TwoWrongReferencesAreOneFinding`, `TestVerify_SameKeyWithAnotherHashIsAFinding`, `TestVerify_SegmentIsOneObjectPerKey` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | | `INV-VERIFY-NO-FALSE-CLEAN-001` | In a complete pass, a chunk the final view names that was bad when checked, or whose key HEAD dropped earlier in the pass and names again, has a finding. | M6 (reader) | `core/frontend/chunkstore/verify.go` `refresh`, `reconcile` | `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_PublishDuringClosingReadIsChecked` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-CLOSE-BOUND-001` | A pass closes on a closing read that names no chunk it had not seen, within `ClosingRounds` such reads (default 3); otherwise its result is incomplete, with that reason, never clean. | M6 (reader) | `core/frontend/chunkstore/verify.go` `run`, `Catalog.Verify` | `TestVerify_ClosingRoundsExhaustedIsIncomplete` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-CLOSE-BOUND-001` | A pass completes only on a closing read that returns a decodable HEAD naming no chunk it had not seen, within `ClosingRounds` such reads (default 3); otherwise it is incomplete, with its reason, never clean. | M6 (reader) | `core/frontend/chunkstore/verify.go` `run`, `readHead`, `Catalog.Verify` | `TestVerify_ClosingRoundsExhaustedIsIncomplete`, `TestVerify_ClosingReadWithoutUsableHeadIsIncomplete` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | | `INV-VERIFY-NOTFOUND-001` | Verify reports `NEEDLE_MISSING` only when the blob store answers that the needle does not exist (for SeaweedFS, every location of a fresh volume lookup answers 404); any other read failure is retried and then reported as `READ_ERROR`, which means not verified. | M6 (reader) | `core/frontend/chunkstore/verify.go` `Catalog.Verify`; `core/frontend/chunkstore/swfs.go` `Get` (`ErrBlobNotFound`) | `TestVerify_PersistentReadErrorIsNotAMissingNeedle`, `TestVerify_TransientReadIsRetried`, `TestSWFS_GetNotFoundIsErrBlobNotFound`, `TestSWFS_GetStaleCachedLocationLooksUpAgain`, `TestVerify_MovedVolumeIsNotAMissingNeedle` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | | `INV-VERIFY-CANCEL-001` | A failed dispatch of chunk reads (a filer error, or the caller's context ending) cancels the reads in progress before joining them, and Verify returns the originating error. | M6 (reader) | `core/frontend/chunkstore/verify.go` `checkData` | `TestVerify_FailedRefreshCancelsReadInProgress`, `TestVerify_CancelDuringReadJoinsReaders` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | | `INV-RESTORE-INDEPENDENT-001` | `RESTORE-INDEPENDENT` is written once, only for a restore volume with a live HEAD whose resolved image holds no ref owned by another volume; a restore without a live HEAD (absent or aborted) never attaches and is never marked. | M6 snapshot: restore → independent | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestRestore_MarkIndependentOnlyWithoutQualifiedRefs`, `TestRestore_WithoutLiveHeadNeverAttaches`, `TestRestore_SourceGoneIsNormal` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent`, `NoForeignList` | ACTIVE | From 635cf50c16e3f8f8542261c3b3be01a98543fcd7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 00:27:27 -0800 Subject: [PATCH 18/34] chunkstore: verify: judge each reference against the object's one outcome, at the end Nothing is stored about a reference except that a root carried it. An object (a chunk or a manifest segment, by owner and key) has one outcome from its one check; whether a reference to it is sound is a pure function of that outcome and the reference, so the findings no longer depend on which reference was seen first. An object that had a problem under any reference seen and yields no finding is counted once. Co-Authored-By: Claude Fable 5.2 --- seaweed-block/core/frontend/chunkstore/GC.md | 28 +- .../core/frontend/chunkstore/verify.go | 529 +++++++++--------- .../core/frontend/chunkstore/verify_test.go | 159 +++++- seaweed-block/docs/design/invariants.md | 5 +- 4 files changed, 422 insertions(+), 299 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/GC.md b/seaweed-block/core/frontend/chunkstore/GC.md index 39d89aba90..e6a5dc5763 100644 --- a/seaweed-block/core/frontend/chunkstore/GC.md +++ b/seaweed-block/core/frontend/chunkstore/GC.md @@ -195,15 +195,25 @@ those outcomes and the roots at its final read: no read follows it. Only a HEAD that decodes can be part of it: if that read finds no HEAD, or one that does not decode, the final view has no HEAD root and the pass is incomplete. -- A segment is read once per key, whatever reference names it: a root whose - reference matches its content uses it; a root whose reference does not has a - `CONTENT_MISMATCH` for that segment. -- A bad chunk (or segment) is one finding per class, under the first root that - names it at the final read (HEAD, then the snapshots still active, in order), at - that root's first index for it. A bad one no root names then is not reported: it is counted in - `rootDeletedDuringVerify` when a checked snapshot that was deleted during the - pass names it, otherwise in `supersededDuringVerify`. Deleted snapshots are - listed in `snapshotsDeletedDuringVerify` as not fully covered. +- Chunks and segments alike are read once per key, whatever reference names them, + and keep that one outcome: the content (a segment keeps its bytes), or binding + missing or tombstoned, needle missing, or a read error. +- At the end, each reference is judged against that one outcome, the same way + whatever the order the pass met them in: a bad outcome stays that outcome; a + reference with another hash is a `CONTENT_MISMATCH`; a chunk that matches its + reference but is not a chunk long is a `SIZE_MISMATCH`; a segment that does not + decode under that reference's own fields is `SEGMENT_UNREADABLE`; else it is + sound (and a sound segment reference gives that root its chunks). +- For each object and class a reference of the final read has, there is one + finding, under the first root having such a reference (HEAD, then the snapshots + still active, in order), at its first such index. +- A chunk or segment that had a problem under any reference the pass saw (or a bad + outcome) but has no finding, because no reference of the final read has one, is + counted once: in `rootDeletedDuringVerify` when a checked snapshot that was + deleted during the pass carried a problem reference, otherwise in + `supersededDuringVerify`. This includes an object still named, but only by sound + references. Deleted snapshots are listed in `snapshotsDeletedDuringVerify` as not + fully covered. The counters do not make a pass unclean. - A key that an earlier HEAD read named, a later one did not, and the final HEAD names again is a `ROOT_INVALID` finding ("HEAD names a key it had dropped"), whatever its chunk's state: a key that left every root may have been collected, diff --git a/seaweed-block/core/frontend/chunkstore/verify.go b/seaweed-block/core/frontend/chunkstore/verify.go index 50b9992857..0c11116d75 100644 --- a/seaweed-block/core/frontend/chunkstore/verify.go +++ b/seaweed-block/core/frontend/chunkstore/verify.go @@ -22,10 +22,12 @@ package chunkstore // The pass runs beside a live owner and beside GC, so what it reports about // chunks comes from a small automaton (the V.* names on the functions): // -// - V.Discover: a chunk (owner, key) a root view names that the pass has -// not seen is queued for one check. -// - V.Settle: the check records the chunk's outcome and reports nothing; -// a settled chunk is never checked again. +// - V.Discover: an object (a chunk or a segment, by owner and key) a root +// view names that the pass has not seen is queued for one check; every +// reference met is recorded as seen, with nothing judged about it. +// - V.Settle: the check records the object's one outcome (its content, or +// binding missing or tombstoned, needle missing, read error) and reports +// nothing; a settled object is never checked again. // - V.Refresh: HEAD is read again at least every RefreshInterval; a newer // generation replaces the HEAD view (an older one is ignored), the keys // the old view named and the new one does not are marked dropped, and @@ -38,22 +40,23 @@ package chunkstore // Only a decodable HEAD, not older than the view, can close a pass as // complete: a closing read that finds no HEAD, or one that does not // decode (ROOT_INVALID), leaves no HEAD root and the pass incomplete. -// - V.Reconcile: the findings about chunks and segments are computed from -// the outcomes and the final view alone, nowhere else: a bad chunk is -// one finding under the first final root naming its key (HEAD, then the -// snapshots not gone, in order) at that root's first index; a key HEAD +// - V.Reconcile: the findings and counters are computed from the outcomes, +// the references seen and the final view alone, nowhere else. Judge, a +// pure function of an object's outcome and one reference, gives the +// outcome when it is bad, else CONTENT_MISMATCH (another hash), +// SIZE_MISMATCH (a chunk not a chunk long) or SEGMENT_UNREADABLE (a +// segment that does not decode under that reference's fields), else +// sound. Per object and class Judge gives a final reference: one finding, +// under the first final root having one (HEAD, then the snapshots not +// gone, in order) at its first such index. An object with a problem +// under any reference seen, and no finding, is counted once. A key HEAD // dropped and names again is ROOT_INVALID, whatever its outcome. // -// A segment is an object of the same automaton, keyed by (owner, key): read -// once, its outcome kept; a root whose reference matches its content gets its -// chunk references, a root whose reference does not has a mismatch; its -// problems are reported by the chunk rule. -// // The pass therefore reports the state of each named chunk at its check, // for the roots at the final read; a chunk damaged after its check is the // next pass's finding. A chunk that left HEAD can be collected after GC's -// grace, and a deleted snapshot's chunks are kept only for the grace, so a -// bad chunk that no root names at the final read is not a finding. +// grace, and a deleted snapshot's chunks are kept only for the grace, so an +// object that no root names at the final read is not a finding. // // A needle is NEEDLE_MISSING only when the store reports it absent // (ErrBlobNotFound). Any other read failure is retried; if it persists it is @@ -220,9 +223,11 @@ type VerifyResult struct { // DistinctChunksRead and BytesRead count the chunk data read. DistinctChunksRead int `json:"distinctChunksRead"` BytesRead int64 `json:"bytesRead"` - // SupersededDuringVerify counts bad chunks and segments no root names - // at the final read (not findings); RootDeletedDuringVerify those of - // them that a selected snapshot deleted during the pass names. + // SupersededDuringVerify counts the chunks and segments that had a bad + // outcome or a problem under a reference seen during the pass, yet yield + // no finding (no final reference has a problem), once each; + // RootDeletedDuringVerify counts instead those whose problem reference + // was carried by a selected snapshot deleted during the pass. SupersededDuringVerify int `json:"supersededDuringVerify"` RootDeletedDuringVerify int `json:"rootDeletedDuringVerify"` // SnapshotsDeletedDuringVerify lists, as name/attempt, the checked @@ -285,6 +290,7 @@ func (c *Catalog) Verify(ctx context.Context, vol string, opts VerifyOptions) (V } v := &verifier{c: c, vol: vol, root: root, opts: opts, res: &res, blobs: c.blobs, segs: map[string]*verifySegment{}, chunks: map[string]*verifyChunk{}, dropped: map[string]bool{}, + seenChunks: map[string]map[seenChunk]bool{}, seenSegs: map[string]map[seenSeg]bool{}, pacer: &verifyPacer{rate: opts.BytesPerSecond}} err = v.run(ctx) v.reconcile() @@ -321,42 +327,52 @@ var ( ) // verifySegment is one segment object (owner, key): read once, like a chunk -// (keys are never rebound), its outcome kept, and per root reference the -// result of using it. Its chunk references are decoded under the first -// reference that matches its content; the body is kept until then. +// (keys are never rebound). Its one outcome is a bad one (class and detail: +// binding missing, needle missing, read error) or its content (sum, body: +// a segment keeps its bytes). A reference to it is judged at need +// (judgeSegment); nothing about a reference is kept but the decode memo. type verifySegment struct { - owner, key string - fid string - tombstoned bool - issue *segIssue // the object could not be read: its outcome - sum [32]byte // the content's SHA-256, once read - body []byte - decoded *segUse // the use that decoded it (with decodedBy) - decodedBy segRef - uses map[segRef]segUse + owner, key string + fid string + tombstoned bool + class, detail string + sum [32]byte + body []byte + memo map[segRef]segJudged // decodes by the full reference (every input of the decode) } -// segRef is one root's reference to a segment, with what decoding it depends on. +// segRef is one root's reference to a segment, with every root field its +// decode depends on. type segRef struct { group, chunkBytes, remoteLSN uint64 ref storage.ChunkSegment } -// segUse is the result of using a segment under one reference: its chunk -// references, or the problem for that root (issue). -type segUse struct { - chunks map[uint64]storage.ChunkRef - issue *segIssue -} - -// segIssue is why a segment could not be used. -type segIssue struct { - class, fid, detail string +// segJudged is Judge's answer for a segment reference: a class (and detail) +// when it is not sound, else this root's chunk references. +type segJudged struct { + class, detail string + chunks map[uint64]storage.ChunkRef } // segID is a segment's identity: its owner and key. func segID(vol string, ref storage.ChunkSegment) string { return chunkIdentity(vol, ref.Key) } +// Seen references, per object: the root (HEAD, or a snapshot's label), the +// index (a chunk's) or the reference with its root fields (a segment's). +type seenChunk struct { + root string + idx uint64 + sha [32]byte +} + +type seenSeg struct { + root string + ref segRef +} + +const headRoot = "HEAD" // the root of every HEAD generation's references + // verifyChunk is one distinct chunk (owner volume + the owner's own key): // unseen while absent from the verifier's map, then queued, then settled. type verifyChunk struct { @@ -367,12 +383,13 @@ type verifyChunk struct { // The outcome, under the verifier's lock until the checks are joined: // class and detail of a bad outcome (binding missing or tombstoned, - // needle missing, read error, size mismatch), or the SHA-256 of the - // content read (read). + // needle missing, read error), or the content read (read: its SHA-256 + // and length). settled bool class, detail string read bool digest [32]byte + length int } // verifyView is one root as last read: its references by index, and its @@ -410,6 +427,9 @@ type verifier struct { dropped map[string]bool // keys a HEAD view named and a later one did not snaps []*verifyView // the selected snapshots, in order lastRefresh time.Time + + seenChunks map[string]map[seenChunk]bool // the references seen, per chunk + seenSegs map[string]map[seenSeg]bool // the references seen, per segment } func (v *verifier) hook(stage string) { @@ -633,15 +653,15 @@ func (v *verifier) readSegment(ctx context.Context, ref storage.ChunkSegment) (* if err != nil { return nil, err } - s := &verifySegment{owner: ref.Owner, key: ref.Key, uses: map[segRef]segUse{}} + s := &verifySegment{owner: ref.Owner, key: ref.Key, memo: map[segRef]segJudged{}} dir, name, err := r.keyLocation(ref.Key) if err != nil { - s.issue = &segIssue{FindingSegmentUnreadable, "", err.Error()} + s.class, s.detail = FindingBindingMissing, "segment binding: "+err.Error() return s, nil } e, err := v.c.f.LookupEntry(ctx, dir, name) if errors.Is(err, ErrNotFound) { - s.issue = &segIssue{FindingSegmentUnreadable, "", "segment binding not found"} + s.class, s.detail = FindingBindingMissing, "segment binding not found" return s, nil } if err != nil { @@ -649,7 +669,7 @@ func (v *verifier) readSegment(ctx context.Context, ref storage.ChunkSegment) (* } s.fid = string(e.Extended[extFid]) if bad := bindingProblem(e); bad != "" { - s.issue = &segIssue{FindingSegmentUnreadable, s.fid, "segment binding: " + bad} + s.class, s.detail = FindingBindingMissing, "invalid segment binding: "+bad return s, nil } s.tombstoned = len(e.Extended[extGCDeleted]) != 0 @@ -662,64 +682,48 @@ func (v *verifier) readSegment(ctx context.Context, ref storage.ChunkSegment) (* case isContextErr(ctx, err): return nil, abortErr(ctx, err, "read segment %s", ref.Key) case errors.Is(err, ErrBlobNotFound): - s.issue = &segIssue{FindingSegmentUnreadable, s.fid, "segment needle not found: " + err.Error()} + s.class, s.detail = FindingNeedleMissing, "segment needle not found: "+err.Error() return s, nil default: - s.issue = &segIssue{FindingReadError, s.fid, readErrorDetail(err)} - return s, nil - } - if len(body) > maxManifestBytes { - s.issue = &segIssue{FindingSegmentUnreadable, s.fid, fmt.Sprintf("segment holds %d bytes, above the %d byte bound", len(body), maxManifestBytes)} + s.class, s.detail = FindingReadError, readErrorDetail(err) return s, nil } s.sum, s.body = sha256.Sum256(body), body return s, nil } -// use returns what root h gets from segment s at group: its chunk references -// when h's reference matches the content (decoded through the decoder GC -// and the chunk layer use), else the problem for h: a reference whose hash, -// or whose other fields, differ from the content's is a CONTENT_MISMATCH; -// content that does not decode under a matching reference is unreadable. -// Nothing is read: the body is kept until a reference decodes it. -func (v *verifier) use(ctx context.Context, s *verifySegment, h storage.ChunkHead, group uint64) segUse { - if s.issue != nil { - return segUse{issue: s.issue} - } - k := segRef{group: group, chunkBytes: h.ChunkBytes, remoteLSN: h.RemoteLSN, ref: h.Segments[group]} - if u, ok := s.uses[k]; ok { - return u - } - u := segUse{} - d := s.decodedBy +// V.Reconcile's Judge for a segment reference (also used to walk a root): the segment's bad outcome; a hash mismatch; bytes that do not decode under this reference's own fields (SEGMENT_UNREADABLE); else this root's chunk references. +func (v *verifier) judgeSegment(ctx context.Context, s *verifySegment, k segRef) segJudged { switch { + case s.class != "": + return segJudged{class: s.class, detail: s.detail} case k.ref.SHA256 != s.sum: - u.issue = &segIssue{FindingContentMismatch, s.fid, fmt.Sprintf("segment SHA-256 %s, reference %s", hex.EncodeToString(s.sum[:]), hex.EncodeToString(k.ref.SHA256[:]))} - case s.decoded != nil && d.ref == k.ref && d.group == k.group && d.chunkBytes == k.chunkBytes && (k.ref.SegFormat == 1 || k.ref.MaxBirthLSN <= k.remoteLSN): - u.chunks = s.decoded.chunks - case s.body == nil: - u.issue = &segIssue{FindingContentMismatch, s.fid, "the reference has the segment's SHA-256 but not the rest of the reference it was decoded under"} - default: - r, err := NewChunkRemote(v.c.f, verifyPrefetched{s.fid, s.body}, v.root) - if err != nil { - u.issue = &segIssue{FindingSegmentUnreadable, s.fid, err.Error()} - break - } + return segJudged{class: FindingContentMismatch, detail: fmt.Sprintf("segment SHA-256 %s, reference %s", hex.EncodeToString(s.sum[:]), hex.EncodeToString(k.ref.SHA256[:]))} + } + // A memo of the decode, keyed by the full reference: the decode is a + // function of the bytes and of k alone, so the memo cannot change an + // answer; it only saves decoding a segment again at each walk. + if j, ok := s.memo[k]; ok { + return j + } + j := segJudged{} + r, err := NewChunkRemote(v.c.f, verifyPrefetched{s.fid, s.body}, v.root) + if err == nil { r.mu.Lock() r.fids[k.ref.Key] = s.fid r.mu.Unlock() - one := storage.ChunkHead{Segments: map[uint64]storage.ChunkSegment{group: k.ref}, ChunkBytes: h.ChunkBytes, - ManifestChunkCount: k.ref.Count, RemoteLSN: h.RemoteLSN, State: storage.ChunkHeadActive} - resolved, err := r.resolveManifest(ctx, one) - if err != nil { - u.issue = &segIssue{FindingSegmentUnreadable, s.fid, err.Error()} - break + one := storage.ChunkHead{Segments: map[uint64]storage.ChunkSegment{k.group: k.ref}, ChunkBytes: k.chunkBytes, + ManifestChunkCount: k.ref.Count, RemoteLSN: k.remoteLSN, State: storage.ChunkHeadActive} + var resolved storage.ChunkHead + if resolved, err = r.resolveManifest(ctx, one); err == nil { + j.chunks = resolved.Chunks } - u.chunks = resolved.Chunks - s.decoded, s.decodedBy, s.body = &u, k, nil } - s.uses[k] = u - return u + if err != nil { + j = segJudged{class: FindingSegmentUnreadable, detail: err.Error()} + } + s.memo[k] = j + return j } // bindingProblem is what makes e unusable as a chunk key binding, or "". @@ -737,16 +741,17 @@ func bindingProblem(e *filerpb.Entry) string { return "" } -// walk reads the segments root h names and returns its chunk references by -// index, and the segment groups it could not use (their chunks are unknown). -func (v *verifier) walk(ctx context.Context, h storage.ChunkHead) (map[uint64]storage.ChunkRef, map[uint64]bool, error) { +// walk reads the segments root h (of root, HEAD or a snapshot's label) names +// and returns its chunk references by index, and the segment groups whose +// reference Judge does not find sound (their chunks are unknown). Every +// reference met is recorded as seen. +func (v *verifier) walk(ctx context.Context, root string, h storage.ChunkHead) (map[uint64]storage.ChunkRef, map[uint64]bool, error) { out := map[uint64]storage.ChunkRef{} unusable := map[uint64]bool{} if h.Segments == nil { for idx, ref := range h.Chunks { out[idx] = ref } - return out, unusable, nil } for _, g := range sortedGroups(h.Segments) { v.mu.Lock() @@ -756,18 +761,31 @@ func (v *verifier) walk(ctx context.Context, h storage.ChunkHead) (map[uint64]st if err != nil { return out, unusable, err } - u := v.use(ctx, s, h, g) - if u.issue != nil { + k := segRef{group: g, chunkBytes: h.ChunkBytes, remoteLSN: h.RemoteLSN, ref: h.Segments[g]} + see(v.seenSegs, segID(v.vol, k.ref), seenSeg{root, k}) + j := v.judgeSegment(ctx, s, k) + if j.class != "" { unusable[g] = true continue } - for idx, cr := range u.chunks { + for idx, cr := range j.chunks { out[idx] = cr } } + for idx, ref := range out { + see(v.seenChunks, chunkIdentity(v.vol, ref.Key), seenChunk{root, idx, ref.SHA256}) + } return out, unusable, nil } +// see records a reference to object id as seen. +func see[R comparable](seen map[string]map[R]bool, id string, r R) { + if seen[id] == nil { + seen[id] = map[R]bool{} + } + seen[id][r] = true +} + // geometry reports a root's chunk size and chunk indices against VOLUME. func (v *verifier) geometry(label string, h storage.ChunkHead, chunks map[uint64]storage.ChunkRef) { if h.Segments != nil && h.ChunkBytes != v.chunkBytes { @@ -924,7 +942,7 @@ func (v *verifier) snapshot(ctx context.Context, name string, ref snapRef) error if ref.info.geo != (Geometry{}) && ref.info.geo != v.geo { v.finding(VerifyFinding{Root: s.label, Class: FindingGeometry, Detail: fmt.Sprintf("snapshot geometry %+v, VOLUME %+v", ref.info.geo, v.geo)}) } - chunks, _, err := v.walk(ctx, s.h) + chunks, _, err := v.walk(ctx, s.label, s.h) if err != nil { return err } @@ -1104,7 +1122,7 @@ func (v *verifier) refresh(ctx context.Context, h storage.ChunkHead) (bool, erro if v.head != nil && (h.Gen < v.head.h.Gen || h.Gen == v.head.h.Gen && h.Epoch == v.head.h.Epoch) { return false, nil } - chunks, unusable, err := v.walk(ctx, h) + chunks, unusable, err := v.walk(ctx, headRoot, h) if err != nil { return false, err } @@ -1335,108 +1353,103 @@ func (v *verifier) readChunk(ctx context.Context, w *verifyChunk) error { defer v.mu.Unlock() v.res.DistinctChunksRead++ v.res.BytesRead += int64(len(data)) - w.settled, w.read, w.digest = true, true, sum - if uint64(len(data)) != v.chunkBytes { - w.class, w.detail = FindingSizeMismatch, fmt.Sprintf("needle holds %d bytes, chunk size %d", len(data), v.chunkBytes) - } + w.settled, w.read, w.digest, w.length = true, true, sum, len(data) return nil } // ---- reconcile ---- -// verifyRef is a final-view reference: the root (its position among the -// final roots), the index and the SHA-256. -type verifyRef struct { - root int - idx uint64 - sha [32]byte +// V.Reconcile's Judge for a chunk reference: the chunk's bad outcome; a hash mismatch; a wrong length; else sound (""). +func (v *verifier) judgeChunk(w *verifyChunk, sha [32]byte) (string, string) { + switch { + case w.class != "": + return w.class, w.detail + case !w.read: // checked to its binding (depth bindings), or not checked (depth meta) + return "", "" + case sha != w.digest: + return FindingContentMismatch, fmt.Sprintf("needle SHA-256 %s, reference %s", hex.EncodeToString(w.digest[:]), hex.EncodeToString(sha[:])) + case uint64(w.length) != v.chunkBytes: + return FindingSizeMismatch, fmt.Sprintf("needle holds %d bytes, chunk size %d", w.length, v.chunkBytes) + } + return "", "" } -// V.Reconcile: compute every chunk and segment finding from the outcomes and the final view alone; an unnamed bad chunk counts as root deleted if a gone selected snapshot names it, else as superseded. +// judged is Judge's answer for one final reference: its root (position +// among the final roots), its index (a chunk's) or group (a segment's), the +// SHA-256 it expects, and its class ("" when sound) and detail. +type judged struct { + root int + at uint64 + sha [32]byte + class, detail string +} + +// V.Reconcile: every finding and counter, from the settled outcomes, the references seen and the final view alone (an incomplete pass: its last view); root deleted takes precedence over superseded. func (v *verifier) reconcile() { - // The final roots are the HEAD view, then each selected snapshot not - // gone, in order. A chunk with a bad outcome: one finding under the - // first final root that names its key, at that root's first index; if - // none does, no finding, counted once (root deleted takes precedence - // over superseded). A chunk read and verified: one CONTENT_MISMATCH, - // under the first final reference that differs from the content, its - // detail counting the others (and naming the next root carrying one). - // At most one finding per key and class. Below depth data, final - // references to one chunk with different SHA-256s are one - // CONTENT_MISMATCH. A key HEAD - // dropped earlier in the pass and names again is one ROOT_INVALID. A - // segment problem follows the bad-chunk rule over the final roots that - // name that segment. Chunks never settled (an incomplete pass) are not - // judged. + // The final roots: the HEAD view, then each selected snapshot not gone, + // in order. Per object and class Judge gives a final reference: one + // finding (byClass). An object with a bad outcome or a problem under any + // reference seen, and no finding, is counted once (count). Objects never + // settled (an incomplete pass) are not judged. var roots []*verifyView + gone := map[string]bool{} if v.head != nil { roots = append(roots, v.head) v.geometry(v.head.label, v.head.h, v.head.chunks) } for _, s := range v.snaps { if s.gone { + gone[s.label] = true v.res.SnapshotsDeletedDuringVerify = append(v.res.SnapshotsDeletedDuringVerify, s.name+"/"+s.attempt) } else { roots = append(roots, s) } } - named := map[string][]verifyRef{} + finalChunks := map[string][]judged{} for ri, r := range roots { for _, idx := range sortedIndexes(r.chunks) { ref := r.chunks[idx] id := chunkIdentity(v.vol, ref.Key) - named[id] = append(named[id], verifyRef{root: ri, idx: idx, sha: ref.SHA256}) + finalChunks[id] = append(finalChunks[id], judged{root: ri, at: idx, sha: ref.SHA256}) v.res.ChunksChecked++ } } - ids := make([]string, 0, len(v.chunks)) - for id := range v.chunks { - ids = append(ids, id) - } - sort.Strings(ids) - for _, id := range ids { - w, refs := v.chunks[id], named[id] - report := func(at verifyRef, class, detail string) { - idx := at.idx - v.finding(VerifyFinding{Root: roots[at.root].label, Index: &idx, Owner: w.owner, Key: w.key, FID: w.fid, Class: class, Detail: detail}) + for _, id := range sortedKeys(v.chunks) { + w := v.chunks[id] + if !w.settled { + continue } - switch { - case !w.settled: - case w.class != "" && len(refs) == 0: - v.unnamed(func(s *verifyView) bool { return s.namesChunk(v.vol, id) }) - case w.class != "": - report(refs[0], w.class, w.detail) - case w.read: - var differ []verifyRef - for _, r := range refs { - if r.sha != w.digest { - differ = append(differ, r) - } - } - if len(differ) == 0 { - break - } - detail := fmt.Sprintf("needle SHA-256 %s, reference %s", hex.EncodeToString(w.digest[:]), hex.EncodeToString(differ[0].sha[:])) - if more := differ[1:]; len(more) > 0 { - detail += fmt.Sprintf("; %d more final reference(s) differ", len(more)) - for _, r := range more { - if r.root != differ[0].root { - detail += ", next under " + roots[r.root].label - break - } - } - } - report(differ[0], FindingContentMismatch, detail) + refs := finalChunks[id] + for i := range refs { + refs[i].class, refs[i].detail = v.judgeChunk(w, refs[i].sha) } + mk := func(j judged) VerifyFinding { + idx := j.at + return VerifyFinding{Root: roots[j.root].label, Index: &idx, Owner: w.owner, Key: w.key, FID: w.fid, Class: j.class, Detail: j.detail} + } + reported := v.byClass(roots, refs, mk) if v.opts.Depth != VerifyData { + // Below depth data no content was read: final references to one + // chunk with different SHA-256s disagree with each other. for _, r := range refs[min(1, len(refs)):] { if r.sha != refs[0].sha { - report(r, FindingContentMismatch, fmt.Sprintf("references to this chunk disagree: SHA-256 %s here, %s under %s at index %d (depth data reads the chunk)", - hex.EncodeToString(r.sha[:]), hex.EncodeToString(refs[0].sha[:]), roots[refs[0].root].label, refs[0].idx)) + v.finding(mk(judged{root: r.root, at: r.at, class: FindingContentMismatch, detail: fmt.Sprintf( + "references to this chunk disagree: SHA-256 %s here, %s under %s at index %d (depth data reads the chunk)", + hex.EncodeToString(r.sha[:]), hex.EncodeToString(refs[0].sha[:]), roots[refs[0].root].label, refs[0].at)})) + reported = true break } } } + if !reported { + var problem []string + for r := range v.seenChunks[id] { + if c, _ := v.judgeChunk(w, r.sha); c != "" { + problem = append(problem, r.root) + } + } + v.count(problem, w.class != "", gone) + } } if v.head != nil { reported := map[string]bool{} @@ -1455,90 +1468,100 @@ func (v *verifier) reconcile() { } } } - segIDs := make([]string, 0, len(v.segs)) - for id := range v.segs { - segIDs = append(segIDs, id) - } - sort.Strings(segIDs) - for _, id := range segIDs { - v.reconcileSegment(roots, id, v.segs[id]) + for _, id := range sortedKeys(v.segs) { + s := v.segs[id] + var refs []judged + for ri, r := range roots { + for _, g := range sortedGroups(r.h.Segments) { + if ref := r.h.Segments[g]; segID(v.vol, ref) == id { + j := v.judgeSegment(context.Background(), s, segRef{group: g, chunkBytes: r.h.ChunkBytes, remoteLSN: r.h.RemoteLSN, ref: ref}) + refs = append(refs, judged{root: ri, at: g, class: j.class, detail: j.detail}) + } + } + } + mk := func(j judged) VerifyFinding { + g := j.at + return VerifyFinding{Root: roots[j.root].label, Segment: &g, Owner: s.owner, Key: s.key, FID: s.fid, Class: j.class, Detail: j.detail} + } + reported := v.byClass(roots, refs, mk) + // A tombstoned segment binding is reported beside the segment's + // outcome, at depths that check bindings. + tomb := s.tombstoned && v.opts.Depth != VerifyMeta + if tomb && len(refs) > 0 { + v.finding(mk(judged{root: refs[0].root, at: refs[0].at, class: FindingBindingTombstoned, detail: "segment binding tombstoned by GC"})) + reported = true + } + if !reported { + var problem []string + for r := range v.seenSegs[id] { + if tomb || v.judgeSegment(context.Background(), s, r.ref).class != "" { + problem = append(problem, r.root) + } + } + v.count(problem, s.class != "" || tomb, gone) + } } } -// reconcileSegment reports segment id by the chunk rule: its own problems -// (unreadable, read error, tombstoned binding) and each final reference's -// (mismatch, undecodable) at most once per class, under the first final root -// naming it at that root's first group; a problem no final root names is -// counted once. -func (v *verifier) reconcileSegment(roots []*verifyView, id string, s *verifySegment) { - type at struct { - root int - group uint64 - } - var naming []at - for ri, r := range roots { - for _, g := range sortedGroups(r.h.Segments) { - if segID(v.vol, r.h.Segments[g]) == id { - naming = append(naming, at{ri, g}) - } - } - } - var own []segIssue - if s.tombstoned && v.opts.Depth != VerifyMeta { - own = append(own, segIssue{FindingBindingTombstoned, s.fid, "segment binding tombstoned by GC"}) - } - if s.issue != nil { - own = append(own, *s.issue) - } - if len(naming) == 0 { - if len(own) != 0 { - v.unnamed(func(r *verifyView) bool { return r.namesSegment(v.vol, id) }) - } - return - } - report := func(a at, is segIssue) { - g := a.group - v.finding(VerifyFinding{Root: roots[a.root].label, Segment: &g, Owner: s.owner, Key: s.key, FID: is.fid, Class: is.class, Detail: is.detail}) - } - for _, is := range own { - report(naming[0], is) - } - if s.issue != nil { - return - } - type problem struct { - at at - issue segIssue - more int - next string - } - var problems []*problem - byClass := map[string]*problem{} - for _, a := range naming { - u := v.use(context.Background(), s, roots[a.root].h, a.group) - if u.issue == nil { +// byClass reports one finding per class among refs (in final-root order): +// under the first reference of that class, its detail counting the others +// of that class and naming the next root carrying one. It reports whether it +// made one. +func (v *verifier) byClass(roots []*verifyView, refs []judged, mk func(judged) VerifyFinding) bool { + var order []string + first, more, next := map[string]int{}, map[string]int{}, map[string]string{} + for i, j := range refs { + if j.class == "" { continue } - if p := byClass[u.issue.class]; p != nil { - p.more++ - if p.next == "" && a.root != p.at.root { - p.next = roots[a.root].label - } + f, ok := first[j.class] + if !ok { + first[j.class] = i + order = append(order, j.class) continue } - p := &problem{at: a, issue: *u.issue} - byClass[u.issue.class] = p - problems = append(problems, p) + more[j.class]++ + if next[j.class] == "" && j.root != refs[f].root { + next[j.class] = roots[j.root].label + } } - for _, p := range problems { - if p.more > 0 { - p.issue.detail += fmt.Sprintf("; %d more final reference(s) with this problem", p.more) - if p.next != "" { - p.issue.detail += ", next under " + p.next + for _, c := range order { + j := refs[first[c]] + if n := more[c]; n > 0 { + j.detail += fmt.Sprintf("; %d more final reference(s) of this class", n) + if next[c] != "" { + j.detail += ", next under " + next[c] } } - report(p.at, p.issue) + v.finding(mk(j)) } + return len(order) > 0 +} + +// count counts an object that yields no finding but had a bad outcome (bad) +// or a problem under a reference seen (problem: those references' roots), +// once: root deleted when a snapshot that is gone carried such a reference, +// otherwise superseded. +func (v *verifier) count(problem []string, bad bool, gone map[string]bool) { + if len(problem) == 0 && !bad { + return + } + for _, r := range problem { + if gone[r] { + v.res.RootDeletedDuringVerify++ + return + } + } + v.res.SupersededDuringVerify++ +} + +func sortedKeys[T any](m map[string]T) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + sort.Strings(out) + return out } func sortedGroups(m map[uint64]storage.ChunkSegment) []uint64 { @@ -1550,36 +1573,6 @@ func sortedGroups(m map[uint64]storage.ChunkSegment) []uint64 { return out } -// unnamed counts a bad chunk or segment no final root names: root deleted -// when a selected snapshot that is gone names it, otherwise superseded. -func (v *verifier) unnamed(namedBy func(*verifyView) bool) { - for _, s := range v.snaps { - if s.gone && namedBy(s) { - v.res.RootDeletedDuringVerify++ - return - } - } - v.res.SupersededDuringVerify++ -} - -func (r *verifyView) namesChunk(vol, id string) bool { - for _, ref := range r.chunks { - if chunkIdentity(vol, ref.Key) == id { - return true - } - } - return false -} - -func (r *verifyView) namesSegment(vol, id string) bool { - for _, ref := range r.h.Segments { - if segID(vol, ref) == id { - return true - } - } - return false -} - // verifyPacer spaces reads so they average at most rate bytes per second. type verifyPacer struct { mu sync.Mutex diff --git a/seaweed-block/core/frontend/chunkstore/verify_test.go b/seaweed-block/core/frontend/chunkstore/verify_test.go index 38b0e4b0d1..407b223b36 100644 --- a/seaweed-block/core/frontend/chunkstore/verify_test.go +++ b/seaweed-block/core/frontend/chunkstore/verify_test.go @@ -313,11 +313,18 @@ func TestVerify_FlippedByteDataOnly(t *testing.T) { } } +// A reference is judged by its hash first: a needle truncated in the store +// no longer matches its reference (CONTENT_MISMATCH); a needle that matches +// its reference but is not a chunk long is SIZE_MISMATCH. func TestVerify_TruncatedNeedleSizeMismatch(t *testing.T) { fx := newVerifyFixture(t, "v1") h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) fx.needle(fx.fid(h.Chunks[1].Key), truncate) - wantClasses(t, "data", fx.verify("v1", VerifyOptions{Depth: VerifyData}), "SIZE_MISMATCH@1") + wantClasses(t, "truncated in the store", fx.verify("v1", VerifyOptions{Depth: VerifyData}), "CONTENT_MISMATCH@1") + + fx = newVerifyFixture(t, "v1") + fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)[:verifyChunkBytes-4096]}, false) + wantClasses(t, "short but as referenced", fx.verify("v1", VerifyOptions{Depth: VerifyData}), "SIZE_MISMATCH@1") } func TestVerify_MissingNeedle(t *testing.T) { @@ -576,7 +583,7 @@ func TestVerify_UnreadableSegmentContinues(t *testing.T) { fx.deleteBinding(h.Segments[1].Key) fx.deleteBinding(h.Chunks[2*verifyPer].Key) res := fx.verify("v1", VerifyOptions{}) - wantClasses(t, "bindings", res, "CONTENT_MISMATCH@seg0", "SEGMENT_UNREADABLE@seg1", fmt.Sprintf("BINDING_MISSING@%d", 2*verifyPer)) + wantClasses(t, "bindings", res, "CONTENT_MISMATCH@seg0", "BINDING_MISSING@seg1", fmt.Sprintf("BINDING_MISSING@%d", 2*verifyPer)) if res.SegmentsChecked != 3 || res.ChunksChecked != 1 { t.Fatalf("summary %+v", res) } @@ -643,12 +650,12 @@ func TestVerify_SupersededDuringPass(t *testing.T) { } } superseded := 0 - if !withSnap && tc.class != FindingContentMismatch { - superseded = 1 + if !withSnap { + superseded = 1 // a problem under a reference seen, and no finding } // The closing read sees the owner's new HEAD: it is the final view. if hooked != 1 || res.SupersededDuringVerify != superseded || len(res.HeadGens) != 2 || res.HeadGens[0] != h.Gen { - t.Fatalf("hooked %d, superseded %d, gens %v; want 1, %d, [%d next]", hooked, res.SupersededDuringVerify, superseded, res.HeadGens, h.Gen) + t.Fatalf("hooked %d, superseded %d, gens %v; want 1, %d, [%d next]", hooked, res.SupersededDuringVerify, res.HeadGens, superseded, h.Gen) } }) } @@ -672,7 +679,7 @@ func TestVerify_SnapshotDeletedDuringPass(t *testing.T) { fx.needle(fid, dropNeedle) }, FindingBindingMissing}, {"needle overwritten", VerifyData, func(fx *verifyFixture, k string) { fx.needle(fx.fid(k), flipByte) }, FindingContentMismatch}, - {"needle truncated", VerifyData, func(fx *verifyFixture, k string) { fx.needle(fx.fid(k), truncate) }, FindingSizeMismatch}, + {"needle truncated", VerifyData, func(fx *verifyFixture, k string) { fx.needle(fx.fid(k), truncate) }, FindingContentMismatch}, {"needle unreadable", VerifyData, func(fx *verifyFixture, k string) { fx.cb.failReads(fx.fid(k), -1) }, FindingReadError}, } for _, tc := range cases { @@ -712,11 +719,8 @@ func TestVerify_SnapshotDeletedDuringPass(t *testing.T) { return } wantClasses(t, "deleted snapshot", res) - rootDeleted := 1 // a bad outcome; read content has no reference left to compare with - if tc.class == FindingContentMismatch { - rootDeleted = 0 - } - if res.RootDeletedDuringVerify != rootDeleted || res.SupersededDuringVerify != 0 || + // The gone snapshot carried the only problem reference. + if res.RootDeletedDuringVerify != 1 || res.SupersededDuringVerify != 0 || len(res.SnapshotsDeletedDuringVerify) != 1 || res.SnapshotsDeletedDuringVerify[0] != res.Snapshots[0] { t.Fatalf("deleted snapshot: root deleted %d, superseded %d, deleted list %v (checked %v, created %+v)", res.RootDeletedDuringVerify, res.SupersededDuringVerify, res.SnapshotsDeletedDuringVerify, res.Snapshots, s.Name) @@ -1780,7 +1784,8 @@ func TestVerify_ClosingReadWithoutUsableHeadIsIncomplete(t *testing.T) { } // casHead installs a HEAD whose segment references edit changes, without -// writing segments (the chunk references stay those of the current HEAD). +// writing segments (the current HEAD is read without resolving them, so it +// may already carry a wrong reference). func (fx *verifyFixture) casHead(vol string, edit func(segs map[uint64]storage.ChunkSegment)) storage.ChunkHead { fx.t.Helper() ctx := context.Background() @@ -1788,9 +1793,9 @@ func (fx *verifyFixture) casHead(vol string, edit func(segs map[uint64]storage.C if err != nil { fx.t.Fatal(err) } - cur, err := r.GetHead(ctx) - if err != nil { - fx.t.Fatal(err) + cur, ok, err := fx.c.ReadHead(ctx, vol) + if err != nil || !ok { + fx.t.Fatalf("HEAD of %s: %v %v", vol, ok, err) } next := cur next.Chunks = nil @@ -1800,6 +1805,10 @@ func (fx *verifyFixture) casHead(vol string, edit func(segs map[uint64]storage.C next.Segments[g] = s } edit(next.Segments) + next.ManifestChunkCount = 0 + for _, s := range next.Segments { + next.ManifestChunkCount += s.Count + } if next.Gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, next); err != nil { fx.t.Fatal(err) } @@ -1888,11 +1897,16 @@ func TestVerify_QuietClosingReadIsTheFinalView(t *testing.T) { if err != nil { t.Fatal(err) } - atClose := -1 + beforeRound, atClose := -1, -1 var h2 storage.ChunkHead opts := VerifyOptions{Depth: VerifyData, BytesPerSecond: -1} opts.hook = func(stage string) { - if stage == verifyHookClosed { + switch stage { + case verifyHookClosingRead: + if beforeRound < 0 { + beforeRound = filer.count() // before the closing round reads anything + } + case verifyHookClosed: atClose = filer.count() h2 = fx.publish("v1", map[uint64][]byte{2: verifyData(3)}, true) fx.needle(fx.fid(h2.Chunks[2].Key), dropNeedle) @@ -1904,14 +1918,119 @@ func TestVerify_QuietClosingReadIsTheFinalView(t *testing.T) { if err != nil || !res.Complete { t.Fatalf("verify: %v, %+v", err, res) } - if atClose < 0 { + if beforeRound < 0 || atClose < 0 { t.Fatal("the quiet closing read was never reached") } - if n := filer.count(); n != atClose { - t.Fatalf("%d HEAD reads after the quiet closing read, want none", n-atClose) + // The closing round reads HEAD exactly once, and nothing reads it after. + if n := filer.count(); n-beforeRound != 1 { + t.Fatalf("%d HEAD reads from the start of the closing round to the end of the pass, want 1", n-beforeRound) } wantClasses(t, "publication after the quiet read", res) if res.HeadGens[len(res.HeadGens)-1] != h.Gen || h2.Gen <= h.Gen { t.Fatalf("covered gens %v (published %d after the close); want the quiet read's %d last", res.HeadGens, h2.Gen, h.Gen) } } + +// HEAD and an active snapshot name one segment key; the snapshot's reference +// is valid, HEAD's is changed by edit. Whichever reference the pass meets +// first, the findings are the same: each reference is judged against the +// segment's one outcome at the end, nothing about a reference is kept. +func TestVerify_SegmentFindingsDoNotDependOnOrder(t *testing.T) { + for _, tc := range []struct { + name string + edit func(s *storage.ChunkSegment) + want string + }{ + {"HEAD's reference has the right hash and wrong fields", func(s *storage.ChunkSegment) { s.Count++ }, "SEGMENT_UNREADABLE@seg0"}, + {"HEAD's reference has a wrong hash", func(s *storage.ChunkSegment) { s.SHA256[0] ^= 0xff }, "CONTENT_MISMATCH@seg0"}, + } { + for _, headFirst := range []bool{true, false} { + t.Run(fmt.Sprintf("%s/HEAD's reference first=%v", tc.name, headFirst), func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + ctx := context.Background() + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + if _, err := fx.c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err != nil { + t.Fatal(err) + } + var bad storage.ChunkHead + breakHead := func() { + bad = fx.casHead("v1", func(segs map[uint64]storage.ChunkSegment) { + s := segs[0] + tc.edit(&s) + segs[0] = s + }) + } + opts := VerifyOptions{Depth: VerifyData, AllSnapshots: true, BytesPerSecond: -1} + if headFirst { + breakHead() // the pass starts on HEAD's changed reference + } else { + // The pass first meets the valid reference (HEAD and the + // snapshot share it); the changed one comes at the closing read. + opts.hook = func(stage string) { + if stage == verifyHookRootsWalked { + breakHead() + } + } + } + res := fx.verify("v1", opts) + wantClasses(t, tc.name, res, tc.want) + if f := res.Findings[0]; f.Root != headLabel(bad.Gen) || f.Key != h.Segments[0].Key { + t.Fatalf("finding %+v; want under %q", f, headLabel(bad.Gen)) + } + // The snapshot's valid reference is used: its chunks are checked. + if res.ChunksChecked != 2 || res.DistinctChunks != 2 || res.DistinctChunksRead != 2 { + t.Fatalf("chunks checked %d, distinct %d, read %d; want the snapshot's 2", res.ChunksChecked, res.DistinctChunks, res.DistinctChunksRead) + } + if n := fx.cb.reads(fx.fid(h.Segments[0].Key)); n != 1 { + t.Fatalf("segment read %d times, want once", n) + } + }) + } + } +} + +// A problem under a reference that the final view no longer carries is not +// a finding, but it is counted once (superseded): the segment HEAD named +// with a wrong hash and then dropped; the segment HEAD named with a wrong +// hash and then named again soundly; a chunk read whose content a dropped +// reference did not match. +func TestVerify_DroppedReferenceProblemIsCounted(t *testing.T) { + wrongSegHash := func(segs map[uint64]storage.ChunkSegment) { s := segs[0]; s.SHA256[0] ^= 0xff; segs[0] = s } + for _, tc := range []struct { + name string + setup func(fx *verifyFixture) (before, during func()) + }{ + {"segment with a wrong hash, then dropped", func(fx *verifyFixture) (func(), func()) { + fx.publish("v1", map[uint64][]byte{0: verifyData(1), verifyPer: verifyData(2)}, false) + return func() { fx.casHead("v1", wrongSegHash) }, + func() { fx.casHead("v1", func(segs map[uint64]storage.ChunkSegment) { delete(segs, 0) }) } + }}, + {"segment with a wrong hash, then named soundly", func(fx *verifyFixture) (func(), func()) { + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + return func() { fx.casHead("v1", wrongSegHash) }, + func() { fx.casHead("v1", func(segs map[uint64]storage.ChunkSegment) { segs[0] = h.Segments[0] }) } + }}, + {"chunk read, a dropped reference did not match it", func(fx *verifyFixture) (func(), func()) { + h := fx.publish("v1", map[uint64][]byte{0: verifyData(1), 1: verifyData(2)}, false) + return func() { fx.republish("v1", wrongHash(0)) }, + func() { fx.republish("v1", func(c map[uint64]storage.ChunkRef) { c[0] = h.Chunks[0] }) } + }}, + } { + t.Run(tc.name, func(t *testing.T) { + fx := newVerifyFixture(t, "v1") + before, during := tc.setup(fx) + before() + opts := VerifyOptions{Depth: VerifyData, BytesPerSecond: -1} + opts.hook = func(stage string) { + if stage == verifyHookHeadWalked { + during() + } + } + res := fx.verify("v1", opts) + wantClasses(t, tc.name, res) + if res.SupersededDuringVerify != 1 || res.RootDeletedDuringVerify != 0 { + t.Fatalf("superseded %d, root deleted %d; want 1, 0", res.SupersededDuringVerify, res.RootDeletedDuringVerify) + } + }) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 8529810c86..49041e0fac 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -382,7 +382,7 @@ with a separate scope/config-bound mark. Incomplete marks carry no coverage. ## Part B. Invariant ledger -146 `INV-` rows: 126 ACTIVE, 18 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 131 new. One further row, `PROGRESS-DESTRUCTIVE`, has no `INV-` ID. +147 `INV-` rows: 127 ACTIVE, 18 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 132 new. One further row, `PROGRESS-DESTRUCTIVE`, has no `INV-` ID. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -577,10 +577,11 @@ Notes: | `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | | `INV-VERIFY-READONLY-001` | Verify writes nothing to the filer or the blob store at any depth: no intent, mark, tombstone, binding or needle. | M6 (reader; no transition) | `core/frontend/chunkstore/verify.go` `Catalog.Verify` | `TestVerify_ReadOnlyAtEveryDepth` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-RECHECK-001` | Verify reports a bad chunk or segment only if a root of the final view names it: the HEAD the closing read returned (none if it found none or could not decode it), then the selected snapshots still published; else it is counted, not reported. | M6 (reader beside GC mark) | `core/frontend/chunkstore/verify.go` `round`, `readHead`, `reconcile` | `TestVerify_SupersededDuringPass`, `TestVerify_SnapshotDeletedDuringPass`, `TestVerify_SharedChunkReportedUnderStillNamingRoot`, `TestVerify_SnapshotDocumentNamingAnotherSnapshot`, `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_ClosingReadWithoutUsableHeadIsIncomplete` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-RECHECK-001` | No finding is reported for a chunk or segment that no root of the final view names: the HEAD the closing read returned (none if it found none or could not decode it), then the selected snapshots still published. | M6 (reader beside GC mark) | `core/frontend/chunkstore/verify.go` `round`, `readHead`, `reconcile` | `TestVerify_SupersededDuringPass`, `TestVerify_SnapshotDeletedDuringPass`, `TestVerify_SharedChunkReportedUnderStillNamingRoot`, `TestVerify_SnapshotDocumentNamingAnotherSnapshot`, `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_ClosingReadWithoutUsableHeadIsIncomplete`, `TestVerify_DroppedReferenceProblemIsCounted` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | | `INV-VERIFY-ONE-READ-001` | Verify checks each distinct chunk and reads each segment key at most once per pass: a settled object is never checked again, however often or under whatever reference a root names it again. | M6 (reader) | `core/frontend/chunkstore/verify.go` `discover`, `settle`, `segment` | `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_DedupSharedChunkReadOnce`, `TestVerify_HeadRefreshRewalksChangedSegments`, `TestVerify_SegmentIsOneObjectPerKey` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | | `INV-VERIFY-NAMED-HAVE-OUTCOME-001` | In a complete pass every chunk the final view names has a settled outcome: the final view is the closing read itself, one that names no chunk the pass had not seen, with no read after it. | M6 (reader) | `core/frontend/chunkstore/verify.go` `run`, `round` | `TestVerify_PublishDuringClosingReadIsChecked`, `TestVerify_QuietClosingReadIsTheFinalView`, `TestVerify_SchedulesGiveTheSameFindings` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | | `INV-VERIFY-REPORT-ONCE-001` | A complete pass yields at most one finding per chunk or segment key and class, computed only at Reconcile from the outcomes and the final view. | M6 (reader) | `core/frontend/chunkstore/verify.go` `reconcile`, `reconcileSegment` | `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_TwoWrongReferencesAreOneFinding`, `TestVerify_SameKeyWithAnotherHashIsAFinding`, `TestVerify_SegmentIsOneObjectPerKey` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-ORDER-FREE-001` | Findings and counters are a function of the outcomes, the references seen and the final view, not of the order of reads. | M6 (reader) | `core/frontend/chunkstore/verify.go` `judgeChunk`, `judgeSegment`, `reconcile` | `TestVerify_SegmentFindingsDoNotDependOnOrder`, `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_DroppedReferenceProblemIsCounted` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | | `INV-VERIFY-NO-FALSE-CLEAN-001` | In a complete pass, a chunk the final view names that was bad when checked, or whose key HEAD dropped earlier in the pass and names again, has a finding. | M6 (reader) | `core/frontend/chunkstore/verify.go` `refresh`, `reconcile` | `TestVerify_SchedulesGiveTheSameFindings`, `TestVerify_PublishDuringClosingReadIsChecked` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | | `INV-VERIFY-CLOSE-BOUND-001` | A pass completes only on a closing read that returns a decodable HEAD naming no chunk it had not seen, within `ClosingRounds` such reads (default 3); otherwise it is incomplete, with its reason, never clean. | M6 (reader) | `core/frontend/chunkstore/verify.go` `run`, `readHead`, `Catalog.Verify` | `TestVerify_ClosingRoundsExhaustedIsIncomplete`, `TestVerify_ClosingReadWithoutUsableHeadIsIncomplete` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | | `INV-VERIFY-NOTFOUND-001` | Verify reports `NEEDLE_MISSING` only when the blob store answers that the needle does not exist (for SeaweedFS, every location of a fresh volume lookup answers 404); any other read failure is retried and then reported as `READ_ERROR`, which means not verified. | M6 (reader) | `core/frontend/chunkstore/verify.go` `Catalog.Verify`; `core/frontend/chunkstore/swfs.go` `Get` (`ErrBlobNotFound`) | `TestVerify_PersistentReadErrorIsNotAMissingNeedle`, `TestVerify_TransientReadIsRetried`, `TestSWFS_GetNotFoundIsErrBlobNotFound`, `TestSWFS_GetStaleCachedLocationLooksUpAgain`, `TestVerify_MovedVolumeIsNotAMissingNeedle` (`core/frontend/chunkstore/verify_test.go`) | — | ACTIVE | From 6d6dcdd341d200f4051441fe02988c4169b15f6d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 01:19:32 -0800 Subject: [PATCH 19/34] storage: the re-entrant hook test cancels its cuts before the join; drainer doc states the dequeue boundary Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_publish_settled.go | 3 ++- seaweed-block/core/storage/chunk_publish_settled_test.go | 9 ++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/storage/chunk_publish_settled.go b/seaweed-block/core/storage/chunk_publish_settled.go index 2f2c0b905a..2895433cca 100644 --- a/seaweed-block/core/storage/chunk_publish_settled.go +++ b/seaweed-block/core/storage/chunk_publish_settled.go @@ -25,7 +25,8 @@ func (l *chunkLayerImpl) unlockCap() { // caller at a time drains the queue (any other caller only leaves its // reports queued for it, so a hook that publishes again cannot deadlock); // the drainer is registered with Close. Once Close has begun, no further -// report is delivered: the rest are dropped. +// report is dequeued and the rest are dropped; a report already dequeued +// may still reach the hook, and Close waits for it. func (l *chunkLayerImpl) runPublishSettled() { hook := l.cfg.OnPublishSettled if hook == nil { diff --git a/seaweed-block/core/storage/chunk_publish_settled_test.go b/seaweed-block/core/storage/chunk_publish_settled_test.go index 51171e81e2..186c7b25fc 100644 --- a/seaweed-block/core/storage/chunk_publish_settled_test.go +++ b/seaweed-block/core/storage/chunk_publish_settled_test.go @@ -319,7 +319,10 @@ func TestChunkPublishSettled_HookThatPublishes(t *testing.T) { var mu sync.Mutex var got [][2]uint64 nested := false - layer.cfg.OnPublishSettled = func(ctx context.Context, prev, next ChunkHead) { + // One cancellation covers the outer cut and the cut its hook makes; + // cleanup cancels it before the bounded join. + cutCtx, cancelCuts := context.WithCancel(context.Background()) + layer.cfg.OnPublishSettled = func(_ context.Context, prev, next ChunkHead) { mu.Lock() got = append(got, [2]uint64{prev.Gen, next.Gen}) again := !nested @@ -327,13 +330,13 @@ func TestChunkPublishSettled_HookThatPublishes(t *testing.T) { mu.Unlock() if again { w.write(t, s, 9, 0x29) - if _, err := layer.Cut(ctx); err != nil { + if _, err := layer.Cut(cutCtx); err != nil { t.Errorf("cut from the hook: %v", err) } } } w.write(t, s, 2, 0x22) - cut := launch(t, "a cut whose hook publishes", nil, func() error { _, err := layer.Cut(context.Background()); return err }) + cut := launch(t, "a cut whose hook publishes", cancelCuts, func() error { _, err := layer.Cut(cutCtx); return err }) if err, ok := cut.result(10 * time.Second); !ok { t.Fatal("a hook that publishes deadlocked") } else if err != nil { From c041d9e28e2b822721aa8a030cf6f90f2f1e0329 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 01:23:17 -0800 Subject: [PATCH 20/34] spec: RestoreIndependence no-claim variant (exhausted) replaces the claim-era model The model this part rests on, as checked (no-claim variant; only comment lines changed: seat and note names removed), with its 26 configurations: the no-claim safe cfgs exhausted with no error (360 k to 2.75 M states), the boundary G >= D on one clock (ForkDelete's G >= D + E + P with E = P = 0), 13 reds and 2 witnesses on their properties, and the claim-frame regression cfgs. The claim-era configurations not re-run against this spec are removed. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/spec/README.md | 2 +- .../docs/spec/RestoreIndependence.tla | 107 ++++++++++++++++-- ...fg => RestoreIndependence_nc_bnd_G0D1.cfg} | 11 +- .../cfg/RestoreIndependence_nc_bnd_G1D1.cfg | 30 +++++ .../cfg/RestoreIndependence_nc_bnd_G2D3.cfg | 30 +++++ .../cfg/RestoreIndependence_nc_bnd_G3D3.cfg | 30 +++++ ...reIndependence_nc_red_CasBeforeUpload.cfg} | 10 +- .../cfg/RestoreIndependence_nc_red_GltD.cfg | 30 +++++ ...estoreIndependence_nc_red_ListForeign.cfg} | 10 +- ...reIndependence_nc_red_MarkerBeforeCas.cfg} | 10 +- ...estoreIndependence_nc_red_MarkerEarly.cfg} | 10 +- ...> RestoreIndependence_nc_red_NoIntent.cfg} | 10 +- ...estoreIndependence_nc_red_ResumeLocal.cfg} | 10 +- ...Independence_nc_red_SnapDuringRestore.cfg} | 10 +- .../RestoreIndependence_nc_red_noDeadline.cfg | 30 +++++ .../RestoreIndependence_nc_red_notRooted.cfg | 30 +++++ ...toreIndependence_nc_red_resumeNoReread.cfg | 30 +++++ .../spec/cfg/RestoreIndependence_nc_safe.cfg | 30 +++++ .../cfg/RestoreIndependence_nc_safe_G3D2.cfg | 30 +++++ ...cfg => RestoreIndependence_nc_safe_b2.cfg} | 12 +- ...cfg => RestoreIndependence_nc_safe_n4.cfg} | 12 +- .../RestoreIndependence_nc_wit_DelInFork.cfg | 31 +++++ ...estoreIndependence_nc_wit_FailNotFound.cfg | 31 +++++ ...t.cfg => RestoreIndependence_oldframe.cfg} | 8 ++ .../cfg/RestoreIndependence_oldframe_drop.cfg | 31 +++++ ....cfg => RestoreIndependence_opt1_safe.cfg} | 8 +- ...eIndependence_red_DropClaimAtFork_gap.cfg} | 10 +- ...ependence_red_retention_ignores_marker.cfg | 24 ---- .../spec/cfg/RestoreIndependence_safe.cfg | 11 +- 30 files changed, 574 insertions(+), 66 deletions(-) rename seaweed-block/docs/spec/cfg/{RestoreIndependence_wit_crash_resume.cfg => RestoreIndependence_nc_bnd_G0D1.cfg} (74%) create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G1D1.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G2D3.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G3D3.cfg rename seaweed-block/docs/spec/cfg/{RestoreIndependence_red_cas_before_upload.cfg => RestoreIndependence_nc_red_CasBeforeUpload.cfg} (74%) create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_GltD.cfg rename seaweed-block/docs/spec/cfg/{RestoreIndependence_red_list_foreign.cfg => RestoreIndependence_nc_red_ListForeign.cfg} (74%) rename seaweed-block/docs/spec/cfg/{RestoreIndependence_red_marker_before_cas.cfg => RestoreIndependence_nc_red_MarkerBeforeCas.cfg} (74%) rename seaweed-block/docs/spec/cfg/{RestoreIndependence_red_marker_early.cfg => RestoreIndependence_nc_red_MarkerEarly.cfg} (74%) rename seaweed-block/docs/spec/cfg/{RestoreIndependence_red_no_intent.cfg => RestoreIndependence_nc_red_NoIntent.cfg} (74%) rename seaweed-block/docs/spec/cfg/{RestoreIndependence_red_resume_local.cfg => RestoreIndependence_nc_red_ResumeLocal.cfg} (74%) rename seaweed-block/docs/spec/cfg/{RestoreIndependence_red_snap_during_restore.cfg => RestoreIndependence_nc_red_SnapDuringRestore.cfg} (74%) create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_noDeadline.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_notRooted.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_resumeNoReread.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_G3D2.cfg rename seaweed-block/docs/spec/cfg/{RestoreIndependence_safe_b2.cfg => RestoreIndependence_nc_safe_b2.cfg} (69%) rename seaweed-block/docs/spec/cfg/{RestoreIndependence_safe_n4.cfg => RestoreIndependence_nc_safe_n4.cfg} (69%) create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_DelInFork.cfg create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_FailNotFound.cfg rename seaweed-block/docs/spec/cfg/{RestoreIndependence_strict_claim_until_independent.cfg => RestoreIndependence_oldframe.cfg} (76%) create mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe_drop.cfg rename seaweed-block/docs/spec/cfg/{RestoreIndependence_wit_done.cfg => RestoreIndependence_opt1_safe.cfg} (78%) rename seaweed-block/docs/spec/cfg/{RestoreIndependence_red_drop_claim_at_fork.cfg => RestoreIndependence_red_DropClaimAtFork_gap.cfg} (72%) delete mode 100644 seaweed-block/docs/spec/cfg/RestoreIndependence_red_retention_ignores_marker.cfg diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index e94549d468..e04cf77a34 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -577,7 +577,7 @@ Notes: | `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | | `INV-RESTORE-INDEPENDENT-001` | `RESTORE-INDEPENDENT` is written once, only for a restore volume with a live HEAD whose resolved image holds no ref owned by another volume; a restore without a live HEAD (absent or aborted) never attaches and is never marked. | M6 snapshot: restore → independent | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestRestore_MarkIndependentOnlyWithoutQualifiedRefs`, `TestRestore_WithoutLiveHeadNeverAttaches`, `TestRestore_SourceGoneIsNormal` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent`, `NoForeignList` | ACTIVE | -| `INV-RESTORE-SNAPSHOT-001` | A snapshot of a restore volume is refused until it is independent, and the snapshot image itself must hold no ref owned by another volume (a cut saved before the marker is refused after it); a refused request leaves no name or attempt. | M6 snapshot: restore (not independent) → name held (refused) | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestRestore_SnapshotsRefusedUntilIndependent`, `TestRestore_SnapshotOfAStalePreIndependenceImageRefused` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent` (`red_snap_during_restore`) | ACTIVE | +| `INV-RESTORE-SNAPSHOT-001` | A snapshot of a restore volume is refused until it is independent, and the snapshot image itself must hold no ref owned by another volume (a cut saved before the marker is refused after it); a refused request leaves no name or attempt. | M6 snapshot: restore (not independent) → name held (refused) | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestRestore_SnapshotsRefusedUntilIndependent`, `TestRestore_SnapshotOfAStalePreIndependenceImageRefused` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent` (`nc_red_SnapDuringRestore`) | ACTIVE | | `INV-RESTORE-PARENT-HOLD-001` | A restore target with an aborted first HEAD no longer has a live fork claim (any HEAD ends the claim), but retention still keeps the parent snapshot as `fork_parent` (the fork-record scan treats an aborted HEAD as no HEAD) until the target volume is deleted. | M6 snapshot: published (parent of an aborted restore) | `core/frontend/chunkstore/retention.go` `liveClaims`, `forkParentsNeeded` | `TestRestore_AbortedFirstHeadKeepsTheParentUntilTheTargetIsDeleted` (`core/frontend/chunkstore/restore_test.go`) | — (Go only: the model's `ClaimUntilHead` does not cover retention of an aborted target) | ACTIVE | | `INV-RESTORE-HYDRATE-001` | The background hydrate walker fills only through the shared fill flights (one fetch per chunk, never over a local write), yields while a guest waits, and holds one host fill permit (no cut payload, the caller's class) per flight until that flight's I/O is over, also when it returns early on cancel or revocation. | M4 Holder (background hydrate) | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `HydrateAllAt`, `startWalkerFill`, `admitFill` | `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld`, `TestHydrateAll_PacedByByteRate` (`core/storage/chunk_hydrate_all_test.go`) | — | ACTIVE | | `INV-RESTORE-OWN-BATCH-001` | A batch cut re-uploads at most N local chunks whose HEAD keys name another volume under new own keys, even when their bytes equal HEAD's, in one ordinary cut (one intent, one HEAD CAS); it never fetches an absent chunk. | M6.Restore.Owning>Owning | `core/storage/chunk_own.go` `OwnBatch`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`, `TestOwnBatch_SkipsChunksNotLocal`, `TestOwnBatch_CarriesGuestWrites` (`core/storage/chunk_own_test.go`) | `RestoreIndependence` `NoGap` | ACTIVE | diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 920aa86a83..0ca7540f3b 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -117,7 +117,7 @@ length of TLC's shortest counterexample. | S5 | `ControlPlane` | Blockmaster authority store: one volume record `{epoch, holder, move journal}`, two retried move requests, durable Puts that succeed, fail, or land with the reply lost, and restarts. | `UniqueEpoch` (issued epochs strictly increase), `Idempotent` (one epoch per request id), `JournalComplete` | `S5_code` pass (298). **RED:** `S5_red_noUncertain` UniqueEpoch violated (5-step: a lost-reply Put, then a reservation from stale memory puts the old assignment back). `S5_red_noReserve` passes (the reservation step is not needed for these invariants). | `core/authority/authority.go:436` applyWithWorkspaceMove (uncertain refusal `:442-444`, Put `:564`, mark uncertain `:568`); `core/authority/workspace.go:309` prepareWorkspaceMoveLocked (expected line `:313`, resume a reserved entry `:324-333`, reserve max+1 `:344-355`), journal replay `:192-219`, persist and mark uncertain `:276-288` | | S6 | `ReplicationFailover` | RF=2: P ships to R, R acks what is durable, the client is acked when both are durable; promotion of R at a new epoch with an evidence gate; R refuses old-epoch shipping; cuts and snapshots cover only the replicated-durable frontier; an in-flight snapshot create from the old primary may still land after the failover. Design-level. | `AckedSurvive`, `HeadOnLineage`, `SnapOnLineage`, `NoStaleAck` | `S6_design` pass (52,897), `S6_design_big` (598,353). **RED:** `S6_red_localCut` HeadOnLineage; `S6_red_noFence` AckedSurvive. `S6_red_noEvidence` passes: with synchronous RF=2 acks the gate is redundant (it matters for quorum or async shipping, not modelled). | `core/transport/replica.go:362` replica rejects a stale-lineage ship entry; `core/replication/volume.go:680` RebaseShipLSN; takeover CAS as in S2 | | S9 | `RetentionGCTiming`, `RetentionGCMulti` | GC timing with an explicit clock: a copy operation with deadline D, marks of duration up to MD, deletion only after two marks at least Grace apart; then marks across two volumes with a fork and a snapshot delete. | `NoLiveDelete` | **Single op:** `S9_rule_G4` (G > D + MD) pass (10,798; `_big` 43,780); G = D passes (`S9_red_G2_noguard`, 11,953). **RED:** `S9_red_G1_noguard`, `S9_red_G1_D3` (G < D) NoLiveDelete violated. **Two volumes:** `S9b_G1_MD2`, `_G2_MD2`, `_G2_MD3`, `_G3_MD1` pass (5,743-9,079). | `core/frontend/chunkstore/gc.go:89` grace > operation deadline, `:280` mark-duration margin, `:306-318` two-mark rule, `:214-221` intent expiry; `catalog.go:896-905` intent deadline re-checked before publish; `gc_copy.go:143`, `:177` a deleting attempt stays a root until grace | -| S10 | `RestoreIndependence` | Independent restore: claim, two-step fork, hydrate, bounded batch cuts (own keys uploaded under an intent, one HEAD CAS per batch), the independence marker after the last foreign ref, claim drop; GC, source snapshot and volume delete, snapshot retention, and crashes with resume from remote facts at any point. `ClaimUntilHead` selects today's fork claim (dropped at the first HEAD); the strict variant keeps the claim until independent. | `NoGap` (the target's chunks are always rooted), `Independent`, `NoForeignList`, `ClaimUntilHead_Inv`, `LifecycleFree`, `StateRemote` | **Exhaustive (TLC breadth-first, complete state graph, no error)** at MaxCrash 2, MaxGc 3 (4 for `n4`): option 1 (claim dropped at the first HEAD, the code): `safe` (NIdx 3, Batch 1) 3,639 distinct states; `safe_b2` 4,492; `safe_n4` (NIdx 4, Batch 2) 25,240. Strict variant `strict_claim_until_independent` 1,599 (and 2,003 / 9,838 at the `b2` / `n4` sizes, not shipped as cfgs here). **RED** (each violated at its invariant): `red_drop_claim_at_fork` ClaimUntilHead_Inv; `red_cas_before_upload`, `red_no_intent` NoGap; `red_marker_early`, `red_marker_before_cas`, `red_snap_during_restore` Independent; `red_list_foreign` NoForeignList; `red_resume_local` StateRemote; `red_retention_ignores_marker` LifecycleFree. **Witnesses reached:** `wit_done`, `wit_crash_resume`. Limits: no guest writes to the target while it takes ownership, GC acts immediately (no grace), one restore per snapshot. | `core/frontend/chunkstore/catalog.go` `Restore`, `CreateSnapshot` (restore refusal); `restore.go` `MarkIndependent`, `foreignRefsOf`; `retention.go` `liveClaims`, `forkParentsNeeded`; `gc.go` `Collector.run` (qualified refs rooted by owner); `core/storage/chunk_hydrate_all.go` `HydrateAll`. Batch cuts and the restore driver are not merged yet. | +| S10 | `RestoreIndependence` | Independent restore: fork of a sealed snapshot, hydrate, bounded batch cuts (own fids uploaded under an intent, one HEAD CAS per batch), the independence marker after the last foreign ref; GC, source delete, snapshot retention, and crashes with resume from remote facts at any point. `NoClaim` (the code): no claim; the fork window is safe by two time rules on one clock, ForkEnd only while now < readAt + D and a deleted snapshot rooted while now < delAt + G. The older claim variants stay as regression configurations. | `NoGap`, `Independent`, `NoForeignList`, `LifecycleFree`, `StateRemote` | **Exhaustive (TLC breadth-first, complete state graph, no error)**, no-claim: `nc_safe` 405,198 distinct states; `nc_safe_b2` 504,097; `nc_safe_n4` 2,752,518; `nc_safe_G3D2` 379,500; boundary `nc_bnd_G1D1` 444,564 and `nc_bnd_G3D3` 360,615 safe, `nc_bnd_G0D1` and `nc_bnd_G2D3` violate NoGap: safe iff G >= D on one clock, which is `ForkDelete`'s G >= D + E + P with E = P = 0 (the production inequality is ForkDelete's). **RED** (each violated): `nc_red_CasBeforeUpload`, `nc_red_NoIntent`, `nc_red_GltD`, `nc_red_noDeadline`, `nc_red_notRooted`, `nc_red_resumeNoReread` NoGap; `nc_red_MarkerEarly`, `nc_red_MarkerBeforeCas`, `nc_red_SnapDuringRestore` Independent; `nc_red_ListForeign` NoForeignList; `nc_red_ResumeLocal` StateRemote. **Witnesses reached:** `nc_wit_DelInFork` (the source snapshot deleted inside the fork window and the restore completes), `nc_wit_FailNotFound`. Regression (claim frame): `safe` 1,599, `opt1_safe` 3,639, `oldframe` 1,599 safe; `oldframe_drop`, `red_DropClaimAtFork_gap` violate NoGap. Limits: no guest writes to the target while it takes ownership, GC acts immediately, one restore per snapshot. | `core/frontend/chunkstore/catalog.go` `Restore`, `CreateSnapshot` (restore refusal); `restore.go` `MarkIndependent`, `foreignRefsOf`; `gc.go` `Collector.run` (qualified refs rooted by owner); `core/storage/chunk_hydrate_all.go` `HydrateAllAt`; `core/storage/chunk_own.go` `OwnBatch`; `core/host/volume/chunk_restore.go` `runRestore` | ## Limits diff --git a/seaweed-block/docs/spec/RestoreIndependence.tla b/seaweed-block/docs/spec/RestoreIndependence.tla index 796850fe6a..66b87257ff 100644 --- a/seaweed-block/docs/spec/RestoreIndependence.tla +++ b/seaweed-block/docs/spec/RestoreIndependence.tla @@ -1,7 +1,6 @@ ------------------------------ MODULE RestoreIndependence ------------------------------ (***************************************************************************) -(* Independent restore: restore a snapshot into a volume that ends up *) -(* owning all its chunks, with no lineage to the source. *) +(* Independent restore of a snapshot into a new volume. *) (* Source volume V with HEAD and one sealed snapshot S; target T restored *) (* from S. T's HEAD maps indexes to fids; a fid is owned by V (a "@V/" *) (* ref) or by T. Steps: 0 claim S; 1 fork (T HEAD = S's fids, all V-owned) *) @@ -12,8 +11,14 @@ (* no root reaches) may run at any point; V may be deleted at any point; *) (* the restore process may crash and a new owner resumes from REMOTE facts *) (* only (forced move). Mutants are constants (FALSE = the design). *) -(* Reuse: the fid/owner/root vocabulary of the chunk GC model; this *) +(* Reuse: the fid/owner/root vocabulary of the chunk GC model; this *) (* spec models only what the restore adds, not the superseded list/grace. *) +(* NOCLAIM: with NoClaim = TRUE claims are removed; *) +(* a snapshot delete never looks at a fork. Safety of the ForkBegin.. *) +(* ForkEnd window comes from two time rules on one clock: (D) ForkEnd only *) +(* while now < readAt + D, else ForkFail; (G) a deleted S stays a GC root *) +(* while now < delAt + G. With NoClaim = FALSE nothing below changes the *) +(* old model (Tick, ForkFail, ForkNotFound disabled; new variables fixed). *) (***************************************************************************) EXTENDS Integers, FiniteSets, TLC @@ -33,7 +38,15 @@ CONSTANTS RetentionIgnoresMarker, \* after the marker, V's retention still treats T as holding S \* ---- added in review (r0.1) ---- ClaimUntilHead, \* r0.2 OPTION 1: the claim is dropped when T's HEAD is published (today's fork semantics) - NoIntent \* uploaded batch fids are not rooted by an intent before the HEAD CAS + NoIntent, \* uploaded batch fids are not rooted by an intent before the HEAD CAS + \* ---- NOCLAIM variant; old cfgs: NoClaim = FALSE, D = G = MaxTick = 0, the three below TRUE ---- + NoClaim, \* TRUE: no claim ever holds S; DeleteS needs only slive; time rules D and G apply + D, \* fork deadline: ForkEnd only while now < readAt + D (read only when NoClaim) + G, \* grace: a deleted S stays a root while now < delAt + G (read only when NoClaim) + MaxTick, \* bound of the clock (Tick is enabled only when NoClaim) + ForkChecksDeadline,\* design TRUE; mutant FALSE = ForkEnd at any time + DeletedRooted, \* design TRUE; mutant FALSE = a deleted S stops being a root at once + ResumeRereads \* design TRUE; mutant FALSE = a resume in the fork window reuses the old read (fresh deadline, S not re-read) Idx == 1..NIdx VF == [i \in Idx |-> <<"V", i>>] \* the source fid of index i @@ -41,6 +54,7 @@ TF == [i \in Idx |-> <<"T", i>>] \* T's own fid for index i Fids == {VF[i] : i \in Idx} \cup {TF[i] : i \in Idx} \* r0.1: "no HEAD yet" is a function too (TLC cannot compare a function with a string) NoHead == [i \in Idx |-> <<"N", i>>] +None == -1 \* nc: "no tick" encoding for readAt / delAt VARIABLES store, \* Fids -> "none" | "pres" | "del" @@ -54,40 +68,70 @@ VARIABLES tsnap, \* a snapshot of T (its fid set), {} if none gclist, \* fids put on a GC list (rule 8 check) localdone,\* local "restore done" flag of the current owner (ResumeLocal mutant) - crashes, gcs + crashes, gcs, + \* ---- nc (all fixed at their Init value when NoClaim = FALSE) ---- + now, \* the one clock + readAt, \* tick at which the current fork attempt read S (None if no attempt in progress) + delAt, \* tick at which S was deleted (None while S lives) + sdelfk, \* history: S was deleted while step = "fk" (for the witness) + ffail \* history: a fork attempt failed on its deadline (for the witness) -vars == <> +tvars == <> +vars == <> THeadFids == IF thead = NoHead THEN {} ELSE {thead[i] : i \in Idx} VRefs == {i \in Idx : thead # NoHead /\ thead[i][1] = "V"} \* roots: V's HEAD (while V lives), S (while it lives), T's HEAD, T's snapshot, \* uploaded-but-unpublished batch fids (intent roots them), S's fids while claimed SFids == {VF[i] : i \in Idx} +\* nc rule G: a deleted S stays a root for G ticks (FALSE whenever NoClaim = FALSE) +SGrace == NoClaim /\ DeletedRooted /\ ~ slive /\ delAt # None /\ now < delAt + G Roots == (IF vlive THEN SFids ELSE {}) - \cup (IF slive THEN SFids ELSE {}) + \cup (IF (slive \/ SGrace) THEN SFids ELSE {}) \cup THeadFids \cup tsnap \cup (IF NoIntent THEN {} ELSE up) \* S may be deleted by retention when nothing holds it SHeld == claim \/ (RetentionIgnoresMarker /\ thead # NoHead) +\* nc: with NoClaim the snapshot delete never looks at a fork +SDeletable == slive /\ (NoClaim \/ ~ SHeld) +\* nc rule D (TRUE whenever NoClaim = FALSE) +DeadlineOK == (~ NoClaim) \/ (~ ForkChecksDeadline) \/ (now < readAt + D) Init == /\ store = [f \in Fids |-> IF f[1] = "V" THEN "pres" ELSE "none"] /\ vlive = TRUE /\ slive = TRUE /\ claim = FALSE /\ thead = NoHead /\ step = "start" /\ up = {} /\ marker = FALSE /\ tsnap = {} /\ gclist = {} /\ localdone = FALSE /\ crashes = 0 /\ gcs = 0 + /\ now = 0 /\ readAt = None /\ delAt = None /\ sdelfk = FALSE /\ ffail = FALSE \* step 0: S is sealed (given) and claimed -Claim == step = "start" /\ slive /\ claim' = TRUE /\ step' = "c" +\* nc: the step is kept (S found, step counter) but takes no claim +Claim == step = "start" /\ slive /\ claim' = (~ NoClaim) /\ step' = "c" /\ UNCHANGED <> + /\ UNCHANGED tvars \* step 1: fork (T HEAD names S's fids, all V-owned) \* r0.1: two steps. Between them T exists without a HEAD, so only the claim keeps S (and \* through S its fids) alive; that window is what the claim is for. +\* nc: ForkBegin reads S (requires S live) and records readAt; ForkEnd only within the deadline ForkBegin == step = "c" /\ step' = "fk" + /\ (NoClaim => slive) /\ claim' = (IF DropClaimAtFork THEN FALSE ELSE claim) + /\ readAt' = (IF NoClaim THEN now ELSE readAt) /\ UNCHANGED <> -ForkEnd == step = "fk" /\ thead' = VF /\ step' = "own" + /\ UNCHANGED <> +ForkEnd == step = "fk" /\ DeadlineOK /\ thead' = VF /\ step' = "own" /\ claim' = (IF ClaimUntilHead THEN FALSE ELSE claim) /\ UNCHANGED <> + /\ UNCHANGED tvars +\* nc: past the deadline the fork fails cleanly: T stays without a HEAD, a retry is a new ForkBegin +ForkFail == NoClaim /\ step = "fk" /\ now >= readAt + D + /\ step' = "c" /\ readAt' = None /\ ffail' = TRUE + /\ UNCHANGED <> + /\ UNCHANGED <> +\* nc: a (re)try that re-reads S and finds it gone ends with "not found" (terminal) +ForkNotFound == NoClaim /\ step = "c" /\ ~ slive /\ step' = "nf" + /\ UNCHANGED <> + /\ UNCHANGED tvars \* step 3: one batch: upload own fids for up to Batch V-owned indexes (intent roots them) BatchSet == {B \in SUBSET VRefs : B # {} /\ Cardinality(B) <= Batch} @@ -96,6 +140,7 @@ Upload(B) == step = "own" /\ up = {} /\ ~ CasBeforeUpload /\ store' = [f \in Fids |-> IF f \in {TF[j] : j \in B} THEN "pres" ELSE store[f]] /\ up' = {TF[j] : j \in B} /\ UNCHANGED <> + /\ UNCHANGED tvars \* the batch HEAD CAS: swap exactly the uploaded indexes Cas == step = "own" /\ up # {} /\ thead' = [i \in Idx |-> IF TF[i] \in up THEN TF[i] ELSE thead[i]] @@ -103,50 +148,75 @@ Cas == step = "own" /\ up # {} /\ up' = {} /\ localdone' = (localdone \/ \A i \in Idx : (thead[i][1] = "V") => (TF[i] \in up)) /\ UNCHANGED <> + /\ UNCHANGED tvars \* mutant: CAS a batch whose upload is not durable (the T fid is still "none") CasEarly(B) == CasBeforeUpload /\ step = "own" /\ up = {} /\ thead' = [i \in Idx |-> IF i \in B THEN TF[i] ELSE thead[i]] /\ UNCHANGED <> + /\ UNCHANGED tvars UploadLate == CasBeforeUpload /\ step = "own" /\ \E i \in Idx : thead[i] = TF[i] /\ store[TF[i]] = "none" /\ store' = [store EXCEPT ![TF[i]] = "pres"] /\ UNCHANGED <> + /\ UNCHANGED tvars \* step 4: marker after the last V ref is gone (and the final CAS is done), then drop the claim Marker == step = "own" /\ ~ marker /\ up = {} /\ (VRefs = {} \/ MarkerEarly \/ (MarkerBeforeCas /\ Cardinality(VRefs) <= Batch)) /\ marker' = TRUE /\ step' = "done" /\ localdone' = TRUE /\ UNCHANGED <> + /\ UNCHANGED tvars DropClaim == marker /\ claim /\ claim' = FALSE /\ UNCHANGED <> + /\ UNCHANGED tvars \* a snapshot of T: refused before the marker (unless the mutant allows it) SnapT == tsnap = {} /\ thead # NoHead /\ (marker \/ SnapDuringRestore) /\ tsnap' = THeadFids /\ UNCHANGED <> + /\ UNCHANGED tvars \* crash of the restore process; the new owner resumes from remote facts (thead, marker) +\* nc: a resume in the fork window (no HEAD) is a retry that re-reads S (back to "c", new +\* ForkBegin requires S live); mutant ~ResumeRereads: stays "fk" with a fresh deadline (readAt = now) +\* and the content read before the crash Crash == crashes < MaxCrash /\ step \in {"fk", "own", "done"} /\ up' = {} \* an unpublished batch is abandoned; its fids are collectable /\ step' = (IF ResumeLocal /\ localdone THEN "done" - ELSE IF marker THEN "done" ELSE IF thead = NoHead THEN "fk" ELSE "own") + ELSE IF marker THEN "done" + ELSE IF thead = NoHead THEN (IF (NoClaim /\ ResumeRereads) THEN "c" ELSE "fk") + ELSE "own") + /\ readAt' = (IF (NoClaim /\ thead = NoHead) THEN (IF ResumeRereads THEN None ELSE now) ELSE readAt) /\ crashes' = crashes + 1 /\ UNCHANGED <> + /\ UNCHANGED <> \* user deletes V; retention deletes S when nothing holds it DeleteV == vlive /\ vlive' = FALSE /\ UNCHANGED <> -DeleteS == slive /\ ~ SHeld /\ slive' = FALSE + /\ UNCHANGED tvars +\* nc: whenever S is live (SDeletable = slive); records delAt and whether a fork was in its window +DeleteS == SDeletable /\ slive' = FALSE + /\ delAt' = (IF NoClaim THEN now ELSE delAt) + /\ sdelfk' = (IF (NoClaim /\ step = "fk") THEN TRUE ELSE sdelfk) /\ UNCHANGED <> + /\ UNCHANGED <> \* GC (reduced machine E): deletes present fids no root reaches, and fids put on the list Gc == gcs < MaxGc /\ store' = [f \in Fids |-> IF store[f] = "pres" /\ (f \notin Roots \/ f \in gclist) THEN "del" ELSE store[f]] /\ gcs' = gcs + 1 /\ UNCHANGED <> + /\ UNCHANGED tvars + +\* nc: time advances by one tick (never when NoClaim = FALSE) +Tick == NoClaim /\ now < MaxTick /\ now' = now + 1 + /\ UNCHANGED <> + /\ UNCHANGED <> Next == Claim \/ ForkBegin \/ ForkEnd \/ Cas \/ Marker \/ DropClaim \/ SnapT \/ Crash \/ DeleteV \/ DeleteS \/ Gc \/ UploadLate \/ (\E B \in BatchSet : Upload(B) \/ CasEarly(B)) + \/ ForkFail \/ ForkNotFound \/ Tick Spec == Init /\ [][Next]_vars @@ -163,11 +233,24 @@ ClaimUntilIndependent == (thead # NoHead /\ ~ marker) => claim ClaimUntilHead_Inv == (step = "fk") => claim \* lifecycle independence: after the marker and the claim drop, nothing of T holds S LifecycleFree == (marker /\ ~ claim) => ~ SHeld +\* nc replacement of LifecycleFree: nothing ever holds S; S is deletable at every moment it lives +LifecycleFreeNC == NoClaim => (~ claim /\ (SDeletable = slive)) +\* nc frame check for old cfgs: with NoClaim = FALSE the new variables never move +OldFrame == (~ NoClaim) => (now = 0 /\ readAt = None /\ delAt = None /\ ~ sdelfk /\ ~ ffail) \* INV-RESTORE-STATE-REMOTE: "done" only when the remote marker exists StateRemote == step = "done" => marker -TypeOK == /\ step \in {"start", "c", "fk", "own", "done"} /\ up \subseteq Fids /\ tsnap \subseteq Fids +TypeOK == /\ step \in {"start", "c", "fk", "own", "done", "nf"} /\ up \subseteq Fids /\ tsnap \subseteq Fids + /\ now \in 0..MaxTick /\ readAt \in {None} \cup (0..MaxTick) /\ delAt \in {None} \cup (0..MaxTick) + /\ sdelfk \in BOOLEAN /\ ffail \in BOOLEAN \* witnesses (r0.1): each is an invariant expected to be VIOLATED, proving the state is reachable W_Done == ~ (marker /\ ~ claim /\ ~ slive /\ ~ vlive /\ \A i \in Idx : store[VF[i]] = "del") W_CrashResume == ~ (marker /\ crashes = MaxCrash) +\* nc witnesses: S deleted inside the fork window and the restore still completes, every block present, +\* every V fid physically gone +W_nc_DelInFork == ~ (sdelfk /\ marker /\ step = "done" /\ ~ vlive /\ ~ slive + /\ (\A i \in Idx : store[VF[i]] = "del") + /\ (\A i \in Idx : store[thead[i]] = "pres")) +\* nc witness: a fork failed on its deadline and a retry found S gone +W_nc_FailNotFound == ~ (ffail /\ step = "nf") ============================================================================= diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_crash_resume.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G0D1.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_wit_crash_resume.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G0D1.cfg index 1ab2298c47..8102f6b6cf 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_crash_resume.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G0D1.cfg @@ -14,12 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 1 + G = 0 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote - W_CrashResume diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G1D1.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G1D1.cfg new file mode 100644 index 0000000000..5b319dceb8 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G1D1.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 1 + G = 1 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G2D3.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G2D3.cfg new file mode 100644 index 0000000000..959c1e147f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G2D3.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 3 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G3D3.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G3D3.cfg new file mode 100644 index 0000000000..dabec4a948 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_bnd_G3D3.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 3 + G = 3 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_cas_before_upload.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_CasBeforeUpload.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_cas_before_upload.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_CasBeforeUpload.cfg index 70a61b6cee..b398ea33a7 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_cas_before_upload.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_CasBeforeUpload.cfg @@ -14,11 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_GltD.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_GltD.cfg new file mode 100644 index 0000000000..d5a4f2f982 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_GltD.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 1 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_list_foreign.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ListForeign.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_list_foreign.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ListForeign.cfg index 82592e7bc4..460f66230b 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_list_foreign.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ListForeign.cfg @@ -14,11 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_before_cas.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerBeforeCas.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_before_cas.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerBeforeCas.cfg index 560a8c4cc7..088e125bd2 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_before_cas.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerBeforeCas.cfg @@ -14,11 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_early.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerEarly.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_early.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerEarly.cfg index 38b2ecc46a..de0c18acac 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_marker_early.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_MarkerEarly.cfg @@ -14,11 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_no_intent.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_NoIntent.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_no_intent.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_NoIntent.cfg index b2ed698e1f..a9584e358a 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_no_intent.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_NoIntent.cfg @@ -14,11 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = TRUE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_resume_local.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ResumeLocal.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_resume_local.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ResumeLocal.cfg index 383cbda367..a5690276cb 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_resume_local.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_ResumeLocal.cfg @@ -14,11 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_snap_during_restore.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_SnapDuringRestore.cfg similarity index 74% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_snap_during_restore.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_SnapDuringRestore.cfg index dce285726d..00961ba3fb 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_snap_during_restore.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_SnapDuringRestore.cfg @@ -14,11 +14,17 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilIndependent - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_noDeadline.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_noDeadline.cfg new file mode 100644 index 0000000000..1d114c2163 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_noDeadline.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = FALSE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_notRooted.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_notRooted.cfg new file mode 100644 index 0000000000..cd8b15a2c1 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_notRooted.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = FALSE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_resumeNoReread.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_resumeNoReread.cfg new file mode 100644 index 0000000000..a623dd8f51 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_red_resumeNoReread.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = FALSE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe.cfg new file mode 100644 index 0000000000..fef3519c2c --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_G3D2.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_G3D2.cfg new file mode 100644 index 0000000000..24ee54e48a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_G3D2.cfg @@ -0,0 +1,30 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 3 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_b2.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_b2.cfg similarity index 69% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_safe_b2.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_b2.cfg index bf269afeae..9b33687854 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_b2.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_b2.cfg @@ -12,13 +12,19 @@ CONSTANTS ResumeLocal = FALSE SnapDuringRestore = FALSE RetentionIgnoresMarker = FALSE - ClaimUntilHead = TRUE + ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilHead_Inv - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_n4.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_n4.cfg similarity index 69% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_safe_n4.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_n4.cfg index 34c9db075b..c0c370f29e 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe_n4.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_safe_n4.cfg @@ -12,13 +12,19 @@ CONSTANTS ResumeLocal = FALSE SnapDuringRestore = FALSE RetentionIgnoresMarker = FALSE - ClaimUntilHead = TRUE + ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilHead_Inv - LifecycleFree + LifecycleFreeNC StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_DelInFork.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_DelInFork.cfg new file mode 100644 index 0000000000..79708ebd36 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_DelInFork.cfg @@ -0,0 +1,31 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote + W_nc_DelInFork diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_FailNotFound.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_FailNotFound.cfg new file mode 100644 index 0000000000..74cc24ef9f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_nc_wit_FailNotFound.cfg @@ -0,0 +1,31 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = FALSE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = TRUE + D = 2 + G = 2 + MaxTick = 6 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFreeNC + StateRemote + W_nc_FailNotFound diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_strict_claim_until_independent.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe.cfg similarity index 76% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_strict_claim_until_independent.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe.cfg index 9590e854ad..ae5548a57e 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_strict_claim_until_independent.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe.cfg @@ -14,6 +14,13 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = FALSE + D = 0 + G = 0 + MaxTick = 0 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap @@ -22,3 +29,4 @@ INVARIANTS ClaimUntilIndependent LifecycleFree StateRemote + OldFrame diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe_drop.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe_drop.cfg new file mode 100644 index 0000000000..33e1c88fdb --- /dev/null +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_oldframe_drop.cfg @@ -0,0 +1,31 @@ +SPECIFICATION Spec +CONSTANTS + NIdx = 3 + Batch = 1 + MaxCrash = 2 + MaxGc = 3 + DropClaimAtFork = TRUE + CasBeforeUpload = FALSE + ListForeign = FALSE + MarkerEarly = FALSE + MarkerBeforeCas = FALSE + ResumeLocal = FALSE + SnapDuringRestore = FALSE + RetentionIgnoresMarker = FALSE + ClaimUntilHead = FALSE + NoIntent = FALSE + NoClaim = FALSE + D = 0 + G = 0 + MaxTick = 0 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE +INVARIANTS + TypeOK + NoGap + Independent + NoForeignList + LifecycleFree + StateRemote + OldFrame diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_done.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_opt1_safe.cfg similarity index 78% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_wit_done.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_opt1_safe.cfg index 3d9c60ac18..c4f0281674 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_wit_done.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_opt1_safe.cfg @@ -14,6 +14,13 @@ CONSTANTS RetentionIgnoresMarker = FALSE ClaimUntilHead = TRUE NoIntent = FALSE + NoClaim = FALSE + D = 0 + G = 0 + MaxTick = 0 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap @@ -22,4 +29,3 @@ INVARIANTS ClaimUntilHead_Inv LifecycleFree StateRemote - W_Done diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_drop_claim_at_fork.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_DropClaimAtFork_gap.cfg similarity index 72% rename from seaweed-block/docs/spec/cfg/RestoreIndependence_red_drop_claim_at_fork.cfg rename to seaweed-block/docs/spec/cfg/RestoreIndependence_red_DropClaimAtFork_gap.cfg index 5dae146b29..6bd867a906 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_drop_claim_at_fork.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_DropClaimAtFork_gap.cfg @@ -12,13 +12,19 @@ CONSTANTS ResumeLocal = FALSE SnapDuringRestore = FALSE RetentionIgnoresMarker = FALSE - ClaimUntilHead = TRUE + ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = FALSE + D = 0 + G = 0 + MaxTick = 0 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilHead_Inv LifecycleFree StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_retention_ignores_marker.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_red_retention_ignores_marker.cfg deleted file mode 100644 index 6c115a1f13..0000000000 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_red_retention_ignores_marker.cfg +++ /dev/null @@ -1,24 +0,0 @@ -SPECIFICATION Spec -CONSTANTS - NIdx = 3 - Batch = 1 - MaxCrash = 2 - MaxGc = 3 - DropClaimAtFork = FALSE - CasBeforeUpload = FALSE - ListForeign = FALSE - MarkerEarly = FALSE - MarkerBeforeCas = FALSE - ResumeLocal = FALSE - SnapDuringRestore = FALSE - RetentionIgnoresMarker = TRUE - ClaimUntilHead = FALSE - NoIntent = FALSE -INVARIANTS - TypeOK - NoGap - Independent - NoForeignList - ClaimUntilIndependent - LifecycleFree - StateRemote diff --git a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe.cfg b/seaweed-block/docs/spec/cfg/RestoreIndependence_safe.cfg index 682ed72f1f..5327a664e4 100644 --- a/seaweed-block/docs/spec/cfg/RestoreIndependence_safe.cfg +++ b/seaweed-block/docs/spec/cfg/RestoreIndependence_safe.cfg @@ -12,13 +12,20 @@ CONSTANTS ResumeLocal = FALSE SnapDuringRestore = FALSE RetentionIgnoresMarker = FALSE - ClaimUntilHead = TRUE + ClaimUntilHead = FALSE NoIntent = FALSE + NoClaim = FALSE + D = 0 + G = 0 + MaxTick = 0 + ForkChecksDeadline = TRUE + DeletedRooted = TRUE + ResumeRereads = TRUE INVARIANTS TypeOK NoGap Independent NoForeignList - ClaimUntilHead_Inv + ClaimUntilIndependent LifecycleFree StateRemote From 7a9d0f7008ab6c22b1f9e96f073101d56fff21b6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 02:17:05 -0800 Subject: [PATCH 21/34] fold: re-own fully local absent chunks, drop keyless cached payloads, owner-bound driver, stricter tests - OwnBatch, its cut candidates and its progress use one predicate: a chunk is local when present or when every block was written locally (a guest overwrite flushed before the walker reached it), so such a chunk is owned with no fetch instead of stalling the driver. - OwnBatch drops a remembered payload of a picked chunk that matched HEAD and was never uploaded (no key), so the cut reads and uploads it under an own key. - The driver runs inside the serving provider's lifetime (DurableProvider GoOwned: ctx ends at Close, Close joins it); a closed provider admits none. - Tests (each red without its fix): fully overwritten absent chunk owned with no Get; equal keyless payload from a failed cut still re-owned; a second start joins the running run (one walk); owner close cancels and joins a run held in a provider call and no marker follows; Close joins GoOwned; the pacing test requires all 8 fills and Gets and witnesses admission times. - Restore diagram and bullet without claims (same text as the snapshot-delete change). Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/durable/provider_restore.go | 23 +++ .../frontend/durable/provider_restore_test.go | 44 +++++ .../core/host/volume/chunk_restore.go | 26 ++- .../core/host/volume/chunk_restore_test.go | 162 ++++++++++++++---- .../core/storage/chunk_hydrate_all_test.go | 46 ++++- seaweed-block/core/storage/chunk_own.go | 35 +++- seaweed-block/core/storage/chunk_own_test.go | 96 +++++++++++ .../docs/design/agent-workspace-design.md | 8 +- 8 files changed, 389 insertions(+), 51 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/provider_restore_test.go diff --git a/seaweed-block/core/frontend/durable/provider_restore.go b/seaweed-block/core/frontend/durable/provider_restore.go index fde0c680aa..6956c2d0f5 100644 --- a/seaweed-block/core/frontend/durable/provider_restore.go +++ b/seaweed-block/core/frontend/durable/provider_restore.go @@ -2,6 +2,7 @@ package durable import ( "context" + "errors" "fmt" "github.com/seaweedfs/seaweed-block/core/hostlimit" @@ -49,3 +50,25 @@ func (p *DurableProvider) OwnVolumeBatch(ctx context.Context, volumeID string, n defer cancel() return r.OwnBatch(ctx, n, foreign) } + +// ErrProviderClosed refuses work admitted after Close. +var ErrProviderClosed = errors.New("durable: provider closed") + +// GoOwned runs fn on its own goroutine inside the provider's lifetime: its +// ctx ends when Close starts, and Close waits for fn to return before it +// closes any store. A restore driver runs this way, so it never outlives the +// volume it drives. +func (p *DurableProvider) GoOwned(fn func(ctx context.Context)) error { + p.mu.Lock() + if p.closed { + p.mu.Unlock() + return ErrProviderClosed + } + p.inflight.Add(1) + p.mu.Unlock() + go func() { + defer p.inflight.Done() + fn(p.closeCtx) + }() + return nil +} diff --git a/seaweed-block/core/frontend/durable/provider_restore_test.go b/seaweed-block/core/frontend/durable/provider_restore_test.go new file mode 100644 index 0000000000..63cc0ab70f --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_restore_test.go @@ -0,0 +1,44 @@ +package durable_test + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" +) + +// A goroutine started with GoOwned sees its ctx end when Close starts, and +// Close returns only after it has returned; after Close nothing is admitted. +func TestDurableProvider_GoOwnedIsCancelledAndJoinedByClose(t *testing.T) { + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 64}, v1View()) + if err != nil { + t.Fatal(err) + } + started, finished := make(chan struct{}), make(chan struct{}) + if err := p.GoOwned(func(ctx context.Context) { + close(started) + <-ctx.Done() + time.Sleep(20 * time.Millisecond) // still settling when Close is called + close(finished) + }); err != nil { + t.Fatal(err) + } + <-started + closed := make(chan struct{}) + go func() { _ = p.Close(); close(closed) }() + select { + case <-closed: + select { + case <-finished: + default: + t.Fatal("Close returned before the owned goroutine finished") + } + case <-time.After(5 * time.Second): + t.Fatal("Close did not return") + } + if err := p.GoOwned(func(context.Context) {}); !errors.Is(err, durable.ErrProviderClosed) { + t.Fatalf("GoOwned after Close: %v, want ErrProviderClosed", err) + } +} diff --git a/seaweed-block/core/host/volume/chunk_restore.go b/seaweed-block/core/host/volume/chunk_restore.go index eb334788df..94521f0134 100644 --- a/seaweed-block/core/host/volume/chunk_restore.go +++ b/seaweed-block/core/host/volume/chunk_restore.go @@ -149,12 +149,13 @@ type restoreRuns struct { } // Restore reports vol's restore status and, with start, starts a run unless -// one is running (POST /chunk/restore). A run outlives the request; it ends -// independent, or failed with the error (a later start resumes from the -// target's remote facts). +// one is running (POST /chunk/restore). A run outlives the request but not +// the serving provider (RestoreOwner); it ends independent, or failed with +// the error (a later start resumes from the target's remote facts). func (c *chunkControl) Restore(ctx context.Context, vol string, start bool) (RestoreStatus, error) { p, ok := c.p.(RestoreProvider) - if !ok { + owner, owned := c.p.(RestoreOwner) + if !ok || !owned { return RestoreStatus{}, fmt.Errorf("restore: provider has no restore surface: %w", errNotRestore) } c.restores.mu.Lock() @@ -176,18 +177,29 @@ func (c *chunkControl) Restore(ctx context.Context, vol string, start bool) (Res *st = s c.restores.mu.Unlock() } - go func() { - final, err := runRestore(context.Background(), c.cat, p, vol, RestoreConfig{}, report) + run := func(ctx context.Context) { + final, err := runRestore(ctx, c.cat, p, vol, RestoreConfig{}, report) final.Running = false if err != nil { _, code, _ := chunkErrorCode(err) final.Phase, final.ErrorCode, final.ErrorText = RestoreFailed, code, err.Error() } report(final) - }() + } + if err := owner.GoOwned(run); err != nil { + delete(c.restores.runs, vol) + return RestoreStatus{}, err + } return *st, nil } +// RestoreOwner runs the driver inside the serving volume's lifetime: the +// driver's ctx ends when the owner closes, and the owner waits for it +// (DurableProvider.GoOwned). +type RestoreOwner interface { + GoOwned(fn func(ctx context.Context)) error +} + // handleChunkRestore serves GET /chunk/restore?volume=V (status) and // POST /chunk/restore {"volumeID": V} (start or join a run; with // "statusOnly": true, status only). Both answer 200 with the status. diff --git a/seaweed-block/core/host/volume/chunk_restore_test.go b/seaweed-block/core/host/volume/chunk_restore_test.go index b4eebd880c..17b264e38a 100644 --- a/seaweed-block/core/host/volume/chunk_restore_test.go +++ b/seaweed-block/core/host/volume/chunk_restore_test.go @@ -8,6 +8,7 @@ import ( "path" "sort" "strings" + "sync" "testing" "time" @@ -59,10 +60,24 @@ type fakeRestoreProvider struct { hydrations int batches int failAtBatch int // a batch with this 1-based number fails (0: never) + mu sync.Mutex + entered chan struct{} // if set, HydrateVolume signals entry and + gate chan struct{} // then waits for gate or its ctx } func (p *fakeRestoreProvider) HydrateVolume(ctx context.Context, vol string, bps int64) (storage.HydrateProgress, error) { + p.mu.Lock() p.hydrations++ + entered, gate := p.entered, p.gate + p.mu.Unlock() + if entered != nil { + entered <- struct{}{} + select { + case <-gate: + case <-ctx.Done(): + return storage.HydrateProgress{}, ctx.Err() + } + } if bps != DefaultRestoreBytesPerSecond { return storage.HydrateProgress{}, fmt.Errorf("walker pace %d, want the default %d", bps, DefaultRestoreBytesPerSecond) } @@ -244,38 +259,44 @@ func TestRestoreDriver_RefusesAVolumeNotMadeByRestore(t *testing.T) { } } -// POST /chunk/restore starts one background run; GET reports it. -func TestRestoreDriver_ChunkControlStartsOneRunAndReportsIt(t *testing.T) { - _, cat, p := restoreFixtureHost(t, 3) - ctl := &chunkControl{p: restoreOnlyProvider{p}, cat: cat} - ctx := context.Background() - if st, err := ctl.Restore(ctx, "v2", false); err != nil || st.Phase != "" { - t.Fatalf("status before any run: %+v %v", st, err) - } - if _, err := ctl.Restore(ctx, "v2", true); err != nil { - t.Fatal(err) - } - deadline := time.Now().Add(5 * time.Second) - for { - st, err := ctl.Restore(ctx, "v2", false) - if err != nil { - t.Fatal(err) - } - if !st.Running { - if st.Phase != RestoreIndependent || st.Owned != 3 { - t.Fatalf("final status %+v", st) - } - break - } - if time.Now().After(deadline) { - t.Fatalf("restore still running: %+v", st) - } - time.Sleep(time.Millisecond) +// testOwner runs owned goroutines until close, which cancels and joins them +// (bounded), like DurableProvider.Close. +type testOwner struct { + ctx context.Context + cancel context.CancelFunc + wg sync.WaitGroup +} + +func newTestOwner(t *testing.T) *testOwner { + o := &testOwner{} + o.ctx, o.cancel = context.WithCancel(context.Background()) + t.Cleanup(func() { o.close(t) }) + return o +} + +func (o *testOwner) GoOwned(fn func(context.Context)) error { + o.wg.Add(1) + go func() { defer o.wg.Done(); fn(o.ctx) }() + return nil +} + +func (o *testOwner) close(t *testing.T) { + o.cancel() + done := make(chan struct{}) + go func() { o.wg.Wait(); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("owned restore run did not return after close") } } -// restoreOnlyProvider is a ChunkProvider whose cut and detach are unused. -type restoreOnlyProvider struct{ *fakeRestoreProvider } +// restoreOnlyProvider is a ChunkProvider (cut and detach unused) with the +// restore surface and an owner. +type restoreOnlyProvider struct { + *fakeRestoreProvider + *testOwner +} func (restoreOnlyProvider) CutVolume(context.Context, string, uint64) (storage.ChunkCutResult, error) { return storage.ChunkCutResult{}, errors.New("unused") @@ -284,4 +305,87 @@ func (restoreOnlyProvider) DetachVolume(context.Context, string) (storage.ChunkC return storage.ChunkCutResult{}, 0, errors.New("unused") } +func waitRestore(t *testing.T, ctl *chunkControl, vol string) RestoreStatus { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for { + st, err := ctl.Restore(context.Background(), vol, false) + if err != nil { + t.Fatal(err) + } + if !st.Running { + return st + } + if time.Now().After(deadline) { + t.Fatalf("restore still running: %+v", st) + } + time.Sleep(time.Millisecond) + } +} + +// POST /chunk/restore starts one background run: a second start while the +// first is held joins it (one walk), and the run is reported to the end. +func TestRestoreDriver_ChunkControlStartsOneRunAndReportsIt(t *testing.T) { + _, cat, p := restoreFixtureHost(t, 3) + owner := newTestOwner(t) + p.entered, p.gate = make(chan struct{}, 2), make(chan struct{}) + release := func() { + select { + case <-p.gate: + default: + close(p.gate) + } + } + t.Cleanup(release) // registered before launch; the owner joins after it + ctl := &chunkControl{p: restoreOnlyProvider{p, owner}, cat: cat} + ctx := context.Background() + if st, err := ctl.Restore(ctx, "v2", false); err != nil || st.Phase != "" { + t.Fatalf("status before any run: %+v %v", st, err) + } + if _, err := ctl.Restore(ctx, "v2", true); err != nil { + t.Fatal(err) + } + select { + case <-p.entered: + case <-time.After(5 * time.Second): + t.Fatal("the run never reached the walker") + } + if st, err := ctl.Restore(ctx, "v2", true); err != nil || !st.Running { + t.Fatalf("second start while the first runs: %+v %v, want it joined", st, err) + } + release() + st := waitRestore(t, ctl, "v2") + p.mu.Lock() + walks := p.hydrations + p.mu.Unlock() + if walks != 1 || st.Phase != RestoreIndependent || st.Owned != 3 { + t.Fatalf("walks=%d status %+v, want one run to independence", walks, st) + } +} + +// Closing the serving owner cancels a run held in a provider call and joins +// it: the run ends failed and publishes no marker after the close. +func TestRestoreDriver_OwnerCloseCancelsAndJoinsTheRun(t *testing.T) { + _, cat, p := restoreFixtureHost(t, 3) + owner := newTestOwner(t) + p.entered, p.gate = make(chan struct{}, 1), make(chan struct{}) // gate never opens + ctl := &chunkControl{p: restoreOnlyProvider{p, owner}, cat: cat} + if _, err := ctl.Restore(context.Background(), "v2", true); err != nil { + t.Fatal(err) + } + select { + case <-p.entered: + case <-time.After(5 * time.Second): + t.Fatal("the run never reached the walker") + } + owner.close(t) // cancel and bounded join, like DurableProvider.Close + st, err := ctl.Restore(context.Background(), "v2", false) + if err != nil || st.Running || st.Phase != RestoreFailed { + t.Fatalf("status after the owner closed: %+v %v, want a finished failed run", st, err) + } + if _, ok, _ := cat.ReadIndependence(context.Background(), "v2"); ok { + t.Fatal("a marker was published after the owner closed") + } +} + var _ RestoreProvider = (*durable.DurableProvider)(nil) diff --git a/seaweed-block/core/storage/chunk_hydrate_all_test.go b/seaweed-block/core/storage/chunk_hydrate_all_test.go index 34e981ea67..bed6e2297b 100644 --- a/seaweed-block/core/storage/chunk_hydrate_all_test.go +++ b/seaweed-block/core/storage/chunk_hydrate_all_test.go @@ -411,15 +411,47 @@ func TestHydrateAll_StatsReportAbsentChunks(t *testing.T) { // at least (8-1)/4 s. func TestHydrateAll_PacedByByteRate(t *testing.T) { fastWalker(t) - _, layer, _, _ := hydrationFixture(t, 2, 64) + _, layer, remote, _ := hydrationFixture(t, 2, 64) + budget := &timedBudget{} + layer.cfg.Budget = budget // admission times witness the pace rate := int64(4 * ctChunkBytes) - start := time.Now() p, err := layer.HydrateAllAt(boundedCtx(t, context.Background()), rate) - took := time.Since(start) - if err != nil || p.Remaining != 0 { - t.Fatalf("paced walk: %+v %v", p, err) + want := ctNumBlocks / ctChunkBlocks + if err != nil || p.Remaining != 0 || p.Filled != want { + t.Fatalf("paced walk: %+v %v, want all %d chunks filled", p, err, want) } - if min := time.Duration(p.Filled-1) * time.Second / 4; took < min { - t.Fatalf("%d fills at %d B/s took %v, want at least %v", p.Filled, rate, took, min) + gets := 0 + for _, n := range countGets(remote) { + gets += n + } + if gets != want { + t.Fatalf("%d remote Gets, want %d", gets, want) + } + budget.mu.Lock() + defer budget.mu.Unlock() + if len(budget.at) != want { + t.Fatalf("%d admissions, want %d", len(budget.at), want) + } + for i := 1; i < len(budget.at); i++ { + // fill i is admitted no earlier than i chunks at the rate from the start + due := budget.at[0].Add(time.Duration(i) * time.Second / 4) + if budget.at[i].Before(due.Add(-10 * time.Millisecond)) { + t.Fatalf("fill %d admitted %v after the first, before its pace time %v", i, budget.at[i].Sub(budget.at[0]), due.Sub(budget.at[0])) + } } } + +// timedBudget admits every fill and records when. +type timedBudget struct { + mu sync.Mutex + at []time.Time +} + +func (b *timedBudget) Admit(context.Context, int64, func(error)) (uint64, error) { + b.mu.Lock() + defer b.mu.Unlock() + b.at = append(b.at, time.Now()) + return uint64(len(b.at)), nil +} +func (b *timedBudget) ReserveCOW(uint64, int64) error { return nil } +func (b *timedBudget) Release(uint64) {} diff --git a/seaweed-block/core/storage/chunk_own.go b/seaweed-block/core/storage/chunk_own.go index 5f9188f8b4..6b004e08ee 100644 --- a/seaweed-block/core/storage/chunk_own.go +++ b/seaweed-block/core/storage/chunk_own.go @@ -17,7 +17,8 @@ type OwnProgress struct { // OwnBatch runs one bounded cut (M6.Restore.Owning>Owning): it picks up to n // chunks, lowest index first, whose HEAD key is foreign (foreign reports -// whether a key names another volume's object) and that are local, and cuts +// whether a key names another volume's object) and that are local (present, +// or every block written locally), and cuts // with them as candidates: each is uploaded under a new own key under the // cut's intent and published by the cut's one HEAD CAS, even when its bytes // equal HEAD's. Absent chunks are skipped (never fetched by the cut). The cut @@ -30,7 +31,7 @@ func (l *chunkLayerImpl) OwnBatch(ctx context.Context, n int, foreign func(key s l.stMu.Lock() var picked []uint64 for _, idx := range sortedForeign(l.head.Chunks, foreign) { - if len(picked) < n && !l.absent[idx] { + if len(picked) < n && l.chunkLocalLocked(idx) { picked = append(picked, idx) } } @@ -42,6 +43,12 @@ func (l *chunkLayerImpl) OwnBatch(ctx context.Context, n int, foreign func(key s l.own = make(map[uint64]bool, len(picked)) for _, idx := range picked { l.own[idx] = true + // A payload remembered from an earlier failed cut that matched HEAD + // was never uploaded (no key, data discarded): reusing it would skip + // the re-own upload. Drop it, so this cut reads and uploads the chunk. + if sc, ok := l.reusable[idx]; ok && sc.key == "" { + delete(l.reusable, idx) + } } l.stMu.Unlock() _, err := l.captureLocked(ctx, false) @@ -69,7 +76,7 @@ func (l *chunkLayerImpl) ownProgressLocked(foreign func(string) bool) ownCount { c := ownCount{head: l.head.Chunks} for _, idx := range sortedForeign(l.head.Chunks, foreign) { c.Remaining++ - if l.absent[idx] { + if !l.chunkLocalLocked(idx) { c.NotLocal++ } } @@ -100,12 +107,32 @@ func (l *chunkLayerImpl) owning(idx uint64) bool { // Caller holds stMu. func (l *chunkLayerImpl) addOwnCandidatesLocked(out map[uint64]bool) { for idx := range l.own { - if !l.absent[idx] { + if l.chunkLocalLocked(idx) { out[idx] = true } } } +// chunkLocalLocked reports whether a re-own can read chunk idx without a +// fetch: it is present, or absent with every block written locally (a guest +// overwrite flushed before the walker reached it). Caller holds stMu. +func (l *chunkLayerImpl) chunkLocalLocked(idx uint64) bool { + if !l.absent[idx] { + return true + } + first := idx * l.chunkBlocks + for i := uint64(0); i < l.chunkBlocks; i++ { + b := first + i + if b >= uint64(l.s.NumBlocks()) { + break + } + if !l.localBlocks[b] { + return false + } + } + return true +} + // unchangedFromHead reports whether a captured chunk equals HEAD's and was // not uploaded: such a chunk keeps its HEAD ref. A re-owned chunk equal to // HEAD was uploaded by streamCutPayloads under a new own key (c.key set), so diff --git a/seaweed-block/core/storage/chunk_own_test.go b/seaweed-block/core/storage/chunk_own_test.go index fa986a0df5..a1a902d597 100644 --- a/seaweed-block/core/storage/chunk_own_test.go +++ b/seaweed-block/core/storage/chunk_own_test.go @@ -3,8 +3,10 @@ package storage import ( "bytes" "context" + "errors" "strings" "testing" + "time" ) func seedForeign(key string) bool { return strings.HasPrefix(key, "seed/") } @@ -94,3 +96,97 @@ func TestOwnBatch_CarriesGuestWrites(t *testing.T) { t.Fatal("the guest write did not reach HEAD with the batch") } } + +// A chunk whose every block the guest overwrote and flushed before the walker +// reached it stays absent but is fully local: a batch owns it with no fetch +// (codex01 #340 S1: otherwise nothing ever cuts it and the driver stalls). +func TestOwnBatch_OwnsAFullyOverwrittenAbsentChunkWithoutAFetch(t *testing.T) { + fastWalker(t) + s, layer, remote, _ := hydrationFixture(t, 2, 64) + const idx = 3 + for i := uint32(0); i < ctChunkBlocks; i++ { + if _, err := s.Write(idx*ctChunkBlocks+i, makeBlock(ctBlockSize, 0xC0+byte(i))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + layer.stMu.Lock() + absent := layer.absent[idx] + layer.stMu.Unlock() + if !absent { + t.Fatal("fixture: the overwritten chunk must still be absent") + } + if _, err := layer.HydrateAll(ownCtx(t)); err != nil { + t.Fatal(err) + } + seedKey := remote.stats().head.Chunks[idx].Key + // The stall needs this chunk to be the only foreign one left: then no + // other pick triggers the cut that would carry its guest write. + onlyThis := func(key string) bool { return key == seedKey } + p, err := layer.OwnBatch(ownCtx(t), 3, onlyThis) + if err != nil || p.Owned != 1 || p.Remaining != 0 { + t.Fatalf("batch with only the fully overwritten chunk foreign: %+v %v, want it owned", p, err) + } + if n := countGets(remote)[seedKey]; n != 0 { + t.Fatalf("the fully overwritten chunk was fetched %d times", n) + } + img := remote.imageOf(t, remote.stats().head) + for i := 0; i < ctChunkBlocks; i++ { + off := (idx*ctChunkBlocks + i) * ctBlockSize + if !bytes.Equal(img[off:off+ctBlockSize], makeBlock(ctBlockSize, 0xC0+byte(i))) { + t.Fatalf("block %d of the overwritten chunk is not the guest's in HEAD", i) + } + } +} + +// A failed ordinary cut remembers an equal-to-HEAD chunk without a key; the +// next batch must still upload it under an own key (codex01 #340 S2). +func TestOwnBatch_UploadsAChunkRememberedEqualByAFailedCut(t *testing.T) { + fastWalker(t) + s, layer, remote, _ := hydrationFixture(t, 2, 64) + if _, err := layer.HydrateAll(ownCtx(t)); err != nil { + t.Fatal(err) + } + same := makeBlock(ctBlockSize, 0x40) // block 0 rewritten with HEAD's own bytes + if _, err := s.Write(0, same); err != nil { + t.Fatal(err) + } + if _, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0xEE)); err != nil { // chunk 1 changed + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + remote.mu.Lock() + remote.failPut = errors.New("test: put refused") + remote.mu.Unlock() + failCtx, cancelFail := context.WithTimeout(context.Background(), 300*time.Millisecond) + defer cancelFail() + if _, err := layer.Cut(failCtx); err == nil { + t.Fatal("fixture: the ordinary cut must fail") + } + remote.mu.Lock() + remote.failPut = nil + remote.mu.Unlock() + layer.stMu.Lock() + sc, kept := layer.reusable[0] + layer.stMu.Unlock() + if !kept || sc.key != "" { + t.Fatalf("fixture: the failed cut must remember chunk 0 equal and keyless: kept=%v key=%q", kept, sc.key) + } + p, err := layer.OwnBatch(ownCtx(t), 1, seedForeign) + if err != nil || p.Owned != 1 { + t.Fatalf("batch after the failed cut: %+v %v, want chunk 0 owned", p, err) + } + if k := remote.stats().head.Chunks[0].Key; seedForeign(k) { + t.Fatalf("chunk 0 still names the foreign key %s", k) + } + if !bytes.Equal(remote.imageOf(t, remote.stats().head)[:ctBlockSize], same) { + t.Fatal("chunk 0's bytes changed") + } +} diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index c537e968ec..31935923de 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -187,7 +187,7 @@ stateDiagram-v2 - **Snapshot** (`Catalog.CreateSnapshot`): claim the name with an exclusive name record `{request, attempt}` (a retry gets its own attempt back); check the volume is not being deleted; write an intent with a deadline; re-check the deadline; exclusively create `snaps//` holding a copy of the HEAD root. An unknown outcome keeps the intent; the caller retries with the same request id. - **Fork** (`Catalog.Fork`): claim the parent snapshot, check the source is not being deleted, write the target `VOLUME` (origin fork), then a HEAD at gen 1, epoch 0, no holder, with the parent's `RemoteLSN` and references. No segment or chunk is copied: the fork's references are owner-qualified, so it reads the parent's objects, and its root alone keeps them live after the parent snapshot is deleted. -- **Restore** (`Catalog.Restore`, independent restore): the fork steps with `VOLUME` origin `restore`; the claim is the fork's (live until the target has a HEAD), and from then on the target's owner-qualified refs keep the source's chunks live, so deleting the source snapshot or volume mid-restore is normal. The background walker (`HydrateAll`) makes every chunk local through the shared fill flights, under one host fill permit per flight. Bounded batch cuts then upload the chunks under the target's own keys; when the resolved HEAD holds no ref to another volume, the write-once `RESTORE-INDEPENDENT` entry is created (`MarkIndependent`). Snapshots of the target are refused until then, and a snapshot image that still names another volume's chunks is refused even after it. An aborted first HEAD keeps the parent snapshot as `fork_parent` until the target is deleted. Model: `docs/spec/RestoreIndependence.tla`. +- **Restore** (`Catalog.Restore`, independent restore): the fork steps with `VOLUME` origin `restore`; until its first HEAD the parent stays rooted by GC's grace after any delete, and from then on the target's owner-qualified refs keep the source's chunks live, so deleting the source snapshot or volume mid-restore is normal. The background walker (`HydrateAll`) makes every chunk local through the shared fill flights, under one host fill permit per flight. Bounded batch cuts then upload the chunks under the target's own keys; when the resolved HEAD holds no ref to another volume, the write-once `RESTORE-INDEPENDENT` entry is created (`MarkIndependent`). Snapshots of the target are refused until then, and a snapshot image that still names another volume's chunks is refused even after it. Model: `docs/spec/RestoreIndependence.tla`. - **Retention** (`retention.go`): classes `semantic` and `pinned`; newest N, recent window and log-spaced keeps; a snapshot with a live fork claim is always kept; deletion uses the same conditional mark as `DeleteSnapshot`. - **GC** (`gc.go` `Collector.run`, operator-driven through `sw-block ops chunk gc`, preview by default; see also `core/frontend/chunkstore/GC.md`): - roots: every HEAD, every named snapshot (including one whose delete is still in progress), every snapshot attempt that is not aborted, live intents, and segment objects; an unreadable segment aborts the mark. A deleted snapshot's attempt stays a root for one grace period after its delete time, then stops counting (`Collector.snapshotAttemptHeads` in `gc_copy.go`); @@ -240,9 +240,9 @@ Restore (target volume): ```mermaid stateDiagram-v2 - [*] --> Claimed: claim parent snapshot, write VOLUME (origin restore) - Claimed --> Restoring: first HEAD (parent's refs, owner-qualified); claim dropped - Claimed --> Aborted: GC tombstones the HEAD (parent kept as fork_parent) + [*] --> Forking: read the parent snapshot, write VOLUME (origin restore) + Forking --> Restoring: first HEAD (parent's refs, owner-qualified) before read time + deadline + Forking --> Aborted: GC tombstones the HEAD Restoring --> Hydrating: driver starts the paced walker Hydrating --> Owning: batch cuts start (the walker may still run) Owning --> Owning: one bounded batch cut replaces up to N foreign refs with own keys From ef9155e6607714a53c3f253bd4c741039a735b50 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 02:48:26 -0800 Subject: [PATCH 22/34] test: give the failing-cut fixture 2 s (300 ms was tight on a loaded runner) Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_own_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/chunk_own_test.go b/seaweed-block/core/storage/chunk_own_test.go index a1a902d597..75e8496a76 100644 --- a/seaweed-block/core/storage/chunk_own_test.go +++ b/seaweed-block/core/storage/chunk_own_test.go @@ -165,7 +165,7 @@ func TestOwnBatch_UploadsAChunkRememberedEqualByAFailedCut(t *testing.T) { remote.mu.Lock() remote.failPut = errors.New("test: put refused") remote.mu.Unlock() - failCtx, cancelFail := context.WithTimeout(context.Background(), 300*time.Millisecond) + failCtx, cancelFail := context.WithTimeout(context.Background(), 2*time.Second) defer cancelFail() if _, err := layer.Cut(failCtx); err == nil { t.Fatal("fixture: the ordinary cut must fail") From f2369fad11e52e43ee850661b69cf68dcf8f6b2e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 03:04:56 -0800 Subject: [PATCH 23/34] docs: INV-SHARE-ACTIVATION-001 has no TLA+ property Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 27e557b315..c2299624cd 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -527,7 +527,7 @@ Notes: | `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | | `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | -| `INV-SHARE-ACTIVATION-001` | With a `ShareGuard` installed, a snapshot or fork activates (snapshot entry, child HEAD) only after `Finish` accepts the share; a refused `Begin` or `Finish` aborts before activation and drops the new intent. With no guard, nothing is called or checked. | M6 snapshot: Pending → Published; fork: child HEAD create | `core/frontend/chunkstore/share_guard.go` `beginShare`, `finishShare`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `Fork`; `core/host/volume/chunk_control.go` `chunkControl.Snapshot` | `TestShareGuard_SnapshotFinishesBeforeActivation`, `TestShareGuard_RefusedFinishAbortsTheSnapshot`, `TestShareGuard_StaleHeadIsRefused`, `TestShareGuard_CallerToken`, `TestShareGuard_Fork`, `TestShareGuard_BeginRefused` (`core/frontend/chunkstore/share_guard_test.go`); `TestChunkControl_SnapshotBeginsShareBeforeTheCut`, `TestChunkControl_SnapshotBeginRefusedCutsNothing` (`core/host/volume/chunk_control_order_test.go`) | — (the enterprise policy's protocol is modelled in `ShareMarker`) | ACTIVE | +| `INV-SHARE-ACTIVATION-001` | With a `ShareGuard` installed, a snapshot or fork activates (snapshot entry, child HEAD) only after `Finish` accepts the share; a refused `Begin` or `Finish` aborts before activation and drops the new intent. With no guard, nothing is called or checked. | M6 snapshot: Pending → Published; fork: child HEAD create | `core/frontend/chunkstore/share_guard.go` `beginShare`, `finishShare`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `Fork`; `core/host/volume/chunk_control.go` `chunkControl.Snapshot` | `TestShareGuard_SnapshotFinishesBeforeActivation`, `TestShareGuard_RefusedFinishAbortsTheSnapshot`, `TestShareGuard_StaleHeadIsRefused`, `TestShareGuard_CallerToken`, `TestShareGuard_Fork`, `TestShareGuard_BeginRefused` (`core/frontend/chunkstore/share_guard_test.go`); `TestChunkControl_SnapshotBeginsShareBeforeTheCut`, `TestChunkControl_SnapshotBeginRefusedCutsNothing` (`core/host/volume/chunk_control_order_test.go`) | — | ACTIVE | | `INV-PUBLISH-SETTLED-001` | With `OnPublishSettled` set, each confirmed publication (a new HEAD generation) is delivered once, in publication order, one at a time, outside the capture and state locks. After Close begins, no report is dequeued. | M5 CAS → Settled; M6 HEAD: published | `core/storage/chunk_publish_settled.go` `noteSettled`, `unlockCap`, `runPublishSettled`; `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince` | `TestChunkPublishSettled_ReportsEachPublication`, `TestChunkPublishSettled_ReportsALatePublication`, `TestChunkPublishSettled_ClosedAndUnset`, `TestChunkPublishSettled_OverlappingPublishersStayOrdered`, `TestChunkPublishSettled_CloseDropsUnstartedReports`, `TestChunkPublishSettled_HookThatPublishes`, `TestChunkPublishSettled_PeriodicCutReports` (`core/storage/chunk_publish_settled_test.go`); `TestWALStoreChunk_PublishSettledHook` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE | Notes: From 7fa772b97596242fb9ba26eec011e2a33f093709 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 03:08:35 -0800 Subject: [PATCH 24/34] test fold: pace origin before the call, GoOwned held settlement, owner-close teardown order - The pacing test measures each admission from a time taken before the call, a lower bound of the walker's own start, keeping the exact 8 fills, Gets and admissions. - The GoOwned test bounds every wait, pre-registers release and a bounded join of Close, and witnesses that Close does not return while the owned goroutine is held after its ctx ended (no sleep). - The owner-close driver test releases the held provider call before the owner's join at teardown, so its red case cannot leave a worker behind. Co-Authored-By: Claude Opus 5.5 --- .../frontend/durable/provider_restore_test.go | 45 +++++++++++++------ .../core/host/volume/chunk_restore_test.go | 5 ++- .../core/storage/chunk_hydrate_all_test.go | 10 +++-- 3 files changed, 42 insertions(+), 18 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_restore_test.go b/seaweed-block/core/frontend/durable/provider_restore_test.go index 63cc0ab70f..f52f111b48 100644 --- a/seaweed-block/core/frontend/durable/provider_restore_test.go +++ b/seaweed-block/core/frontend/durable/provider_restore_test.go @@ -10,34 +10,53 @@ import ( ) // A goroutine started with GoOwned sees its ctx end when Close starts, and -// Close returns only after it has returned; after Close nothing is admitted. +// Close does not return while it is still settling; after Close nothing is +// admitted. func TestDurableProvider_GoOwnedIsCancelledAndJoinedByClose(t *testing.T) { p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 64}, v1View()) if err != nil { t.Fatal(err) } - started, finished := make(chan struct{}), make(chan struct{}) + started, cancelled, release := make(chan struct{}), make(chan struct{}), make(chan struct{}) + closed := make(chan struct{}) + released := false + t.Cleanup(func() { // registered before launch: release, then a bounded join of Close + if !released { + close(release) + } + select { + case <-closed: + case <-time.After(5 * time.Second): + t.Error("cleanup: Close did not return") + } + }) if err := p.GoOwned(func(ctx context.Context) { close(started) <-ctx.Done() - time.Sleep(20 * time.Millisecond) // still settling when Close is called - close(finished) + close(cancelled) + <-release // held settlement: Close must wait for this }); err != nil { t.Fatal(err) } - <-started - closed := make(chan struct{}) + wait := func(ch <-chan struct{}, what string) { + t.Helper() + select { + case <-ch: + case <-time.After(5 * time.Second): + t.Fatalf("timed out waiting for %s", what) + } + } + wait(started, "the owned goroutine to start") go func() { _ = p.Close(); close(closed) }() + wait(cancelled, "Close to cancel the owned goroutine's ctx") select { case <-closed: - select { - case <-finished: - default: - t.Fatal("Close returned before the owned goroutine finished") - } - case <-time.After(5 * time.Second): - t.Fatal("Close did not return") + t.Fatal("Close returned while the owned goroutine was still settling") + default: } + released = true + close(release) + wait(closed, "Close to return after the owned goroutine returned") if err := p.GoOwned(func(context.Context) {}); !errors.Is(err, durable.ErrProviderClosed) { t.Fatalf("GoOwned after Close: %v, want ErrProviderClosed", err) } diff --git a/seaweed-block/core/host/volume/chunk_restore_test.go b/seaweed-block/core/host/volume/chunk_restore_test.go index 17b264e38a..d70420b8b4 100644 --- a/seaweed-block/core/host/volume/chunk_restore_test.go +++ b/seaweed-block/core/host/volume/chunk_restore_test.go @@ -368,7 +368,10 @@ func TestRestoreDriver_ChunkControlStartsOneRunAndReportsIt(t *testing.T) { func TestRestoreDriver_OwnerCloseCancelsAndJoinsTheRun(t *testing.T) { _, cat, p := restoreFixtureHost(t, 3) owner := newTestOwner(t) - p.entered, p.gate = make(chan struct{}, 1), make(chan struct{}) // gate never opens + p.entered, p.gate = make(chan struct{}, 1), make(chan struct{}) // opened only at teardown + // Registered after the owner: it runs first, so a run that ignored the + // owner's cancel (the red case) is released before the owner's join. + t.Cleanup(func() { close(p.gate) }) ctl := &chunkControl{p: restoreOnlyProvider{p, owner}, cat: cat} if _, err := ctl.Restore(context.Background(), "v2", true); err != nil { t.Fatal(err) diff --git a/seaweed-block/core/storage/chunk_hydrate_all_test.go b/seaweed-block/core/storage/chunk_hydrate_all_test.go index bed6e2297b..9efd0c2d57 100644 --- a/seaweed-block/core/storage/chunk_hydrate_all_test.go +++ b/seaweed-block/core/storage/chunk_hydrate_all_test.go @@ -415,6 +415,7 @@ func TestHydrateAll_PacedByByteRate(t *testing.T) { budget := &timedBudget{} layer.cfg.Budget = budget // admission times witness the pace rate := int64(4 * ctChunkBytes) + origin := time.Now() // a lower bound of the walker's own pace start p, err := layer.HydrateAllAt(boundedCtx(t, context.Background()), rate) want := ctNumBlocks / ctChunkBlocks if err != nil || p.Remaining != 0 || p.Filled != want { @@ -433,10 +434,11 @@ func TestHydrateAll_PacedByByteRate(t *testing.T) { t.Fatalf("%d admissions, want %d", len(budget.at), want) } for i := 1; i < len(budget.at); i++ { - // fill i is admitted no earlier than i chunks at the rate from the start - due := budget.at[0].Add(time.Duration(i) * time.Second / 4) - if budget.at[i].Before(due.Add(-10 * time.Millisecond)) { - t.Fatalf("fill %d admitted %v after the first, before its pace time %v", i, budget.at[i].Sub(budget.at[0]), due.Sub(budget.at[0])) + // fill i is admitted no earlier than i chunks at the rate after the + // walker started, and the walker started after origin + due := origin.Add(time.Duration(i) * time.Second / 4) + if budget.at[i].Before(due) { + t.Fatalf("fill %d admitted %v after the call, before its pace time %v", i, budget.at[i].Sub(origin), due.Sub(origin)) } } } From daad372367ff7a310c3c818009240102cbc93e8c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 03:18:11 -0800 Subject: [PATCH 25/34] test fold: GoOwned ordering witness and a once-only Close in cleanup The test records the owned goroutine's settlement and Close's return with sequence numbers and requires settlement first; before releasing it gives a Close that does not join 200 ms to return while the goroutine is held. One Close launcher (sync.OnceFunc) serves the body and the pre-registered cleanup, which always cancels, releases and joins, also when GoOwned or the start wait fails. Co-Authored-By: Claude Opus 5.5 --- .../frontend/durable/provider_restore_test.go | 62 ++++++++++++------- 1 file changed, 40 insertions(+), 22 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider_restore_test.go b/seaweed-block/core/frontend/durable/provider_restore_test.go index f52f111b48..5f57567ab5 100644 --- a/seaweed-block/core/frontend/durable/provider_restore_test.go +++ b/seaweed-block/core/frontend/durable/provider_restore_test.go @@ -3,6 +3,8 @@ package durable_test import ( "context" "errors" + "sync" + "sync/atomic" "testing" "time" @@ -10,20 +12,26 @@ import ( ) // A goroutine started with GoOwned sees its ctx end when Close starts, and -// Close does not return while it is still settling; after Close nothing is -// admitted. +// Close returns only after it has returned (ordering witnessed by sequence +// numbers); after Close nothing is admitted. func TestDurableProvider_GoOwnedIsCancelledAndJoinedByClose(t *testing.T) { p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 64}, v1View()) if err != nil { t.Fatal(err) } - started, cancelled, release := make(chan struct{}), make(chan struct{}), make(chan struct{}) - closed := make(chan struct{}) - released := false - t.Cleanup(func() { // registered before launch: release, then a bounded join of Close - if !released { - close(release) - } + var seq, settledAt, closedAt atomic.Int64 + started, cancelled, release, closed := make(chan struct{}), make(chan struct{}), make(chan struct{}), make(chan struct{}) + releaseOnce := sync.OnceFunc(func() { close(release) }) + startClose := sync.OnceFunc(func() { // one Close, launched by the body or by cleanup + go func() { + _ = p.Close() + closedAt.Store(seq.Add(1)) + close(closed) + }() + }) + t.Cleanup(func() { // registered before launch: always cancels, releases and joins + startClose() + releaseOnce() select { case <-closed: case <-time.After(5 * time.Second): @@ -35,28 +43,38 @@ func TestDurableProvider_GoOwnedIsCancelledAndJoinedByClose(t *testing.T) { <-ctx.Done() close(cancelled) <-release // held settlement: Close must wait for this + settledAt.Store(seq.Add(1)) }); err != nil { t.Fatal(err) } - wait := func(ch <-chan struct{}, what string) { + wait := func(ch <-chan struct{}, d time.Duration, what string) bool { t.Helper() select { case <-ch: - case <-time.After(5 * time.Second): - t.Fatalf("timed out waiting for %s", what) + return true + case <-time.After(d): + return false } } - wait(started, "the owned goroutine to start") - go func() { _ = p.Close(); close(closed) }() - wait(cancelled, "Close to cancel the owned goroutine's ctx") - select { - case <-closed: - t.Fatal("Close returned while the owned goroutine was still settling") - default: + if !wait(started, 5*time.Second, "start") { + t.Fatal("the owned goroutine never started") + } + startClose() + if !wait(cancelled, 5*time.Second, "cancel") { + t.Fatal("Close did not cancel the owned goroutine's ctx") + } + // Adverse schedule for a Close that does not join: give it time to + // return while the goroutine is still held. + if wait(closed, 200*time.Millisecond, "early close") { + t.Fatal("Close returned while the owned goroutine was still held") + } + releaseOnce() + if !wait(closed, 5*time.Second, "close") { + t.Fatal("Close did not return after the owned goroutine returned") + } + if s, c := settledAt.Load(), closedAt.Load(); s == 0 || c <= s { + t.Fatalf("Close returned (seq %d) before the owned goroutine settled (seq %d)", c, s) } - released = true - close(release) - wait(closed, "Close to return after the owned goroutine returned") if err := p.GoOwned(func(context.Context) {}); !errors.Is(err, durable.ErrProviderClosed) { t.Fatalf("GoOwned after Close: %v, want ErrProviderClosed", err) } From fd9781af14f502d97c60238d9bcd823055245b02 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 03:56:24 -0800 Subject: [PATCH 26/34] durable, storage: tests for pre-copy and I/O-gate rules no test pinned A pause's drain waits for every admitted I/O (two in flight), a pause does not begin on an unusable backend, a drain that loses readiness ends with an error, the sample history is bounded at 32, the round loop retries only the named errors, the attach wait fails fast on a terminal state, a plain-detach stop refuses a closed backend. Tests only. Co-Authored-By: Claude Fable 5.2 --- .../durable/attach_ready_fail_fast_test.go | 102 +++++++++++ .../durable/plain_detach_closed_test.go | 20 +++ .../durable/precopy_drain_admitted_io_test.go | 162 ++++++++++++++++++ .../precopy_drain_readiness_loss_test.go | 80 +++++++++ .../precopy_pause_entry_checks_test.go | 81 +++++++++ .../chunk_precopy_retry_errors_test.go | 47 +++++ .../chunk_precopy_sample_bound_test.go | 25 +++ 7 files changed, 517 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/attach_ready_fail_fast_test.go create mode 100644 seaweed-block/core/frontend/durable/plain_detach_closed_test.go create mode 100644 seaweed-block/core/frontend/durable/precopy_drain_admitted_io_test.go create mode 100644 seaweed-block/core/frontend/durable/precopy_drain_readiness_loss_test.go create mode 100644 seaweed-block/core/frontend/durable/precopy_pause_entry_checks_test.go create mode 100644 seaweed-block/core/storage/chunk_precopy_retry_errors_test.go create mode 100644 seaweed-block/core/storage/chunk_precopy_sample_bound_test.go diff --git a/seaweed-block/core/frontend/durable/attach_ready_fail_fast_test.go b/seaweed-block/core/frontend/durable/attach_ready_fail_fast_test.go new file mode 100644 index 0000000000..fee3162129 --- /dev/null +++ b/seaweed-block/core/frontend/durable/attach_ready_fail_fast_test.go @@ -0,0 +1,102 @@ +package durable + +import ( + "context" + "errors" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" +) + +// TestAttachReadinessWaitFailsFastOnTerminalState pins that an I/O waiting for +// chunk attachment returns at once, without another readiness wait, when an +// observer install failed, readiness was withdrawn or a fence is seen. +func TestAttachReadinessWaitFailsFastOnTerminalState(t *testing.T) { + for _, tc := range []struct { + name string + // before runs before the read; afterRefusal runs between the first gate + // refusal and the wait; whileWaiting runs once the read is waiting. + before func(t *testing.T, b *StorageBackend) + afterRefusal func(b *StorageBackend) + whileWaiting func(b *StorageBackend) + want error + wantWaits int32 + }{ + { + name: "observer install failed", + before: func(t *testing.T, b *StorageBackend) { + if err := b.SetWriteObserver(refusingRebaser{}); err == nil { + t.Fatal("refused observer install reported success") + } + }, + want: frontend.ErrNotReady, + }, + { + name: "fence seen after the attach refusal", + afterRefusal: func(b *StorageBackend) { + b.mu.Lock() + b.chunkFenced = func() bool { return true } + b.mu.Unlock() + }, + want: frontend.ErrStalePrimary, + }, + { + name: "readiness withdrawn while waiting", + whileWaiting: func(b *StorageBackend) { b.SetOperational(false, "host drain") }, + want: frontend.ErrNotReady, + wantWaits: 1, + }, + } { + t.Run(tc.name, func(t *testing.T) { + b := precopyTestBackend(newHeldReadStore()) + b.setChunkAttachPending("attachment pending") + if tc.before != nil { + tc.before(t, b) + } + if tc.afterRefusal != nil { + b.testAfterAttachRefusal = func() { tc.afterRefusal(b) } + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + var waits atomic.Int32 + waiting, resume := make(chan struct{}), make(chan struct{}) + b.testBeforeReadReadyWait = func() { + if waits.Add(1) == 1 && tc.whileWaiting != nil { + close(waiting) + <-resume + return + } + // A wait the rule forbids: end it now instead of after 3 s. + cancel() + } + result := make(chan error, 1) + go func() { + _, err := b.Read(ctx, 0, make([]byte, 4096)) + result <- err + }() + if tc.whileWaiting != nil { + select { + case <-waiting: + case <-time.After(3 * time.Second): + t.Fatal("read never waited for attachment readiness") + } + tc.whileWaiting(b) + close(resume) + } + var err error + select { + case err = <-result: + case <-time.After(5 * time.Second): + t.Fatal("read did not return") + } + if got := waits.Load(); got != tc.wantWaits { + t.Fatalf("read waited %d times for readiness, want %d (err=%v)", got, tc.wantWaits, err) + } + if !errors.Is(err, tc.want) { + t.Fatalf("err=%v, want %v", err, tc.want) + } + }) + } +} diff --git a/seaweed-block/core/frontend/durable/plain_detach_closed_test.go b/seaweed-block/core/frontend/durable/plain_detach_closed_test.go new file mode 100644 index 0000000000..07740f2329 --- /dev/null +++ b/seaweed-block/core/frontend/durable/plain_detach_closed_test.go @@ -0,0 +1,20 @@ +package durable + +import ( + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend" +) + +// TestPlainDetachStopRefusesClosedBackend pins that the plain-detach stop of a +// closed backend returns ErrBackendClosed instead of reporting a clean stop. +func TestPlainDetachStopRefusesClosedBackend(t *testing.T) { + b := precopyTestBackend(newHeldReadStore()) + if err := b.Close(); err != nil { + t.Fatal(err) + } + if err := b.stopPlainDetachIfIdle(); !errors.Is(err, frontend.ErrBackendClosed) { + t.Fatalf("plain-detach stop of a closed backend: %v", err) + } +} diff --git a/seaweed-block/core/frontend/durable/precopy_drain_admitted_io_test.go b/seaweed-block/core/frontend/durable/precopy_drain_admitted_io_test.go new file mode 100644 index 0000000000..541e1feb39 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_drain_admitted_io_test.go @@ -0,0 +1,162 @@ +package durable + +import ( + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// heldReadStore parks each ReadContext call on its LBA until the test releases +// that LBA, so every Read stays an admitted I/O for as long as the test needs. +type heldReadStore struct { + storage.LogicalStorage + entered chan uint32 + release map[uint32]chan struct{} +} + +func newHeldReadStore(lbas ...uint32) *heldReadStore { + s := &heldReadStore{entered: make(chan uint32, len(lbas)), release: make(map[uint32]chan struct{}, len(lbas))} + for _, lba := range lbas { + s.release[lba] = make(chan struct{}) + } + return s +} + +func (s *heldReadStore) ReadContext(ctx context.Context, lba uint32) ([]byte, error) { + s.entered <- lba + select { + case <-s.release[lba]: + return make([]byte, 4096), nil + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +func (s *heldReadStore) Read(lba uint32) ([]byte, error) { + return s.ReadContext(context.Background(), lba) +} + +func (s *heldReadStore) NextLSN() uint64 { return 1 } + +// precopyTestBackend is an operational backend over store with a matching +// healthy projection, so admission depends only on the state under test. +func precopyTestBackend(store storage.LogicalStorage) *StorageBackend { + id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1} + b := &StorageBackend{storage: store, blockSize: 4096, id: id, view: readinessProjection{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1, Healthy: true}} + b.SetOperational(true, "serving") + return b +} + +// startHeldReads starts one Read per LBA and returns once every one of them is +// admitted and parked inside storage. Cleanup releases and joins them. +func startHeldReads(t *testing.T, b *StorageBackend, store *heldReadStore, lbas ...uint32) <-chan error { + t.Helper() + done := make(chan error, len(lbas)) + for _, lba := range lbas { + go func(off int64) { + _, err := b.Read(context.Background(), off, make([]byte, 4096)) + done <- err + }(int64(lba) * 4096) + } + t.Cleanup(func() { + for _, ch := range store.release { + select { + case <-ch: + default: + close(ch) + } + } + _ = b.Close() + }) + for range lbas { + select { + case <-store.entered: + case <-time.After(3 * time.Second): + t.Fatal("read never reached storage") + } + } + return done +} + +// installedPause waits until BeginPrecopyPause has installed its pause and +// returns the pause's drain channel. +func installedPause(t *testing.T, b *StorageBackend) <-chan struct{} { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for { + b.mu.Lock() + p := b.precopy + b.mu.Unlock() + if p != nil { + return p.drained + } + if time.Now().After(deadline) { + t.Fatal("pre-copy pause was never installed") + } + time.Sleep(time.Millisecond) + } +} + +type pauseResult struct { + resume func() + err error +} + +func beginPauseAsync(ctx context.Context, b *StorageBackend) <-chan pauseResult { + out := make(chan pauseResult, 1) + go func() { + resume, err := b.BeginPrecopyPause(ctx) + out <- pauseResult{resume, err} + }() + return out +} + +// TestPrecopyDrainWaitsForEveryAdmittedIO pins that a pre-copy pause reports +// its drain done only after every I/O admitted before it has finished, not +// when the first of several completes. +func TestPrecopyDrainWaitsForEveryAdmittedIO(t *testing.T) { + store := newHeldReadStore(0, 1) + b := precopyTestBackend(store) + reads := startHeldReads(t, b, store, 0, 1) + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + pause := beginPauseAsync(ctx, b) + drained := installedPause(t, b) + + close(store.release[0]) + if err := <-reads; err != nil { + t.Fatalf("first admitted read: %v", err) + } + // The first read has returned, so its admission release has run. + select { + case <-drained: + t.Fatal("drain reported done while a second admitted I/O is still in flight") + default: + } + select { + case r := <-pause: + t.Fatalf("pause returned while a second admitted I/O is still in flight: err=%v", r.err) + default: + } + + close(store.release[1]) + if err := <-reads; err != nil { + t.Fatalf("second admitted read: %v", err) + } + select { + case r := <-pause: + if r.err != nil { + t.Fatalf("drain after the last admitted I/O: %v", r.err) + } + r.resume() + case <-time.After(3 * time.Second): + t.Fatal("drain not reported done after the last admitted I/O finished") + } + if _, err := b.Read(context.Background(), 0, nil); err != nil { + t.Fatalf("resume did not reopen admission: %v", err) + } +} diff --git a/seaweed-block/core/frontend/durable/precopy_drain_readiness_loss_test.go b/seaweed-block/core/frontend/durable/precopy_drain_readiness_loss_test.go new file mode 100644 index 0000000000..1acde5c023 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_drain_readiness_loss_test.go @@ -0,0 +1,80 @@ +package durable + +import ( + "context" + "testing" + "time" +) + +// TestPrecopyDrainEndsWithErrorOnReadinessLossOrClose pins that a pre-copy +// drain still pending when the backend loses readiness or is closed ends with +// an error and never reports a clean drain. +func TestPrecopyDrainEndsWithErrorOnReadinessLossOrClose(t *testing.T) { + for _, tc := range []struct { + name string + // bound is the drain's caller context, as the pre-copy caller gives it. + bound time.Duration + spoil func(b *StorageBackend) + }{ + {"readiness lost", 3 * time.Second, func(b *StorageBackend) { b.SetOperational(false, "host drain") }}, + // Close does not signal the drain; the waiter ends at its own bound. + {"closed", 200 * time.Millisecond, func(b *StorageBackend) { _ = b.Close() }}, + } { + t.Run(tc.name, func(t *testing.T) { + store := newHeldReadStore(0) + b := precopyTestBackend(store) + reads := startHeldReads(t, b, store, 0) + ctx, cancel := context.WithTimeout(context.Background(), tc.bound) + defer cancel() + pause := beginPauseAsync(ctx, b) + installedPause(t, b) + + tc.spoil(b) + close(store.release[0]) + <-reads + select { + case r := <-pause: + if r.err == nil { + r.resume() + t.Fatal("drain reported clean after the backend became unusable") + } + case <-time.After(tc.bound + 3*time.Second): + t.Fatal("drain waiter did not end") + } + b.mu.Lock() + left := b.precopy + b.mu.Unlock() + if left != nil { + t.Fatal("failed drain left its pause installed") + } + }) + } +} + +// TestPrecopyFinalStopRefusedAfterReadinessLossOrClose pins that the final +// pre-copy stop refuses to commit a freeze when the backend lost readiness or +// was closed after the drain completed. +func TestPrecopyFinalStopRefusedAfterReadinessLossOrClose(t *testing.T) { + for _, tc := range []struct { + name string + spoil func(b *StorageBackend) + }{ + {"readiness lost", func(b *StorageBackend) { b.SetOperational(false, "host drain") }}, + {"closed", func(b *StorageBackend) { _ = b.Close() }}, + } { + t.Run(tc.name, func(t *testing.T) { + b := precopyTestBackend(newHeldReadStore()) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + resume, err := b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + defer resume() + tc.spoil(b) + if b.TryStopIO("chunk pre-copy: final detached cut") { + t.Fatal("final stop committed a freeze on an unusable backend") + } + }) + } +} diff --git a/seaweed-block/core/frontend/durable/precopy_pause_entry_checks_test.go b/seaweed-block/core/frontend/durable/precopy_pause_entry_checks_test.go new file mode 100644 index 0000000000..fb8b5b3bb2 --- /dev/null +++ b/seaweed-block/core/frontend/durable/precopy_pause_entry_checks_test.go @@ -0,0 +1,81 @@ +package durable + +import ( + "context" + "errors" + "testing" + "time" +) + +type refusingRebaser struct{} + +func (refusingRebaser) Observe(context.Context, uint32, uint64, []byte) error { return nil } +func (refusingRebaser) Sync(context.Context, uint64) error { return nil } +func (refusingRebaser) RebaseShipLSN(uint64) error { + return errors.New("injected: ship LSN cannot follow the store") +} + +// TestPrecopyPauseRefusedOnUnusableBackend pins that a pre-copy pause never +// begins on a backend that is closed, not operational, has a failed observer +// install, or already has a pause installed. +func TestPrecopyPauseRefusedOnUnusableBackend(t *testing.T) { + for _, tc := range []struct { + name string + spoil func(t *testing.T, b *StorageBackend) + }{ + {"observer install failed", func(t *testing.T, b *StorageBackend) { + if err := b.SetWriteObserver(refusingRebaser{}); err == nil { + t.Fatal("refused observer install reported success") + } + }}, + {"closed", func(t *testing.T, b *StorageBackend) { _ = b.Close() }}, + {"not operational", func(t *testing.T, b *StorageBackend) { b.SetOperational(false, "host drain") }}, + } { + t.Run(tc.name, func(t *testing.T) { + b := precopyTestBackend(newHeldReadStore()) + tc.spoil(t, b) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + resume, err := b.BeginPrecopyPause(ctx) + if err == nil { + resume() + t.Fatal("pre-copy pause began on an unusable backend") + } + b.mu.Lock() + left := b.precopy + b.mu.Unlock() + if left != nil { + t.Fatal("refused pause left a pause installed") + } + }) + } + + t.Run("already paused", func(t *testing.T) { + b := precopyTestBackend(newHeldReadStore()) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + resume, err := b.BeginPrecopyPause(ctx) + if err != nil { + t.Fatal(err) + } + defer resume() + b.mu.Lock() + first := b.precopy + b.mu.Unlock() + second, err := b.BeginPrecopyPause(ctx) + if err == nil { + second() + t.Fatal("second pre-copy pause began while one is installed") + } + b.mu.Lock() + current := b.precopy + b.mu.Unlock() + if current != first { + t.Fatal("refused second pause replaced the installed pause") + } + resume() + if _, err := b.Read(context.Background(), 0, nil); err != nil { + t.Fatalf("resume of the first pause did not reopen admission: %v", err) + } + }) +} diff --git a/seaweed-block/core/storage/chunk_precopy_retry_errors_test.go b/seaweed-block/core/storage/chunk_precopy_retry_errors_test.go new file mode 100644 index 0000000000..c7e84cdc6e --- /dev/null +++ b/seaweed-block/core/storage/chunk_precopy_retry_errors_test.go @@ -0,0 +1,47 @@ +package storage + +import ( + "errors" + "testing" +) + +// TestPrecopyRoundLoopRetriesOnlyNamedErrors pins that a failed rolling +// pre-copy round starts another round only after a COW abort, an unavailable +// remote or a HEAD precondition failure; any other error ends the loop at once. +func TestPrecopyRoundLoopRetriesOnlyNamedErrors(t *testing.T) { + errNotPrimary := errors.New("test: not primary") + for _, tc := range []struct { + name string + first error + rounds int + }{ + {"other error", errNotPrimary, 1}, + {"COW aborted", errCutCOWAborted, 2}, + {"remote unavailable", errChunkRemoteUnavailable, 2}, + {"HEAD precondition", errChunkHeadPrecondition, 2}, + } { + t.Run(tc.name, func(t *testing.T) { + _, _, l, _ := precopyLayer(t, 1024, 0) + // Every round fails at capture admission: the first with the error + // under test, any later one with an error that is never retried. + calls := 0 + l.cfg.CaptureAllowed = func() error { + calls++ + if calls == 1 { + return tc.first + } + return errNotPrimary + } + r, err := l.PrecopyDetach(ctTimeout(t), func() bool { + t.Error("refused rounds reached the final stop") + return true + }) + if !errors.Is(err, errNotPrimary) { + t.Fatalf("err=%v, want the non-retried refusal", err) + } + if calls != tc.rounds || len(r.Precopy.Rounds) != tc.rounds { + t.Fatalf("rounds: admission calls=%d reported=%d, want %d", calls, len(r.Precopy.Rounds), tc.rounds) + } + }) + } +} diff --git a/seaweed-block/core/storage/chunk_precopy_sample_bound_test.go b/seaweed-block/core/storage/chunk_precopy_sample_bound_test.go new file mode 100644 index 0000000000..5be9c0093f --- /dev/null +++ b/seaweed-block/core/storage/chunk_precopy_sample_bound_test.go @@ -0,0 +1,25 @@ +package storage + +import ( + "testing" + "time" +) + +// TestPrecopySampleHistoryKeepsNewest32 pins that the pre-copy cost sample +// history is bounded at 32 entries and keeps the newest ones. +func TestPrecopySampleHistoryKeepsNewest32(t *testing.T) { + l := &chunkLayerImpl{} + const taken = 40 + for i := 1; i <= taken; i++ { + // The fixed cost carries the sample's order. + l.samplePrecopy(chunkCutStats{CASNs: 1}, int64(i)) + } + if len(l.precopySamples) != 32 { + t.Fatalf("sample history holds %d entries, want 32", len(l.precopySamples)) + } + for j, s := range l.precopySamples { + if want := time.Duration(taken - 32 + 1 + j); s.fixed != want { + t.Fatalf("sample %d has fixed=%s, want %s (newest 32 kept in order)", j, s.fixed, want) + } + } +} From 95bba3051161d5f456d02c137dcbb315e828d81e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 04:16:03 -0800 Subject: [PATCH 27/34] test(storage): witness cut progress at explicit events --- .../core/storage/chunk_cut_progress_test.go | 20 ++-- .../core/storage/chunk_layer_contract_test.go | 100 ++++++------------ 2 files changed, 45 insertions(+), 75 deletions(-) diff --git a/seaweed-block/core/storage/chunk_cut_progress_test.go b/seaweed-block/core/storage/chunk_cut_progress_test.go index 34b469a152..97a0b0784b 100644 --- a/seaweed-block/core/storage/chunk_cut_progress_test.go +++ b/seaweed-block/core/storage/chunk_cut_progress_test.go @@ -129,13 +129,15 @@ type deadlineProgressRemote struct { *fakeChunkRemote completed int calls int + interrupt context.CancelCauseFunc } func (r *deadlineProgressRemote) Put(ctx context.Context, key string, b []byte) error { r.calls++ - if r.completed == 2 { + if r.completed == 2 && r.interrupt != nil { + r.interrupt(context.DeadlineExceeded) <-ctx.Done() - return ctx.Err() + return context.Cause(ctx) } err := r.fakeChunkRemote.Put(ctx, key, b) if err == nil { @@ -164,11 +166,17 @@ func TestChunkStageV3_MultipleDeadlinesKeepProgress(t *testing.T) { for pass := 0; pass < 3; pass++ { r.completed = 0 r.calls = 0 - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - result, err := l.Cut(ctx) - cancel() + // Expire at the third PUT event, not one second after setup. This + // witnesses two completed immutable uploads even on a loaded host. + ctx, cancel := context.WithCancelCause(context.Background()) + r.interrupt = nil if pass < 2 { - if !errors.Is(err, context.DeadlineExceeded) { + r.interrupt = cancel + } + result, err := l.Cut(ctx) + cancel(nil) + if pass < 2 { + if !errors.Is(err, context.DeadlineExceeded) || r.calls != 3 || r.completed != 2 { t.Fatalf("pass %d did not reach injected deadline: %v", pass, err) } if f.stats().head.Gen != base { diff --git a/seaweed-block/core/storage/chunk_layer_contract_test.go b/seaweed-block/core/storage/chunk_layer_contract_test.go index 86dd77f065..a6d28d8b67 100644 --- a/seaweed-block/core/storage/chunk_layer_contract_test.go +++ b/seaweed-block/core/storage/chunk_layer_contract_test.go @@ -170,9 +170,9 @@ func TestChunkLayer_C2_StalledUploadDoesNotGateLocal(t *testing.T) { } // C3 no torn chunk: chunks are copied under the capture barrier, so every -// HEAD ever installed equals the image at its RemoteLSN even while a writer -// keeps overwriting the same chunk and flushing. Overlap is forced: each -// round holds the upload until the writer has completed rounds after it. +// HEAD ever installed equals the image at its RemoteLSN while the same chunk +// is overwritten and flushed. Each upload-entry event precedes three complete +// writer rounds, and the upload is released only after those rounds finish. func TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites(t *testing.T) { s, _ := newChunkTestStore(t) f := newFakeChunkRemote() @@ -183,88 +183,50 @@ func TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites(t *testing.T) { } mustSyncFlush(t, s) - stop := make(chan struct{}) - var stopOnce sync.Once - stopWriter := func() { stopOnce.Do(func() { close(stop) }) } - progress := make(chan struct{}, 1024) - werr := make(chan error, 1) - var rounds atomic.Int64 - t.Cleanup(func() { - stopWriter() - select { - case <-werr: - case <-time.After(ctLocalBound): - t.Errorf("writer not joined within %v", ctLocalBound) + // The test goroutine is the writer: each upload-entry event is followed + // by three complete write/sync/flush rounds before that upload is released. + // This proves overlap without a throughput deadline or free-running writer. + writes := 0 + writeRound := func() { + lba := uint32(writes % ctChunkBlocks) + w.write(t, s, lba, byte(writes)) + if _, err := s.Sync(); err != nil { + t.Fatal(err) } - }) - go func() { - defer close(werr) - for i := 0; ; i++ { - select { - case <-stop: - return - default: - } - lba := uint32(i % ctChunkBlocks) - data := makeBlock(ctBlockSize, byte(i)) - lsn, err := s.Write(lba, data) - if err == nil { - w.record(lsn, lba, data) - _, err = s.Sync() - } - if err == nil { - err = s.flusher.flushOnce() - // A concurrent cut can invalidate a prepared checkpoint map; - // the production worker retries this explicit stale-proof outcome. - if errors.Is(err, ErrMapCoverageStale) { - err = nil - } - } - if err != nil { - werr <- err - return - } - rounds.Add(1) - select { - case progress <- struct{}{}: - default: - } + if err := s.flusher.flushOnce(); err != nil && !errors.Is(err, ErrMapCoverageStale) { + t.Fatal(err) } - }() - + writes++ + } for round := 0; round < 5; round++ { entered, release := holdPuts(t, f) done := startCapture(t, layer) - waitKey(t, entered, "held upload") - for len(progress) > 0 { - <-progress + select { + case <-entered: + case err := <-done: + t.Fatalf("round %d Capture ended before upload entry: %v", round, err) } - for need := 0; need < 3; need++ { // the writer must advance while the upload is held - select { - case <-progress: - case <-time.After(ctLocalBound): - t.Fatalf("round %d: writer made no progress while an upload was held", round) - } + for need := 0; need < 3; need++ { + writeRound() + } + select { + case err := <-done: + t.Fatalf("round %d Capture ended before upload release: %v", round, err) + default: } release() - if err := waitErr(t, done, "held capture"); err != nil { + if err := <-done; err != nil { t.Fatalf("round %d Capture: %v", round, err) } } for i := 0; i < 20; i++ { + writeRound() if _, err := layer.Capture(ctTimeout(t)); err != nil { t.Fatalf("free-running Capture %d: %v", i, err) } } - stopWriter() - if err := waitErr(t, werr, "writer"); err != nil { - t.Fatalf("writer: %v", err) - } - if rounds.Load() < 15 { - t.Fatalf("writer completed only %d rounds; overlap not established", rounds.Load()) - } - // Each held round installs a HEAD; a free-running capture with no new - // LSN since the last cut is idle and may skip its CAS. + // Every held and subsequent unheld capture has new writes. Retain the + // historical minimum of five held HEADs plus one unheld HEAD. if n := len(f.installedHeads()); n < 6 { t.Fatalf("%d HEADs installed, want the 5 held rounds plus at least one free-running", n) } From 071dfc96fd076a6f92c9ea420c9f215b612028d7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 04:21:42 -0800 Subject: [PATCH 28/34] test(storage): map complementary capture and barrier coverage --- seaweed-block/core/storage/chunk_layer_contract_test.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/seaweed-block/core/storage/chunk_layer_contract_test.go b/seaweed-block/core/storage/chunk_layer_contract_test.go index a6d28d8b67..4be2a15173 100644 --- a/seaweed-block/core/storage/chunk_layer_contract_test.go +++ b/seaweed-block/core/storage/chunk_layer_contract_test.go @@ -173,6 +173,13 @@ func TestChunkLayer_C2_StalledUploadDoesNotGateLocal(t *testing.T) { // HEAD ever installed equals the image at its RemoteLSN while the same chunk // is overwritten and flushed. Each upload-entry event precedes three complete // writer rounds, and the upload is released only after those rounds finish. +// Complementary capture/barrier witnesses: +// TestChunkLayer_C3_WriteDuringCopyWaitsForTheCut parks a writer on a held +// local copy and checks its exclusion from the at-H image; +// TestChunkPrecopy_RedirtiedStagedChunkIsRecopied checks an overwrite between +// staging and the barrier (both WAL-resident and flushed); +// TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier checks that the barrier +// includes the admitted writer completed by its pre-barrier drain. func TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites(t *testing.T) { s, _ := newChunkTestStore(t) f := newFakeChunkRemote() From c82ecff5f8f6d23b0cc6bb97f17c4a8c4880aefd Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 04:39:45 -0800 Subject: [PATCH 29/34] authority: print all goroutine stacks when the lease horizon test stalls The three deadlock failures of TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose now print the stack of every goroutine. One CI failure of this test gave no way to see where the parties were blocked. No timeout changed, nothing skipped. Co-Authored-By: Claude Fable 5.2 --- .../authority/workspace_lease_horizon_test.go | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/authority/workspace_lease_horizon_test.go b/seaweed-block/core/authority/workspace_lease_horizon_test.go index 7d35415762..ce19c81325 100644 --- a/seaweed-block/core/authority/workspace_lease_horizon_test.go +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "runtime" "strings" "sync" "sync/atomic" @@ -911,7 +912,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { case werr = <-writersDone: writersDone <- werr // keep it for the cleanup join case <-time.After(20 * time.Second): - t.Fatal("deadlock: writers did not finish after the release") + t.Fatal("deadlock: writers did not finish after the release", allGoroutineStacks()) } if werr != nil { t.Fatal("writer:", werr) @@ -919,7 +920,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { select { case <-closed: case <-time.After(20 * time.Second): - t.Fatal("deadlock: Close did not finish after the release") + t.Fatal("deadlock: Close did not finish after the release", allGoroutineStacks()) } time.Sleep(50 * time.Millisecond) // renewals continue after Close stopRenewers() @@ -928,7 +929,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { select { case <-settled: case <-time.After(20 * time.Second): - t.Fatal("deadlock: renewers did not finish") + t.Fatal("deadlock: renewers did not finish", allGoroutineStacks()) } if s := time.Duration(slowest.Load()); s >= 2*time.Second { @@ -1218,3 +1219,16 @@ func TestLeaseTestClockMonotonicAcrossFreezeResume(t *testing.T) { t.Fatal(e) } } + +// allGoroutineStacks returns the stack of every goroutine on a new line, so +// that a stall reported by a test shows where each party is blocked. +func allGoroutineStacks() string { + buf := make([]byte, 1<<20) + for { + n := runtime.Stack(buf, true) + if n < len(buf) { + return string('\n') + string(buf[:n]) + } + buf = make([]byte, 2*len(buf)) + } +} From 64c717f8b37fdb1b3fe54c43208d7d5841eef582 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 04:08:23 -0800 Subject: [PATCH 30/34] storage: each cut's COW spill cap is min(the configured cap, half the free space minus 1 GiB) The free space of the side file's filesystem (--durable-root, statfs on Linux) is read at each cut, for the staging bound and when the copy window opens; a read error counts as no free space. At the cap the cut aborts (cow_capacity) and the guest write completes. Adds Part E. Quantities to the ledger with this row. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/durable/provider_chunk.go | 1 + .../core/frontend/durable/spill_free_linux.go | 17 ++++ .../frontend/durable/spill_free_linux_test.go | 29 ++++++ .../core/frontend/durable/spill_free_other.go | 6 ++ seaweed-block/core/storage/chunk_cut_cow.go | 20 +++- .../storage/chunk_cut_cow_spillfree_test.go | 96 +++++++++++++++++++ seaweed-block/core/storage/chunk_layer.go | 2 +- seaweed-block/core/storage/chunk_seam.go | 5 + seaweed-block/docs/design/invariants.md | 8 ++ 9 files changed, 182 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/spill_free_linux.go create mode 100644 seaweed-block/core/frontend/durable/spill_free_linux_test.go create mode 100644 seaweed-block/core/frontend/durable/spill_free_other.go create mode 100644 seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 2c194a39e8..2a5c6d6f1c 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -389,6 +389,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h PayloadMemoryBudget: p.cfg.ChunkPayloadMemoryBudget, Budget: p.cfg.ChunkBudget, COWSpillLimit: p.cfg.ChunkCOWSpillLimit, + COWSpillFree: spillFree(p.cfg.StorageRoot), CaptureAllowed: func() error { cur := p.view.Projection() if !cur.Healthy || cur.VolumeID != volumeID || lin.volumeID != volumeID { diff --git a/seaweed-block/core/frontend/durable/spill_free_linux.go b/seaweed-block/core/frontend/durable/spill_free_linux.go new file mode 100644 index 0000000000..92843c70ff --- /dev/null +++ b/seaweed-block/core/frontend/durable/spill_free_linux.go @@ -0,0 +1,17 @@ +//go:build linux + +package durable + +import "syscall" + +// spillFree returns the free bytes available to an unprivileged writer on +// the filesystem holding dir (the COW side files). +func spillFree(dir string) func() (int64, error) { + return func() (int64, error) { + var st syscall.Statfs_t + if err := syscall.Statfs(dir, &st); err != nil { + return 0, err + } + return int64(st.Bavail) * int64(st.Bsize), nil + } +} diff --git a/seaweed-block/core/frontend/durable/spill_free_linux_test.go b/seaweed-block/core/frontend/durable/spill_free_linux_test.go new file mode 100644 index 0000000000..2bd3081dec --- /dev/null +++ b/seaweed-block/core/frontend/durable/spill_free_linux_test.go @@ -0,0 +1,29 @@ +//go:build linux + +package durable + +import ( + "syscall" + "testing" +) + +// The provider's spill free-space reader reports the bytes an unprivileged +// writer has on the storage root's filesystem. +func TestSpillFree_ReadsTheStorageRootFilesystem(t *testing.T) { + dir := t.TempDir() + free, err := spillFree(dir)() + if err != nil { + t.Fatal(err) + } + var st syscall.Statfs_t + if err := syscall.Statfs(dir, &st); err != nil { + t.Fatal(err) + } + want := int64(st.Bavail) * int64(st.Bsize) + if free <= 0 || free > 2*want+1<<30 || want > 2*free+1<<30 { + t.Fatalf("spill free %d bytes; statfs says %d", free, want) + } + if _, err := spillFree(dir + "/missing")(); err == nil { + t.Fatal("a missing storage root read as free space") + } +} diff --git a/seaweed-block/core/frontend/durable/spill_free_other.go b/seaweed-block/core/frontend/durable/spill_free_other.go new file mode 100644 index 0000000000..7ba44e278c --- /dev/null +++ b/seaweed-block/core/frontend/durable/spill_free_other.go @@ -0,0 +1,6 @@ +//go:build !linux + +package durable + +// spillFree is nil off Linux: the COW spill cap is the configured one. +func spillFree(string) func() (int64, error) { return nil } diff --git a/seaweed-block/core/storage/chunk_cut_cow.go b/seaweed-block/core/storage/chunk_cut_cow.go index c9fc09dc5c..e431016650 100644 --- a/seaweed-block/core/storage/chunk_cut_cow.go +++ b/seaweed-block/core/storage/chunk_cut_cow.go @@ -21,6 +21,24 @@ const cutCOWMemoryLimit = DefaultCutPayloadMemoryBudget // defaultCOWSpillLimit caps a copy window's side-file bytes by default. const defaultCOWSpillLimit = 1 << 30 + +// cowSpillFreeReserve is the free space a cut's side file never takes, +// on top of leaving half of the rest. +const cowSpillFreeReserve = 1 << 30 + +// cowSpillLimit is this cut's side-file cap: COWSpillLimit, lowered to +// half the free space minus cowSpillFreeReserve when COWSpillFree is set. +func (l *chunkLayerImpl) cowSpillLimit() int64 { + limit := l.cfg.COWSpillLimit + if l.cfg.COWSpillFree == nil { + return limit + } + free, err := l.cfg.COWSpillFree() + if err != nil { + free = 0 + } + return max(0, min(limit, free/2-cowSpillFreeReserve)) +} const ( cowPending uint8 = iota cowCopying @@ -148,7 +166,7 @@ func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool, he if size == 0 || size > math.MaxInt64 || uint64(len(candidates)) > math.MaxInt64/size { return nil, fmt.Errorf("%w: side-store geometry", errCutCOWAborted) } - w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), head: head, spillLimit: l.cfg.COWSpillLimit, chunkBytes: int64(size)} + w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), head: head, spillLimit: l.cowSpillLimit(), chunkBytes: int64(size)} w.ctx, w.cancel = context.WithCancel(context.Background()) _, reserved, limit := l.cutPayloadWorkers() savers := min(max(1, int((16<<20)/int64(size))), int((limit-reserved)/(2*int64(size)))) diff --git a/seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go b/seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go new file mode 100644 index 0000000000..ea6cfbbce0 --- /dev/null +++ b/seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go @@ -0,0 +1,96 @@ +package storage + +import ( + "errors" + "strings" + "sync/atomic" + "testing" + "time" +) + +// The spill cap is min(COWSpillLimit, free/2 - reserve), at least 0, read +// from COWSpillFree on every call; an error counts as no free space, and +// without COWSpillFree the configured cap applies. +func TestCOWSpillLimit_FromFreeSpace(t *testing.T) { + l := &chunkLayerImpl{cfg: ChunkLayerConfig{COWSpillLimit: 4 << 30}} + if got := l.cowSpillLimit(); got != 4<<30 { + t.Fatalf("no free-space reader: cap %d, want the configured 4 GiB", got) + } + var free atomic.Int64 + var reads atomic.Int64 + var fail atomic.Bool + l.cfg.COWSpillFree = func() (int64, error) { + reads.Add(1) + if fail.Load() { + return 1 << 40, errors.New("statfs failed") + } + return free.Load(), nil + } + for _, c := range []struct { + free, want int64 + }{ + {100 << 30, 4 << 30}, // plenty: the configured cap + {6 << 30, 2 << 30}, // 6 GiB free: half is 3, minus the 1 GiB reserve + {2 << 30, 0}, // half the free space is all reserve + {1 << 30, 0}, // below the reserve: never negative + {10<<30 + 2, 4 << 30}, // the configured cap still bounds it + {3 << 30, (3<<30)/2 - (1 << 30)}, // 1.5 GiB - 1 GiB + } { + free.Store(c.free) + if got := l.cowSpillLimit(); got != c.want { + t.Fatalf("free %d: cap %d, want %d", c.free, got, c.want) + } + } + if reads.Load() != 6 { + t.Fatalf("free space read %d times for 6 calls; want once per call", reads.Load()) + } + fail.Store(true) + if got := l.cowSpillLimit(); got != 0 { + t.Fatalf("free-space error: cap %d, want 0 (no free space)", got) + } +} + +// The copy window reads the free space when it opens, not only when the +// cut starts staging: free space that shrinks below the reserve between +// the two gives the window a cap of 0, so once the in-memory budget is used +// a save aborts that cut (the guest write completes); after space is freed +// the cap reads the new value. +func TestCutCOWV3_SpillCapFollowsFreeSpaceEachCut(t *testing.T) { + s, l, _, gate := cowFixture(t) + var free, reads atomic.Int64 + free.Store(100 << 30) + l.cfg.COWSpillFree = func() (int64, error) { + if reads.Add(1) == 2 { // the window opens: the filesystem has filled up + free.Store(1 << 30) + } + return free.Load(), nil + } + cutDone, cutErr := cowStartCut(t, l, gate) + w := l.cowActive.Load() + w.mu.Lock() + w.memory = cutCOWMemoryLimit // the in-memory budget is used + limit := w.spillLimit + w.mu.Unlock() + if limit != 0 { + t.Fatalf("window cap %d with 1 GiB free; want 0", limit) + } + writeDone := make(chan error, 1) + go func() { _, err := s.Write(5, makeBlock(ctBlockSize, 0xd6)); writeDone <- err }() + select { + case err := <-writeDone: + if err != nil { + t.Fatal("guest write refused at the free-space cap:", err) + } + case <-time.After(ctLocalBound): + t.Fatal("guest write did not complete at the free-space cap") + } + gate.unblock() + cowWaitSignal(t, cutDone, "cut at the free-space cap") + if err := <-cutErr; !errors.Is(err, errCutCOWAborted) || !strings.Contains(err.Error(), "cap of 0 bytes") { + t.Fatalf("cut at a 0 cap: %v, want the cap abort", err) + } + free.Store(100 << 30) + if got := l.cowSpillLimit(); got != l.cfg.COWSpillLimit { + t.Fatalf("after freeing space the cap is %d, want the configured %d", got, l.cfg.COWSpillLimit) + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 3ed9ec97b5..9a4bebad77 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1543,7 +1543,7 @@ func (l *chunkLayerImpl) dropIntents(ctx context.Context, ids []string) { func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint64]stagedChunk, []string, error) { // Leave at most half the side budget exposed at the barrier. Streaming // staging uses no local payload file, even for a much larger image. - bound := int(l.cfg.COWSpillLimit / (2 * int64(l.blockSize) * int64(l.chunkBlocks))) + bound := int(l.cowSpillLimit() / (2 * int64(l.blockSize) * int64(l.chunkBlocks))) staged := map[uint64]stagedChunk{} var intents []string diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index c8461ba69a..b83e6fa4b8 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -382,6 +382,11 @@ type chunkLayerConfig struct { // retries), never publishes a partial image or refuses the guest mutation. // 0 defaults to defaultCOWSpillLimit; negative is refused. COWSpillLimit int64 + // COWSpillFree, optional, returns the free bytes of the filesystem that + // holds the side file. When set, it is read at each cut and that cut's + // spill cap is min(COWSpillLimit, free/2 - 1 GiB), at least 0; an error + // counts as no free space. + COWSpillFree func() (int64, error) // testReconcileHold, set only by this package's tests, holds the // reconciler before each slice until a token is received or the diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 0c69765881..156673db86 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -27,6 +27,8 @@ The design is described in three documents, and this one collects their machines - [M6 Chunk lifecycle](#m6-chunk-lifecycle) - [Part B. Invariant ledger](#part-b-invariant-ledger) - [Part C. Change rules](#part-c-change-rules) +- [Part D. Wait ownership](#part-d-wait-ownership) +- [Part E. Quantities](#part-e-quantities) --- @@ -671,3 +673,9 @@ Format v3 row 4 remains dark. Its typed scan result preserves trusted records, a | Frontend pre-copy admission | M5 tentative admission -> resume; `INV-CUT-PRECOPY-001` | Earlier of caller deadline and this command arrival + 5 s; one bound across retries, no inherited pause clock | Owner `finishPrecopyLocked`: resume or terminal Close clears the pause and grants all waiters in FIFO arrival order under one `b.mu` hold; each rechecks the ordinary gate. Expiry removes only its waiter and refuses with typed `ErrBackendBusy` + deadline cause (guest-visible: yes). Only a typed pause refusal requeues a granted waiter under the original command deadline; already-observed stale-primary and other gate errors are returned unchanged. Grant versus queue expiry is decided under the same lock; timely grants survive later queue-timer expiry but never caller expiry or a terminal gate. No dependency on another command's completion. | No `ioMu`, store lock, or remote call while queued. Admitted I/O retains normal per-LBA serialization and lifecycle accounting. | Frozen estimate reporting: a tail above the existing 60 s estimator ceiling reports the same 60 s rejection sentinel used by admission. It is known but saturated, not a complete fixed-plus-tail duration; quiesce slack is zero. Consumers must not use it as a completion forecast. Drain refusals retain the observation before their reason changes; this reporting does not reclassify refusal causes. + +## Part E. Quantities + +| Quantity | Unit | Cap | Enforced at (producer) | Drained | Outcome at the cap | +|---|---|---|---|---|---| +| COW side-file spill per cut | bytes | min(`COWSpillLimit` (default 1 GiB, or the host limit's COW bytes), free space on `--durable-root` / 2 - 1 GiB), at least 0; free space read at each cut (staging bound and window open); a read error counts as no free space; off Linux, the configured cap | the saver: `core/storage/chunk_cut_cow.go` `cowSpillLimit`, the save's cap check | at the cut's end (the side file is removed on publish, abort or close) | that cut aborts (`cow_capacity`, retryable); the guest write completes and nothing partial is published | From 3204537cb50fe2663a83b6f21dbf61c0704f36a3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 04:41:27 -0800 Subject: [PATCH 31/34] storage: test that low free space at the cut stages before the barrier; the cap test's writer has its own bounded join Co-Authored-By: Claude Opus 5.5 --- .../storage/chunk_cut_cow_spillfree_test.go | 52 +++++++++++++++---- 1 file changed, 42 insertions(+), 10 deletions(-) diff --git a/seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go b/seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go index ea6cfbbce0..9e42a126cd 100644 --- a/seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go +++ b/seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go @@ -1,11 +1,11 @@ package storage import ( + "context" "errors" "strings" "sync/atomic" "testing" - "time" ) // The spill cap is min(COWSpillLimit, free/2 - reserve), at least 0, read @@ -74,15 +74,19 @@ func TestCutCOWV3_SpillCapFollowsFreeSpaceEachCut(t *testing.T) { if limit != 0 { t.Fatalf("window cap %d with 1 GiB free; want 0", limit) } - writeDone := make(chan error, 1) - go func() { _, err := s.Write(5, makeBlock(ctBlockSize, 0xd6)); writeDone <- err }() - select { - case err := <-writeDone: - if err != nil { - t.Fatal("guest write refused at the free-space cap:", err) - } - case <-time.After(ctLocalBound): - t.Fatal("guest write did not complete at the free-space cap") + writeDone := make(chan struct{}) + writeErr := make(chan error, 1) + // Registered before the writer starts: release the copier and join the + // writer (bounded) whatever the test's outcome. + t.Cleanup(func() { gate.unblock(); cowWaitSignal(t, writeDone, "free-space-cap writer cleanup") }) + go func() { + defer close(writeDone) + _, err := s.Write(5, makeBlock(ctBlockSize, 0xd6)) + writeErr <- err + }() + cowWaitSignal(t, writeDone, "guest write at the free-space cap") + if err := <-writeErr; err != nil { + t.Fatal("guest write refused at the free-space cap:", err) } gate.unblock() cowWaitSignal(t, cutDone, "cut at the free-space cap") @@ -94,3 +98,31 @@ func TestCutCOWV3_SpillCapFollowsFreeSpaceEachCut(t *testing.T) { t.Fatalf("after freeing space the cap is %d, want the configured %d", got, l.cfg.COWSpillLimit) } } + +// The staging bound follows the free space read at the cut: with ample +// free space the fixture's two dirty chunks are within the bound and go to +// the barrier unstaged; with free space below the reserve the cap is 0, so +// the cut pre-uploads them in a staging round before the barrier. +func TestCutCOWV3_LowFreeSpaceStagesBeforeTheBarrier(t *testing.T) { + for _, c := range []struct { + name string + free int64 + wantStaged bool + }{ + {"ample free space", 100 << 30, false}, + {"free space below the reserve", 1 << 30, true}, + } { + t.Run(c.name, func(t *testing.T) { + _, l, _, gate := cowFixture(t) + gate.unblock() + l.cfg.COWSpillFree = func() (int64, error) { return c.free, nil } + r, err := l.Cut(context.Background()) + if err != nil { + t.Fatal(err) + } + if staged := r.Stats.StageRounds > 0 && r.Stats.StagedChunks >= 2; staged != c.wantStaged { + t.Fatalf("free %d: %d staging rounds, %d staged chunks; want staged=%v", c.free, r.Stats.StageRounds, r.Stats.StagedChunks, c.wantStaged) + } + }) + } +} From 827cec9752177e4c284c44f3de7b1c83032a52da Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 05:20:09 -0800 Subject: [PATCH 32/34] docs: restore the S11 ForkDelete row dropped in the merge (verbatim from main) Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/spec/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 9a280f9a02..2dee559ccc 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -119,6 +119,7 @@ length of TLC's shortest counterexample. | S6 | `ReplicationFailover` | RF=2: P ships to R, R acks what is durable, the client is acked when both are durable; promotion of R at a new epoch with an evidence gate; R refuses old-epoch shipping; cuts and snapshots cover only the replicated-durable frontier; an in-flight snapshot create from the old primary may still land after the failover. Design-level. | `AckedSurvive`, `HeadOnLineage`, `SnapOnLineage`, `NoStaleAck` | `S6_design` pass (52,897), `S6_design_big` (598,353). **RED:** `S6_red_localCut` HeadOnLineage; `S6_red_noFence` AckedSurvive. `S6_red_noEvidence` passes: with synchronous RF=2 acks the gate is redundant (it matters for quorum or async shipping, not modelled). | `core/transport/replica.go:362` replica rejects a stale-lineage ship entry; `core/replication/volume.go:680` RebaseShipLSN; takeover CAS as in S2 | | S9 | `RetentionGCTiming`, `RetentionGCMulti` | GC timing with an explicit clock: a copy operation with deadline D, marks of duration up to MD, deletion only after two marks at least Grace apart; then marks across two volumes with a fork and a snapshot delete. | `NoLiveDelete` | **Single op:** `S9_rule_G4` (G > D + MD) pass (10,798; `_big` 43,780); G = D passes (`S9_red_G2_noguard`, 11,953). **RED:** `S9_red_G1_noguard`, `S9_red_G1_D3` (G < D) NoLiveDelete violated. **Two volumes:** `S9b_G1_MD2`, `_G2_MD2`, `_G2_MD3`, `_G3_MD1` pass (5,743-9,079). | `core/frontend/chunkstore/gc.go:89` grace > operation deadline, `:280` mark-duration margin, `:306-318` two-mark rule, `:214-221` intent expiry; `catalog.go:896-905` intent deadline re-checked before publish; `gc_copy.go:143`, `:177` a deleting attempt stays a root until grace | | S10 | `RestoreIndependence` | Independent restore: fork of a sealed snapshot, hydrate, bounded batch cuts (own fids uploaded under an intent, one HEAD CAS per batch), the independence marker after the last foreign ref; GC, source delete, snapshot retention, and crashes with resume from remote facts at any point. `NoClaim` (the code): no claim; the fork window is safe by two time rules on one clock, ForkEnd only while now < readAt + D and a deleted snapshot rooted while now < delAt + G. The older claim variants stay as regression configurations. | `NoGap`, `Independent`, `NoForeignList`, `LifecycleFree`, `StateRemote` | **Exhaustive (TLC breadth-first, complete state graph, no error)**, no-claim: `nc_safe` 405,198 distinct states; `nc_safe_b2` 504,097; `nc_safe_n4` 2,752,518; `nc_safe_G3D2` 379,500; boundary `nc_bnd_G1D1` 444,564 and `nc_bnd_G3D3` 360,615 safe, `nc_bnd_G0D1` and `nc_bnd_G2D3` violate NoGap: safe iff G >= D on one clock, which is `ForkDelete`'s G >= D + E + P with E = P = 0 (the production inequality is ForkDelete's). **RED** (each violated): `nc_red_CasBeforeUpload`, `nc_red_NoIntent`, `nc_red_GltD`, `nc_red_noDeadline`, `nc_red_notRooted`, `nc_red_resumeNoReread` NoGap; `nc_red_MarkerEarly`, `nc_red_MarkerBeforeCas`, `nc_red_SnapDuringRestore` Independent; `nc_red_ListForeign` NoForeignList; `nc_red_ResumeLocal` StateRemote. **Witnesses reached:** `nc_wit_DelInFork` (the source snapshot deleted inside the fork window and the restore completes), `nc_wit_FailNotFound`. Regression (claim frame): `safe` 1,599, `opt1_safe` 3,639, `oldframe` 1,599 safe; `oldframe_drop`, `red_DropClaimAtFork_gap` violate NoGap. Limits: no guest writes to the target while it takes ownership, GC acts immediately, one restore per snapshot. | `core/frontend/chunkstore/catalog.go` `Restore`, `CreateSnapshot` (restore refusal); `restore.go` `MarkIndependent`, `foreignRefsOf`; `gc.go` `Collector.run` (qualified refs rooted by owner); `core/storage/chunk_hydrate_all.go` `HydrateAllAt`; `core/storage/chunk_own.go` `OwnBatch`; `core/host/volume/chunk_restore.go` `runRestore` | +| S11 | `ForkDelete` | Fork or restore against snapshot delete with no claim: the fork reads the parent, may crash and retry (a retry re-reads it), and publishes only before its read time + D, as one atomic step or check-then-publish with up to P ticks between; delete stamps its time; GC (one atomic step) keeps a deleted attempt rooted while its clock is below delete time + G. Three clocks with pairwise skew up to E. | `NoGap` (a published fork HEAD names only existing chunks) | **Exhaustive (TLC breadth-first, complete state graph, no error)**: all 11 safe cfgs, from `safe_D2E0G2` (18,672 distinct states) to `safe_na_P2_D1E2G5` (15,730,209), including every boundary G = D + E + P (atomic and two-step, NC = 2). **RED**, each violating NoGap: the boundary minus one (`red_bnd_*`, `red_na_P*`), `red_noDeadlineCheck`, `red_deletedNotRooted`, `red_noRetryReread`. **Witnesses reached:** `wit_benefit`, `wit_benefit_na_P1`, `wit_deadlineLoss`, `wit_gcDeletes`, `wit_retryNotFound`. Safe iff G >= D + E + P. | `core/frontend/chunkstore/catalog.go` `Fork` (deadline start before `readForkParent`, publish before start + deadline); `retention.go` `markDeleting` (no claim); `gc.go` `NewCollector` (grace >= deadline + skew + CAS apply bound); `gc_copy.go` `snapshotAttemptHeads` (deleted attempt rooted for grace) | ## Limits From dad0b347d31cfd5084f970d1d9760f4d0e66b060 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 05:29:30 -0800 Subject: [PATCH 33/34] storage: one free-space read per cut for staging and the window; a zero cap shows its cause (no_room_to_cut, free_space_unreadable) in stats and abort counts Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_cut_cow.go | 54 ++++++- .../storage/chunk_cut_cow_spillfree_test.go | 151 +++++++++++------- .../storage/chunk_cut_payload_budget_test.go | 2 +- seaweed-block/core/storage/chunk_layer.go | 13 +- seaweed-block/core/storage/chunk_seam.go | 8 +- seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/status-schema.md | 4 +- 7 files changed, 166 insertions(+), 68 deletions(-) diff --git a/seaweed-block/core/storage/chunk_cut_cow.go b/seaweed-block/core/storage/chunk_cut_cow.go index e431016650..35144e34ff 100644 --- a/seaweed-block/core/storage/chunk_cut_cow.go +++ b/seaweed-block/core/storage/chunk_cut_cow.go @@ -26,19 +26,57 @@ const defaultCOWSpillLimit = 1 << 30 // on top of leaving half of the rest. const cowSpillFreeReserve = 1 << 30 +var ( + // errCutNoRoom: the free space leaves this cut no side-file room. + errCutNoRoom = errors.New("storage: no room to cut") + // errCutFreeUnreadable: the free space could not be read, so this cut + // has no side-file room. + errCutFreeUnreadable = errors.New("storage: free space unreadable") +) + +// cowSpillCap is one cut's side-file cap. cause is set when the free space +// made it zero: errCutNoRoom or errCutFreeUnreadable. +type cowSpillCap struct { + bytes int64 + cause error +} + // cowSpillLimit is this cut's side-file cap: COWSpillLimit, lowered to // half the free space minus cowSpillFreeReserve when COWSpillFree is set. -func (l *chunkLayerImpl) cowSpillLimit() int64 { +// A read error gives a cap of 0 with its own cause. +func (l *chunkLayerImpl) cowSpillLimit() cowSpillCap { limit := l.cfg.COWSpillLimit if l.cfg.COWSpillFree == nil { - return limit + return cowSpillCap{bytes: limit} } free, err := l.cfg.COWSpillFree() if err != nil { - free = 0 + return cowSpillCap{cause: fmt.Errorf("%w: %w", errCutFreeUnreadable, err)} } - return max(0, min(limit, free/2-cowSpillFreeReserve)) + c := cowSpillCap{bytes: max(0, min(limit, free/2-cowSpillFreeReserve))} + if c.bytes == 0 { + c.cause = errCutNoRoom + } + return c } + +// readCutSpill reads this cut's side-file cap once, for both the staging +// bound and the copy window, and records it in the stats. +func (l *chunkLayerImpl) readCutSpill() cowSpillCap { + c := l.cowSpillLimit() + reason := "" + switch { + case errors.Is(c.cause, errCutFreeUnreadable): + reason = "free_space_unreadable" + case errors.Is(c.cause, errCutNoRoom): + reason = "no_room_to_cut" + } + l.stMu.Lock() + l.stats.COWSpillCap, l.stats.COWSpillCapReason = c.bytes, reason + l.stMu.Unlock() + return c +} + const ( cowPending uint8 = iota cowCopying @@ -86,6 +124,7 @@ type cutCOWWindow struct { memory int64 spillBytes int64 // bytes written to the side file; at most spillLimit spillLimit int64 + spillCause error // why spillLimit is 0, when the free space made it so chunkBytes int64 memoryLimit int64 saverSlots chan struct{} @@ -161,12 +200,12 @@ func (l *chunkLayerImpl) holdCOWDestructive() func() { } // The caller owns captureMu exclusive, so no writer can miss this publication. -func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool, head map[uint64]chunkRef) (*cutCOWWindow, error) { +func (l *chunkLayerImpl) installCOWWindow(candidates, staged map[uint64]bool, head map[uint64]chunkRef, spill cowSpillCap) (*cutCOWWindow, error) { size := uint64(l.blockSize) * l.chunkBlocks if size == 0 || size > math.MaxInt64 || uint64(len(candidates)) > math.MaxInt64/size { return nil, fmt.Errorf("%w: side-store geometry", errCutCOWAborted) } - w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), head: head, spillLimit: l.cowSpillLimit(), chunkBytes: int64(size)} + w := &cutCOWWindow{layer: l, ended: make(chan struct{}), entries: make(map[uint64]*cutCOWEntry), head: head, spillLimit: spill.bytes, spillCause: spill.cause, chunkBytes: int64(size)} w.ctx, w.cancel = context.WithCancel(context.Background()) _, reserved, limit := l.cutPayloadWorkers() savers := min(max(1, int((16<<20)/int64(size))), int((limit-reserved)/(2*int64(size)))) @@ -391,6 +430,9 @@ func (w *cutCOWWindow) save(e *cutCOWEntry, data []byte, missing []uint64) error // The side file is sparse but its saved chunks are real bytes on the // volume's filesystem: abort the cut (retried) instead of filling it. w.mu.Unlock() + if w.spillCause != nil { + return fmt.Errorf("%w: %w: %w: COW spill cap is 0", errCutCOWAborted, errCutCOWCapacity, w.spillCause) + } return fmt.Errorf("%w: %w: COW spill would exceed its cap of %d bytes", errCutCOWAborted, errCutCOWCapacity, w.spillLimit) } else { w.spillBytes += w.chunkBytes diff --git a/seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go b/seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go index 9e42a126cd..b3db646ae3 100644 --- a/seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go +++ b/seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go @@ -3,18 +3,19 @@ package storage import ( "context" "errors" - "strings" + "fmt" "sync/atomic" "testing" ) // The spill cap is min(COWSpillLimit, free/2 - reserve), at least 0, read -// from COWSpillFree on every call; an error counts as no free space, and -// without COWSpillFree the configured cap applies. +// from COWSpillFree on every call. A cap of 0 carries its cause: no room +// (the free space is within the reserve) or a read error, which is not +// reported as a full disk. Without COWSpillFree the configured cap applies. func TestCOWSpillLimit_FromFreeSpace(t *testing.T) { l := &chunkLayerImpl{cfg: ChunkLayerConfig{COWSpillLimit: 4 << 30}} - if got := l.cowSpillLimit(); got != 4<<30 { - t.Fatalf("no free-space reader: cap %d, want the configured 4 GiB", got) + if got := l.cowSpillLimit(); got.bytes != 4<<30 || got.cause != nil { + t.Fatalf("no free-space reader: cap %+v, want the configured 4 GiB", got) } var free atomic.Int64 var reads atomic.Int64 @@ -28,74 +29,116 @@ func TestCOWSpillLimit_FromFreeSpace(t *testing.T) { } for _, c := range []struct { free, want int64 + cause error }{ - {100 << 30, 4 << 30}, // plenty: the configured cap - {6 << 30, 2 << 30}, // 6 GiB free: half is 3, minus the 1 GiB reserve - {2 << 30, 0}, // half the free space is all reserve - {1 << 30, 0}, // below the reserve: never negative - {10<<30 + 2, 4 << 30}, // the configured cap still bounds it - {3 << 30, (3<<30)/2 - (1 << 30)}, // 1.5 GiB - 1 GiB + {100 << 30, 4 << 30, nil}, // plenty: the configured cap + {6 << 30, 2 << 30, nil}, // 6 GiB free: half is 3, minus the 1 GiB reserve + {2 << 30, 0, errCutNoRoom}, // half the free space is all reserve + {1 << 30, 0, errCutNoRoom}, // below the reserve: never negative + {10<<30 + 2, 4 << 30, nil}, // the configured cap still bounds it + {3 << 30, (3<<30)/2 - (1 << 30), nil}, // 1.5 GiB - 1 GiB } { free.Store(c.free) - if got := l.cowSpillLimit(); got != c.want { - t.Fatalf("free %d: cap %d, want %d", c.free, got, c.want) + if got := l.cowSpillLimit(); got.bytes != c.want || !errors.Is(got.cause, c.cause) || (c.cause == nil) != (got.cause == nil) { + t.Fatalf("free %d: cap %+v, want %d (cause %v)", c.free, got, c.want, c.cause) } } if reads.Load() != 6 { t.Fatalf("free space read %d times for 6 calls; want once per call", reads.Load()) } fail.Store(true) - if got := l.cowSpillLimit(); got != 0 { - t.Fatalf("free-space error: cap %d, want 0 (no free space)", got) + if got := l.cowSpillLimit(); got.bytes != 0 || !errors.Is(got.cause, errCutFreeUnreadable) || errors.Is(got.cause, errCutNoRoom) { + t.Fatalf("free-space read error: cap %+v, want 0 with cause free_space_unreadable (not no room)", got) } } -// The copy window reads the free space when it opens, not only when the -// cut starts staging: free space that shrinks below the reserve between -// the two gives the window a cap of 0, so once the in-memory budget is used -// a save aborts that cut (the guest write completes); after space is freed -// the cap reads the new value. -func TestCutCOWV3_SpillCapFollowsFreeSpaceEachCut(t *testing.T) { +// Each cut reads the free space once, for both the staging bound and the +// window, and shows the cap in the stats: the configured cap with ample +// free space; 0 with reason no_room_to_cut when the free space is within +// the reserve (the cut still completes by staging before the barrier); +// 0 with reason free_space_unreadable when the read fails. +func TestCutCOWV3_SpillCapIsReadOncePerCutAndShown(t *testing.T) { s, l, _, gate := cowFixture(t) + gate.unblock() var free, reads atomic.Int64 - free.Store(100 << 30) + var fail atomic.Bool l.cfg.COWSpillFree = func() (int64, error) { - if reads.Add(1) == 2 { // the window opens: the filesystem has filled up - free.Store(1 << 30) + reads.Add(1) + if fail.Load() { + return 0, errors.New("statfs failed") } return free.Load(), nil } - cutDone, cutErr := cowStartCut(t, l, gate) - w := l.cowActive.Load() - w.mu.Lock() - w.memory = cutCOWMemoryLimit // the in-memory budget is used - limit := w.spillLimit - w.mu.Unlock() - if limit != 0 { - t.Fatalf("window cap %d with 1 GiB free; want 0", limit) + for i, c := range []struct { + free int64 + fail bool + cap int64 + reason string + }{ + {100 << 30, false, l.cfg.COWSpillLimit, ""}, + {1 << 30, false, 0, "no_room_to_cut"}, + {100 << 30, true, 0, "free_space_unreadable"}, + } { + free.Store(c.free) + fail.Store(c.fail) + if _, err := s.Write(uint32(i*ctChunkBlocks+1), makeBlock(ctBlockSize, byte(0x60+i))); err != nil { + t.Fatal(err) + } + before := reads.Load() + if _, err := l.Cut(context.Background()); err != nil && c.reason == "" { + t.Fatal(err) + } + if n := reads.Load() - before; n != 1 { + t.Fatalf("cut %d read the free space %d times; want once", i, n) + } + if st := l.Stats(); st.COWSpillCap != c.cap || st.COWSpillCapReason != c.reason { + t.Fatalf("cut %d: stats cap %d reason %q; want %d %q", i, st.COWSpillCap, st.COWSpillCapReason, c.cap, c.reason) + } } - writeDone := make(chan struct{}) - writeErr := make(chan error, 1) - // Registered before the writer starts: release the copier and join the - // writer (bounded) whatever the test's outcome. - t.Cleanup(func() { gate.unblock(); cowWaitSignal(t, writeDone, "free-space-cap writer cleanup") }) - go func() { - defer close(writeDone) - _, err := s.Write(5, makeBlock(ctBlockSize, 0xd6)) - writeErr <- err - }() - cowWaitSignal(t, writeDone, "guest write at the free-space cap") - if err := <-writeErr; err != nil { - t.Fatal("guest write refused at the free-space cap:", err) - } - gate.unblock() - cowWaitSignal(t, cutDone, "cut at the free-space cap") - if err := <-cutErr; !errors.Is(err, errCutCOWAborted) || !strings.Contains(err.Error(), "cap of 0 bytes") { - t.Fatalf("cut at a 0 cap: %v, want the cap abort", err) - } - free.Store(100 << 30) - if got := l.cowSpillLimit(); got != l.cfg.COWSpillLimit { - t.Fatalf("after freeing space the cap is %d, want the configured %d", got, l.cfg.COWSpillLimit) +} + +// A save that meets a zero cap aborts the cut under the cap's own cause: +// no_room_to_cut or free_space_unreadable, not cow_capacity; the guest +// write completes and the next cut is not blocked. +func TestCutCOWV3_ZeroCapAbortIsCountedByItsCause(t *testing.T) { + for _, c := range []struct { + cause error + reason string + }{ + {errCutNoRoom, "no_room_to_cut"}, + {fmt.Errorf("%w: %w", errCutFreeUnreadable, errors.New("statfs failed")), "free_space_unreadable"}, + } { + t.Run(c.reason, func(t *testing.T) { + s, l, _, gate := cowFixture(t) + cutDone, cutErr := cowStartCut(t, l, gate) + w := l.cowActive.Load() + w.mu.Lock() + w.memory = cutCOWMemoryLimit // the in-memory budget is used + w.spillLimit, w.spillCause = 0, c.cause + w.mu.Unlock() + writeDone := make(chan struct{}) + writeErr := make(chan error, 1) + // Registered before the writer starts: release the copier and + // join the writer (bounded) whatever the test's outcome. + t.Cleanup(func() { gate.unblock(); cowWaitSignal(t, writeDone, "zero-cap writer cleanup") }) + go func() { + defer close(writeDone) + _, err := s.Write(5, makeBlock(ctBlockSize, 0xd7)) + writeErr <- err + }() + cowWaitSignal(t, writeDone, "guest write at a zero cap") + if err := <-writeErr; err != nil { + t.Fatal("guest write refused at a zero cap:", err) + } + gate.unblock() + cowWaitSignal(t, cutDone, "cut at a zero cap") + if err := <-cutErr; !errors.Is(err, errCutCOWAborted) || !errors.Is(err, c.cause) { + t.Fatalf("cut at a zero cap: %v, want an abort carrying %v", err, c.cause) + } + if st := l.Stats(); st.CutsAborted[c.reason] != 1 || st.CutsAborted["cow_capacity"] != 0 { + t.Fatalf("aborts %v; want one %s and no cow_capacity", st.CutsAborted, c.reason) + } + }) } } diff --git a/seaweed-block/core/storage/chunk_cut_payload_budget_test.go b/seaweed-block/core/storage/chunk_cut_payload_budget_test.go index bf141d776b..7fae795b32 100644 --- a/seaweed-block/core/storage/chunk_cut_payload_budget_test.go +++ b/seaweed-block/core/storage/chunk_cut_payload_budget_test.go @@ -13,7 +13,7 @@ func TestCutPayloadBudgetBoundsSlots(t *testing.T) { for i := 0; i < candidates; i++ { pending[uint64(i)] = true } - w, err := l.installCOWWindow(pending, nil, nil) + w, err := l.installCOWWindow(pending, nil, nil, l.cowSpillLimit()) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 9a4bebad77..0c7dbd8a17 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -765,8 +765,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch var staged map[uint64]stagedChunk var intents []string _, guestFrozen := FrozenDetachFromContext(ctx) + spill := l.readCutSpill() if !guestFrozen { - staged, intents, err = l.stage(ctx, &st) + staged, intents, err = l.stage(ctx, &st, spill.bytes) } if st.UploadedBytes > 0 { st.PayloadNs += time.Since(stageStart).Nanoseconds() @@ -911,7 +912,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch { var w *cutCOWWindow windowStart := time.Now() - w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks) + w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks, spill) if copyErr == nil { w.budget = budget } @@ -1405,6 +1406,10 @@ func (l *chunkLayerImpl) recordCut(r chunkCutResult, st chunkCutStats, err error switch { case errors.Is(err, errCutSaverCapacity): abortReason = "saver_capacity" + case errors.Is(err, errCutFreeUnreadable): + abortReason = "free_space_unreadable" + case errors.Is(err, errCutNoRoom): + abortReason = "no_room_to_cut" case errors.Is(err, errCutCOWCapacity): abortReason = "cow_capacity" case errors.Is(err, errCutBudgetRevoked): @@ -1540,10 +1545,10 @@ func (l *chunkLayerImpl) dropIntents(ctx context.Context, ids []string) { // stage uploads large native dirty sets through logical reads, before fixing H. // It stops when the spill-budget remainder is reached or a round makes no // progress. Versions/HEAD generation bind every reusable immutable result. -func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint64]stagedChunk, []string, error) { +func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats, spillCap int64) (map[uint64]stagedChunk, []string, error) { // Leave at most half the side budget exposed at the barrier. Streaming // staging uses no local payload file, even for a much larger image. - bound := int(l.cowSpillLimit() / (2 * int64(l.blockSize) * int64(l.chunkBlocks))) + bound := int(spillCap / (2 * int64(l.blockSize) * int64(l.chunkBlocks))) staged := map[uint64]stagedChunk{} var intents []string diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index b83e6fa4b8..453cb20f7c 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -486,7 +486,7 @@ type chunkLayerStats struct { CutsNoop uint64 // cuts with nothing new (no CAS) CutsFailed uint64 // every other cut failure CutsRefused map[string]uint64 // refusals by reason: admission, fenced, detached - CutsAborted map[string]uint64 // saver_capacity, cow_capacity, budget_revoked, upload + CutsAborted map[string]uint64 // saver_capacity, cow_capacity, no_room_to_cut, free_space_unreadable, budget_revoked, upload CASConflicts uint64 // HEAD CAS precondition failures CASUnknown uint64 // HEAD CAS results still unresolved after the re-read PendingUnresolved bool // an unresolved HEAD proposal is held now @@ -503,6 +503,12 @@ type chunkLayerStats struct { // AbsentChunks is the number of HEAD-named chunks still absent with a // block not local (what HydrateAll would still fetch); 0 = fully local. AbsentChunks int + // COWSpillCap is the last cut's side-file cap in bytes, read once per + // cut; COWSpillCapReason is why it is 0, when the free space made it so: + // no_room_to_cut (half the free space is within the 1 GiB reserve) or + // free_space_unreadable (the free space could not be read). + COWSpillCap int64 + COWSpillCapReason string `json:",omitempty"` } // chunkCutResult is the outcome of one successful cut. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 156673db86..1e0171588d 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -678,4 +678,4 @@ Frozen estimate reporting: a tail above the existing 60 s estimator ceiling repo | Quantity | Unit | Cap | Enforced at (producer) | Drained | Outcome at the cap | |---|---|---|---|---|---| -| COW side-file spill per cut | bytes | min(`COWSpillLimit` (default 1 GiB, or the host limit's COW bytes), free space on `--durable-root` / 2 - 1 GiB), at least 0; free space read at each cut (staging bound and window open); a read error counts as no free space; off Linux, the configured cap | the saver: `core/storage/chunk_cut_cow.go` `cowSpillLimit`, the save's cap check | at the cut's end (the side file is removed on publish, abort or close) | that cut aborts (`cow_capacity`, retryable); the guest write completes and nothing partial is published | +| COW side-file spill per cut | bytes | min(`COWSpillLimit` (default 1 GiB, or the host limit's COW bytes), free space on `--durable-root` / 2 - 1 GiB), at least 0; the free space is read once per cut and that cap bounds both staging and the copy window; off Linux, the configured cap. Shown per cut in the layer stats (`COWSpillCap`, `COWSpillCapReason`: `no_room_to_cut` when the free space is within the reserve, `free_space_unreadable` when the read fails) | the saver: `core/storage/chunk_cut_cow.go` `readCutSpill`, the save's cap check | at the cut's end (the side file is removed on publish, abort or close) | that cut aborts (retryable), counted as `cow_capacity`, or as `no_room_to_cut` / `free_space_unreadable` when the free space made the cap 0; the guest write completes and nothing partial is published | diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 02d7a1d468..25a61677d0 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -222,7 +222,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.CutsNoop` | uint64 | cuts with nothing new (no CAS) | | `Volumes[].Chunk.Stats.CutsFailed` | uint64 | every other cut failure | | `Volumes[].Chunk.Stats.CutsRefused{}` | uint64 | refusals by reason: admission, fenced, detached | -| `Volumes[].Chunk.Stats.CutsAborted{}` | uint64 | saver_capacity, cow_capacity, budget_revoked, upload | +| `Volumes[].Chunk.Stats.CutsAborted{}` | uint64 | saver_capacity, cow_capacity, no_room_to_cut, free_space_unreadable, budget_revoked, upload | | `Volumes[].Chunk.Stats.CASConflicts` | uint64 | HEAD CAS precondition failures | | `Volumes[].Chunk.Stats.CASUnknown` | uint64 | HEAD CAS results still unresolved after the re-read | | `Volumes[].Chunk.Stats.PendingUnresolved` | bool | an unresolved HEAD proposal is held now | @@ -275,6 +275,8 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.LastCutNs` | int64 | when it completed (wall clock, Unix ns) | | `Volumes[].Chunk.Stats.BarrierOverBound` | uint64 | BarrierOverBound counts cuts whose barrier copied more than the bound after the staging rounds. | | `Volumes[].Chunk.Stats.AbsentChunks` | int | AbsentChunks is the number of HEAD-named chunks still absent with a block not local (what HydrateAll would still fetch); 0 = fully local. | +| `Volumes[].Chunk.Stats.COWSpillCap` | int64 | COWSpillCap is the last cut's side-file cap in bytes, read once per cut; COWSpillCapReason is why it is 0, when the free space made it so: no_room_to_cut (half the free space is within the 1 GiB reserve) or free_space_unreadable (the free space could not be read). | +| `Volumes[].Chunk.Stats.COWSpillCapReason` | string | (group of `COWSpillCap`) COWSpillCap is the last cut's side-file cap in bytes, read once per cut; COWSpillCapReason is why it is 0, when the free space made it so: no_room_to_cut (half the free space is within the 1 GiB reserve) or free_space_unreadable (the free space could not be read). (omitted when empty) | | `Volumes[].Chunk.HostBudget` | interface | the host background-cut budget state, with --host-limit-dir (omitted when empty) | | `Volumes[].Warnings[]` | string | Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) | | `Volumes[].HolesSuspected` | uint64 | (group of `Warnings`) Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) | From b9bc1515743101de1848991f2947558bf67d1b31 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 05:43:57 -0800 Subject: [PATCH 34/34] storage: test that the copy window holds the cut's own read cap and cause; zero-cap cuts that stage must complete Co-Authored-By: Claude Opus 5.5 --- .../storage/chunk_cut_cow_spillfree_test.go | 58 ++++++++++++++++++- 1 file changed, 56 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go b/seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go index b3db646ae3..eefd41798b 100644 --- a/seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go +++ b/seaweed-block/core/storage/chunk_cut_cow_spillfree_test.go @@ -85,8 +85,11 @@ func TestCutCOWV3_SpillCapIsReadOncePerCutAndShown(t *testing.T) { t.Fatal(err) } before := reads.Load() - if _, err := l.Cut(context.Background()); err != nil && c.reason == "" { - t.Fatal(err) + if _, err := l.Cut(context.Background()); err != nil { + t.Fatalf("cut %d (free %d, read error %v): %v; want it to complete by staging, not refuse", i, c.free, c.fail, err) + } + if st := l.Stats(); len(st.CutsAborted) != 0 { + t.Fatalf("cut %d: aborts %v; want none", i, st.CutsAborted) } if n := reads.Load() - before; n != 1 { t.Fatalf("cut %d read the free space %d times; want once", i, n) @@ -97,6 +100,57 @@ func TestCutCOWV3_SpillCapIsReadOncePerCutAndShown(t *testing.T) { } } +// The cap the window holds is the one this cut read: with the free space +// within the reserve (or unreadable) the copy window opens with a cap of 0 +// and that cause, straight from the reader. The window is caught open by +// holding its copy of chunk 0: staging runs with the read gate disarmed, +// and the stage hook re-dirties chunk 0 each round and arms the gate after +// the second, so the barrier leaves chunk 0 to the window. +func TestCutCOWV3_WindowGetsTheCutsReadCap(t *testing.T) { + for _, c := range []struct { + name string + read func() (int64, error) + cause error + }{ + {"no room", func() (int64, error) { return 1 << 30, nil }, errCutNoRoom}, + {"unreadable", func() (int64, error) { return 0, errors.New("statfs failed") }, errCutFreeUnreadable}, + } { + t.Run(c.name, func(t *testing.T) { + s, l, _, gate := cowFixture(t) + gate.mu.Lock() + gate.armed = false + gate.mu.Unlock() + l.cfg.COWSpillFree = c.read + l.testAfterStageHook = func(round int) { + if _, err := s.Write(1, makeBlock(ctBlockSize, byte(0x70+round))); err != nil { + t.Error(err) + } + if round == 1 { + gate.mu.Lock() + gate.armed = true + gate.mu.Unlock() + } + } + cutDone, cutErr := cowStartCut(t, l, gate) + w := l.cowActive.Load() + if w == nil { + t.Fatal("no copy window open while its copy is held") + } + w.mu.Lock() + limit, cause := w.spillLimit, w.spillCause + w.mu.Unlock() + if limit != 0 || !errors.Is(cause, c.cause) { + t.Fatalf("window cap %d cause %v; want 0 and %v from the cut's read", limit, cause, c.cause) + } + gate.unblock() + cowWaitSignal(t, cutDone, "cut with the window held") + if err := <-cutErr; err != nil { + t.Fatalf("cut: %v; want it to complete (the held copy needs no spill)", err) + } + }) + } +} + // A save that meets a zero cap aborts the cut under the cap's own cause: // no_room_to_cut or free_space_unreadable, not cow_capacity; the guest // write completes and the next cut is not blocked.