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/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) + } +}