From 73707d9f6137916bfaea24a3c20877c41af43ca0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 01:04:54 -0800 Subject: [PATCH 01/12] test(storage): require initialized prezero files and crash readback --- seaweed-block/core/storage/data_sync_linux.go | 54 +++++++ .../core/storage/data_sync_linux_test.go | 153 ++++++++++++++++++ 2 files changed, 207 insertions(+) create mode 100644 seaweed-block/core/storage/data_sync_linux.go create mode 100644 seaweed-block/core/storage/data_sync_linux_test.go diff --git a/seaweed-block/core/storage/data_sync_linux.go b/seaweed-block/core/storage/data_sync_linux.go new file mode 100644 index 0000000000..a572caae2a --- /dev/null +++ b/seaweed-block/core/storage/data_sync_linux.go @@ -0,0 +1,54 @@ +//go:build linux + +package storage + +import ( + "fmt" + "golang.org/x/sys/unix" + "os" + "unsafe" +) + +// FIEMAP with SYNC resolves delayed allocation before inspecting the mapping. +// Reject holes, unknown/delayed mappings and unwritten extents; fallocate alone +// does not satisfy the initialized-file experiment's precondition. +func verifyInitializedFile(f *os.File) error { + info, err := f.Stat() + if err != nil { + return err + } + type extent struct { + Logical, Physical, Length uint64 + Reserved [2]uint64 + Flags uint32 + Reserved2 [3]uint32 + } + type mapping struct { + Start, Length uint64 + Flags, Mapped, Count, Reserved uint32 + Extents [128]extent + } + end := uint64(info.Size()) + var covered uint64 + for covered < end { + m := mapping{Start: covered, Length: end - covered, Flags: 1, Count: 128} + _, _, errno := unix.Syscall(unix.SYS_IOCTL, f.Fd(), 0xc020660b, uintptr(unsafe.Pointer(&m))) + if errno != 0 { + return fmt.Errorf("storage: FIEMAP: %w", errno) + } + if m.Mapped == 0 || m.Mapped > m.Count { + return fmt.Errorf("storage: uninitialized file at %d", covered) + } + for _, e := range m.Extents[:m.Mapped] { + if e.Logical > covered || e.Length == 0 || e.Logical+e.Length < e.Logical || e.Flags&(2|4|0x800) != 0 { + return fmt.Errorf("storage: hole or unwritten extent at %d (logical=%d flags=%#x)", covered, e.Logical, e.Flags) + } + next := e.Logical + e.Length + if next <= covered { + return fmt.Errorf("storage: FIEMAP made no progress") + } + covered = next + } + } + return nil +} diff --git a/seaweed-block/core/storage/data_sync_linux_test.go b/seaweed-block/core/storage/data_sync_linux_test.go new file mode 100644 index 0000000000..0e2c28eeed --- /dev/null +++ b/seaweed-block/core/storage/data_sync_linux_test.go @@ -0,0 +1,153 @@ +//go:build linux + +package storage + +import ( + "bufio" + "bytes" + "context" + "fmt" + "golang.org/x/sys/unix" + "os" + "os/exec" + "path/filepath" + "syscall" + "testing" + "time" +) + +func TestPrezeroCreatesInitializedVolume(t *testing.T) { + t.Setenv("SWBLOCK_SYNC", "fdatasync") + t.Setenv("SWBLOCK_PREZERO", "1") + path := filepath.Join(t.TempDir(), "volume") + s, e := CreateWALStore(path, 32, 4096) + if e != nil { + t.Fatal(e) + } + defer s.Close() + f, e := os.Open(path) + if e != nil { + t.Fatal(e) + } + defer f.Close() + if e = verifyInitializedFile(f); e != nil { + t.Fatalf("prezero must eliminate holes and unwritten extents: %v", e) + } + if _, e = s.Recover(); e != nil { + t.Fatal(e) + } + b, e := s.Read(31) + if e != nil || !bytes.Equal(b, make([]byte, 4096)) { + t.Fatalf("new extent bytes: %v", e) + } +} + +func TestInitializedFileRejectsSparseAndUnwritten(t *testing.T) { + f, e := os.CreateTemp(t.TempDir(), "volume") + if e != nil { + t.Fatal(e) + } + defer f.Close() + if e = f.Truncate(1 << 20); e != nil { + t.Fatal(e) + } + if e = verifyInitializedFile(f); e == nil { + t.Fatal("sparse file accepted") + } + if e = unix.Fallocate(int(f.Fd()), 0, 0, 1<<20); e != nil { + t.Fatal(e) + } + if e = verifyInitializedFile(f); e == nil { + t.Fatal("unwritten extents accepted") + } +} + +func TestFdatasyncAcknowledgedWritesSurviveSIGKILL(t *testing.T) { + if path := os.Getenv("SWBLOCK_TEST_SYNC_CRASH"); path != "" { + s, e := CreateWALStore(path, 32, 4096) + if e != nil { + panic(e) + } + s.DisableAutoFlushForRecoveryTest() + if _, e = s.Recover(); e != nil { + panic(e) + } + for _, lba := range []uint32{0, 13, 31} { + if _, e = s.Write(lba, bytes.Repeat([]byte{byte(lba + 17)}, 4096)); e != nil { + panic(e) + } + } + if n, e := s.Sync(); e != nil || n < 3 { + panic(fmt.Sprintf("Sync=%d %v", n, e)) + } + if os.Getenv("SWBLOCK_TEST_EXTENT") == "1" { + if e = s.flusher.flushOnce(); e != nil { + panic(e) + } + } + fmt.Println("SYNC_ACKNOWLEDGED") + for { + time.Sleep(time.Hour) + } + } + for _, prezero := range []string{"0", "1"} { + for _, extent := range []string{"0", "1"} { + t.Run("prezero"+prezero+"/extent"+extent, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "volume") + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestFdatasyncAcknowledgedWritesSurviveSIGKILL$") + cmd.Env = append(os.Environ(), "SWBLOCK_SYNC=fdatasync", "SWBLOCK_PREZERO="+prezero, "SWBLOCK_TEST_SYNC_CRASH="+path, "SWBLOCK_TEST_EXTENT="+extent) + out, e := cmd.StdoutPipe() + if e != nil { + t.Fatal(e) + } + var stderr bytes.Buffer + cmd.Stderr = &stderr + if e = cmd.Start(); e != nil { + t.Fatal(e) + } + defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }() + scan := bufio.NewScanner(out) + ready := false + for scan.Scan() { + if scan.Text() == "SYNC_ACKNOWLEDGED" { + ready = true + break + } + } + if !ready { + t.Fatalf("no sync ACK: %v %s", scan.Err(), stderr.String()) + } + if e = cmd.Process.Kill(); e != nil { + t.Fatal(e) + } + e = cmd.Wait() + exit, ok := e.(*exec.ExitError) + if !ok { + t.Fatalf("not killed: %v", e) + } + status, ok := exit.Sys().(syscall.WaitStatus) + if !ok || status.Signal() != syscall.SIGKILL { + t.Fatalf("wrong exit: %v", e) + } + t.Setenv("SWBLOCK_SYNC", "fdatasync") + t.Setenv("SWBLOCK_PREZERO", prezero) + s, e := OpenWALStore(path) + if e != nil { + t.Fatal(e) + } + defer s.Close() + if _, e = s.Recover(); e != nil { + t.Fatal(e) + } + for _, lba := range []uint32{0, 13, 31} { + b, e := s.Read(lba) + if e != nil || !bytes.Equal(b, bytes.Repeat([]byte{byte(lba + 17)}, 4096)) { + t.Fatalf("acknowledged block%d differs: %v", lba, e) + } + } + }) + } + } +} From 2042e3422bc0fff2855179326556d03acefe3922 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 01:05:56 -0800 Subject: [PATCH 02/12] feat(storage): add opt-in data sync and initialized file experiments --- seaweed-block/core/storage/data_sync.go | 61 +++++++++++++++++++ seaweed-block/core/storage/data_sync_linux.go | 3 + seaweed-block/core/storage/data_sync_other.go | 14 +++++ seaweed-block/core/storage/wal_writer.go | 8 ++- seaweed-block/core/storage/walstore.go | 8 ++- seaweed-block/core/storage/walstore_v3.go | 3 + 6 files changed, 94 insertions(+), 3 deletions(-) create mode 100644 seaweed-block/core/storage/data_sync.go create mode 100644 seaweed-block/core/storage/data_sync_other.go diff --git a/seaweed-block/core/storage/data_sync.go b/seaweed-block/core/storage/data_sync.go new file mode 100644 index 0000000000..91190f600d --- /dev/null +++ b/seaweed-block/core/storage/data_sync.go @@ -0,0 +1,61 @@ +package storage + +import ( + "fmt" + "io" + "log" + "os" +) + +// Experimental data-only sync applies to WAL/extent data. Descriptor slots, +// chunk maps, creation and directory operations retain full fsync. +func newDataFileSync(f *os.File) (func() error, error) { + switch mode := os.Getenv("SWBLOCK_SYNC"); mode { + case "", "fsync": + return f.Sync, nil + case "fdatasync": + if err := dataSyncSupported(); err != nil { + return nil, err + } + log.Printf("storage: experimental WAL/extent sync=fdatasync file=%s", f.Name()) + return func() error { return fdatasyncFile(f) }, nil + default: + return nil, fmt.Errorf("storage: invalid SWBLOCK_SYNC %q", mode) + } +} + +// Only newly-created files reach this hook: existing volume bytes are never +// rewritten. Writing zeros (not fallocate) converts unwritten extents too. +func prezeroNewStore(f *os.File, size int64) error { + switch mode := os.Getenv("SWBLOCK_PREZERO"); mode { + case "", "0": + return nil + case "1": + if err := dataSyncSupported(); err != nil { + return err + } + default: + return fmt.Errorf("storage: invalid SWBLOCK_PREZERO %q", mode) + } + zero := make([]byte, 1<<20) + for off := int64(0); off < size; { + b := zero[:min(int64(len(zero)), size-off)] + n, err := f.WriteAt(b, off) + if err != nil { + return fmt.Errorf("storage: prezero: %w", err) + } + if n != len(b) { + return io.ErrShortWrite + } + off += int64(n) + } + // Allocation/size/extent metadata must be fully durable before the check. + if err := f.Sync(); err != nil { + return err + } + if err := verifyInitializedFile(f); err != nil { + return fmt.Errorf("storage: prezero verification: %w", err) + } + log.Printf("storage: prezero FIEMAP verified initialized file=%s bytes=%d", f.Name(), size) + return nil +} diff --git a/seaweed-block/core/storage/data_sync_linux.go b/seaweed-block/core/storage/data_sync_linux.go index a572caae2a..6e37a9e181 100644 --- a/seaweed-block/core/storage/data_sync_linux.go +++ b/seaweed-block/core/storage/data_sync_linux.go @@ -52,3 +52,6 @@ func verifyInitializedFile(f *os.File) error { } return nil } + +func dataSyncSupported() error { return nil } +func fdatasyncFile(f *os.File) error { return unix.Fdatasync(int(f.Fd())) } diff --git a/seaweed-block/core/storage/data_sync_other.go b/seaweed-block/core/storage/data_sync_other.go new file mode 100644 index 0000000000..fd456efdff --- /dev/null +++ b/seaweed-block/core/storage/data_sync_other.go @@ -0,0 +1,14 @@ +//go:build !linux + +package storage + +import ( + "errors" + "os" +) + +func dataSyncSupported() error { + return errors.New("storage: fdatasync/prezero experiment requires Linux") +} +func fdatasyncFile(*os.File) error { return dataSyncSupported() } +func verifyInitializedFile(*os.File) error { return dataSyncSupported() } diff --git a/seaweed-block/core/storage/wal_writer.go b/seaweed-block/core/storage/wal_writer.go index 1b6bf33638..558eb8b064 100644 --- a/seaweed-block/core/storage/wal_writer.go +++ b/seaweed-block/core/storage/wal_writer.go @@ -479,7 +479,13 @@ func (w *walWriter) logicalTailValue() uint64 { } // fsync forces buffered data to durable storage. -func (w *walWriter) fsync() error { return w.fd.Sync() } +func (w *walWriter) fsync() error { + sync, err := newDataFileSync(w.fd) + if err != nil { + return err + } + return sync() +} // usedFraction returns the fraction of the WAL region currently in // use, in the range [0, 1]. Used by the admission controller to diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 754caec8d4..bba62eb0a8 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -309,6 +309,10 @@ func openInitializedWithMetadata(path string, f *os.File, sb *superblock, metada // init hook that runs before the committer and flusher goroutines start // (the v3 store attaches its state there). func openInitializedInternal(path string, f *os.File, sb *superblock, metadata BlockMetadata, init func(*WALStore) error) (*WALStore, error) { + dataSync, err := newDataFileSync(f) + if err != nil { + return nil, err + } dm := newDirtyMap(64) // 64 shards is plenty for Phase 07 demo workloads s := &WALStore{ @@ -333,9 +337,9 @@ func openInitializedInternal(path string, f *os.File, sb *superblock, metadata B s.walMutation.Store(1) s.syncWALFile = func() error { s.walSyncCalls.Add(1) - return f.Sync() + return dataSync() } - s.syncExtentFile = f.Sync + s.syncExtentFile = dataSync if init != nil { if err := init(s); err != nil { return nil, err diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 99d911141e..716edeb1e9 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -269,6 +269,9 @@ func createWALStoreV3Configured(path string, numBlocks, blockSize uint32, walSiz return nil, err } err = fd.Truncate(totalSize) + if err == nil { + err = prezeroNewStore(fd, totalSize) + } if err == nil && chunkBlocks != 0 { var m *chunkLSNMapV3 m, err = createChunkLSNMapV3(path+".chunkmap", d, chunkBlocks) From 781e842ef196af0c3aaf91f4e99a93da7ff35840 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 01:06:31 -0800 Subject: [PATCH 03/12] test(storage): expose syscall probe and record sync contract --- .../core/storage/data_sync_linux_test.go | 27 +++++++++++++++++++ seaweed-block/docs/design/invariants.md | 6 +++++ 2 files changed, 33 insertions(+) diff --git a/seaweed-block/core/storage/data_sync_linux_test.go b/seaweed-block/core/storage/data_sync_linux_test.go index 0e2c28eeed..9643077fe5 100644 --- a/seaweed-block/core/storage/data_sync_linux_test.go +++ b/seaweed-block/core/storage/data_sync_linux_test.go @@ -151,3 +151,30 @@ func TestFdatasyncAcknowledgedWritesSurviveSIGKILL(t *testing.T) { } } } + +// Run under strace with the experiment environment unset/set to verify the +// syscall boundary independently of the selected function's Go identity. +func TestDataSyncSyscallProbe(t *testing.T) { + s, e := CreateWALStore(filepath.Join(t.TempDir(), "volume"), 32, 4096) + if e != nil { + t.Fatal(e) + } + defer s.Close() + s.DisableAutoFlushForRecoveryTest() + if _, e = s.Recover(); e != nil { + t.Fatal(e) + } + if _, e = s.Write(7, bytes.Repeat([]byte{0x6d}, 4096)); e != nil { + t.Fatal(e) + } + if _, e = s.Sync(); e != nil { + t.Fatal(e) + } + if e = s.flusher.flushOnce(); e != nil { + t.Fatal(e) + } + b, e := s.Read(7) + if e != nil || !bytes.Equal(b, bytes.Repeat([]byte{0x6d}, 4096)) { + t.Fatalf("readback: %v", e) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9068b36a7b..7c12d9c6bd 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -527,6 +527,12 @@ Notes: |---|---|---|---|---|---|---| | `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | +### Experimental data-file synchronization + +| ID | Invariant | Machine / transition | Enforced in | Tests | TLA+ | Status | +|---|---|---|---|---|---|---| +| `INV-WAL-DATA-SYNC-001` | Default WAL/extent sync remains fsync. Linux `SWBLOCK_SYNC=fdatasync` selects data-only sync for WAL/extent data; descriptor/map/create/directory durability still uses fsync. `SWBLOCK_PREZERO=1` writes every byte only at create, fsyncs, then refuses holes/unwritten FIEMAP mappings. Existing files are never prezeroed. | M1 Create / Sync / Checkpoint | `data_sync.go`, `data_sync_linux.go`; `walstore_v3.go` Create; `walstore.go` data sync seams | `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten`, `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE | + ## Part C. Change rules How a fix or a feature is calibrated against this model: From 94a9aac74f5249a3181c1ce917a0bb5e022a9fb2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 01:08:56 -0800 Subject: [PATCH 04/12] test(storage): cover strict and lagged sync crash paths --- .../core/storage/data_sync_linux_test.go | 127 ++++++++++-------- 1 file changed, 69 insertions(+), 58 deletions(-) diff --git a/seaweed-block/core/storage/data_sync_linux_test.go b/seaweed-block/core/storage/data_sync_linux_test.go index 9643077fe5..520495e46d 100644 --- a/seaweed-block/core/storage/data_sync_linux_test.go +++ b/seaweed-block/core/storage/data_sync_linux_test.go @@ -64,7 +64,11 @@ func TestInitializedFileRejectsSparseAndUnwritten(t *testing.T) { func TestFdatasyncAcknowledgedWritesSurviveSIGKILL(t *testing.T) { if path := os.Getenv("SWBLOCK_TEST_SYNC_CRASH"); path != "" { - s, e := CreateWALStore(path, 32, 4096) + opts := WALStoreOptions{} + if os.Getenv("SWBLOCK_TEST_STRICT") == "1" { + opts.WMode = WModeStrict + } + s, e := CreateWALStoreWithOptions(path, 32, 4096, opts) if e != nil { panic(e) } @@ -90,72 +94,79 @@ func TestFdatasyncAcknowledgedWritesSurviveSIGKILL(t *testing.T) { time.Sleep(time.Hour) } } - for _, prezero := range []string{"0", "1"} { - for _, extent := range []string{"0", "1"} { - t.Run("prezero"+prezero+"/extent"+extent, func(t *testing.T) { - path := filepath.Join(t.TempDir(), "volume") - ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) - defer cancel() - cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestFdatasyncAcknowledgedWritesSurviveSIGKILL$") - cmd.Env = append(os.Environ(), "SWBLOCK_SYNC=fdatasync", "SWBLOCK_PREZERO="+prezero, "SWBLOCK_TEST_SYNC_CRASH="+path, "SWBLOCK_TEST_EXTENT="+extent) - out, e := cmd.StdoutPipe() - if e != nil { - t.Fatal(e) - } - var stderr bytes.Buffer - cmd.Stderr = &stderr - if e = cmd.Start(); e != nil { - t.Fatal(e) - } - defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }() - scan := bufio.NewScanner(out) - ready := false - for scan.Scan() { - if scan.Text() == "SYNC_ACKNOWLEDGED" { - ready = true - break + for _, strict := range []string{"0", "1"} { + for _, prezero := range []string{"0", "1"} { + for _, extent := range []string{"0", "1"} { + t.Run("strict"+strict+"/prezero"+prezero+"/extent"+extent, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "volume") + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestFdatasyncAcknowledgedWritesSurviveSIGKILL$") + cmd.Env = append(os.Environ(), "SWBLOCK_SYNC=fdatasync", "SWBLOCK_PREZERO="+prezero, "SWBLOCK_TEST_SYNC_CRASH="+path, "SWBLOCK_TEST_EXTENT="+extent, "SWBLOCK_TEST_STRICT="+strict) + out, e := cmd.StdoutPipe() + if e != nil { + t.Fatal(e) } - } - if !ready { - t.Fatalf("no sync ACK: %v %s", scan.Err(), stderr.String()) - } - if e = cmd.Process.Kill(); e != nil { - t.Fatal(e) - } - e = cmd.Wait() - exit, ok := e.(*exec.ExitError) - if !ok { - t.Fatalf("not killed: %v", e) - } - status, ok := exit.Sys().(syscall.WaitStatus) - if !ok || status.Signal() != syscall.SIGKILL { - t.Fatalf("wrong exit: %v", e) - } - t.Setenv("SWBLOCK_SYNC", "fdatasync") - t.Setenv("SWBLOCK_PREZERO", prezero) - s, e := OpenWALStore(path) - if e != nil { - t.Fatal(e) - } - defer s.Close() - if _, e = s.Recover(); e != nil { - t.Fatal(e) - } - for _, lba := range []uint32{0, 13, 31} { - b, e := s.Read(lba) - if e != nil || !bytes.Equal(b, bytes.Repeat([]byte{byte(lba + 17)}, 4096)) { - t.Fatalf("acknowledged block%d differs: %v", lba, e) + var stderr bytes.Buffer + cmd.Stderr = &stderr + if e = cmd.Start(); e != nil { + t.Fatal(e) } - } - }) + defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }() + scan := bufio.NewScanner(out) + ready := false + for scan.Scan() { + if scan.Text() == "SYNC_ACKNOWLEDGED" { + ready = true + break + } + } + if !ready { + t.Fatalf("no sync ACK: %v %s", scan.Err(), stderr.String()) + } + if e = cmd.Process.Kill(); e != nil { + t.Fatal(e) + } + e = cmd.Wait() + exit, ok := e.(*exec.ExitError) + if !ok { + t.Fatalf("not killed: %v", e) + } + status, ok := exit.Sys().(syscall.WaitStatus) + if !ok || status.Signal() != syscall.SIGKILL { + t.Fatalf("wrong exit: %v", e) + } + t.Setenv("SWBLOCK_SYNC", "fdatasync") + t.Setenv("SWBLOCK_PREZERO", prezero) + s, e := OpenWALStore(path) + if e != nil { + t.Fatal(e) + } + defer s.Close() + if _, e = s.Recover(); e != nil { + t.Fatal(e) + } + for _, lba := range []uint32{0, 13, 31} { + b, e := s.Read(lba) + if e != nil || !bytes.Equal(b, bytes.Repeat([]byte{byte(lba + 17)}, 4096)) { + t.Fatalf("acknowledged block%d differs: %v", lba, e) + } + } + }) + } } + } } // Run under strace with the experiment environment unset/set to verify the // syscall boundary independently of the selected function's Go identity. func TestDataSyncSyscallProbe(t *testing.T) { - s, e := CreateWALStore(filepath.Join(t.TempDir(), "volume"), 32, 4096) + opts := WALStoreOptions{} + if os.Getenv("SWBLOCK_TEST_STRICT") == "1" { + opts.WMode = WModeStrict + } + s, e := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "volume"), 32, 4096, opts) if e != nil { t.Fatal(e) } From 6121830f795128a61f43ffc0d52594bfe1f15e59 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 01:14:33 -0800 Subject: [PATCH 05/12] feat(storage): expose sparse fallocate and prezero allocation arms --- seaweed-block/core/storage/data_sync.go | 31 ++++++++++++++++--- seaweed-block/core/storage/data_sync_linux.go | 8 +++-- .../core/storage/data_sync_linux_test.go | 30 ++++++++++++++++++ seaweed-block/core/storage/data_sync_other.go | 3 ++ 4 files changed, 66 insertions(+), 6 deletions(-) diff --git a/seaweed-block/core/storage/data_sync.go b/seaweed-block/core/storage/data_sync.go index 91190f600d..89105d9272 100644 --- a/seaweed-block/core/storage/data_sync.go +++ b/seaweed-block/core/storage/data_sync.go @@ -27,15 +27,38 @@ func newDataFileSync(f *os.File) (func() error, error) { // Only newly-created files reach this hook: existing volume bytes are never // rewritten. Writing zeros (not fallocate) converts unwritten extents too. func prezeroNewStore(f *os.File, size int64) error { - switch mode := os.Getenv("SWBLOCK_PREZERO"); mode { - case "", "0": + mode := os.Getenv("SWBLOCK_ALLOCATION") + prezero := os.Getenv("SWBLOCK_PREZERO") + if prezero != "" && prezero != "0" && prezero != "1" { + return fmt.Errorf("storage: invalid SWBLOCK_PREZERO %q", prezero) + } + if prezero == "1" { + if mode != "" && mode != "prezero" { + return fmt.Errorf("storage: SWBLOCK_PREZERO conflicts with SWBLOCK_ALLOCATION %q", mode) + } + mode = "prezero" + } + switch mode { + case "", "sparse": return nil - case "1": + case "fallocate": + if err := fallocateFile(f, size); err != nil { + return err + } + if err := f.Sync(); err != nil { + return err + } + if err := verifyAllocatedFile(f, false); err != nil { + return err + } + log.Printf("storage: FIEMAP verified allocated file=%s bytes=%d (unwritten extents allowed)", f.Name(), size) + return nil + case "prezero": if err := dataSyncSupported(); err != nil { return err } default: - return fmt.Errorf("storage: invalid SWBLOCK_PREZERO %q", mode) + return fmt.Errorf("storage: invalid SWBLOCK_ALLOCATION %q", mode) } zero := make([]byte, 1<<20) for off := int64(0); off < size; { diff --git a/seaweed-block/core/storage/data_sync_linux.go b/seaweed-block/core/storage/data_sync_linux.go index 6e37a9e181..cbc07c8832 100644 --- a/seaweed-block/core/storage/data_sync_linux.go +++ b/seaweed-block/core/storage/data_sync_linux.go @@ -12,7 +12,9 @@ import ( // FIEMAP with SYNC resolves delayed allocation before inspecting the mapping. // Reject holes, unknown/delayed mappings and unwritten extents; fallocate alone // does not satisfy the initialized-file experiment's precondition. -func verifyInitializedFile(f *os.File) error { +func verifyInitializedFile(f *os.File) error { return verifyAllocatedFile(f, true) } + +func verifyAllocatedFile(f *os.File, written bool) error { info, err := f.Stat() if err != nil { return err @@ -40,7 +42,7 @@ func verifyInitializedFile(f *os.File) error { return fmt.Errorf("storage: uninitialized file at %d", covered) } for _, e := range m.Extents[:m.Mapped] { - if e.Logical > covered || e.Length == 0 || e.Logical+e.Length < e.Logical || e.Flags&(2|4|0x800) != 0 { + if e.Logical > covered || e.Length == 0 || e.Logical+e.Length < e.Logical || e.Flags&(2|4) != 0 || (written && e.Flags&0x800 != 0) { return fmt.Errorf("storage: hole or unwritten extent at %d (logical=%d flags=%#x)", covered, e.Logical, e.Flags) } next := e.Logical + e.Length @@ -55,3 +57,5 @@ func verifyInitializedFile(f *os.File) error { func dataSyncSupported() error { return nil } func fdatasyncFile(f *os.File) error { return unix.Fdatasync(int(f.Fd())) } + +func fallocateFile(f *os.File, size int64) error { return unix.Fallocate(int(f.Fd()), 0, 0, size) } diff --git a/seaweed-block/core/storage/data_sync_linux_test.go b/seaweed-block/core/storage/data_sync_linux_test.go index 520495e46d..0c76a670a2 100644 --- a/seaweed-block/core/storage/data_sync_linux_test.go +++ b/seaweed-block/core/storage/data_sync_linux_test.go @@ -189,3 +189,33 @@ func TestDataSyncSyscallProbe(t *testing.T) { t.Fatalf("readback: %v", e) } } + +func TestFallocateCreatesAllocatedUnwrittenVolume(t *testing.T) { + t.Setenv("SWBLOCK_SYNC", "fdatasync") + t.Setenv("SWBLOCK_PREZERO", "0") + t.Setenv("SWBLOCK_ALLOCATION", "fallocate") + path := filepath.Join(t.TempDir(), "volume") + s, e := CreateWALStore(path, 32, 4096) + if e != nil { + t.Fatal(e) + } + defer s.Close() + f, e := os.Open(path) + if e != nil { + t.Fatal(e) + } + defer f.Close() + if e = verifyAllocatedFile(f, false); e != nil { + t.Fatalf("fallocate left holes: %v", e) + } + if e = verifyInitializedFile(f); e == nil { + t.Fatal("fallocate unexpectedly reports every extent written") + } + if _, e = s.Recover(); e != nil { + t.Fatal(e) + } + b, e := s.Read(31) + if e != nil || !bytes.Equal(b, make([]byte, 4096)) { + t.Fatalf("unwritten extent bytes: %v", e) + } +} diff --git a/seaweed-block/core/storage/data_sync_other.go b/seaweed-block/core/storage/data_sync_other.go index fd456efdff..8469247cfe 100644 --- a/seaweed-block/core/storage/data_sync_other.go +++ b/seaweed-block/core/storage/data_sync_other.go @@ -12,3 +12,6 @@ func dataSyncSupported() error { } func fdatasyncFile(*os.File) error { return dataSyncSupported() } func verifyInitializedFile(*os.File) error { return dataSyncSupported() } + +func fallocateFile(*os.File, int64) error { return dataSyncSupported() } +func verifyAllocatedFile(*os.File, bool) error { return dataSyncSupported() } From 9fc77218b2c9677c7923b9d38350f75be58a7e0e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 01:15:39 -0800 Subject: [PATCH 06/12] test(storage): add isolated block replay helper for sync controls --- .../storage/data_sync_replay_linux_test.go | 148 ++++++++++++++++++ seaweed-block/docs/design/invariants.md | 2 +- 2 files changed, 149 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/storage/data_sync_replay_linux_test.go diff --git a/seaweed-block/core/storage/data_sync_replay_linux_test.go b/seaweed-block/core/storage/data_sync_replay_linux_test.go new file mode 100644 index 0000000000..758c95ffe8 --- /dev/null +++ b/seaweed-block/core/storage/data_sync_replay_linux_test.go @@ -0,0 +1,148 @@ +//go:build linux + +package storage + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "testing" +) + +// External dm-log-writes harness calls prepare/write, replays only through +// the post-sync ACK mark onto a fresh device, then calls verify. Without that +// block-layer harness this helper is not a power-loss test. +func TestDataSyncPowerLossReplayHelper(t *testing.T) { + root := os.Getenv("SWBLOCK_REPLAY_ROOT") + if root == "" { + t.Skip("requires isolated dm-log-writes replay harness") + } + phase, kind := os.Getenv("SWBLOCK_REPLAY_PHASE"), os.Getenv("SWBLOCK_REPLAY_CASE") + path := filepath.Join(root, "probe") + payload := bytes.Repeat([]byte{0x7d}, 4096) + if kind == "wal" { + switch phase { + case "prepare": + s, e := CreateWALStore(path, 32, 4096) + if e != nil { + t.Fatal(e) + } + if e = s.Close(); e != nil { + t.Fatal(e) + } + case "write": + s, e := OpenWALStore(path) + if e != nil { + t.Fatal(e) + } + s.DisableAutoFlushForRecoveryTest() + if _, e = s.Recover(); e != nil { + t.Fatal(e) + } + if _, e = s.Write(13, payload); e != nil { + t.Fatal(e) + } + if os.Getenv("SWBLOCK_REPLAY_DROP_SYNC") != "1" { + if _, e = s.Sync(); e != nil { + t.Fatal(e) + } + } + // Deliberately no Close: only the explicit Sync precedes the ACK mark. + case "verify": + s, e := OpenWALStore(path) + if e != nil { + t.Fatal(e) + } + defer s.Close() + if _, e = s.Recover(); e != nil { + t.Fatal(e) + } + b, e := s.Read(13) + if e != nil || !bytes.Equal(b, payload) { + t.Fatalf("REPLAY_BYTES_MISMATCH WAL: %v", e) + } + default: + t.Fatalf("unknown replay phase %q", phase) + } + } else { + switch phase { + case "prepare": + f, e := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600) + if e != nil { + t.Fatal(e) + } + defer f.Close() + switch kind { + case "written": + if _, e = f.WriteAt(make([]byte, 1<<20), 0); e != nil { + t.Fatal(e) + } + case "unwritten": + if e = fallocateFile(f, 1<<20); e != nil { + t.Fatal(e) + } + case "hole": + if e = f.Truncate(1 << 20); e != nil { + t.Fatal(e) + } + case "growth": + if _, e = f.WriteAt(make([]byte, 4096), 0); e != nil { + t.Fatal(e) + } + default: + t.Fatalf("unknown replay case %q", kind) + } + if e = f.Sync(); e != nil { + t.Fatal(e) + } + case "write": + f, e := os.OpenFile(path, os.O_RDWR, 0) + if e != nil { + t.Fatal(e) + } + defer f.Close() + if _, e = f.WriteAt(payload, 128<<10); e != nil { + t.Fatal(e) + } + if os.Getenv("SWBLOCK_REPLAY_DROP_SYNC") != "1" { + if kind == "growth" { + e = f.Sync() + } else { + var sync func() error + sync, e = newDataFileSync(f) + if e == nil { + e = sync() + } + } + if e != nil { + t.Fatal(e) + } + } + case "verify": + f, e := os.Open(path) + if e != nil { + t.Fatal(e) + } + defer f.Close() + b := make([]byte, 4096) + n, e := f.ReadAt(b, 128<<10) + if e != nil || n != len(b) || !bytes.Equal(b, payload) { + t.Fatalf("REPLAY_BYTES_MISMATCH %s: n=%d err=%v", kind, n, e) + } + default: + t.Fatalf("unknown replay phase %q", phase) + } + } + if phase == "prepare" { + d, e := os.Open(root) + if e != nil { + t.Fatal(e) + } + defer d.Close() + if e = d.Sync(); e != nil { + t.Fatal(e) + } + } + fmt.Printf("REPLAY_%s_OK %s\n", phase, kind) +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7c12d9c6bd..3801ba765a 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -531,7 +531,7 @@ Notes: | ID | Invariant | Machine / transition | Enforced in | Tests | TLA+ | Status | |---|---|---|---|---|---|---| -| `INV-WAL-DATA-SYNC-001` | Default WAL/extent sync remains fsync. Linux `SWBLOCK_SYNC=fdatasync` selects data-only sync for WAL/extent data; descriptor/map/create/directory durability still uses fsync. `SWBLOCK_PREZERO=1` writes every byte only at create, fsyncs, then refuses holes/unwritten FIEMAP mappings. Existing files are never prezeroed. | M1 Create / Sync / Checkpoint | `data_sync.go`, `data_sync_linux.go`; `walstore_v3.go` Create; `walstore.go` data sync seams | `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten`, `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE | +| `INV-WAL-DATA-SYNC-001` | Default WAL/extent sync remains fsync. Linux `SWBLOCK_SYNC=fdatasync` selects data-only sync for WAL/extent data; descriptor/map/create/directory durability still uses fsync. `SWBLOCK_ALLOCATION=sparse|fallocate|prezero` selects allocation at create; fallocate retains unwritten extents. `SWBLOCK_PREZERO=1` aliases prezero, which writes every byte only at create, fsyncs, then refuses holes/unwritten FIEMAP mappings. Existing files are never prezeroed. | M1 Create / Sync / Checkpoint | `data_sync.go`, `data_sync_linux.go`; `walstore_v3.go` Create; `walstore.go` data sync seams | `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten`, `TestFallocateCreatesAllocatedUnwrittenVolume`, `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE | ## Part C. Change rules From 0b5a980bc8c674743e8a8134cb551f7fe55df98a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:21:58 -0800 Subject: [PATCH 07/12] test(storage): require sparse creation and refuse fallocate policy --- .../core/storage/data_sync_linux_test.go | 42 +++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/seaweed-block/core/storage/data_sync_linux_test.go b/seaweed-block/core/storage/data_sync_linux_test.go index 0c76a670a2..379c2a6248 100644 --- a/seaweed-block/core/storage/data_sync_linux_test.go +++ b/seaweed-block/core/storage/data_sync_linux_test.go @@ -190,32 +190,32 @@ func TestDataSyncSyscallProbe(t *testing.T) { } } -func TestFallocateCreatesAllocatedUnwrittenVolume(t *testing.T) { - t.Setenv("SWBLOCK_SYNC", "fdatasync") +func TestFallocateAllocationIsRefused(t *testing.T) { t.Setenv("SWBLOCK_PREZERO", "0") t.Setenv("SWBLOCK_ALLOCATION", "fallocate") + s, err := CreateWALStore(filepath.Join(t.TempDir(), "volume"), 32, 4096) + if err == nil { + s.Close() + t.Fatal("fallocate allocation must be refused") + } +} + +func TestDefaultCreatedVolumeStaysSparse(t *testing.T) { + t.Setenv("SWBLOCK_SYNC", "") + t.Setenv("SWBLOCK_PREZERO", "") + t.Setenv("SWBLOCK_ALLOCATION", "") path := filepath.Join(t.TempDir(), "volume") - s, e := CreateWALStore(path, 32, 4096) - if e != nil { - t.Fatal(e) + s, err := CreateWALStore(path, 8192, 4096) + if err != nil { + t.Fatal(err) } defer s.Close() - f, e := os.Open(path) - if e != nil { - t.Fatal(e) - } - defer f.Close() - if e = verifyAllocatedFile(f, false); e != nil { - t.Fatalf("fallocate left holes: %v", e) - } - if e = verifyInitializedFile(f); e == nil { - t.Fatal("fallocate unexpectedly reports every extent written") - } - if _, e = s.Recover(); e != nil { - t.Fatal(e) + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) } - b, e := s.Read(31) - if e != nil || !bytes.Equal(b, make([]byte, 4096)) { - t.Fatalf("unwritten extent bytes: %v", e) + stat := info.Sys().(*syscall.Stat_t) + if allocated := stat.Blocks * 512; allocated >= info.Size()/4 { + t.Fatalf("default volume lost sparse allocation: allocated=%d size=%d", allocated, info.Size()) } } From a1ce2a4d9e8d75898dc770fe8893f2518f9455f3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:22:34 -0800 Subject: [PATCH 08/12] fix(storage): default Linux data sync to fdatasync and retain sparse creation --- seaweed-block/core/storage/data_sync.go | 24 +++++++------------ seaweed-block/core/storage/data_sync_linux.go | 2 ++ seaweed-block/core/storage/data_sync_other.go | 2 ++ 3 files changed, 13 insertions(+), 15 deletions(-) diff --git a/seaweed-block/core/storage/data_sync.go b/seaweed-block/core/storage/data_sync.go index 89105d9272..ee6efd7a46 100644 --- a/seaweed-block/core/storage/data_sync.go +++ b/seaweed-block/core/storage/data_sync.go @@ -7,17 +7,21 @@ import ( "os" ) -// Experimental data-only sync applies to WAL/extent data. Descriptor slots, +// Data-only sync applies to WAL/extent data on Linux by default. Descriptor slots, // chunk maps, creation and directory operations retain full fsync. func newDataFileSync(f *os.File) (func() error, error) { - switch mode := os.Getenv("SWBLOCK_SYNC"); mode { - case "", "fsync": + mode := os.Getenv("SWBLOCK_SYNC") + if mode == "" { + mode = defaultDataFileSyncMode + } + switch mode { + case "fsync": return f.Sync, nil case "fdatasync": if err := dataSyncSupported(); err != nil { return nil, err } - log.Printf("storage: experimental WAL/extent sync=fdatasync file=%s", f.Name()) + log.Printf("storage: WAL/extent sync=fdatasync file=%s", f.Name()) return func() error { return fdatasyncFile(f) }, nil default: return nil, fmt.Errorf("storage: invalid SWBLOCK_SYNC %q", mode) @@ -42,17 +46,7 @@ func prezeroNewStore(f *os.File, size int64) error { case "", "sparse": return nil case "fallocate": - if err := fallocateFile(f, size); err != nil { - return err - } - if err := f.Sync(); err != nil { - return err - } - if err := verifyAllocatedFile(f, false); err != nil { - return err - } - log.Printf("storage: FIEMAP verified allocated file=%s bytes=%d (unwritten extents allowed)", f.Name(), size) - return nil + return fmt.Errorf("storage: fallocate allocation is disabled; use sparse or explicit prezero") case "prezero": if err := dataSyncSupported(); err != nil { return err diff --git a/seaweed-block/core/storage/data_sync_linux.go b/seaweed-block/core/storage/data_sync_linux.go index cbc07c8832..23273f33f4 100644 --- a/seaweed-block/core/storage/data_sync_linux.go +++ b/seaweed-block/core/storage/data_sync_linux.go @@ -12,6 +12,8 @@ import ( // FIEMAP with SYNC resolves delayed allocation before inspecting the mapping. // Reject holes, unknown/delayed mappings and unwritten extents; fallocate alone // does not satisfy the initialized-file experiment's precondition. +const defaultDataFileSyncMode = "fdatasync" + func verifyInitializedFile(f *os.File) error { return verifyAllocatedFile(f, true) } func verifyAllocatedFile(f *os.File, written bool) error { diff --git a/seaweed-block/core/storage/data_sync_other.go b/seaweed-block/core/storage/data_sync_other.go index 8469247cfe..7018474354 100644 --- a/seaweed-block/core/storage/data_sync_other.go +++ b/seaweed-block/core/storage/data_sync_other.go @@ -7,6 +7,8 @@ import ( "os" ) +const defaultDataFileSyncMode = "fsync" + func dataSyncSupported() error { return errors.New("storage: fdatasync/prezero experiment requires Linux") } From ccd94bd232b882b9144e98231c01190749a1719e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:23:32 -0800 Subject: [PATCH 09/12] docs(storage): align data sync and sparse creation contract --- seaweed-block/core/storage/data_sync_linux_test.go | 2 +- seaweed-block/docs/design/invariants.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/storage/data_sync_linux_test.go b/seaweed-block/core/storage/data_sync_linux_test.go index 379c2a6248..4540d255a1 100644 --- a/seaweed-block/core/storage/data_sync_linux_test.go +++ b/seaweed-block/core/storage/data_sync_linux_test.go @@ -159,7 +159,7 @@ func TestFdatasyncAcknowledgedWritesSurviveSIGKILL(t *testing.T) { } } -// Run under strace with the experiment environment unset/set to verify the +// Run under strace with the sync environment unset/set to verify the // syscall boundary independently of the selected function's Go identity. func TestDataSyncSyscallProbe(t *testing.T) { opts := WALStoreOptions{} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 3801ba765a..2c6706d810 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -531,7 +531,7 @@ Notes: | ID | Invariant | Machine / transition | Enforced in | Tests | TLA+ | Status | |---|---|---|---|---|---|---| -| `INV-WAL-DATA-SYNC-001` | Default WAL/extent sync remains fsync. Linux `SWBLOCK_SYNC=fdatasync` selects data-only sync for WAL/extent data; descriptor/map/create/directory durability still uses fsync. `SWBLOCK_ALLOCATION=sparse|fallocate|prezero` selects allocation at create; fallocate retains unwritten extents. `SWBLOCK_PREZERO=1` aliases prezero, which writes every byte only at create, fsyncs, then refuses holes/unwritten FIEMAP mappings. Existing files are never prezeroed. | M1 Create / Sync / Checkpoint | `data_sync.go`, `data_sync_linux.go`; `walstore_v3.go` Create; `walstore.go` data sync seams | `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten`, `TestFallocateCreatesAllocatedUnwrittenVolume`, `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE | +| `INV-WAL-DATA-SYNC-001` | Linux WAL/extent sync defaults to fdatasync; `SWBLOCK_SYNC=fsync` explicitly restores full data-file sync (other platforms retain fsync). descriptor/map/create/directory durability still uses fsync. `SWBLOCK_ALLOCATION=sparse|prezero` selects allocation at create; sparse is the default and fallocate is refused. `SWBLOCK_PREZERO=1` aliases prezero, which explicitly writes every byte only at create, fsyncs, then refuses holes/unwritten FIEMAP mappings. Existing files are never prezeroed. | M1 Create / Sync / Checkpoint | `data_sync.go`, `data_sync_linux.go`; `walstore_v3.go` Create; `walstore.go` data sync seams | `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten`, `TestFallocateCreatesAllocatedUnwrittenVolume`, `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE | ## Part C. Change rules From 802b159c9fabf1f43a3250a3bd93020f3db73a7c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:24:59 -0800 Subject: [PATCH 10/12] test(storage): distinguish sparse volume space from initialized WAL --- seaweed-block/core/storage/data_sync_linux_test.go | 2 +- seaweed-block/docs/design/invariants.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/storage/data_sync_linux_test.go b/seaweed-block/core/storage/data_sync_linux_test.go index 4540d255a1..c040f2287f 100644 --- a/seaweed-block/core/storage/data_sync_linux_test.go +++ b/seaweed-block/core/storage/data_sync_linux_test.go @@ -205,7 +205,7 @@ func TestDefaultCreatedVolumeStaysSparse(t *testing.T) { t.Setenv("SWBLOCK_PREZERO", "") t.Setenv("SWBLOCK_ALLOCATION", "") path := filepath.Join(t.TempDir(), "volume") - s, err := CreateWALStore(path, 8192, 4096) + s, err := CreateWALStore(path, 262144, 4096) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 2c6706d810..c94cedf021 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -531,7 +531,7 @@ Notes: | ID | Invariant | Machine / transition | Enforced in | Tests | TLA+ | Status | |---|---|---|---|---|---|---| -| `INV-WAL-DATA-SYNC-001` | Linux WAL/extent sync defaults to fdatasync; `SWBLOCK_SYNC=fsync` explicitly restores full data-file sync (other platforms retain fsync). descriptor/map/create/directory durability still uses fsync. `SWBLOCK_ALLOCATION=sparse|prezero` selects allocation at create; sparse is the default and fallocate is refused. `SWBLOCK_PREZERO=1` aliases prezero, which explicitly writes every byte only at create, fsyncs, then refuses holes/unwritten FIEMAP mappings. Existing files are never prezeroed. | M1 Create / Sync / Checkpoint | `data_sync.go`, `data_sync_linux.go`; `walstore_v3.go` Create; `walstore.go` data sync seams | `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten`, `TestFallocateCreatesAllocatedUnwrittenVolume`, `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE | +| `INV-WAL-DATA-SYNC-001` | Linux WAL/extent sync defaults to fdatasync; `SWBLOCK_SYNC=fsync` explicitly restores full data-file sync (other platforms retain fsync). Descriptor/map/create/directory durability still uses fsync. `SWBLOCK_ALLOCATION=sparse|prezero` selects allocation at create; sparse is the default and fallocate is refused. `SWBLOCK_PREZERO=1` aliases prezero, which explicitly writes every byte only at create, fsyncs, then refuses holes/unwritten FIEMAP mappings. Existing files are never prezeroed. | M1 Create / Sync / Checkpoint | `data_sync.go`, `data_sync_linux.go`; `walstore_v3.go` Create; `walstore.go` data sync seams | `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten`, `TestFallocateAllocationIsRefused`, `TestDefaultCreatedVolumeStaysSparse`, `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE | ## Part C. Change rules From 33904ff61d75dca413f04504a86fb058c08b5c61 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:36:11 -0800 Subject: [PATCH 11/12] test(storage): expose create-policy side effects and sync control lifetime gaps --- .../core/storage/data_sync_linux_test.go | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/seaweed-block/core/storage/data_sync_linux_test.go b/seaweed-block/core/storage/data_sync_linux_test.go index c040f2287f..2c87bcfa9d 100644 --- a/seaweed-block/core/storage/data_sync_linux_test.go +++ b/seaweed-block/core/storage/data_sync_linux_test.go @@ -11,6 +11,7 @@ import ( "os" "os/exec" "path/filepath" + "strings" "syscall" "testing" "time" @@ -64,6 +65,12 @@ func TestInitializedFileRejectsSparseAndUnwritten(t *testing.T) { func TestFdatasyncAcknowledgedWritesSurviveSIGKILL(t *testing.T) { if path := os.Getenv("SWBLOCK_TEST_SYNC_CRASH"); path != "" { + if os.Getenv("SWBLOCK_TEST_SYNC_CHILD_FAILURE") == "1" { + _ = os.Stdout.Close() + time.Sleep(30 * time.Millisecond) + fmt.Fprintln(os.Stderr, "SYNC_CHILD_FAILURE_SETTLED") + os.Exit(7) + } opts := WALStoreOptions{} if os.Getenv("SWBLOCK_TEST_STRICT") == "1" { opts.WMode = WModeStrict @@ -72,6 +79,9 @@ func TestFdatasyncAcknowledgedWritesSurviveSIGKILL(t *testing.T) { if e != nil { panic(e) } + if os.Getenv("SWBLOCK_PREZERO") == "0" && verifyInitializedFile(s.fd) == nil { + panic("sparse crash arm was silently prezeroed") + } s.DisableAutoFlushForRecoveryTest() if _, e = s.Recover(); e != nil { panic(e) @@ -219,3 +229,68 @@ func TestDefaultCreatedVolumeStaysSparse(t *testing.T) { t.Fatalf("default volume lost sparse allocation: allocated=%d size=%d", allocated, info.Size()) } } + +func TestInvalidCreatePolicyLeavesNoFileAndAllowsRetry(t *testing.T) { + for _, tc := range []struct{ name, sync, allocation, prezero string }{ + {"sync-before-prezero", "bad", "prezero", "1"}, + {"allocation", "fdatasync", "bad", "0"}, + {"fallocate", "fdatasync", "fallocate", "0"}, + {"prezero", "fdatasync", "", "bad"}, + {"conflict", "fdatasync", "sparse", "1"}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("SWBLOCK_SYNC", tc.sync) + t.Setenv("SWBLOCK_ALLOCATION", tc.allocation) + t.Setenv("SWBLOCK_PREZERO", tc.prezero) + path := filepath.Join(t.TempDir(), "volume") + s, err := CreateWALStore(path, 32, 4096) + if err == nil { + s.Close() + t.Fatal("invalid policy accepted") + } + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("invalid policy touched volume before refusal: %v", err) + } + t.Setenv("SWBLOCK_SYNC", "fdatasync") + t.Setenv("SWBLOCK_ALLOCATION", "sparse") + t.Setenv("SWBLOCK_PREZERO", "0") + s, err = CreateWALStore(path, 32, 4096) + if err != nil { + t.Fatalf("corrected retry failed: %v", err) + } + s.Close() + }) + } +} + +func TestSyncCrashFailureDiagnosticsWaitForStderr(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestFdatasyncAcknowledgedWritesSurviveSIGKILL$") + cmd.Env = append(os.Environ(), "SWBLOCK_TEST_SYNC_CRASH=", "SWBLOCK_TEST_SYNC_CHILD_FAILURE=1", "SWBLOCK_ALLOCATION=", "SWBLOCK_PREZERO=0") + out, err := cmd.CombinedOutput() + if err == nil || ctx.Err() != nil { + t.Fatalf("wrong failed-child outcome: %v %v", err, ctx.Err()) + } + if !strings.Contains(string(out), "SYNC_CHILD_FAILURE_SETTLED") || strings.Contains(string(out), "WARNING: DATA RACE") { + t.Fatalf("failure diagnostics read before child settlement: %s", out) + } +} + +func TestSyncControlsIgnoreAmbientAllocation(t *testing.T) { + for _, tc := range []struct{ name, test, allocation string }{ + {"prezero", "TestPrezeroCreatesInitializedVolume", "sparse"}, + {"crash-matrix", "TestFdatasyncAcknowledgedWritesSurviveSIGKILL", "prezero"}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^"+tc.test+"$") + cmd.Env = append(os.Environ(), "SWBLOCK_TEST_SYNC_CRASH=", "SWBLOCK_TEST_SYNC_CHILD_FAILURE=", "SWBLOCK_ALLOCATION="+tc.allocation, "SWBLOCK_PREZERO=0") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("ambient allocation contaminated control: %v: %s", err, out) + } + }) + } +} From 5a50d30dddbd5a1e8ed74408be949048c3b46ac3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:38:01 -0800 Subject: [PATCH 12/12] fix(storage): validate creation policy before file ownership and settle sync helpers --- seaweed-block/core/storage/data_sync.go | 62 +++++++++++++------ .../core/storage/data_sync_linux_test.go | 21 ++++--- seaweed-block/core/storage/walstore.go | 9 ++- seaweed-block/core/storage/walstore_v3.go | 3 + 4 files changed, 68 insertions(+), 27 deletions(-) diff --git a/seaweed-block/core/storage/data_sync.go b/seaweed-block/core/storage/data_sync.go index ee6efd7a46..c09081897c 100644 --- a/seaweed-block/core/storage/data_sync.go +++ b/seaweed-block/core/storage/data_sync.go @@ -9,50 +9,74 @@ import ( // Data-only sync applies to WAL/extent data on Linux by default. Descriptor slots, // chunk maps, creation and directory operations retain full fsync. -func newDataFileSync(f *os.File) (func() error, error) { +func configuredDataSyncMode() (string, error) { mode := os.Getenv("SWBLOCK_SYNC") if mode == "" { mode = defaultDataFileSyncMode } switch mode { case "fsync": - return f.Sync, nil + return mode, nil case "fdatasync": - if err := dataSyncSupported(); err != nil { - return nil, err - } - log.Printf("storage: WAL/extent sync=fdatasync file=%s", f.Name()) - return func() error { return fdatasyncFile(f) }, nil + return mode, dataSyncSupported() default: - return nil, fmt.Errorf("storage: invalid SWBLOCK_SYNC %q", mode) + return "", fmt.Errorf("storage: invalid SWBLOCK_SYNC %q", mode) } } -// Only newly-created files reach this hook: existing volume bytes are never -// rewritten. Writing zeros (not fallocate) converts unwritten extents too. -func prezeroNewStore(f *os.File, size int64) error { +func newDataFileSync(f *os.File) (func() error, error) { + mode, err := configuredDataSyncMode() + if err != nil { + return nil, err + } + if mode == "fsync" { + return f.Sync, nil + } + log.Printf("storage: WAL/extent sync=fdatasync file=%s", f.Name()) + return func() error { return fdatasyncFile(f) }, nil +} + +// Configuration errors must not create or initialize a volume file. +func validateNewStorePolicy() error { + if _, err := configuredDataSyncMode(); err != nil { + return err + } + _, err := configuredAllocationMode() + return err +} + +func configuredAllocationMode() (string, error) { mode := os.Getenv("SWBLOCK_ALLOCATION") prezero := os.Getenv("SWBLOCK_PREZERO") if prezero != "" && prezero != "0" && prezero != "1" { - return fmt.Errorf("storage: invalid SWBLOCK_PREZERO %q", prezero) + return "", fmt.Errorf("storage: invalid SWBLOCK_PREZERO %q", prezero) } if prezero == "1" { if mode != "" && mode != "prezero" { - return fmt.Errorf("storage: SWBLOCK_PREZERO conflicts with SWBLOCK_ALLOCATION %q", mode) + return "", fmt.Errorf("storage: SWBLOCK_PREZERO conflicts with SWBLOCK_ALLOCATION %q", mode) } mode = "prezero" } switch mode { case "", "sparse": - return nil + return "sparse", nil case "fallocate": - return fmt.Errorf("storage: fallocate allocation is disabled; use sparse or explicit prezero") + return "", fmt.Errorf("storage: fallocate allocation is disabled; use sparse or explicit prezero") case "prezero": - if err := dataSyncSupported(); err != nil { - return err - } + return mode, dataSyncSupported() default: - return fmt.Errorf("storage: invalid SWBLOCK_ALLOCATION %q", mode) + return "", fmt.Errorf("storage: invalid SWBLOCK_ALLOCATION %q", mode) + } +} + +// Only newly-created files reach this hook; existing bytes are never rewritten. +func prezeroNewStore(f *os.File, size int64) error { + mode, err := configuredAllocationMode() + if err != nil { + return err + } + if mode == "sparse" { + return nil } zero := make([]byte, 1<<20) for off := int64(0); off < size; { diff --git a/seaweed-block/core/storage/data_sync_linux_test.go b/seaweed-block/core/storage/data_sync_linux_test.go index 2c87bcfa9d..e91897834f 100644 --- a/seaweed-block/core/storage/data_sync_linux_test.go +++ b/seaweed-block/core/storage/data_sync_linux_test.go @@ -12,12 +12,14 @@ import ( "os/exec" "path/filepath" "strings" + "sync" "syscall" "testing" "time" ) func TestPrezeroCreatesInitializedVolume(t *testing.T) { + t.Setenv("SWBLOCK_ALLOCATION", "") t.Setenv("SWBLOCK_SYNC", "fdatasync") t.Setenv("SWBLOCK_PREZERO", "1") path := filepath.Join(t.TempDir(), "volume") @@ -112,7 +114,7 @@ func TestFdatasyncAcknowledgedWritesSurviveSIGKILL(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestFdatasyncAcknowledgedWritesSurviveSIGKILL$") - cmd.Env = append(os.Environ(), "SWBLOCK_SYNC=fdatasync", "SWBLOCK_PREZERO="+prezero, "SWBLOCK_TEST_SYNC_CRASH="+path, "SWBLOCK_TEST_EXTENT="+extent, "SWBLOCK_TEST_STRICT="+strict) + cmd.Env = append(os.Environ(), "SWBLOCK_ALLOCATION=", "SWBLOCK_SYNC=fdatasync", "SWBLOCK_PREZERO="+prezero, "SWBLOCK_TEST_SYNC_CRASH="+path, "SWBLOCK_TEST_EXTENT="+extent, "SWBLOCK_TEST_STRICT="+strict) out, e := cmd.StdoutPipe() if e != nil { t.Fatal(e) @@ -122,7 +124,10 @@ func TestFdatasyncAcknowledgedWritesSurviveSIGKILL(t *testing.T) { if e = cmd.Start(); e != nil { t.Fatal(e) } - defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }() + var waitOnce sync.Once + var waitErr error + wait := func() { waitOnce.Do(func() { waitErr = cmd.Wait() }) } + defer func() { _ = cmd.Process.Kill(); wait() }() scan := bufio.NewScanner(out) ready := false for scan.Scan() { @@ -132,20 +137,22 @@ func TestFdatasyncAcknowledgedWritesSurviveSIGKILL(t *testing.T) { } } if !ready { - t.Fatalf("no sync ACK: %v %s", scan.Err(), stderr.String()) + wait() + t.Fatalf("no sync ACK: scan=%v wait=%v %s", scan.Err(), waitErr, stderr.String()) } if e = cmd.Process.Kill(); e != nil { t.Fatal(e) } - e = cmd.Wait() - exit, ok := e.(*exec.ExitError) + wait() + exit, ok := waitErr.(*exec.ExitError) if !ok { - t.Fatalf("not killed: %v", e) + t.Fatalf("not killed: %v", waitErr) } status, ok := exit.Sys().(syscall.WaitStatus) if !ok || status.Signal() != syscall.SIGKILL { - t.Fatalf("wrong exit: %v", e) + t.Fatalf("wrong exit: %v", waitErr) } + t.Setenv("SWBLOCK_ALLOCATION", "") t.Setenv("SWBLOCK_SYNC", "fdatasync") t.Setenv("SWBLOCK_PREZERO", prezero) s, e := OpenWALStore(path) diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index bba62eb0a8..29104f42fb 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -209,6 +209,9 @@ func CreateWALStoreWithOptions(path string, numBlocks uint32, blockSize int, opt // Frozen constructor for legacy-format regression fixtures; public Create // never reaches it after activation. Removed from production in row 14a. func createLegacyWALStoreWithOptions(path string, numBlocks uint32, blockSize int, opts WALStoreOptions) (*WALStore, error) { + if err := validateNewStorePolicy(); err != nil { + return nil, err + } if blockSize == 0 { blockSize = DefaultBlockSize } @@ -254,7 +257,11 @@ func createLegacyWALStoreWithOptions(path string, numBlocks uint32, blockSize in _ = f.Close() return nil, fmt.Errorf("storage: fsync after create: %w", err) } - return openInitializedWithMetadata(path, f, &sb, metadata) + s, err := openInitializedWithMetadata(path, f, &sb, metadata) + if err != nil { + _ = f.Close() + } + return s, err } // OpenWALStore opens an existing store file WITHOUT recovering it. diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 716edeb1e9..9c61731325 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -231,6 +231,9 @@ func createWALStoreV3MapAtCursorForTest(path string, numBlocks, blockSize uint32 } func createWALStoreV3Configured(path string, numBlocks, blockSize uint32, walSize uint64, mode WMode, cursor, chunkBlocks uint64, opts WALStoreOptions) (*WALStore, error) { + if err := validateNewStorePolicy(); err != nil { + return nil, err + } d := descriptorV3{ ImplKind: ImplKindWALStore, ImplVersion: walStoreImplVersion3, VolumeSize: uint64(numBlocks) * uint64(blockSize), ExtentSize: 64 * 1024, BlockSize: blockSize,