From a9e515798f4260158fde78c6e8a3f651fb1a86f1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 10:05:23 -0800 Subject: [PATCH] fix: restore seeded frontier and reactivate detached HEAD before serving --- .../core/frontend/chunkstore/catalog_test.go | 17 +- .../core/frontend/chunkstore/chunk_remote.go | 10 + .../frontend/chunkstore/restore_lsn_test.go | 28 ++ .../core/frontend/durable/provider.go | 5 + .../durable/provider_assignment_test.go | 162 +++++++++ .../core/frontend/durable/provider_chunk.go | 63 +++- .../durable/provider_chunk_holder_test.go | 9 +- .../durable/provider_restore_schedule_test.go | 125 +++++++ .../durable/provider_seed_linux_test.go | 228 +++++++++++++ .../durable/provider_seed_order_test.go | 141 ++++++++ .../durable/provider_zero_bootstrap_test.go | 97 ++++++ .../core/frontend/durable/storage_adapter.go | 5 + .../core/frontend/nvme/group_sync_test.go | 245 +++++++++++++ .../host/master/workspace_restore_test.go | 182 ++++++++++ seaweed-block/core/storage/chunk_frontier.go | 46 +++ .../core/storage/chunk_frontier_test.go | 46 +++ seaweed-block/core/storage/chunk_layer.go | 38 ++- seaweed-block/core/storage/chunk_restore.go | 78 +++++ .../core/storage/chunk_restore_test.go | 191 +++++++++++ seaweed-block/core/storage/chunk_seam.go | 16 +- seaweed-block/core/storage/wal_writer.go | 9 +- seaweed-block/core/storage/walstore.go | 70 +++- .../storage/walstore_sync_generation_test.go | 321 ++++++++++++++++++ 23 files changed, 2112 insertions(+), 20 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/restore_lsn_test.go create mode 100644 seaweed-block/core/frontend/durable/provider_assignment_test.go create mode 100644 seaweed-block/core/frontend/durable/provider_restore_schedule_test.go create mode 100644 seaweed-block/core/frontend/durable/provider_seed_linux_test.go create mode 100644 seaweed-block/core/frontend/durable/provider_seed_order_test.go create mode 100644 seaweed-block/core/frontend/durable/provider_zero_bootstrap_test.go create mode 100644 seaweed-block/core/frontend/nvme/group_sync_test.go create mode 100644 seaweed-block/core/host/master/workspace_restore_test.go create mode 100644 seaweed-block/core/storage/chunk_frontier.go create mode 100644 seaweed-block/core/storage/chunk_frontier_test.go create mode 100644 seaweed-block/core/storage/chunk_restore.go create mode 100644 seaweed-block/core/storage/chunk_restore_test.go create mode 100644 seaweed-block/core/storage/walstore_sync_generation_test.go diff --git a/seaweed-block/core/frontend/chunkstore/catalog_test.go b/seaweed-block/core/frontend/chunkstore/catalog_test.go index 0a6e1adcfd..0079a6ebae 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_test.go @@ -411,8 +411,21 @@ func TestFork_ThenFreshHostReadsSnapshotImage(t *testing.T) { t.Fatal(err) } r, _ := NewChunkRemote(f, b, path.Join(catBase, vol)) - l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: chunkBlocks, Epoch: epoch, Holder: vol, FreshFromHead: fresh, - Bitmap: storage.NewFileChunkBitmapStore(p + ".chunkbitmap")}) + cfg := storage.ChunkLayerConfig{ChunkBlocks: chunkBlocks, Epoch: epoch, Holder: vol, FreshFromHead: fresh, + Bitmap: storage.NewFileChunkBitmapStore(p + ".chunkbitmap")} + if fresh { + // This low-level fixture bypasses the provider: perform the same + // takeover and durable frontier seed before attaching its layer. + head, err := storage.ClaimChunkHead(ctx, r, cfg) + if err != nil { + t.Fatal(err) + } + if err := s.SeedChunkFrontier(head.RemoteLSN); err != nil { + t.Fatal(err) + } + cfg.RestoreGuard = &storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch} + } + l, err := storage.AttachChunkLayer(s, r, cfg) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index a4e6b66f40..cdea709acf 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -377,6 +377,16 @@ func (r *ChunkRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVer if expected.Gen == 0 && expected.Epoch != 0 { return 0, storage.ErrChunkHeadPrecondition // the absent HEAD has epoch 0 } + // Read the LSN under the same generation/epoch guard used by UpdateEntry. + // A competing write after this read makes the conditional update fail; + // no successful CAS can lower the committed lineage frontier. + current, err := r.GetHead(ctx) + if err != nil { + return 0, err + } + if current.Gen != expected.Gen || current.Epoch != expected.Epoch || next.RemoteLSN < current.RemoteLSN { + return 0, storage.ErrChunkHeadPrecondition + } next.Gen = expected.Gen + 1 e, err := headEntry(next) if err != nil { diff --git a/seaweed-block/core/frontend/chunkstore/restore_lsn_test.go b/seaweed-block/core/frontend/chunkstore/restore_lsn_test.go new file mode 100644 index 0000000000..16946ad401 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/restore_lsn_test.go @@ -0,0 +1,28 @@ +package chunkstore + +import ( + "context" + "reflect" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestHEADRefusesLSNRegressionAcrossMove(t *testing.T) { + ctx := context.Background() + r := newTestRemote(t, newFakeFiler(), newFakeBlobs()) + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, head(1, "old", 42, nil)); err != nil { + t.Fatal(err) + } + before, _ := r.GetHead(ctx) + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, head(2, "new", 41, nil)); !isPrecondition(err) { + t.Fatalf("regressing takeover accepted: %v", err) + } + after, _ := r.GetHead(ctx) + if !reflect.DeepEqual(before, after) { + t.Fatal("refused HEAD changed") + } + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, head(2, "new", 42, nil)); err != nil { + t.Fatal(err) + } +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 350bc56fae..996d40b0f1 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -92,6 +92,11 @@ type ProviderConfig struct { // report healthy for the requested volumeID. Zero → default 5s. OpenTimeout time.Duration + // ChunkAssignmentTimeout bounds deferred startup waiting for a healthy, + // nonzero master assignment and attach. Local recovery returns first so + // the host can apply its assignment. Zero defaults to 30s. + ChunkAssignmentTimeout time.Duration + // WALRetentionLSNs is the operator-tunable retention window past // the substrate's checkpoint LSN (G6 §1.A α). Zero = pre-G6 // strict checkpoint-driven recycle. Non-zero relaxes the recycle diff --git a/seaweed-block/core/frontend/durable/provider_assignment_test.go b/seaweed-block/core/frontend/durable/provider_assignment_test.go new file mode 100644 index 0000000000..2bf0853c4e --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_assignment_test.go @@ -0,0 +1,162 @@ +package durable_test + +import ( + "context" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type arrivingAssignment struct { + active atomic.Bool + seen chan struct{} + assigned chan struct{} + calls atomic.Uint64 +} + +func (v *arrivingAssignment) Projection() frontend.Projection { + zero := frontend.Projection{VolumeID: "v1", ReplicaID: "r1"} + if !v.active.Load() { + return zero + } + if v.calls.Add(1) == 1 { + close(v.seen) + return zero + } + select { + case <-v.assigned: + return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1, Healthy: true} + default: + return zero + } +} + +func TestRestoreWaitsForFirstAssignment(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})} + p := chunkProviderForAssignment(t, v) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + v.active.Store(true) + recoverCtx, finishRecovery := context.WithCancel(ctx) + defer finishRecovery() + done := make(chan error, 1) + go func() { _, err := p.RecoverVolume(recoverCtx, "v1"); done <- err }() + select { + case <-v.seen: + case <-ctx.Done(): + t.Fatal("recovery never inspected assignment") + } + select { + case err := <-done: + if err != nil { + t.Fatalf("first assignment did not converge: %v", err) + } + case <-ctx.Done(): + t.Fatal("local recovery must settle before assignment can be applied") + } + if statuses := p.DurableStatuses(); len(statuses) != 1 || statuses[0].Operational { + t.Fatalf("unassigned backend became operational: %+v", statuses) + } + finishRecovery() // deferred attachment outlives a completed recovery caller + close(v.assigned) + for { + statuses := p.DurableStatuses() + if len(statuses) == 1 && statuses[0].Operational { + break + } + select { + case <-ctx.Done(): + t.Fatalf("assignment never became operational: %+v", statuses) + case <-time.After(time.Millisecond): + } + } + if _, err := p.CaptureVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } +} + +func chunkProviderForAssignment(t *testing.T, v frontend.ProjectionView) *durable.DurableProvider { + t.Helper() + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, + BlockSize: 4096, ChunkBlocks: 4, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }, + }, v) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + return p +} + +func TestRestoreDeferredAssignmentWaitEndsOnDeadlineAndClose(t *testing.T) { + for _, mode := range []string{"limit", "close"} { + t.Run(mode, func(t *testing.T) { + v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})} + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, + ChunkAssignmentTimeout: 40 * time.Millisecond, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { + t.Error("remote reached without assignment") + return storage.NewMemChunkRemote(), nil + }, + }, v) + if err != nil { + t.Fatal(err) + } + defer p.Close() + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + v.active.Store(true) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done := make(chan error, 1) + go func() { _, err := p.RecoverVolume(ctx, "v1"); done <- err }() + select { + case <-v.seen: + case <-time.After(2 * time.Second): + t.Fatal("no assignment inspection") + } + // Local recovery must return first, so the host can apply assignment. + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(2 * time.Second): + t.Fatal("local recovery blocked on assignment") + } + cancel() // recovery caller no longer owns the deferred worker + if mode == "close" { + if err := p.Close(); err != nil { + t.Fatal(err) + } + } + if mode == "close" { + return + } + deadline := time.NewTimer(2 * time.Second) + defer deadline.Stop() + for { + status := p.DurableStatuses() + if len(status) == 1 && !status[0].Operational && strings.Contains(status[0].Evidence, "deadline exceeded") { + break + } + select { + case <-deadline.C: + t.Fatalf("assignment wait did not fail closed: %+v", status) + case <-time.After(time.Millisecond): + } + } + }) + } +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 8f93e4579f..a47dcf1250 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -72,7 +72,7 @@ type chunkLineage struct { // host blocks it until local recovery is done) the projection has epoch 0 // and is not healthy; a layer is never attached under that. func chunkAuthority(proj frontend.Projection, volumeID string) bool { - return proj.VolumeID == volumeID && proj.Healthy && proj.Epoch > 0 + return proj.VolumeID == volumeID && proj.Healthy && proj.Epoch > 0 && proj.ReplicaID != "" } // recoverChunk runs after a successful local Recover, generation gen. It @@ -113,6 +113,23 @@ func (p *DurableProvider) current(h *volHandle, gen uint64) bool { func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen uint64) { defer p.inflight.Done() + limit := p.cfg.ChunkAssignmentTimeout + if limit <= 0 { + limit = 30 * time.Second + } + waitCtx, endWait := context.WithTimeout(p.closeCtx, limit) + defer endWait() + defer func() { + if !errors.Is(waitCtx.Err(), context.DeadlineExceeded) { + return + } + // The old wait must not overwrite a newer recovery's readiness. + h.attachMu.Lock() + defer h.attachMu.Unlock() + if p.current(h, gen) && h.chunk == nil { + h.backend.SetOperational(false, "chunk assignment unavailable: "+waitCtx.Err().Error()) + } + }() defer func() { p.mu.Lock() if h.waitGen == gen { @@ -124,7 +141,7 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen defer t.Stop() for { select { - case <-p.closeCtx.Done(): + case <-waitCtx.Done(): return case <-t.C: } @@ -139,7 +156,7 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen h.attachMu.Unlock() return } - ctx, cancel := context.WithTimeout(p.closeCtx, chunkAttachTimeout) + ctx, cancel := context.WithTimeout(waitCtx, chunkAttachTimeout) err := p.attachChunk(ctx, volumeID, h) cancel() if err == nil { @@ -160,7 +177,7 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen } log.Printf("durable: chunk layer attach for volume=%s: %v (retrying)", volumeID, err) select { - case <-p.closeCtx.Done(): + case <-waitCtx.Done(): return case <-time.After(chunkAttachRetry): } @@ -188,6 +205,9 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v return errProviderClosed } h.chunk = layer + h.backend.mu.Lock() + h.backend.chunkFenced = layer.Fenced + h.backend.mu.Unlock() if p.cfg.ChunkCaptureInterval > 0 { ctx, cancel := context.WithCancel(context.Background()) h.chunkStop, h.chunkDone = cancel, make(chan struct{}) @@ -238,7 +258,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h remote := &closeBoundRemote{ChunkRemote: inner, done: p.closeCtx} remote.setAttach(ctx) // the attach's calls also end with the caller's ctx defer remote.setAttach(nil) - return storage.AttachChunkLayer(ws, remote, storage.ChunkLayerConfig{ + cfg := storage.ChunkLayerConfig{ ChunkBlocks: p.cfg.ChunkBlocks, Epoch: lin.epoch, Holder: holder, @@ -256,7 +276,34 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h } return nil }, - }) + } + if h.fresh { + // Attach preparation is gated. Seed the exact observed HEAD before + // its takeover CAS; only then finalize lazy attachment and expose I/O. + cfg.PrepareRestore = func(head storage.ChunkHead) error { + // No HEAD is a new lineage; preserve any pre-assignment local + // writes instead of replacing their frontier with zero. + if head.Gen == 0 { + return nil + } + // EnsureVolume's initial ZERO HEAD is not a remote data image. + // A local frontier already advanced before assignment belongs to + // this bootstrap: retain its extent bytes and unknown dirty set, + // rather than seeding backwards or installing lazy absence. + if head.RemoteLSN == 0 && len(head.Chunks) == 0 && head.State != storage.ChunkHeadDetached && head.DetachedBy == nil && ws.NextLSN() > 1 { + cfg.FreshFromHead = false + return nil + } + return ws.SeedChunkFrontier(head.RemoteLSN) + } + head, err := storage.ClaimChunkHead(ctx, remote, cfg) + if err != nil { + return nil, fmt.Errorf("durable: restore HEAD claim: %w", err) + } + cfg.RestoreGuard = &storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch} + } + + return storage.AttachChunkLayer(ws, remote, cfg) } // closeBoundRemote ends every remote call when the provider closes, so a @@ -481,7 +528,7 @@ func chunkFenced(volumeID string, h *volHandle) error { // CutVolume takes one quiesced cut of volumeID and returns what it // installed: the cut LSN, the HEAD (the current one when nothing changed) -// and the cut's statistics (B9 W2 §2.4, §3.1). With minLSN > 0 it is +// and the cut's statistics (B9 W2 §2.4, §3.1). With minLSN > 0 it is // MakeRemoteDurable(minLSN) returning the cut: an LSN never written is // refused before anything is published, and the cut must reach minLSN. func (p *DurableProvider) CutVolume(ctx context.Context, volumeID string, minLSN uint64) (storage.ChunkCutResult, error) { @@ -507,7 +554,7 @@ func (p *DurableProvider) CutVolume(ctx context.Context, volumeID string, minLSN return r, nil } -// DetachVolume is a clean stop's final cut (B9 W2 §3.6): it stops the +// DetachVolume is a clean stop's final cut (B9 W2 §3.6): it stops the // volume's frontend I/O and waits (bounded by ctx) for the I/O already // admitted to finish, stops the periodic cuts, then publishes one cut with // HEAD state detached. It also returns the last LSN written. From its diff --git a/seaweed-block/core/frontend/durable/provider_chunk_holder_test.go b/seaweed-block/core/frontend/durable/provider_chunk_holder_test.go index dad763f914..505410df36 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_holder_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_holder_test.go @@ -60,7 +60,12 @@ func TestWALStoreChunk_SameReplicaOnAnotherServerIsFenced(t *testing.T) { if _, err := be.Write(ctx, 4096, block(2)); !errors.Is(err, frontend.ErrNotReady) { t.Fatalf("a write on the fenced second server: %v; want ErrNotReady", err) } - if _, err := b.CaptureVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerFenced) { - t.Fatalf("a cut on the fenced second server: %v; want fenced", err) + // The canonical refusal is at Claim, before any layer is installed. + // Later cuts must still refuse; they need not repeat a layer's fence. + if _, err := b.CaptureVolume(ctx, "v1"); err == nil { + t.Fatal("a cut succeeded after refused recovery") + } + if after, _ := remote.GetHead(ctx); after.Gen != head.Gen || after.Holder != head.Holder { + t.Fatalf("refused cut changed HEAD: %+v", after) } } diff --git a/seaweed-block/core/frontend/durable/provider_restore_schedule_test.go b/seaweed-block/core/frontend/durable/provider_restore_schedule_test.go new file mode 100644 index 0000000000..a316013e3b --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_restore_schedule_test.go @@ -0,0 +1,125 @@ +package durable_test + +import ( + "bytes" + "context" + "crypto/sha256" + "errors" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func awaitRestoreCondition(t *testing.T, ctx context.Context, what string, ready func() bool) { + t.Helper() + for !ready() { + select { + case <-ctx.Done(): + t.Fatalf("%s: %v", what, ctx.Err()) + case <-time.After(time.Millisecond): + } + } +} + +func TestRestoreCheckpointBeforeAssignmentPreservesRemoteBytes(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) + p := chunkProvider(t, t.TempDir(), remote, view, 0) + s := openRecovered(t, p) + ws := s.(*storage.WALStore) + want := block(0xD7) + lsn, err := s.Write(33, want) + if err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + // FlushCount increments after checkpoint persistence AND dirty-map removal. + // The authority stays absent until that actual cycle has fully completed. + awaitRestoreCondition(t, ctx, "checkpoint before attach", func() bool { + return ws.CheckpointLSN() >= lsn && ws.FlushCount() > 0 + }) + if h, _ := remote.GetHead(ctx); h.Gen != 0 { + t.Fatal("unexpected HEAD before assignment", h) + } + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1})) + awaitRestoreCondition(t, ctx, "deferred attachment", func() bool { + st := p.DurableStatuses() + return len(st) == 1 && st[0].Operational + }) + if h, err := p.CaptureVolume(ctx, "v1"); err != nil || h != lsn { + t.Fatal("cut", h, err) + } + fresh := chunkProvider(t, t.TempDir(), remote, v1View(), 0) + got, err := openRecovered(t, fresh).Read(33) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("remote restore lost checkpointed bytes: got=%x err=%v", sha256.Sum256(got), err) + } +} + +type publishAfterAbsentRead struct { + storage.ChunkRemote + once sync.Once + beforeReturn func() +} + +func (r *publishAfterAbsentRead) GetHead(ctx context.Context) (storage.ChunkHead, error) { + h, err := r.ChunkRemote.GetHead(ctx) + if err == nil { + r.once.Do(r.beforeReturn) + } + return h, err +} + +func TestRestoreHEADAppearsBetweenClaimAndAttach(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + data := bytes.Repeat([]byte{0xA7}, pcChunkBlocks*4096) + wrapped := &publishAfterAbsentRead{ChunkRemote: remote, beforeReturn: func() { + if err := remote.Put(ctx, "old-cut", data); err != nil { + t.Fatal(err) + } + if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "old", RemoteLSN: 7, + Chunks: map[uint64]storage.ChunkRef{0: {Key: "old-cut", SHA256: sha256.Sum256(data)}}}); err != nil { + t.Fatal(err) + } + }} + p := chunkProvider(t, t.TempDir(), wrapped, v1View(), 0) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + _, err = p.RecoverVolume(ctx, "v1") + if err != nil { + backend, openErr := p.Open(ctx, "v1") + if openErr != nil { + t.Fatal(openErr) + } + if _, readErr := backend.Read(ctx, 0, make([]byte, 4096)); !errors.Is(readErr, frontend.ErrNotReady) { + t.Fatal("failed attach admitted I/O", readErr) + } + if _, err = p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal("retry must claim and seed", err) + } + } + h, err := remote.GetHead(ctx) + if err != nil || h.Epoch != 3 || h.Holder != "r1" { + t.Fatalf("ready without ownership: HEAD=%+v err=%v", h, err) + } + if r, _, h := s.(*storage.WALStore).Boundaries(); r != 7 || h != 7 { + t.Fatalf("ready without seed: R=%d H=%d", r, h) + } + if got, err := s.Read(0); err != nil || !bytes.Equal(got, data[:4096]) { + t.Fatal("exact lazy restore changed", err) + } + if cut, err := p.CaptureVolume(ctx, "v1"); err != nil || cut != 7 { + t.Fatal("capture after settled restore", cut, err) + } +} diff --git a/seaweed-block/core/frontend/durable/provider_seed_linux_test.go b/seaweed-block/core/frontend/durable/provider_seed_linux_test.go new file mode 100644 index 0000000000..fc074b7654 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_seed_linux_test.go @@ -0,0 +1,228 @@ +//go:build linux + +package durable_test + +import ( + "bytes" + "context" + "crypto/sha256" + "errors" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "syscall" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type seedSyncFaultRemote struct { + storage.ChunkRemote + once sync.Once + beforeSeed func() +} + +func (r *seedSyncFaultRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { + head, err := r.ChunkRemote.GetHead(ctx) + if err == nil { + r.once.Do(r.beforeSeed) + } + return head, err +} + +// Replace only this fixture's WAL descriptor after Recover has read it and +// before the seed's real os.File.Sync. /dev/full fsync returns EINVAL. Restore +// the original open-file description before retry; no production fault seam. +func failSeedFD(t *testing.T, root string) func() { + t.Helper() + entries, err := os.ReadDir("/proc/self/fd") + if err != nil { + t.Fatal(err) + } + fd := -1 + for _, e := range entries { + name, err := os.Readlink("/proc/self/fd/" + e.Name()) + if err == nil && strings.HasPrefix(name, root+string(os.PathSeparator)) { + if fd != -1 { + t.Fatal("more than one fixture WAL descriptor") + } + fd, err = strconv.Atoi(e.Name()) + if err != nil { + t.Fatal(err) + } + } + } + if fd < 0 { + t.Fatal("fixture WAL descriptor not found") + } + backup, err := syscall.Dup(fd) + if err != nil { + t.Fatal(err) + } + full, err := os.OpenFile("/dev/full", os.O_RDWR, 0) + if err != nil { + syscall.Close(backup) + t.Fatal(err) + } + defer full.Close() + if err := syscall.Dup2(int(full.Fd()), fd); err != nil { + syscall.Close(backup) + t.Fatal(err) + } + var once sync.Once + restore := func() { + once.Do(func() { + if err := syscall.Dup2(backup, fd); err != nil { + t.Error(err) + } + _ = syscall.Close(backup) + }) + } + t.Cleanup(restore) + return restore +} + +func TestRestoreFailedSeedSyncRetryCaptureAndReopen(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + root := filepath.Join(t.TempDir(), "provider") + remote := storage.NewMemChunkRemote() + data := bytes.Repeat([]byte{0xA7}, 4*4096) + if err := remote.Put(ctx, "seed", data); err != nil { + t.Fatal(err) + } + if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 3, Holder: "r1", RemoteLSN: 7, + Chunks: map[uint64]storage.ChunkRef{0: {Key: "seed", SHA256: sha256.Sum256(data)}}}); err != nil { + t.Fatal(err) + } + var restore func() + fault := &seedSyncFaultRemote{ChunkRemote: remote, beforeSeed: func() { restore = failSeedFD(t, root) }} + makeProvider := func(r storage.ChunkRemote) *durable.DurableProvider { + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, + NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, WALRecoveryTestDisableFlusher: true, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }}, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + return p + } + p := makeProvider(fault) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + ws := s.(*storage.WALStore) + if _, err := p.RecoverVolume(ctx, "v1"); err == nil { + t.Fatal("real seed fsync failure was accepted") + } else if !errors.Is(err, syscall.EINVAL) { + t.Fatalf("expected real fsync EINVAL, got %v", err) + } else { + t.Logf("injected real WAL fsync failure: %v", err) + } + if restore == nil { + t.Fatal("fault not exercised") + } + restore() + blocked, err := p.Open(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if _, err := blocked.Read(ctx, 0, make([]byte, 4096)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("failed recovery exposed backend: %v", err) + } + if got := ws.NextLSN(); got != 1 { + t.Errorf("failed seed published allocator watermark %d, want 1", got) + } + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal("same-handle retry:", err) + } + if r, _, h := ws.Boundaries(); r != 7 || h != 7 { + t.Errorf("retry did not durably seed HEAD: R=%d H=%d", r, h) + } + if cut, err := p.CaptureVolume(ctx, "v1"); err != nil || cut != 7 { + t.Errorf("retry cut=%d err=%v, want 7", cut, err) + } + if err := p.Close(); err != nil { + t.Fatal(err) + } + p2 := makeProvider(remote) + s2, err := p2.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if _, err := p2.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if next := s2.(*storage.WALStore).NextLSN(); next != 8 { + t.Errorf("reopen nextLSN=%d, want 8", next) + } + b, err := p2.Open(ctx, "v1") + if err != nil { + t.Fatal(err) + } + got := make([]byte, 4096) + if _, err := b.Read(ctx, 0, got); err != nil || !bytes.Equal(got, data[:4096]) { + t.Fatal("restored bytes changed:", err) + } + if _, err := b.Write(ctx, 4096, bytes.Repeat([]byte{0xB8}, 4096)); err != nil { + t.Fatal(err) + } + if err := b.Sync(ctx); err != nil { + t.Fatal(err) + } + if cut, err := p2.CaptureVolume(ctx, "v1"); err != nil || cut != 8 { + t.Fatalf("new cut=%d err=%v, want 8", cut, err) + } +} + +func TestRestoreFailedSeedNeverTakesOwnership(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + root := filepath.Join(t.TempDir(), "provider") + remote := storage.NewMemChunkRemote() + if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "old", RemoteLSN: 7}); err != nil { + t.Fatal(err) + } + calls := 0 + watched := &takeoverOrderRemote{ChunkRemote: remote, beforeCAS: func() { calls++ }} + var restore func() + fault := &seedSyncFaultRemote{ChunkRemote: watched, beforeSeed: func() { restore = failSeedFD(t, root) }} + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, WALRecoveryTestDisableFlusher: true, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return fault, nil }}, v1View()) + if err != nil { + t.Fatal(err) + } + defer p.Close() + if _, err = p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err = p.RecoverVolume(ctx, "v1"); !errors.Is(err, syscall.EINVAL) { + t.Fatalf("seed sync should fail with EINVAL: %v", err) + } + if restore == nil { + t.Fatal("real fsync fault not exercised") + } + restore() + h, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if calls != 0 || h.Gen != 1 || h.Epoch != 1 || h.Holder != "old" || h.RemoteLSN != 7 { + t.Fatalf("failed seed changed authority: CAS=%d HEAD=%+v; want untouched old HEAD", calls, h) + } + if _, err := p.Backend("v1").Read(ctx, 0, make([]byte, 4096)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatal("failed seed admitted I/O", err) + } + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal("same-store retry", err) + } + if calls != 1 { + t.Fatal("successful retry must take ownership exactly once", calls) + } +} diff --git a/seaweed-block/core/frontend/durable/provider_seed_order_test.go b/seaweed-block/core/frontend/durable/provider_seed_order_test.go new file mode 100644 index 0000000000..ce1c06c932 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_seed_order_test.go @@ -0,0 +1,141 @@ +package durable_test + +import ( + "bytes" + "context" + "errors" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type takeoverOrderRemote struct { + storage.ChunkRemote + beforeCAS func() +} + +func (r *takeoverOrderRemote) CASHead(ctx context.Context, v storage.ChunkHeadVersion, h storage.ChunkHead) (uint64, error) { + r.beforeCAS() + return r.ChunkRemote.CASHead(ctx, v, h) +} + +func TestRestoreSeedPrecedesTakeoverCAS(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "old", RemoteLSN: 7}); err != nil { + t.Fatal(err) + } + var p *durable.DurableProvider + var checked atomic.Bool + var calls atomic.Int32 + var nextAtCAS, durableAtCAS, headAtCAS uint64 + wrapped := &takeoverOrderRemote{ChunkRemote: remote, beforeCAS: func() { + calls.Add(1) + if !checked.Load() { + t.Error("takeover preceded VOLUME check") + } + s := p.LogicalStorage("v1") + nextAtCAS = s.NextLSN() + durableAtCAS, _, headAtCAS = s.Boundaries() + if _, err := p.Backend("v1").Read(ctx, 0, make([]byte, 4096)); !errors.Is(err, frontend.ErrNotReady) { + t.Errorf("I/O admitted before takeover: %v", err) + } + }} + var err error + p, err = durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return wrapped, nil }, + ChunkAttachCheck: func(context.Context, string, durable.ChunkGeometry) error { checked.Store(true); return nil }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + defer p.Close() + if _, err = p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err = p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if calls.Load() != 1 || nextAtCAS != 8 || durableAtCAS != 7 || headAtCAS != 7 { + t.Fatalf("takeover before durable seed: CAS calls=%d nextLSN=%d durable=%d head=%d; want 1/8/7/7", calls.Load(), nextAtCAS, durableAtCAS, headAtCAS) + } + be, err := p.Open(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if _, err := be.Read(ctx, 0, make([]byte, 4096)); err != nil { + t.Fatal("ready after seed and takeover", err) + } + h, err := remote.GetHead(ctx) + if err != nil || h.Epoch != 3 || h.Holder != "r1" || h.RemoteLSN != 7 { + t.Fatal(h, err) + } + t.Logf("VOLUME check -> seed nextLSN=%d/durable=%d -> takeover -> serve", nextAtCAS, durableAtCAS) +} + +// A restored restart under the same assignment must reactivate a detached +// image before exposing I/O, not treat it as an already-settled active claim. +func TestRestoreEqualOwnerDetachedHEADIsReactivated(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + makeProvider := func() *durable.DurableProvider { + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "node-a/r1", + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + return p + } + source := makeProvider() + openRecovered(t, source) + be, err := source.Open(ctx, "v1") + if err != nil { + t.Fatal(err) + } + want := block(0xA7) + if _, err = be.Write(ctx, 4096, want); err != nil { + t.Fatal(err) + } + if err = be.Sync(ctx); err != nil { + t.Fatal(err) + } + cut, _, err := source.DetachVolume(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if err = source.Close(); err != nil { + t.Fatal(err) + } + restarted := makeProvider() + if _, err = restarted.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err = restarted.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + h, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if h.Gen <= cut.Head.Gen || h.Epoch != cut.Head.Epoch || h.Holder != cut.Head.Holder || h.State != storage.ChunkHeadActive || h.DetachedBy != nil || h.RemoteLSN != cut.H { + t.Errorf("ready with stale detached proof: HEAD=%+v detached=%+v", h, cut.Head) + } + frontend, err := restarted.Open(ctx, "v1") + if err != nil { + t.Fatal(err) + } + got := make([]byte, 4096) + if _, err = frontend.Read(ctx, 4096, got); err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want) { + t.Fatal("restart changed exact data") + } +} diff --git a/seaweed-block/core/frontend/durable/provider_zero_bootstrap_test.go b/seaweed-block/core/frontend/durable/provider_zero_bootstrap_test.go new file mode 100644 index 0000000000..290b5e5536 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_zero_bootstrap_test.go @@ -0,0 +1,97 @@ +package durable_test + +import ( + "bytes" + "context" + "fmt" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" + "sync" + "testing" + "time" +) + +type bootstrapBlobs struct { + mu sync.Mutex + objects map[string][]byte +} + +func (b *bootstrapBlobs) Put(_ context.Context, data []byte) (string, error) { + b.mu.Lock() + defer b.mu.Unlock() + id := fmt.Sprintf("fid-%d", len(b.objects)+1) + b.objects[id] = bytes.Clone(data) + return id, nil +} +func (b *bootstrapBlobs) Get(_ context.Context, id string) ([]byte, error) { + b.mu.Lock() + defer b.mu.Unlock() + data, ok := b.objects[id] + if !ok { + return nil, fmt.Errorf("missing blob %s", id) + } + return bytes.Clone(data), nil +} + +func TestRestoreEnsureVolumeZeroHEADPreservesCheckpointedBootstrap(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) + defer cancel() + filer := chunkstore.NewMemFiler() + catalog, err := chunkstore.NewCatalog(filer, "/bootstrap") + if err != nil { + t.Fatal(err) + } + remote, err := chunkstore.NewChunkRemote(filer, &bootstrapBlobs{objects: map[string][]byte{}}, "/bootstrap/v1") + if err != nil { + t.Fatal(err) + } + view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) + makeProvider := func(view *stubView) *durable.DurableProvider { + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, ChunkHolder: "node-a/r1", + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + ChunkAttachCheck: func(ctx context.Context, vol string, g durable.ChunkGeometry) error { + _, err := catalog.EnsureVolume(ctx, vol, chunkstore.Geometry{NumBlocks: g.NumBlocks, BlockSize: g.BlockSize, ChunkBlocks: g.ChunkBlocks}) + return err + }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + return p + } + p := makeProvider(view) + s := openRecovered(t, p) + ws := s.(*storage.WALStore) + want := block(0xD7) + lsn, err := s.Write(33, want) + if err != nil { + t.Fatal(err) + } + if _, err = s.Sync(); err != nil { + t.Fatal(err) + } + awaitRestoreCondition(t, ctx, "checkpointed local bootstrap", func() bool { return ws.CheckpointLSN() >= lsn && ws.FlushCount() > 0 }) + // This production attach hook, rather than a manufactured fixture HEAD, + // creates the initial ZERO image after the write has left the dirty map. + _, err = catalog.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: pcBlocks, BlockSize: 4096, ChunkBlocks: pcChunkBlocks}) + if err != nil { + t.Fatal(err) + } + h, err := remote.GetHead(ctx) + if err != nil || h.Gen == 0 || h.RemoteLSN != 0 || len(h.Chunks) != 0 { + t.Fatalf("initial ZERO HEAD: %+v %v", h, err) + } + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1})) + awaitRestoreCondition(t, ctx, "ZERO HEAD bootstrap attachment", func() bool { st := p.DurableStatuses(); return len(st) == 1 && st[0].Operational }) + if got, err := p.CaptureVolume(ctx, "v1"); err != nil || got != lsn { + t.Fatalf("capture=%d want=%d err=%v", got, lsn, err) + } + fresh := makeProvider(v1View()) + got, err := openRecovered(t, fresh).Read(33) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("checkpointed local bytes lost on remote restore: exact=%v err=%v", bytes.Equal(got, want), err) + } +} diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 2d5b6bd58a..9a5d08e0d8 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -164,6 +164,7 @@ type StorageBackend struct { mu sync.Mutex closed bool + chunkFenced func() bool // installed under mu; called only after releasing mu observer WriteObserver // optional; nil = no replication fan-out writeAck WriteAckPolicy profile writeProfile @@ -527,10 +528,14 @@ func (b *StorageBackend) gate() error { func (b *StorageBackend) readyCheck() error { b.mu.Lock() closed := b.closed + chunkFenced := b.chunkFenced b.mu.Unlock() if closed { return frontend.ErrBackendClosed } + if chunkFenced != nil && chunkFenced() { + return frontend.ErrStalePrimary + } if !b.operational.Load() { ev, _ := b.opEvidence.Load().(string) return fmt.Errorf("%w: %s", frontend.ErrNotReady, ev) diff --git a/seaweed-block/core/frontend/nvme/group_sync_test.go b/seaweed-block/core/frontend/nvme/group_sync_test.go new file mode 100644 index 0000000000..ef6f6b85ff --- /dev/null +++ b/seaweed-block/core/frontend/nvme/group_sync_test.go @@ -0,0 +1,245 @@ +package nvme_test + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "sort" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "github.com/seaweedfs/seaweed-block/core/storage" + "strings" +) + +type syncPairView struct{ id frontend.Identity } + +func (v syncPairView) Projection() frontend.Projection { + return frontend.Projection{VolumeID: v.id.VolumeID, ReplicaID: v.id.ReplicaID, Epoch: v.id.Epoch, EndpointVersion: v.id.EndpointVersion, Healthy: true} +} + +type syncPairObserver struct { + s *storage.WALStore + calls atomic.Int32 + fail atomic.Bool +} + +func (o *syncPairObserver) Observe(context.Context, uint32, uint64, []byte) error { return nil } +func (o *syncPairObserver) Sync(_ context.Context, target uint64) error { + o.calls.Add(1) + if o.fail.Load() { + return errors.New("injected replica barrier failure") + } + n, err := o.s.Sync() + if err == nil && n < target { + return errors.New("local sync below required frontier") + } + return err +} + +func newSyncPairFixture(t *testing.T, path string) (*storage.WALStore, *durable.StorageBackend, *nvmeClient) { + t.Helper() + id := frontend.Identity{VolumeID: strings.TrimSuffix(filepath.Base(path), ".bin"), ReplicaID: "r1", Epoch: 1, EndpointVersion: 1} + provider, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStore, StorageRoot: filepath.Dir(path), NumBlocks: 32, BlockSize: 4096, + WALRecoveryTestDisableFlusher: true, + }, syncPairView{id}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = provider.Close() }) + rawBackend, err := provider.Open(context.Background(), id.VolumeID) + if err != nil { + t.Fatal(err) + } + if _, err := provider.RecoverVolume(context.Background(), id.VolumeID); err != nil { + t.Fatal(err) + } + s := provider.LogicalStorage(id.VolumeID).(*storage.WALStore) + backend := rawBackend.(*durable.StorageBackend) + tg := nvme.NewTarget(nvme.TargetConfig{Listen: "127.0.0.1:0", SubsysNQN: "nqn.2026-04.example.v3:subsys", VolumeID: id.VolumeID, Provider: provider}) + addr, err := tg.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = tg.Close() }) + c := dialAndConnect(t, addr) + t.Cleanup(c.close) + if err := c.io.SetDeadline(time.Now().Add(15 * time.Second)); err != nil { + t.Fatal(err) + } + return s, backend, c +} +func syncPairFlush(t *testing.T, c *nvmeClient, cid uint16) uint16 { + t.Helper() + cmd := nvme.CapsuleCommand{OpCode: 0, CID: cid, NSID: 1} + if err := c.ioW.SendHeaderOnly(0x4, &cmd, 64); err != nil { + t.Fatal(err) + } + resp := recvCapsuleResp(t, c.ioR) + if resp.CID != cid { + t.Fatalf("Flush CID=%d want %d", resp.CID, cid) + } + return resp.Status +} + +// Model the observed guest fsync's two Flush capsules, not a mounted guest. +func TestNVMePairedFlushSharesPhysicalWALSync(t *testing.T) { + s, backend, c := newSyncPairFixture(t, filepath.Join(t.TempDir(), "store.bin")) + observer := &syncPairObserver{s: s} + backend.SetWriteObserver(observer) + if status := c.writeCmd(t, 0, 8, make([]byte, 4096)); status != 0 { + t.Fatalf("Write status=%x", status) + } + for i := 0; i < 2; i++ { + if status := syncPairFlush(t, c, uint16(90+i)); status != 0 { + t.Fatalf("Flush %d status=%x", i, status) + } + } + if n := s.WALSyncCount(); n != 1 { + t.Fatalf("one write + two Flush capsules: physical WAL syncs=%d want 1", n) + } + if n := backend.WriteProfile().BackendSyncOps; n != 2 { + t.Fatalf("backend Sync calls=%d want 2 (retain gates)", n) + } + if n := observer.calls.Load(); n != 2 { + t.Fatalf("replication barriers=%d want 2", n) + } + observer.fail.Store(true) + if status := syncPairFlush(t, c, 92); status == 0 { + t.Fatal("cached local sync bypassed failed replica barrier") + } + if n := observer.calls.Load(); n != 3 { + t.Fatalf("replication barriers=%d want 3", n) + } + backend.SetOperational(false, "test readiness lost") + if err := backend.Sync(context.Background()); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("cached flush readiness error=%v", err) + } +} + +// The child ACKs real TCP Flush completions and never calls Close. The parent +// kills it, then opens/replays the file. This is process-crash, not power-loss, evidence. +func TestNVMePairedFlushCrashRecovery(t *testing.T) { + const childEnv = "SW_BLOCK_SYNC_CRASH_CHILD" + if path := os.Getenv(childEnv); path != "" { + _, _, c := newSyncPairFixture(t, path) + if status := c.writeCmd(t, 0, 8, bytes.Repeat([]byte{0x6d}, 4096)); status != 0 { + t.Fatalf("Write status=%x", status) + } + for i := 0; i < 2; i++ { + if status := syncPairFlush(t, c, uint16(100+i)); status != 0 { + t.Fatalf("Flush status=%x", status) + } + } + fmt.Println("FLUSH_ACKED_NO_CLOSE") + time.Sleep(time.Hour) + return + } + path := filepath.Join(t.TempDir(), "crashed.bin") + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestNVMePairedFlushCrashRecovery$") + cmd.Env = append(os.Environ(), childEnv+"="+path) + stdout, err := cmd.StdoutPipe() + if err != nil { + t.Fatal(err) + } + var stderr bytes.Buffer + cmd.Stderr = &stderr + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + defer func() { + if cmd.ProcessState == nil { + _ = cmd.Process.Kill() + _ = cmd.Wait() + } + }() + ack := make(chan bool, 1) + go func() { + scan := bufio.NewScanner(stdout) + for scan.Scan() { + if scan.Text() == "FLUSH_ACKED_NO_CLOSE" { + ack <- true + return + } + } + ack <- false + }() + select { + case ok := <-ack: + if !ok { + _ = cmd.Process.Kill() + _ = cmd.Wait() // join stderr copying before reading the buffer + t.Fatalf("child failed before ACK: %s", stderr.String()) + } + case <-ctx.Done(): + t.Fatal("child did not ACK within bound") + } + if err := cmd.Process.Kill(); err != nil { + t.Fatal(err) + } + if err := cmd.Wait(); err == nil { + t.Fatal("child exited normally instead of crash") + } + s, err := storage.OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + defer s.Close() + s.DisableAutoFlushForRecoveryTest() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + got, err := s.Read(0) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, bytes.Repeat([]byte{0x6d}, 4096)) { + t.Fatal("ACKed Flush data lost after process crash") + } +} + +// Opt-in serial tp04 proxy; neither a guest filesystem benchmark nor a gate. +func TestNVMePairedFlushLatency(t *testing.T) { + if os.Getenv("SW_BLOCK_SYNC_PERF") != "1" { + t.Skip("opt-in file-backed latency characterization") + } + s, backend, c := newSyncPairFixture(t, filepath.Join(t.TempDir(), "perf.bin")) + const samples = 100 + ns := make([]int64, 0, samples) + for i := 0; i < samples; i++ { + if status := c.writeCmd(t, 0, 8, bytes.Repeat([]byte{byte(i)}, 4096)); status != 0 { + t.Fatalf("Write status=%x", status) + } + start := time.Now() + for j := 0; j < 2; j++ { + if status := syncPairFlush(t, c, uint16(200+2*i+j)); status != 0 { + t.Fatalf("Flush status=%x", status) + } + } + ns = append(ns, time.Since(start).Nanoseconds()) + } + sort.Slice(ns, func(i, j int) bool { return ns[i] < ns[j] }) + var sum int64 + for _, n := range ns { + sum += n + } + report := map[string]any{"scope": "TCP paired-Flush proxy, no mounted guest", "samples": samples, "mean_ns": sum / samples, "p50_ns": ns[49], "p95_ns": ns[94], "p99_ns": ns[98], "physical_wal_syncs": s.WALSyncCount(), "backend_sync_calls": backend.WriteProfile().BackendSyncOps} + data, err := json.Marshal(report) + if err != nil { + t.Fatal(err) + } + fmt.Printf("SYNC_PERF %s\n", data) +} diff --git a/seaweed-block/core/host/master/workspace_restore_test.go b/seaweed-block/core/host/master/workspace_restore_test.go new file mode 100644 index 0000000000..ac7ddbd188 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_restore_test.go @@ -0,0 +1,182 @@ +package master + +import ( + "bytes" + "context" + "reflect" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type restoreProjection struct{ projection frontend.Projection } + +func (v restoreProjection) Projection() frontend.Projection { return v.projection } + +type restoreRemote struct { + storage.ChunkRemote + gets atomic.Uint64 +} + +func (r *restoreRemote) Get(ctx context.Context, key string) ([]byte, error) { + r.gets.Add(1) + return r.ChunkRemote.Get(ctx, key) +} + +// This CPU component loop uses a real master authority runtime, two real +// temporary-file providers and the existing in-memory ChunkRemote boundary. +// Keep the old projection stale to model delayed assignment delivery; a HEAD +// takeover must independently refuse its cut and then stop its frontend I/O. +func TestWorkspaceMoveRestoresLazilyAndFencesOldHost(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + m := newTestMaster(t, t.TempDir()) + defer closeTestMaster(t, m) + seedVerifiedExistingReplicaPlacement(t, m) + if _, err := m.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + oldLine := waitAuthorityLine(t, m.Publisher(), "vol-a") + remote := &restoreRemote{ChunkRemote: storage.NewMemChunkRemote()} + open := func(line authority.AuthorityBasis) (*durable.DurableProvider, frontend.Backend) { + t.Helper() + view := restoreProjection{frontend.Projection{VolumeID: "vol-a", ReplicaID: line.ReplicaID, + Epoch: line.Epoch, EndpointVersion: line.EndpointVersion, Healthy: true}} + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, + BlockSize: 4096, ChunkBlocks: 4, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + if _, err := p.EnsureStorage("vol-a"); err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(ctx, "vol-a"); err != nil { + t.Fatal(err) + } + backend, err := p.Open(ctx, "vol-a") + if err != nil { + t.Fatal(err) + } + return p, backend + } + oldProvider, oldBackend := open(oldLine) + want := map[int64][]byte{0: bytes.Repeat([]byte{0xA1}, 4096), 8 * 4096: bytes.Repeat([]byte{0xB2}, 4096)} + for offset, data := range want { + if n, err := oldBackend.Write(ctx, offset, data); err != nil || n != len(data) { + t.Fatal(n, err) + } + } + if err := oldBackend.Sync(ctx); err != nil { + t.Fatal(err) + } + cut, err := oldProvider.CaptureVolume(ctx, "vol-a") + if err != nil { + t.Fatal(err) + } + headBefore, err := remote.GetHead(ctx) + if err != nil || headBefore.RemoteLSN != cut || len(headBefore.Chunks) != 2 { + t.Fatalf("initial HEAD=%+v err=%v", headBefore, err) + } + + // The authority runtime, not either provider, allocates the next epoch. + // Admission evidence is supplied by this fixture, as in the runtime's + // existing tests; this is not a VM-stop or physical fencing qualification. + if _, err := m.FailbackAuthorityRuntime().ExecuteFailback(ctx, authority.FailbackRuntimeRequest{ + VolumeID: "vol-a", ReplicaID: "r1", TargetDataAddr: "127.0.0.1:9201", TargetCtrlAddr: "127.0.0.1:9101", + ExpectedCurrentReplicaID: oldLine.ReplicaID, ExpectedCurrentEpoch: oldLine.Epoch, + AckEligible: true, FrontendFencedBeforeFailback: true, + DurableFrontierCovered: true, NoCrossVolumeIdentityChange: true, + }); err != nil { + t.Fatal(err) + } + newLine, ok := m.Publisher().VolumeAuthorityLine("vol-a") + if !ok || newLine.ReplicaID != "r1" || newLine.Epoch <= oldLine.Epoch { + t.Fatalf("master did not move authority: %+v", newLine) + } + gets := remote.gets.Load() + freshProvider, freshBackend := open(newLine) // unrelated empty local directory + if remote.gets.Load() != gets { + t.Error("restore eagerly fetched chunk bodies before any read") + } + claimed, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if claimed.Epoch != newLine.Epoch || claimed.Holder != newLine.ReplicaID || claimed.RemoteLSN != cut { + t.Errorf("restore served before HEAD takeover: HEAD epoch=%d holder=%q cut=%d; want master epoch=%d holder=%q cut=%d", + claimed.Epoch, claimed.Holder, claimed.RemoteLSN, newLine.Epoch, newLine.ReplicaID, cut) + } + for offset, data := range want { + got := make([]byte, len(data)) + if n, err := freshBackend.Read(ctx, offset, got); err != nil || n != len(got) || !bytes.Equal(got, data) { + t.Fatalf("fresh exact read offset=%d n=%d err=%v", offset, n, err) + } + } + if remote.gets.Load() <= gets { + t.Error("fresh reads did not lazily fetch HEAD chunks") + } + // With assignment delivery held, the stale host can still have local dirt. + if n, err := oldBackend.Write(ctx, 0, bytes.Repeat([]byte{0xCC}, 4096)); err != nil || n != 4096 { + t.Fatal(n, err) + } + if _, err := oldProvider.CaptureVolume(ctx, "vol-a"); err == nil { + t.Error("old host cut succeeded after new host restored") + } + if n, err := oldBackend.Read(ctx, 0, make([]byte, 4096)); err == nil || n != 0 { + t.Errorf("old host kept serving after its refused cut: n=%d err=%v", n, err) + } + if n, err := oldBackend.Write(ctx, 0, make([]byte, 4096)); err == nil || n != 0 { + t.Errorf("old host kept accepting writes after its refused cut: n=%d err=%v", n, err) + } + if err := oldBackend.Sync(ctx); err == nil { + t.Error("old host kept acknowledging Sync after its refused cut") + } + afterStale, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(afterStale, claimed) { + t.Errorf("stale host changed claimed HEAD: %+v", afterStale) + } + // A new local WAL must continue after HEAD, not restart its LSN at 1. + want[4*4096] = bytes.Repeat([]byte{0xD4}, 4096) + if n, err := freshBackend.Write(ctx, 4*4096, want[4*4096]); err != nil || n != 4096 { + t.Fatal(n, err) + } + if err := freshBackend.Sync(ctx); err != nil { + t.Fatal(err) + } + newCut, err := freshProvider.CaptureVolume(ctx, "vol-a") + if err != nil { + t.Fatal(err) + } + if newCut <= cut { + t.Errorf("restored WAL did not advance beyond HEAD: old=%d new=%d", cut, newCut) + } + newHead, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + final, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if final.Epoch != newLine.Epoch || final.Holder != newLine.ReplicaID || final.RemoteLSN != newCut || final.Gen != newHead.Gen || !reflect.DeepEqual(final.Chunks, newHead.Chunks) { + t.Errorf("old host changed restored HEAD: %+v", final) + } + for offset, data := range want { + got := make([]byte, len(data)) + if n, err := freshBackend.Read(ctx, offset, got); err != nil || n != len(got) || !bytes.Equal(got, data) { + t.Fatalf("new host bytes changed after stale cut: offset=%d n=%d err=%v", offset, n, err) + } + } +} diff --git a/seaweed-block/core/storage/chunk_frontier.go b/seaweed-block/core/storage/chunk_frontier.go new file mode 100644 index 0000000000..e937254118 --- /dev/null +++ b/seaweed-block/core/storage/chunk_frontier.go @@ -0,0 +1,46 @@ +package storage + +import ( + "errors" + "fmt" +) + +// SeedChunkFrontier installs an empty fresh host's inherited remote frontier. +// Unlike AdvanceFrontier + Sync, it publishes no allocator/head watermark until +// both the data sync and checkpoint-metadata sync have succeeded. Call before +// attaching the chunk layer or admitting writes. Repeating after failure is safe. +// Order: captureMu -> lifecycleMu -> mu; no remote call or layer callback. +func (s *WALStore) SeedChunkFrontier(lsn uint64) error { + s.captureMu.Lock() + defer s.captureMu.Unlock() + s.lifecycleMu.RLock() + defer s.lifecycleMu.RUnlock() + s.mu.Lock() + defer s.mu.Unlock() + if s.closed || s.chunk.Load() != nil { + return errors.New("storage: seed frontier requires an open, unattached store") + } + if lsn == ^uint64(0) || lsn < s.checkpointLSN || s.walHead > s.checkpointLSN || s.nextLSN > lsn+1 { + return errors.New("storage: seed frontier cannot replace local writes or wrap LSN") + } + if s.checkpointLSN == lsn && s.syncedLSN >= lsn && s.nextLSN == lsn+1 { + return nil + } + if err := s.syncCache(); err != nil { + return fmt.Errorf("storage: seed data sync: %w", err) + } + next := *s.sb + next.WALCheckpointLSN = lsn + next.WALHead = s.wal.logicalHeadValue() + buf := newSimpleByteBuf() + if _, err := next.writeTo(buf); err != nil { + return err + } + if err := s.syncDirectFrontierMetadata(buf.bytes()); err != nil { + return fmt.Errorf("storage: seed metadata sync: %w", err) + } + *s.sb = next + s.checkpointLSN, s.syncedLSN, s.walHead, s.nextLSN = lsn, lsn, lsn, lsn+1 + s.pendingDirectFrontierLSN = 0 + return nil +} diff --git a/seaweed-block/core/storage/chunk_frontier_test.go b/seaweed-block/core/storage/chunk_frontier_test.go new file mode 100644 index 0000000000..72555d4de7 --- /dev/null +++ b/seaweed-block/core/storage/chunk_frontier_test.go @@ -0,0 +1,46 @@ +package storage + +import ( + "errors" + "testing" +) + +func TestSeedChunkFrontierMetadataFailureRetry(t *testing.T) { + s, path := newChunkTestStore(t) + s.DisableAutoFlushForRecoveryTest() + syncMetadata := s.syncDirectFrontierMetadata + s.syncDirectFrontierMetadata = func([]byte) error { return errors.New("injected metadata fsync failure") } + if err := s.SeedChunkFrontier(7); err == nil { + t.Fatal("failed metadata sync accepted") + } + if next := s.NextLSN(); next != 1 { + t.Fatalf("failed seed advanced NextLSN to %d", next) + } + if r, _, h := s.Boundaries(); r != 0 || h != 0 { + t.Fatal("failed seed published frontier", r, h) + } + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + s.syncDirectFrontierMetadata = syncMetadata + if err := s.SeedChunkFrontier(7); err != nil { + t.Fatal(err) + } + if s.NextLSN() != 8 { + t.Fatal("retry not seeded") + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + reopened, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + defer reopened.Close() + if _, err := reopened.Recover(); err != nil { + t.Fatal(err) + } + if reopened.NextLSN() != 8 { + t.Fatal("durable seed missing after reopen") + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 8cc0dd2356..e8592269bf 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -132,6 +132,10 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) l.cancel() return nil, fmt.Errorf("storage: chunk layer attach: read HEAD: %w", err) } + if cfg.RestoreGuard != nil && (head.Gen != cfg.RestoreGuard.Gen || head.Epoch != cfg.RestoreGuard.Epoch) { + l.cancel() + return nil, fmt.Errorf("%w: HEAD changed after restore claim/seed", errChunkHeadPrecondition) + } l.head = copyHead(head) l.remoteLSN = head.RemoteLSN // A HEAD that already belongs to a newer epoch or a competing holder is @@ -172,6 +176,24 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) } if cfg.FreshFromHead { + // An existing HEAD defines the fresh host's lazy image. With no HEAD, + // local writes may already have checkpointed out of the WAL dirty map: + // preserve ALL chunks as candidates for the first hash-comparing cut. + // Persist that obligation before publishing hooks/readiness. + l.hdr = chunkBitmapHeader{BaseLSN: head.RemoteLSN, HeadGen: head.Gen, Epoch: cfg.Epoch} + var initialDirty []uint64 + l.dirty = map[uint64]bool{} + l.hashMode = head.Gen == 0 && s.NextLSN() > 1 + if l.hashMode { + for idx := uint64(0); idx < l.numChunks; idx++ { + l.dirty[idx] = true + initialDirty = append(initialDirty, idx) + } + } + if err := cfg.Bitmap.Reset(l.hdr, initialDirty, chunkDelta{}); err != nil { + l.cancel() + return nil, fmt.Errorf("storage: fresh bitmap reset: %w", err) + } for idx := range head.Chunks { l.absent[idx] = true l.absentGen[idx]++ @@ -253,7 +275,7 @@ func (l *chunkLayerImpl) BeforeCheckpointAdvance(lsn uint64) error { return l.persistPresence() } -// saveDirty persists dirty ∪ inflight ∪ the chunks of WAL entries still in +// saveDirty persists dirty ∪ inflight ∪ the chunks of WAL entries still in // the dirty map (all chunks when a BASE block landed or the set is unknown). func (l *chunkLayerImpl) saveDirty() error { l.bmMu.Lock() @@ -666,6 +688,20 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (chunkC changed = append(changed, c.idx) } if !detach && len(changed) == 0 && h == baseHead.RemoteLSN && baseHead.Gen != 0 && !chunkHeadIsDetached(baseHead) { + // A no-op cut still observes authority: a fresh host may have + // claimed HEAD without uploading a single chunk since our last cut. + cur, err := l.remote.GetHead(ctx) + if err != nil { + l.abortCut(all) + return chunkCutResult{}, fmt.Errorf("storage: no-op cut authority read: %w: %w", errChunkRemoteUnavailable, err) + } + if cur.Gen != baseHead.Gen || !sameProposal(cur, baseHead) { + l.abortCut(all) + l.stMu.Lock() + l.fenced, l.head = true, copyHead(cur) + l.stMu.Unlock() + return chunkCutResult{}, errChunkLayerFenced + } l.finishCut(baseHead, h, nil, nil) // nothing new: no CAS return chunkCutResult{H: h, Head: copyHead(baseHead), Noop: true, FullHash: all}, nil } diff --git a/seaweed-block/core/storage/chunk_restore.go b/seaweed-block/core/storage/chunk_restore.go new file mode 100644 index 0000000000..c95f8a9d1f --- /dev/null +++ b/seaweed-block/core/storage/chunk_restore.go @@ -0,0 +1,78 @@ +package storage + +import ( + "context" + "errors" + "fmt" +) + +// ClaimChunkHead transfers only HEAD ownership, never chunk bodies. Epoch is +// supplied by the master's projection, not allocated here. The caller must +// persist lazy-read absence before exposing the local volume for I/O. +// No WALStore, layer-state or provider-map lock is held across remote calls; +// the provider may hold its per-volume attach serialization lock. +func ClaimChunkHead(ctx context.Context, remote ChunkRemote, cfg ChunkLayerConfig) (ChunkHead, error) { + if remote == nil || cfg.Epoch == 0 || cfg.Holder == "" { + return ChunkHead{}, errors.New("storage: HEAD claim needs master epoch and holder") + } + allowed := func() error { + if err := ctx.Err(); err != nil { + return err + } + if cfg.CaptureAllowed != nil { + return cfg.CaptureAllowed() + } + return nil + } + if err := allowed(); err != nil { + return ChunkHead{}, err + } + head, err := remote.GetHead(ctx) + if err != nil { + return ChunkHead{}, err + } + if head.Epoch > cfg.Epoch || (head.Gen != 0 && head.Epoch == cfg.Epoch && head.Holder != cfg.Holder) { + return ChunkHead{}, ErrChunkLayerFenced + } + // Preparation uses exactly the validated image this CAS will protect. + // A failing seed cannot fence the old holder before this host is ready. + if cfg.PrepareRestore != nil { + if err := cfg.PrepareRestore(copyHead(head)); err != nil { + return ChunkHead{}, fmt.Errorf("storage: prepare HEAD restore: %w", err) + } + } + if err := allowed(); err != nil { + return ChunkHead{}, err + } + // No HEAD is a new volume, not a restore: there is no old holder to + // fence. The first content cut keeps exclusive-create semantics. + if head.Gen == 0 { + return head, nil + } + if head.Gen != 0 && head.Epoch == cfg.Epoch && head.Holder == cfg.Holder && !chunkHeadIsDetached(head) && head.DetachedBy == nil { + return head, allowed() // idempotent restart or settled prior claim + } + next := copyHead(head) + next.Epoch, next.Holder = cfg.Epoch, cfg.Holder + // A new holder's takeover starts serving the same image as active. The + // previous holder's final-cut proof belongs only to its detached HEAD. + next.State, next.DetachedBy = chunkHeadActive, nil + if err := allowed(); err != nil { + return ChunkHead{}, err + } + gen, casErr := remote.CASHead(ctx, ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}, next) + if casErr == nil { + next.Gen = gen + return next, allowed() + } + // Never blindly replay a possibly committed takeover. A re-read must + // prove the exact proposal; otherwise the volume remains nonoperational. + current, readErr := remote.GetHead(ctx) + if readErr != nil { + return ChunkHead{}, fmt.Errorf("storage: HEAD claim unresolved: %w", errors.Join(casErr, readErr)) + } + if current.Gen > head.Gen && sameProposal(current, next) { + return current, allowed() + } + return ChunkHead{}, fmt.Errorf("storage: HEAD claim not installed: %w", casErr) +} diff --git a/seaweed-block/core/storage/chunk_restore_test.go b/seaweed-block/core/storage/chunk_restore_test.go new file mode 100644 index 0000000000..115f4e5818 --- /dev/null +++ b/seaweed-block/core/storage/chunk_restore_test.go @@ -0,0 +1,191 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "testing" +) + +func TestClaimChunkHeadClearsProductionDetachProof(t *testing.T) { + s, path := newChunkTestStore(t) + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + remote := NewMemChunkRemote() + layer, err := AttachChunkLayer(s, remote, ChunkLayerConfig{ChunkBlocks: 4, Epoch: 1, Holder: "old", Bitmap: NewFileChunkBitmapStore(path + ".bitmap")}) + if err != nil { + t.Fatal(err) + } + if _, err = s.Write(0, bytes.Repeat([]byte{0xD7}, 4096)); err != nil { + t.Fatal(err) + } + detached, err := layer.Detach(context.Background()) + if err != nil { + t.Fatal(err) + } + if detached.Head.State != chunkHeadDetached || detached.Head.DetachedBy == nil { + t.Fatal("producer did not detach", detached.Head) + } + claimed, err := ClaimChunkHead(context.Background(), remote, ChunkLayerConfig{Epoch: 2, Holder: "new"}) + if err != nil { + t.Fatal("takeover of production detached HEAD", err) + } + if claimed.State != chunkHeadActive || claimed.DetachedBy != nil || claimed.RemoteLSN != detached.H { + t.Fatalf("takeover retained detached proof or changed frontier: %+v", claimed) + } +} + +type claimFaultRemote struct { + ChunkRemote + applied, failRead, called bool + calls int +} + +func (r *claimFaultRemote) CASHead(ctx context.Context, expected ChunkHeadVersion, next ChunkHead) (uint64, error) { + r.calls++ + r.called = true + if r.applied { + if _, err := r.ChunkRemote.CASHead(ctx, expected, next); err != nil { + return 0, err + } + } + return 0, errors.New("injected lost CAS response") +} +func (r *claimFaultRemote) GetHead(ctx context.Context) (ChunkHead, error) { + if r.called && r.failRead { + return ChunkHead{}, errors.New("injected HEAD read outage") + } + return r.ChunkRemote.GetHead(ctx) +} + +func TestClaimChunkHeadSettlesUnknownWithoutReplay(t *testing.T) { + for _, applied := range []bool{false, true} { + for _, failRead := range []bool{false, true} { + remote := NewMemChunkRemote() + if _, err := remote.CASHead(context.Background(), ChunkHeadVersion{}, ChunkHead{Epoch: 1, Holder: "old", RemoteLSN: 7, Chunks: map[uint64]ChunkRef{}}); err != nil { + t.Fatal(err) + } + fault := &claimFaultRemote{ChunkRemote: remote, applied: applied, failRead: failRead} + head, err := ClaimChunkHead(context.Background(), fault, ChunkLayerConfig{Epoch: 2, Holder: "new"}) + if (err == nil) != (applied && !failRead) { + t.Fatalf("applied=%v readFail=%v err=%v", applied, failRead, err) + } + if fault.calls != 1 { + t.Fatalf("CAS replayed %d times", fault.calls) + } + if err == nil && (head.Epoch != 2 || head.Holder != "new" || head.RemoteLSN != 7) { + t.Fatal(head) + } + } + } +} + +func TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift(t *testing.T) { + remote := NewMemChunkRemote() + _, err := remote.CASHead(context.Background(), ChunkHeadVersion{}, ChunkHead{Epoch: 3, Holder: "current", Chunks: map[uint64]ChunkRef{}}) + if err != nil { + t.Fatal(err) + } + for _, cfg := range []ChunkLayerConfig{{Epoch: 2, Holder: "old"}, {Epoch: 3, Holder: "other"}} { + if _, err := ClaimChunkHead(context.Background(), remote, cfg); !errors.Is(err, ErrChunkLayerFenced) { + t.Fatalf("stale claim accepted: %v", err) + } + } + before, _ := remote.GetHead(context.Background()) + checks := 0 + _, err = ClaimChunkHead(context.Background(), remote, ChunkLayerConfig{Epoch: 4, Holder: "new", CaptureAllowed: func() error { + checks++ + if checks == 2 { + return errors.New("lineage moved") + } + return nil + }}) + after, _ := remote.GetHead(context.Background()) + if err == nil || after.Gen != before.Gen || after.Epoch != 3 { + t.Fatalf("drift published: head=%+v err=%v", after, err) + } + // An identical already-settled claim is idempotent and creates no new gen. + if _, err := ClaimChunkHead(context.Background(), remote, ChunkLayerConfig{Epoch: 3, Holder: "current"}); err != nil { + t.Fatal(err) + } + final, _ := remote.GetHead(context.Background()) + if final.Gen != before.Gen { + t.Fatal("idempotent claim advanced HEAD") + } +} + +func TestClaimChunkHeadFencesNoopCut(t *testing.T) { + s, _ := newChunkTestStore(t) + remote := newFakeChunkRemote() + layer := mustAttach(t, s, remote, ctConfig(1)) + if _, err := s.Write(0, makeBlock(4096, 0xAA)); err != nil { + t.Fatal(err) + } + if _, err := layer.Capture(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if _, err := ClaimChunkHead(ctTimeout(t), remote, ChunkLayerConfig{Epoch: 2, Holder: "host-b"}); err != nil { + t.Fatal(err) + } + if _, err := layer.Capture(ctTimeout(t)); !errors.Is(err, ErrChunkLayerFenced) { + t.Fatalf("stale no-op cut returned %v, want fenced", err) + } + if !layer.Fenced() { + t.Fatal("no-op cut did not propagate fence") + } +} + +func TestFreshRestoreBitmapStartsAtClaimedHEAD(t *testing.T) { + s, _ := newChunkTestStore(t) + r := NewMemChunkRemote() + if _, err := r.CASHead(ctTimeout(t), ChunkHeadVersion{}, ChunkHead{Epoch: 2, Holder: "host-a", RemoteLSN: 42}); err != nil { + t.Fatal(err) + } + cfg := ctConfig(2) + cfg.FreshFromHead = true + mustAttach(t, s, r, cfg) + hdr, dirty, ok, err := cfg.Bitmap.Load() + if err != nil || !ok || hdr.BaseLSN != 42 || hdr.HeadGen != 1 || hdr.Epoch != 2 || hdr.Base != chunkBaseNone || len(dirty) != 0 { + t.Fatalf("fresh bitmap not at HEAD: hdr=%+v dirty=%v ok=%v err=%v", hdr, dirty, ok, err) + } +} + +// A no-op cut still consults remote authority. An outage there is retryable +// remote unavailability, not an untyped failure or an ownership fence. +func TestClaimChunkHeadNoopCutClassifiesRemoteReadFailure(t *testing.T) { + s, _ := newChunkTestStore(t) + remote := newFakeChunkRemote() + layer := mustAttach(t, s, remote, ctConfig(1)) + if _, err := s.Write(0, makeBlock(4096, 0xA7)); err != nil { + t.Fatal(err) + } + if _, err := layer.Capture(ctTimeout(t)); err != nil { + t.Fatal(err) + } + before, _ := remote.GetHead(ctTimeout(t)) + remote.mu.Lock() + remote.failGet = errFakeRemoteDown + calls := remote.casCalls + remote.mu.Unlock() + _, err := layer.Capture(ctTimeout(t)) + if !errors.Is(err, ErrChunkRemoteUnavailable) || !errors.Is(err, errFakeRemoteDown) { + t.Errorf("no-op authority read: %v; want remote unavailable and underlying cause", err) + } + if layer.Fenced() { + t.Error("remote read outage latched an ownership fence") + } + remote.mu.Lock() + if remote.casCalls != calls { + t.Error("no-op read failure attempted a CAS") + } + remote.failGet = nil + remote.mu.Unlock() + if _, err := layer.Capture(ctTimeout(t)); err != nil { + t.Fatal("retry after remote recovery", err) + } + after, _ := remote.GetHead(ctTimeout(t)) + if after.Gen != before.Gen || after.RemoteLSN != before.RemoteLSN { + t.Fatal("no-op retry changed HEAD", before, after) + } +} diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 6997265566..91ab3436d3 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -78,7 +78,7 @@ import ( // fetch began); a local version always wins. // // The dirty bitmap stays off the write hot path. WAL entries carry their -// LBA, so the dirty set is always the persisted bitmap ∪ the chunks of WAL +// LBA, so the dirty set is always the persisted bitmap ∪ the chunks of WAL // entries above the checkpoint. The persisted bitmap may over-report, never // under-report. type chunkSink interface { @@ -137,7 +137,7 @@ type chunkDelta struct { // clears post-cut dirt. // // Restart or failover: a header equal to HEAD {RemoteLSN, Gen, Epoch} with -// Base == chunkBaseNone means incremental, dirty = persisted bitmap ∪ +// Base == chunkBaseNone means incremental, dirty = persisted bitmap ∪ // chunks of WAL entries above the checkpoint. A lost bitmap or any header // mismatch falls back to a per-chunk SHA-256 compare against HEAD's chunk // refs; only differing chunks are uploaded (Base == chunkBaseInstalling @@ -304,6 +304,16 @@ type chunkLayerConfig struct { // HEAD (every block absent, read lazily). False means an existing local // volume. Never inferred from the local contents. FreshFromHead bool + // RestoreGuard binds fresh attachment to the HEAD the provider claimed + // and durably seeded. A changed read refuses before hooks/readiness; the + // next recovery must repeat claim and seed. Nil is for direct layer users. + RestoreGuard *chunkHeadVersion + // PrepareRestore runs after ClaimChunkHead validates its observed HEAD + // and before any ownership CAS (also for an idempotent claim). The owner + // durably seeds the local frontier and rebases cached ship cursors here, + // while its frontend is gated. An error leaves remote ownership unchanged. + // No store/layer/remote lock is held across the callback. + PrepareRestore func(head chunkHead) error // CaptureAllowed is supplied by the store owner. It is an admission // check, made when a capture starts and again right before its HEAD CAS: // it refuses a cut during a BASE install or rebuild, or when this node is @@ -396,7 +406,7 @@ var ( errChunkKeyInvalid = errors.New("storage: chunk key is not non-empty valid UTF-8") errChunkLayerDetached = errors.New("storage: chunk layer detached") errChunkCASOutcomeUnknown = errors.New("storage: chunk HEAD CAS outcome unknown") - // The causes a control plane reports as typed codes (B9 W2 §2.2). + // The causes a control plane reports as typed codes (B9 W2 §2.2). errChunkLayerClosed = errors.New("storage: chunk layer closed") errChunkBaseInstalling = errors.New("storage: chunk BASE install in progress") errChunkRemoteUnavailable = errors.New("storage: chunk remote unavailable") diff --git a/seaweed-block/core/storage/wal_writer.go b/seaweed-block/core/storage/wal_writer.go index ee4b098563..97ecdc2ef6 100644 --- a/seaweed-block/core/storage/wal_writer.go +++ b/seaweed-block/core/storage/wal_writer.go @@ -32,6 +32,9 @@ type walWriter struct { logicalHead uint64 // monotonic write position logicalTail uint64 // monotonic flush position instr *writeInstrumentation + + // Optional batch pwrite fault seam; nil uses the real file. + batchWriteAt func([]byte, int64) (int, error) } // newWALWriter constructs a writer over an open file. logicalHead and @@ -148,7 +151,11 @@ func (w *walWriter) appendBatch(entries []walEntry) ([]uint64, error) { return nil } writeStart := time.Now() - if _, err := w.fd.WriteAt(pending, int64(w.walOffset+pendingStart)); err != nil { + writeAt := w.fd.WriteAt + if w.batchWriteAt != nil { + writeAt = w.batchWriteAt + } + if _, err := writeAt(pending, int64(w.walOffset+pendingStart)); err != nil { return fmt.Errorf("walWriter.appendBatch: pwrite at %d: %w", w.walOffset+pendingStart, err) } if w.instr != nil { diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index b15f8a76e3..850eab0566 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -117,13 +117,22 @@ type WALStore struct { // §6 + INV-RECYCLE-GATED-BY-MIN-ACTIVE-PIN. recycleFloorSrc RecycleFloorSource - syncs atomic.Uint64 // total fsync operations performed (test/diagnostic) + syncs atomic.Uint64 // completed logical Sync calls (test/diagnostic) instr writeInstrumentation // multiBlockRecords is a disabled-by-default Phase 148 local prototype. // It must not be wired into production paths before version/compatibility // gates and mounted NVMe/TCP profiling pass. multiBlockRecords bool + + // Physical WAL sync attempts exclude the separate metadata/checkpoint syncs. + syncWALFile func() error + walSyncCalls atomic.Uint64 + // Generations cover completed append attempts and recovery publication. + walMutation atomic.Uint64 + durableMutation atomic.Uint64 + // Replicated/direct paths conservatively disable dedup for this open store. + bypassSyncDedup atomic.Bool } // CreateWALStore initializes a new store file at path. Fails if path @@ -224,8 +233,14 @@ func openInitialized(path string, f *os.File, sb *superblock) (*WALStore, error) if s.nextLSN < 1 { s.nextLSN = 1 } + // The initial superblock must be synced even before the first write. + s.walMutation.Store(1) + s.syncWALFile = func() error { + s.walSyncCalls.Add(1) + return f.Sync() + } committer := NewGroupCommitter(GroupCommitterConfig{ - SyncFunc: func() error { return f.Sync() }, + SyncFunc: s.syncWALBatch, MaxDelay: 1 * time.Millisecond, MaxBatch: 64, }) @@ -423,6 +438,10 @@ func (s *WALStore) Recover() (uint64, error) { if s.closed { return 0, errors.New("storage: Recover after Close") } + // Recovery can republish a prefix left by a failed append (including on + // this same open file). Invalidate before releasing publication, even on + // a failed scan; the next successful sync establishes a reusable new cut. + defer s.walMutation.Add(1) s.dm.clear() res, err := recoverWAL(s.fd, s.sb, s.dm) if err != nil { @@ -498,6 +517,8 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) { Data: data, } walRelOff, err := s.wal.append(entry) + // A failed pwrite may still leave complete records or padding in the file. + s.walMutation.Add(1) if err != nil { s.mu.Unlock() return 0, fmt.Errorf("storage: WAL append: %w", err) @@ -572,6 +593,8 @@ func (s *WALStore) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error } } offsets, err := s.wal.appendBatch(entries) + // A failed pwrite may still leave complete records or padding in the file. + s.walMutation.Add(1) if err != nil { s.mu.Unlock() return nil, fmt.Errorf("storage: WAL batch append: %w", err) @@ -614,6 +637,8 @@ func (s *WALStore) writeBatchMultiBlockLocked(startLBA uint32, blocks [][]byte, Data: payload, } walRelOff, err := s.wal.append(entry) + // A failed pwrite may still leave complete records or padding in the file. + s.walMutation.Add(1) if err != nil { return nil, fmt.Errorf("storage: WAL multiblock append: %w", err) } @@ -774,7 +799,14 @@ func (s *WALStore) Sync() (uint64, error) { targetDirectFrontier := s.pendingDirectFrontierLSN s.mu.RUnlock() - if err := s.syncCache(); err != nil { + if s.walSyncCovered() { + // Preserve shutdown refusal even when no file I/O is necessary. + select { + case <-s.committer.stopCh: + return 0, ErrGroupCommitShutdown + default: + } + } else if err := s.syncCache(); err != nil { return 0, fmt.Errorf("storage: group commit fsync: %w", err) } s.syncs.Add(1) @@ -882,6 +914,7 @@ func (s *WALStore) RecoveryRetentionLSNs() uint64 { // Used by the rebuild server to declare the replica's frontier // matches the primary's head once base blocks are installed. func (s *WALStore) AdvanceFrontier(lsn uint64) { + s.bypassSyncDedup.Store(true) s.lifecycleMu.RLock() defer s.lifecycleMu.RUnlock() s.mu.Lock() @@ -929,6 +962,7 @@ func (s *WALStore) AdvanceWALTail(newTail uint64) { // Durability follows the same rule as Write: bytes become durable // only on the next successful Sync (the extent fsync covers them). func (s *WALStore) WriteExtentDirect(lba uint32, data []byte) error { + s.bypassSyncDedup.Store(true) s.captureMu.RLock() defer s.captureMu.RUnlock() s.lifecycleMu.RLock() @@ -966,6 +1000,7 @@ func (s *WALStore) WriteExtentDirect(lba uint32, data []byte) error { // than allocating a fresh one. Same durability semantics as Write // (becomes durable on next Sync). func (s *WALStore) ApplyEntry(lba uint32, data []byte, lsn uint64) error { + s.bypassSyncDedup.Store(true) s.captureMu.RLock() defer s.captureMu.RUnlock() s.lifecycleMu.RLock() @@ -994,6 +1029,8 @@ func (s *WALStore) ApplyEntry(lba uint32, data []byte, lsn uint64) error { Data: dataCopy, } walRelOff, err := s.wal.append(entry) + // A failed pwrite may still leave complete records or padding in the file. + s.walMutation.Add(1) if err != nil { return fmt.Errorf("storage: WAL append (apply): %w", err) } @@ -1156,3 +1193,30 @@ func (s *WALStore) Close() error { // Compile-time assertion: WALStore satisfies LogicalStorage. var _ LogicalStorage = (*WALStore)(nil) + +// WALSyncCount returns physical WAL sync attempts (including errors), not logical +// Sync calls or the separate checkpoint/extent metadata sync operations. +func (s *WALStore) WALSyncCount() uint64 { return s.walSyncCalls.Load() } + +// walSyncCovered is used only after the caller has captured its publication +// frontier. A later concurrent write may force extra I/O, never a false ACK. +func (s *WALStore) walSyncCovered() bool { + return !s.bypassSyncDedup.Load() && s.chunk.Load() == nil && + s.walMutation.Load() <= s.durableMutation.Load() +} + +// syncWALBatch runs only on the existing committer's single leader. It takes no +// lifecycle/publication/WAL/shard locks and the queue mutex is already released. +// Requests queued during a sync can reuse it only if their mutations predate its +// captured cut. Failure leaves the previous durable generation unchanged. +func (s *WALStore) syncWALBatch() error { + cut := s.walMutation.Load() + if !s.bypassSyncDedup.Load() && s.chunk.Load() == nil && cut <= s.durableMutation.Load() { + return nil + } + if err := s.syncWALFile(); err != nil { + return err + } + s.durableMutation.Store(cut) + return nil +} diff --git a/seaweed-block/core/storage/walstore_sync_generation_test.go b/seaweed-block/core/storage/walstore_sync_generation_test.go new file mode 100644 index 0000000000..2e6861d92e --- /dev/null +++ b/seaweed-block/core/storage/walstore_sync_generation_test.go @@ -0,0 +1,321 @@ +package storage + +import ( + "bytes" + "errors" + "io" + "path/filepath" + "sync/atomic" + "testing" + "time" +) + +func newGenerationStore(t *testing.T) *WALStore { + t.Helper() + s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 32, 4096) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + return s +} +func waitGenerationPending(t *testing.T, s *WALStore, n int) { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + s.committer.mu.Lock() + got := len(s.committer.pending) + s.committer.mu.Unlock() + if got == n { + return + } + time.Sleep(time.Millisecond) + } + t.Fatalf("did not queue %d followers", n) +} +func generationResult(t *testing.T, ch <-chan uint64) uint64 { + t.Helper() + select { + case n := <-ch: + return n + case <-time.After(3 * time.Second): + t.Fatal("Sync did not join") + return 0 + } +} + +func TestWALGenerationSyncFollowersAndNewWrite(t *testing.T) { + for _, newWrite := range []bool{false, true} { + t.Run(map[bool]string{false: "same mutation", true: "write after batch cut"}[newWrite], func(t *testing.T) { + s := newGenerationStore(t) + if _, err := s.Write(0, makeBlock(4096, 0x31)); err != nil { + t.Fatal(err) + } + entered, release := make(chan struct{}), make(chan struct{}) + // Release before store close even if an assertion fails. + defer close(release) + realSync := s.syncWALFile + var attempts atomic.Int32 + s.syncWALFile = func() error { + s.committer.mu.Lock() + s.committer.mu.Unlock() + if attempts.Add(1) == 1 { + close(entered) + <-release + } + return realSync() + } + results := make(chan uint64, 9) + firstResult := make(chan uint64, 1) + errs := make(chan error, 9) + start := func(out chan<- uint64) { go func() { n, err := s.Sync(); errs <- err; out <- n }() } + start(firstResult) + select { + case <-entered: + case <-time.After(3 * time.Second): + t.Fatal("no physical Sync") + } + if newWrite { + if _, err := s.Write(1, makeBlock(4096, 0x42)); err != nil { + t.Fatal(err) + } + } + for i := 0; i < 8; i++ { + start(results) + } + waitGenerationPending(t, s, 8) + release <- struct{}{} + first := generationResult(t, firstResult) + if first != 1 { + t.Fatalf("first batch frontier=%d want 1", first) + } + for i := 0; i < 8; i++ { + n := generationResult(t, results) + want := uint64(1) + if newWrite { + want = 2 + } + if n != want { + t.Fatalf("follower frontier=%d want %d", n, want) + } + } + for i := 0; i < 9; i++ { + if err := <-errs; err != nil { + t.Fatal(err) + } + } + want := uint64(1) + if newWrite { + want = 2 + } + if n := s.WALSyncCount(); n != want { + t.Fatalf("physical syncs=%d want %d", n, want) + } + }) + } +} + +func TestWALGenerationSyncFailureAndShutdown(t *testing.T) { + s := newGenerationStore(t) + if _, err := s.Write(0, makeBlock(4096, 0x61)); err != nil { + t.Fatal(err) + } + realSync := s.syncWALFile + var attempts atomic.Int32 + fault := errors.New("injected fsync error") + s.syncWALFile = func() error { + if attempts.Add(1) == 1 { + return fault + } + return realSync() + } + if _, err := s.Sync(); !errors.Is(err, fault) { + t.Fatalf("first sync err=%v", err) + } + if r, _, _ := s.Boundaries(); r != 0 { + t.Fatalf("failed sync published R=%d", r) + } + if n, err := s.Sync(); err != nil || n != 1 { + t.Fatalf("retry frontier=%d err=%v", n, err) + } + if attempts.Load() != 2 { + t.Fatalf("error was cached: attempts=%d", attempts.Load()) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if attempts.Load() != 2 { + t.Fatal("durable duplicate resynced") + } + s.committer.Stop() + if _, err := s.Sync(); !errors.Is(err, ErrGroupCommitShutdown) { + t.Fatalf("cached request after shutdown err=%v", err) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err == nil { + t.Fatal("cached request after Close accepted") + } +} + +func TestWALGenerationBypassesUntrackedMutationPaths(t *testing.T) { + for _, kind := range []string{"old LSN apply", "direct extent", "direct frontier", "chunk layer"} { + t.Run(kind, func(t *testing.T) { + s := newGenerationStore(t) + if _, err := s.Write(0, makeBlock(4096, 0x81)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + before := s.WALSyncCount() + switch kind { + case "old LSN apply": + if err := s.ApplyEntry(0, makeBlock(4096, 0x82), 1); err != nil { + t.Fatal(err) + } + case "direct extent": + if err := s.WriteExtentDirect(1, makeBlock(4096, 0x83)); err != nil { + t.Fatal(err) + } + case "direct frontier": + s.AdvanceFrontier(5) + case "chunk layer": + mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)) + } + for i := 0; i < 2; i++ { + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + } + if n := s.WALSyncCount() - before; n != 2 { + t.Fatalf("bypass physical syncs=%d want 2", n) + } + }) + } +} + +func TestWALGenerationBatchPublication(t *testing.T) { + for _, multi := range []bool{false, true} { + t.Run(map[bool]string{false: "normal records", true: "multiblock record"}[multi], func(t *testing.T) { + s := newGenerationStore(t) + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } // force the initial file to disk + s.SetMultiBlockRecords(multi) + for i := 0; i < 2; i++ { + before := s.WALSyncCount() + if _, err := s.WriteBatch(0, [][]byte{makeBlock(4096, byte(i+1)), makeBlock(4096, byte(i+2))}); err != nil { + t.Fatal(err) + } + for j := 0; j < 2; j++ { + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + } + if n := s.WALSyncCount() - before; n != 1 { + t.Fatalf("batch %d physical syncs=%d want 1", i, n) + } + } + }) + } +} + +// An actual partial pwrite leaves a valid first record and a torn second record, +// but appendBatch returns before publishing its planned head. Same-open Recover +// must not let the prefix reuse the pre-failure durable generation. +func TestWALGenerationPartialAppendRecoverySync(t *testing.T) { + for _, recoverFirst := range []bool{false, true} { + t.Run(map[bool]string{false: "failed append without recovery", true: "same-open recovery"}[recoverFirst], func(t *testing.T) { + s := newGenerationStore(t) + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + beforeHead := s.wal.logicalHeadValue() + want := makeBlock(4096, 0xa7) + pwriteCalls := 0 + s.wal.batchWriteAt = func(data []byte, off int64) (int, error) { + pwriteCalls++ + limit := walEntryHeaderSize + 4096 + walEntryHeaderSize + 17 + if len(data) <= limit { + return 0, errors.New("fixture needs two whole records") + } + n, err := s.fd.WriteAt(data[:limit], off) + if err != nil { + return n, err + } + return n, io.ErrShortWrite + } + _, err := s.WriteBatch(0, [][]byte{want, makeBlock(4096, 0xb8)}) + s.wal.batchWriteAt = nil + if !errors.Is(err, io.ErrShortWrite) || pwriteCalls != 1 { + t.Fatalf("partial batch err=%v pwrite calls=%d", err, pwriteCalls) + } + if got := s.wal.logicalHeadValue(); got != beforeHead { + t.Fatalf("failed batch published head=%d want %d", got, beforeHead) + } + if recoverFirst { + if n, err := s.Recover(); err != nil || n != 1 { + t.Fatalf("same-open Recover=%d err=%v want1,nil", n, err) + } + if got, err := s.Read(0); err != nil || !bytes.Equal(got, want) { + t.Fatalf("valid prefix not recovered: err=%v", err) + } + } + realSync := s.syncWALFile + fault := errors.New("next physical sync failed") + attempts := 0 + s.syncWALFile = func() error { attempts++; return fault } + _, err = s.Sync() + s.syncWALFile = realSync + if !errors.Is(err, fault) || attempts != 1 { + t.Fatalf("next Sync skipped required physical I/O/error: err=%v attempts=%d", err, attempts) + } + before := s.WALSyncCount() + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if n := s.WALSyncCount() - before; n != 1 { + t.Fatalf("retry+duplicate physical syncs=%d want1", n) + } + }) + } +} + +// Even unchanged recovery must invalidate the prior open-instance coverage; +// its next successful sync may then be reused normally, not permanently bypassed. +func TestWALGenerationSameOpenRecoverInvalidatesCoverage(t *testing.T) { + s := newGenerationStore(t) + if _, err := s.Write(0, makeBlock(4096, 0x92)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + realSync := s.syncWALFile + attempts := 0 + fault := errors.New("post-recovery fsync error") + s.syncWALFile = func() error { attempts++; return fault } + _, err := s.Sync() + s.syncWALFile = realSync + if !errors.Is(err, fault) || attempts != 1 { + t.Fatalf("Recover reused old sync coverage: err=%v attempts=%d", err, attempts) + } + before := s.WALSyncCount() + for i := 0; i < 2; i++ { + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + } + if n := s.WALSyncCount() - before; n != 1 { + t.Fatalf("Recover permanently disabled dedup: syncs=%d want1", n) + } +}