fix(storage): expose immutable auto sync choice in durable status

This commit is contained in:
pingqiu committed 2026-11-20 12:56:27 -08:00
1 parent d14b66d0a6
commit 2816c191cd
8 files changed
+133 -32

No files matched your search

@@ -0,0 +1,50 @@
package durable_test
import (
"context"
"encoding/json"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
)
func TestDurableProvider_DataSyncStatus(t *testing.T) {
t.Setenv("SWBLOCK_SYNC", "fsync")
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 64}, v1View())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { p.Close() })
if _, err := p.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil {
t.Fatal(err)
}
be, err := p.Open(context.Background(), "v1")
if err != nil {
t.Fatal(err)
}
// Neither status nor Sync may re-read the environment during this open.
t.Setenv("SWBLOCK_SYNC", "invalid-after-open")
if _, err := be.Write(context.Background(), 0, make([]byte, 4096)); err != nil {
t.Fatal(err)
}
if err := be.Sync(context.Background()); err != nil {
t.Fatal(err)
}
raw, err := json.Marshal(p.DurableStatuses())
if err != nil {
t.Fatal(err)
}
var wire []struct {
DataSync *struct{ Mode, Reason string }
}
if err := json.Unmarshal(raw, &wire); err != nil {
t.Fatal(err)
}
if len(wire) != 1 || wire[0].DataSync == nil || wire[0].DataSync.Mode != "fsync" || !strings.Contains(wire[0].DataSync.Reason, "override") {
t.Fatalf("open-time data sync absent or changed: %s", raw)
}
}
@@ -291,6 +291,7 @@ type VolumeStatus struct {
Evidence string
Closed bool
WriteProfile WriteProfileStatus
DataSync *storage.DataSyncStatus `json:",omitempty"`
CheckpointPersistence *storage.CheckpointPersistenceStatus `json:",omitempty"`
// Chunk is the chunk layer's state and cut counters; walstore-chunk
// volumes only.
@@ -295,6 +295,11 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus
if c, ok := b.storage.(interface{ HolesSuspected() uint64 }); ok {
holes = c.HolesSuspected()
}
var dataSync *storage.DataSyncStatus
if reporter, ok := b.storage.(interface{ DataSyncPolicy() storage.DataSyncStatus }); ok {
snapshot := reporter.DataSyncPolicy()
dataSync = &snapshot
}
var checkpoint *storage.CheckpointPersistenceStatus
if reporter, ok := b.storage.(interface {
CheckpointPersistence() storage.CheckpointPersistenceStatus
@@ -348,6 +353,7 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus
Closed: closed,
WriteProfile: writeProfile,
CheckpointPersistence: checkpoint,
DataSync: dataSync,
}
}
+20 -6
View File
@@ -11,8 +11,8 @@ import (
// creation and directory operations retain full fsync.
func configuredDataSyncMode() (string, error) {
mode := os.Getenv("SWBLOCK_SYNC")
if mode == "" {
return "", nil
if mode == "" || mode == "auto" {
return "auto", nil
}
switch mode {
case "fsync":
@@ -30,22 +30,36 @@ func selectedDataSyncMode(f *os.File) (string, string, error) {
return "", "", err
}
reason := "explicit SWBLOCK_SYNC override"
if mode == "" {
if mode == "auto" {
mode, reason = defaultDataSyncMode(f)
}
return mode, reason, nil
}
// DataSyncStatus is immutable for the lifetime of an open volume.
type DataSyncStatus struct {
Mode string
Reason string
}
func (s *WALStore) DataSyncPolicy() DataSyncStatus { return s.dataSyncStatus }
func newDataFileSync(f *os.File) (func() error, error) {
sync, _, err := bindDataFileSync(f)
return sync, err
}
func bindDataFileSync(f *os.File) (func() error, DataSyncStatus, error) {
mode, reason, err := selectedDataSyncMode(f)
if err != nil {
return nil, err
return nil, DataSyncStatus{}, err
}
status := DataSyncStatus{Mode: mode, Reason: reason}
log.Printf("storage: WAL/extent sync=%s file=%s reason=%s", mode, f.Name(), reason)
if mode == "fsync" {
return f.Sync, nil
return f.Sync, status, nil
}
return func() error { return fdatasyncFile(f) }, nil
return func() error { return fdatasyncFile(f) }, status, nil
}
// Configuration errors must not create or initialize a volume file.
@@ -64,11 +64,13 @@ func requireWriteThrough(path string, visiting map[string]bool, depth int) error
}
return nil
}
// A dm queue alone does not establish the physical cache policy.
if _, err := os.Stat(filepath.Join(path, "dm")); err == nil {
return fmt.Errorf("dm backing devices unavailable")
} else if !os.IsNotExist(err) {
return fmt.Errorf("dm identity unavailable: %w", err)
// A virtual dm/md queue alone does not establish the physical cache policy.
for _, kind := range []string{"dm", "md"} {
if _, err := os.Stat(filepath.Join(path, kind)); err == nil {
return fmt.Errorf("%s backing devices unavailable", kind)
} else if !os.IsNotExist(err) {
return fmt.Errorf("%s identity unavailable: %w", kind, err)
}
}
cache, err := os.ReadFile(filepath.Join(path, "queue", "write_cache"))
if err != nil {
@@ -11,8 +11,8 @@ import (
func TestDeviceDataSyncPolicy(t *testing.T) {
for _, tc := range []struct {
name, cache, want string
partition, dm, mixed bool
name, cache, want string
partition, dm, md, mixed bool
}{
{name: "write-back", cache: "write back\n", want: "fsync"},
{name: "write-through", cache: "write through\n", want: "fdatasync"},
@@ -22,6 +22,9 @@ func TestDeviceDataSyncPolicy(t *testing.T) {
{name: "dm-through", cache: "write through\n", want: "fdatasync", dm: true},
{name: "dm-mixed", cache: "write through\n", want: "fsync", dm: true, mixed: true},
{name: "dm-missing", want: "fsync", dm: true},
{name: "md-through", cache: "write through\n", want: "fdatasync", md: true},
{name: "md-mixed", cache: "write through\n", want: "fsync", md: true, mixed: true},
{name: "md-missing", want: "fsync", md: true},
} {
t.Run(tc.name, func(t *testing.T) {
root := t.TempDir()
@@ -54,9 +57,14 @@ func TestDeviceDataSyncPolicy(t *testing.T) {
put(disk+"/nvme0n1p1/partition", "1\n")
device = disk + "/nvme0n1p1"
}
if tc.dm {
if tc.dm || tc.md {
device = "devices/virtual/block/dm-0"
put(device+"/dm/name", "volume")
if tc.md {
device = "devices/virtual/block/md0"
put(device+"/md/level", "raid1")
} else {
put(device+"/dm/name", "volume")
}
// A virtual queue's advertised policy is not a backing-device proof.
put(device+"/queue/write_cache", "write through\n")
link(disk, device+"/slaves/nvme0n1")
@@ -65,7 +73,7 @@ func TestDeviceDataSyncPolicy(t *testing.T) {
link("devices/pci/block/nvme1n1", device+"/slaves/nvme1n1")
}
}
if tc.cache != "" || tc.dm {
if tc.cache != "" || tc.dm || tc.md {
link(device, "dev/block/8:1")
}
mode, reason := deviceDataSyncMode(root, 8, 1)
@@ -94,7 +102,7 @@ func TestExplicitDataSyncPolicyDoesNotInspectDevice(t *testing.T) {
}
func TestDeviceDataSyncMalformedTopology(t *testing.T) {
for _, shape := range []string{"empty-dm", "cycle", "unreadable-cache"} {
for _, shape := range []string{"empty-dm", "empty-md", "cycle", "unreadable-cache"} {
t.Run(shape, func(t *testing.T) {
root := t.TempDir()
device := filepath.Join(root, "dev/block/8:1")
@@ -102,8 +110,12 @@ func TestDeviceDataSyncMalformedTopology(t *testing.T) {
t.Fatal(err)
}
switch shape {
case "empty-dm":
if err := os.Mkdir(filepath.Join(device, "dm"), 0755); err != nil {
case "empty-dm", "empty-md":
kind := "dm"
if shape == "empty-md" {
kind = "md"
}
if err := os.Mkdir(filepath.Join(device, kind), 0755); err != nil {
t.Fatal(err)
}
case "cycle":
@@ -138,3 +150,16 @@ func TestDefaultDataSyncUnknownFileFallsBack(t *testing.T) {
t.Fatalf("fallback: %s %q %v", mode, reason, err)
}
}
func TestExplicitAutoDataSyncPolicy(t *testing.T) {
t.Setenv("SWBLOCK_SYNC", "auto")
f, err := os.CreateTemp(t.TempDir(), "volume")
if err != nil {
t.Fatal(err)
}
f.Close()
mode, reason, err := selectedDataSyncMode(f)
if err != nil || mode != "fsync" || !strings.Contains(reason, "unavailable") {
t.Fatalf("auto fallback: %s %q %v", mode, reason, err)
}
}
+15 -12
View File
@@ -47,6 +47,8 @@ import (
// - Online resize
// - Compaction (the WAL is bounded but periodic checkpoints free space)
type WALStore struct {
dataSyncStatus DataSyncStatus // selected before publication; never changes in this open
// recoveryWarnings and holesSuspected: the last Recover's typed
// warnings, and how many recoveries found a WAL hole (issue #51).
recoveryWarnings []string
@@ -205,24 +207,25 @@ func OpenWALStoreWithOptions(path string, opts WALStoreOptions) (*WALStore, erro
// openInitializedV3 binds native state before starting background workers.
func openInitializedV3(path string, f *os.File, sb *superblock, metadata BlockMetadata, init func(*WALStore) error) (*WALStore, error) {
dataSync, err := newDataFileSync(f)
dataSync, syncStatus, err := bindDataFileSync(f)
if err != nil {
return nil, err
}
dm := newDirtyMap(64) // 64 shards is plenty for Phase 07 demo workloads
s := &WALStore{
metadata: metadata,
path: path,
fd: f,
sb: sb,
dm: dm,
extentBase: sb.WALOffset + sb.WALSize,
nextLSN: sb.WALCheckpointLSN + 1,
syncedLSN: sb.WALCheckpointLSN,
walTail: retainedLSNFromCheckpoint(sb.WALCheckpointLSN),
walHead: sb.WALCheckpointLSN,
checkpointLSN: sb.WALCheckpointLSN,
metadata: metadata,
dataSyncStatus: syncStatus,
path: path,
fd: f,
sb: sb,
dm: dm,
extentBase: sb.WALOffset + sb.WALSize,
nextLSN: sb.WALCheckpointLSN + 1,
syncedLSN: sb.WALCheckpointLSN,
walTail: retainedLSNFromCheckpoint(sb.WALCheckpointLSN),
walHead: sb.WALCheckpointLSN,
checkpointLSN: sb.WALCheckpointLSN,
}
if s.nextLSN < 1 {
+1 -1
View File
@@ -563,7 +563,7 @@ Notes:
| ID | Invariant | Machine / transition | Enforced in | Tests | TLA+ | Status |
|---|---|---|---|---|---|---|
| `INV-WAL-DATA-SYNC-001` | At volume open, Linux WAL/extent sync selects fdatasync only when every resolved backing device advertises write through; write back or unknown/unreadable device policy selects fsync. `SWBLOCK_SYNC=fsync|fdatasync` explicitly overrides detection (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 | `TestDeviceDataSyncPolicy`, `TestExplicitDataSyncPolicyDoesNotInspectDevice`, `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten`, `TestFallocateAllocationIsRefused`, `TestDefaultCreatedVolumeStaysSparse`, `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE |
| `INV-WAL-DATA-SYNC-001` | `SWBLOCK_SYNC=auto` is the default. Once at volume open, Linux WAL/extent sync selects fdatasync only when every resolved backing device advertises write through; write back or unknown/unreadable device policy selects fsync. `SWBLOCK_SYNC=fsync|fdatasync` explicitly overrides detection (other platforms retain fsync). The selected mode and reason are logged and exposed in durable status without mid-life reselection. Descriptor/map/create/directory durability still uses fsync. `SWBLOCK_ALLOCATION=sparse|prezero` selects allocation at create; sparse is the default and fallocate is refused. `SWBLOCK_PREZERO=1` aliases prezero, which explicitly writes every byte only at create, fsyncs, then refuses holes/unwritten FIEMAP mappings. Existing files are never prezeroed. | M1 Create / Sync / Checkpoint | `data_sync.go`, `data_sync_linux.go`; `walstore_v3.go` Create; `walstore.go` data sync seams | `TestDurableProvider_DataSyncStatus` (`core/frontend/durable/data_sync_status_test.go`), `TestExplicitAutoDataSyncPolicy`, `TestDeviceDataSyncPolicy`, `TestExplicitDataSyncPolicyDoesNotInspectDevice`, `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