diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index e864488299..211e609993 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -472,18 +472,26 @@ func (l *chunkLayerImpl) admit() error { } if gate := l.cfg.CaptureAllowed; gate != nil { if err := gate(); err != nil { - return fmt.Errorf("%w: %v", errChunkCaptureRefused, err) + return fmt.Errorf("%w: %w", errChunkCaptureRefused, err) } } return nil } -func (l *chunkLayerImpl) Capture(ctx context.Context) (uint64, error) { +func (l *chunkLayerImpl) Cut(ctx context.Context) (chunkCutResult, error) { l.capMu.Lock() defer l.capMu.Unlock() return l.captureLocked(ctx) } +func (l *chunkLayerImpl) Capture(ctx context.Context) (uint64, error) { + r, err := l.Cut(ctx) + if err != nil { + return 0, err + } + return r.H, nil +} + func (l *chunkLayerImpl) MakeRemoteDurable(ctx context.Context, t uint64) error { l.capMu.Lock() defer l.capMu.Unlock() @@ -496,12 +504,12 @@ func (l *chunkLayerImpl) MakeRemoteDurable(ctx context.Context, t uint64) error if last := l.s.NextLSN() - 1; t > last { return fmt.Errorf("storage: MakeRemoteDurable(%d): LSN was never written (last %d)", t, last) } - h, err := l.captureLocked(ctx) + r, err := l.captureLocked(ctx) if err != nil { return err } - if h < t { - return fmt.Errorf("storage: MakeRemoteDurable(%d): cut reached only %d", t, h) + if r.H < t { + return fmt.Errorf("storage: MakeRemoteDurable(%d): cut reached only %d", t, r.H) } return nil } @@ -513,14 +521,14 @@ type capturedChunk struct { zero bool } -func (l *chunkLayerImpl) captureLocked(ctx context.Context) (uint64, error) { +func (l *chunkLayerImpl) captureLocked(ctx context.Context) (chunkCutResult, error) { done, err := l.register() if err != nil { - return 0, err + return chunkCutResult{}, err } defer done() if err := l.admit(); err != nil { - return 0, err + return chunkCutResult{}, err } if hook := l.testAfterAdmitHook; hook != nil { hook() @@ -529,7 +537,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context) (uint64, error) { defer cancel() if err := l.resolvePending(ctx); err != nil { - return 0, err + return chunkCutResult{}, err } // Quiesced cut. @@ -537,7 +545,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context) (uint64, error) { h, err := l.s.Sync() if err != nil { l.s.captureMu.Unlock() - return 0, fmt.Errorf("storage: capture sync: %w", err) + return chunkCutResult{}, fmt.Errorf("storage: capture sync: %w", err) } candidates := map[uint64]bool{} for _, e := range l.s.dm.snapshot() { @@ -589,7 +597,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context) (uint64, error) { l.s.captureMu.Unlock() if copyErr != nil { l.abortCut(all) - return 0, fmt.Errorf("storage: capture copy: %w", copyErr) + return chunkCutResult{}, fmt.Errorf("storage: capture copy: %w", copyErr) } // Upload only what changed against HEAD. @@ -610,7 +618,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context) (uint64, error) { key := l.newKey(c.idx) if err := l.remote.Put(ctx, key, c.data); err != nil { l.abortCut(all) - return 0, fmt.Errorf("storage: capture upload chunk %d: %w", c.idx, err) + return chunkCutResult{}, fmt.Errorf("storage: capture upload chunk %d: %w", c.idx, err) } next.Chunks[c.idx] = chunkRef{Key: key, SHA256: c.sum} newKeys[c.idx] = key @@ -618,25 +626,25 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context) (uint64, error) { } if len(changed) == 0 && h == baseHead.RemoteLSN && baseHead.Gen != 0 { l.finishCut(baseHead, h, nil, nil) // nothing new: no CAS - return h, nil + return chunkCutResult{H: h, Head: copyHead(baseHead), Noop: true, FullHash: all}, nil } if err := l.admit(); err != nil { // admission re-checked right before the CAS l.abortCut(all) - return 0, err + return chunkCutResult{}, err } if l.supersededBy(baseHead) { l.abortCut(all) l.stMu.Lock() l.fenced = true l.stMu.Unlock() - return 0, errChunkLayerFenced + return chunkCutResult{}, errChunkLayerFenced } expected := chunkHeadVersion{Gen: baseHead.Gen, Epoch: baseHead.Epoch} gen, casErr := l.remote.CASHead(ctx, expected, next) if casErr == nil { next.Gen = gen l.finishCut(next, h, changed, newKeys) - return h, nil + return chunkCutResult{H: h, Head: copyHead(next), FullHash: all}, nil } // Precondition or unknown outcome: resolve by re-reading HEAD, never by // a blind retry. @@ -647,11 +655,11 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context) (uint64, error) { l.pending = &p l.stMu.Unlock() l.abortCut(all) - return 0, fmt.Errorf("storage: capture CAS outcome unresolved (%v): %w", casErr, gerr) + return chunkCutResult{}, fmt.Errorf("storage: capture CAS outcome unresolved (%v): %w", casErr, gerr) } if sameProposal(cur, next) { l.finishCut(cur, h, changed, newKeys) - return h, nil + return chunkCutResult{H: h, Head: copyHead(cur), FullHash: all}, nil } l.abortCut(all) if l.supersededBy(cur) { @@ -659,12 +667,12 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context) (uint64, error) { l.fenced = true l.head = copyHead(cur) l.stMu.Unlock() - return 0, errors.Join(errChunkLayerFenced, casErr) + return chunkCutResult{}, errors.Join(errChunkLayerFenced, casErr) } l.stMu.Lock() l.head = copyHead(cur) l.stMu.Unlock() - return 0, fmt.Errorf("storage: capture CAS not applied: %w", casErr) + return chunkCutResult{}, fmt.Errorf("storage: capture CAS not applied: %w", casErr) } // supersededBy reports whether cur belongs to a newer or competing holder. diff --git a/seaweed-block/core/storage/chunk_layer_cut_test.go b/seaweed-block/core/storage/chunk_layer_cut_test.go new file mode 100644 index 0000000000..757f055eb0 --- /dev/null +++ b/seaweed-block/core/storage/chunk_layer_cut_test.go @@ -0,0 +1,106 @@ +package storage + +import ( + "errors" + "fmt" + "testing" +) + +func sameHead(a, b chunkHead) bool { + if a.Gen != b.Gen || a.Epoch != b.Epoch || a.Holder != b.Holder || a.RemoteLSN != b.RemoteLSN || len(a.Chunks) != len(b.Chunks) { + return false + } + for k, v := range a.Chunks { + if b.Chunks[k] != v { + return false + } + } + return true +} + +// Cut returns the HEAD its own CAS installed, so a snapshot can copy exactly +// the image of cut H; a cut with nothing new does no CAS and returns the +// current HEAD. +func TestChunkCut_ReturnsInstalledHead(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 2, 0x22) + w.write(t, s, 9, 0x29) + + r, err := layer.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + heads := f.installedHeads() + if len(heads) != 1 { + t.Fatalf("installed %d HEADs, want 1", len(heads)) + } + if !sameHead(r.Head, heads[0]) { + t.Fatalf("Cut returned HEAD %+v, the remote installed %+v", r.Head, heads[0]) + } + if r.Noop || r.H != heads[0].RemoteLSN || r.H != s.NextLSN()-1 { + t.Fatalf("Cut result noop=%v H=%d; installed remote_lsn %d, last LSN %d", r.Noop, r.H, heads[0].RemoteLSN, s.NextLSN()-1) + } + + casBefore := f.stats().cas + again, err := layer.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if !again.Noop || f.stats().cas != casBefore { + t.Fatalf("a cut with nothing new: noop=%v, CAS calls %d -> %d", again.Noop, casBefore, f.stats().cas) + } + if !sameHead(again.Head, heads[0]) || again.H != r.H { + t.Fatalf("no-op cut returned HEAD %+v H %d, want the current HEAD %+v H %d", again.Head, again.H, heads[0], r.H) + } + + // Capture keeps returning the cut LSN. + w.write(t, s, 2, 0x23) + h, err := layer.Capture(ctTimeout(t)) + if err != nil || h != s.NextLSN()-1 { + t.Fatalf("Capture after Cut: H=%d err=%v, want H=%d", h, err, s.NextLSN()-1) + } + assertEveryHeadIsPrefixImage(t, f, w) +} + +// When the CAS was applied but its response lost, the layer resolves it by +// re-reading HEAD; Cut must then return the HEAD actually installed. +func TestChunkCut_ReturnsInstalledHeadAfterLostResponse(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + f.casModes = []fakeCASMode{casAppliedLost} + layer := mustAttach(t, s, f, ctConfig(1)) + w := newWriteLog() + w.write(t, s, 5, 0x55) + + r, err := layer.Cut(ctTimeout(t)) + if err != nil { + t.Fatalf("applied CAS with a lost response: %v", err) + } + cur := f.stats().head + if !sameHead(r.Head, cur) || r.Head.Gen == 0 { + t.Fatalf("Cut returned HEAD %+v, the remote holds %+v", r.Head, cur) + } +} + +// Cut reports a refused capture with the owner's typed cause, like Capture +// (TestChunkCapture_RefusalIsTyped). +func TestChunkCut_RefusalIsTyped(t *testing.T) { + errNotPrimary := errors.New("test: not primary") + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + cfg := ctConfig(1) + cfg.CaptureAllowed = func() error { return fmt.Errorf("volume v1: %w", errNotPrimary) } + layer := mustAttach(t, s, f, cfg) + newWriteLog().write(t, s, 1, 0x11) + + _, err := layer.Cut(ctTimeout(t)) + if !errors.Is(err, errChunkCaptureRefused) || !errors.Is(err, errNotPrimary) { + t.Fatalf("Cut refusal %v: want both errChunkCaptureRefused and the owner's cause", err) + } + if n := f.stats().cas; n != 0 { + t.Fatalf("a refused cut issued %d CAS calls", n) + } +} diff --git a/seaweed-block/core/storage/chunk_layer_refusal_test.go b/seaweed-block/core/storage/chunk_layer_refusal_test.go new file mode 100644 index 0000000000..056f52a4be --- /dev/null +++ b/seaweed-block/core/storage/chunk_layer_refusal_test.go @@ -0,0 +1,27 @@ +package storage + +import ( + "errors" + "fmt" + "testing" +) + +// A capture refused by the owner's admission check keeps the owner's typed +// cause, so callers can tell "not primary" from "lineage changed" (P1). +func TestChunkCapture_RefusalIsTyped(t *testing.T) { + errNotPrimary := errors.New("test: not primary") + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + cfg := ctConfig(1) + cfg.CaptureAllowed = func() error { return fmt.Errorf("volume v1: %w", errNotPrimary) } + layer := mustAttach(t, s, f, cfg) + newWriteLog().write(t, s, 1, 0x11) + + _, err := layer.Capture(ctTimeout(t)) + if !errors.Is(err, errChunkCaptureRefused) || !errors.Is(err, errNotPrimary) { + t.Fatalf("Capture refusal %v: want both errChunkCaptureRefused and the owner's cause", err) + } + if n := f.stats().cas; n != 0 { + t.Fatalf("a refused capture issued %d CAS calls", n) + } +} diff --git a/seaweed-block/core/storage/chunk_layer_takeover_red_test.go b/seaweed-block/core/storage/chunk_layer_takeover_red_test.go new file mode 100644 index 0000000000..b1169575dd --- /dev/null +++ b/seaweed-block/core/storage/chunk_layer_takeover_red_test.go @@ -0,0 +1,122 @@ +//go:build chunk_takeover_red + +// RED tests for the takeover CAS at attach (W2 spec ยง6.3, P5). They are +// written by W2 and implemented by W4; the build tag keeps them out of the +// default suite until then. Run them with: +// +// go test -tags chunk_takeover_red -run TestChunkAttach_TakeOver ./core/storage/ +// +// The implementation should remove the build tag. + +package storage + +import ( + "bytes" + "crypto/sha256" + "errors" + "testing" +) + +func takeoverImage() []byte { + img := make([]byte, ctNumBlocks*ctBlockSize) + for lba := uint32(0); lba < 16; lba++ { // chunks 0-3 hold data; 4-7 are ZERO + copy(img[int(lba)*ctBlockSize:], makeBlock(ctBlockSize, byte(0x70+lba))) + } + return img +} + +// A fresh host attaching at a newer epoch must raise HEAD's epoch before it +// serves, without changing the published chunks, so a cut-off old holder's +// next CAS fails at once instead of after the new host's first commit. +func TestChunkAttach_TakeOverRaisesEpoch(t *testing.T) { + f := newFakeChunkRemote() + f.seedHead(t, takeoverImage(), 100, 1) + seeded := f.stats().head + + s, _ := newChunkTestStore(t) + cfg := ctConfig(2) + cfg.FreshFromHead = true + mustAttach(t, s, f, cfg) + + head := f.stats().head + if head.Epoch != 2 || head.Holder != cfg.Holder { + t.Fatalf("after attach HEAD is epoch %d holder %q, want the attaching epoch 2 holder %q", head.Epoch, head.Holder, cfg.Holder) + } + if head.RemoteLSN != seeded.RemoteLSN || len(head.Chunks) != len(seeded.Chunks) { + t.Fatalf("takeover changed the image: remote_lsn %d chunks %d, want %d and %d", head.RemoteLSN, len(head.Chunks), seeded.RemoteLSN, len(seeded.Chunks)) + } + for k, v := range seeded.Chunks { + if head.Chunks[k] != v { + t.Fatalf("takeover changed chunk %d: %+v, want %+v", k, head.Chunks[k], v) + } + } + // The old holder (epoch 1) can no longer commit. + if _, err := f.CASHead(ctTimeout(t), chunkHeadVersion{Gen: seeded.Gen, Epoch: 1}, seeded); !errors.Is(err, errChunkHeadPrecondition) { + t.Fatalf("old holder's CAS after takeover: %v, want errChunkHeadPrecondition", err) + } +} + +// The old holder commits a newer generation between the new host's HEAD +// read and its takeover CAS. Attach must then either take over that newer +// generation (and serve exactly its image) or fail; it must never serve a +// mix of two generations. +func TestChunkAttach_TakeOverRacesOldHolder(t *testing.T) { + f := newFakeChunkRemote() + img := takeoverImage() + f.seedHead(t, img, 100, 1) + + // The old holder's newer generation rewrites chunk 1 (LBA 4-7). + newer := append([]byte(nil), img...) + for lba := uint32(4); lba < 8; lba++ { + copy(newer[int(lba)*ctBlockSize:], makeBlock(ctBlockSize, byte(0xE0+lba))) + } + injected := false + f.beforeCAS = func(f *fakeChunkRemote) { + injected = true + next := copyChunkHead(f.head) + key := "seed/newer/1" + c := newer[1*ctChunkBytes : 2*ctChunkBytes] + f.objs[key] = append([]byte(nil), c...) + f.everStored[key] = true + next.Chunks[1] = chunkRef{Key: key, SHA256: sha256.Sum256(c)} + next.RemoteLSN = 101 + f.installLocked(next) + } + + s, _ := newChunkTestStore(t) + cfg := ctConfig(2) + cfg.FreshFromHead = true + layer, err := attachChunkLayer(s, f, cfg) + f.mu.Lock() + ran := injected + f.mu.Unlock() + if !ran { + // The race is injected before the takeover CAS; without that CAS the + // test has not exercised the race at all, whatever attach returned. + t.Fatalf("the old holder's competing CAS was never injected (attach err %v): attach made no takeover CAS", err) + } + if err != nil { + // Failing the attach is an allowed outcome, but only as a refusal + // to serve: nothing may have been published by the new host. + if h := f.stats().head; h.Holder == cfg.Holder { + t.Fatalf("attach failed (%v) but HEAD names the new holder: %+v", err, h) + } + return + } + t.Cleanup(func() { _ = layer.Close() }) + + head := f.stats().head + if head.Epoch != 2 || head.Holder != cfg.Holder { + t.Fatalf("attach returned without taking over: HEAD epoch %d holder %q", head.Epoch, head.Holder) + } + want := f.imageOf(t, head) + for lba := uint32(0); lba < ctNumBlocks; lba++ { + got, err := s.Read(lba) + if err != nil { + t.Fatalf("read LBA %d: %v", lba, err) + } + if !bytes.Equal(got, blockOf(want, lba)) { + t.Fatalf("LBA %d differs from the HEAD the new host took over (gen %d): a mix of generations", lba, head.Gen) + } + } +} diff --git a/seaweed-block/core/storage/chunk_public.go b/seaweed-block/core/storage/chunk_public.go index 8928738c2c..f344493b2a 100644 --- a/seaweed-block/core/storage/chunk_public.go +++ b/seaweed-block/core/storage/chunk_public.go @@ -15,6 +15,8 @@ type ( ChunkDelta = chunkDelta ChunkLayerConfig = chunkLayerConfig ChunkLayer = chunkLayer + ChunkCutResult = chunkCutResult + ChunkCutStats = chunkCutStats ) const ( diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index d6896d91e2..2c3469512e 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -213,12 +213,49 @@ type chunkLayerConfig struct { Bitmap chunkBitmapStore } +// chunkCutStats describes one cut. The periodic-cut work fills it; a zero +// value means "not measured". +type chunkCutStats struct { + BarrierPauseNs int64 + SyncNs int64 + CopyNs int64 + CandidateChunks int + UploadedChunks int + UploadedBytes int64 + ZeroedChunks int + UnchangedChunks int + UploadNs int64 + CASNs int64 + CASResult string + TotalNs int64 +} + +// chunkCutResult is the outcome of one successful cut. +// - H is the cut LSN; Head.RemoteLSN = H when the cut installed a HEAD. +// A volume's LSNs carry forward across hosts: a new host's WAL starts +// at HEAD.RemoteLSN + 1, and a fork starts after its snapshot's +// RemoteLSN, so RemoteLSN never decreases across generations. +// - Head is the HEAD this cut installed (copied, owned by the caller), or +// the current HEAD when the cut had nothing new (Noop: no CAS). +// - FullHash says the cut compared every chunk by hash (no usable bitmap, +// or the first cut after a BASE install). +type chunkCutResult struct { + H uint64 + Head chunkHead + Noop bool + FullHash bool + Stats chunkCutStats +} + // chunkLayer is what the store owner drives. type chunkLayer interface { chunkSink - // Capture takes a quiesced cut at H (the last written LSN), uploads the + // Cut takes a quiesced cut at H (the last written LSN), uploads the // chunks dirtied since the last HEAD and CASes HEAD with RemoteLSN = H. - // It returns H once HEAD is installed. + // It returns the HEAD it installed, so a snapshot can copy exactly the + // image of H even when other cuts follow. + Cut(ctx context.Context) (chunkCutResult, error) + // Capture is Cut, returning only H. Capture(ctx context.Context) (uint64, error) // MakeRemoteDurable is the durability point for snapshot, detach and // migrate: a Capture whose H >= t. Only a nil return makes t remote