phase167: add opt-in parallel WAL candidate

This commit is contained in:
pingqiu committed 2026-07-29 20:04:44 -07:00
1 parent 99bcd363a0
commit 8f8d369746
24 files changed
+3705 -23

No files matched your search

@@ -36,7 +36,7 @@
"additionalProperties": { "type": "string" }
},
"failbackRuntimeRPC": { "type": "boolean" },
"durableImpl": { "type": "string", "enum": ["walstore", "smartwal"] },
"durableImpl": { "type": "string", "enum": ["walstore", "smartwal", "parallel-walstore"] },
"durableWALMultiBlockRecords": { "type": "boolean" },
"durableWALRecoveryTestDisableFlusher": { "type": "boolean" },
"stateHostPath": { "type": "string" },
+1 -1
View File
@@ -84,7 +84,7 @@ func parseFlags(args []string) (flags, error) {
fs.StringVar(&f.launcherImage, "launcher-image", "sw-block:local", "G15d rendered blockvolume container image")
fs.StringVar(&f.launcherMasterAddr, "launcher-master-addr", "", "G15d master address used in rendered blockvolume args; defaults to listener address after bind")
fs.StringVar(&f.launcherDurableRoot, "launcher-durable-root", "/var/lib/sw-block", "G15d rendered blockvolume durable root base")
fs.StringVar(&f.launcherDurableImpl, "launcher-durable-impl", "walstore", "G15d rendered blockvolume durable implementation: walstore (default) or smartwal")
fs.StringVar(&f.launcherDurableImpl, "launcher-durable-impl", "walstore", "G15d rendered blockvolume durable implementation: walstore (default), smartwal, or opt-in parallel-walstore")
fs.BoolVar(&f.launcherWALMultiBlockRecords, "launcher-durable-wal-multiblock-records", false, "G15d render opt-in for experimental walstore multi-block WAL records; default false")
fs.BoolVar(&f.launcherWALRecoveryTestDisableFlusher, "launcher-durable-wal-recovery-test-disable-flusher", false, "test-only G15d render opt-in for blockvolume --durable-wal-recovery-test-disable-flusher; default false")
fs.StringVar(&f.launcherStateHostPath, "launcher-state-hostpath", "", "optional hostPath base mounted at the blockvolume durable root; empty keeps generated blockvolume state on throwaway emptyDir")
@@ -74,3 +74,24 @@ func TestPhase152_BlockvolumeDurableWALRecoveryTestDisableFlusherRequiresWalstor
t.Fatal("parseFlags succeeded; want walstore requirement error")
}
}
func TestPhase167_BlockvolumeParallelWALStoreIsExplicitOptIn(t *testing.T) {
args := append(phase150RequiredBlockvolumeArgs(),
"--durable-root=/tmp/sw-block",
"--durable-impl=parallel-walstore",
)
f, err := parseFlags(args)
if err != nil {
t.Fatalf("parseFlags: %v", err)
}
if f.durableImpl != "parallel-walstore" {
t.Fatalf("durableImpl=%q want parallel-walstore", f.durableImpl)
}
}
func TestPhase167_BlockvolumeRejectsUnknownDurableImpl(t *testing.T) {
args := append(phase150RequiredBlockvolumeArgs(), "--durable-impl=parallel-looking")
if _, err := parseFlags(args); err == nil {
t.Fatal("parseFlags succeeded; want unknown durable impl rejected")
}
}
+9 -3
View File
@@ -91,11 +91,12 @@ type flags struct {
// Durable-backend flags. When --durable-root is set, the iSCSI
// and NVMe providers use DurableProvider instead of memback.
// --durable-impl selects walstore or smartwal (default smartwal).
// --durable-impl selects smartwal, walstore, or the explicit
// parallel-walstore candidate (default smartwal).
// --durable-blocks + --durable-blocksize are used on first-time
// storage create.
durableRoot string
durableImpl string // "smartwal" | "walstore"
durableImpl string // "smartwal" | "walstore" | "parallel-walstore"
durableBlocks uint
durableBlockSize uint
durableWALMultiBlockRecords bool
@@ -165,7 +166,7 @@ func parseFlags(args []string) (flags, error) {
fs.UintVar(&f.nvmeMaxH2C, "nvme-max-h2c-data-length", 0, "NVMe/TCP MaxH2CDataLength in bytes. 0 preserves the target default")
fs.BoolVar(&f.allowExternalNVMeBind, "allow-external-nvme-bind", false, "allow NVMe to bind a non-loopback address; unauthenticated, intended only for explicit gates")
fs.StringVar(&f.durableRoot, "durable-root", "", "directory for persistent storage files; empty = memback (non-durable)")
fs.StringVar(&f.durableImpl, "durable-impl", "smartwal", "LogicalStorage impl: smartwal (default) or walstore; ignored unless --durable-root is set")
fs.StringVar(&f.durableImpl, "durable-impl", "smartwal", "LogicalStorage impl: smartwal (default), walstore, or opt-in parallel-walstore; ignored unless --durable-root is set")
fs.UintVar(&f.durableBlocks, "durable-blocks", 2048, "number of blocks per volume on first create (ignored when opening existing)")
fs.UintVar(&f.durableBlockSize, "durable-blocksize", 4096, "block size in bytes on first create")
fs.BoolVar(&f.durableWALMultiBlockRecords, "durable-wal-multiblock-records", false, "enable experimental walstore multi-block WAL records; default false; requires --durable-impl=walstore")
@@ -214,6 +215,11 @@ func parseFlags(args []string) (flags, error) {
if _, _, err := parseReplicationAckProfile(f.replicationAck); err != nil {
return flags{}, err
}
switch f.durableImpl {
case "smartwal", "walstore", "parallel-walstore":
default:
return flags{}, fmt.Errorf("--durable-impl=%q invalid; want smartwal, walstore, or parallel-walstore", f.durableImpl)
}
if f.durableWALMultiBlockRecords {
if f.durableRoot == "" {
return flags{}, fmt.Errorf("--durable-wal-multiblock-records requires --durable-root")
@@ -38,6 +38,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/storage/parallelwal"
"github.com/seaweedfs/seaweed-block/core/storage/smartwal"
)
@@ -49,6 +50,9 @@ type ImplName string
const (
ImplSmartWAL ImplName = "smartwal" // production default per PM direction
ImplWALStore ImplName = "walstore"
// ImplParallelWALStore is the explicit Phase 167 candidate. It remains
// opt-in until the full recovery, replication, and mounted close gates pass.
ImplParallelWALStore ImplName = "parallel-walstore"
)
// ErrImplKindMismatch is returned by Open when the configured
@@ -158,9 +162,9 @@ func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*Dura
if cfg.Impl == "" {
cfg.Impl = ImplSmartWAL
}
if cfg.Impl != ImplSmartWAL && cfg.Impl != ImplWALStore {
return nil, fmt.Errorf("durable: unknown impl %q (want %q or %q)",
cfg.Impl, ImplSmartWAL, ImplWALStore)
if cfg.Impl != ImplSmartWAL && cfg.Impl != ImplWALStore && cfg.Impl != ImplParallelWALStore {
return nil, fmt.Errorf("durable: unknown impl %q (want %q, %q, or %q)",
cfg.Impl, ImplSmartWAL, ImplWALStore, ImplParallelWALStore)
}
if cfg.BlockSize == 0 {
cfg.BlockSize = 4096
@@ -445,6 +449,14 @@ func (p *DurableProvider) verifyImplOnDisk(path string) error {
return fmt.Errorf("durable: read magic: %w", err)
}
diskImpl, ok := magicToImpl(string(magic))
if !ok {
// parallelwal has two independently checksummed headers. Slot 0
// may be torn while slot 1 remains authoritative, so fall back to
// the format's real header selector instead of rejecting on byte 0.
if err := parallelwal.ProbeStore(path); err == nil {
diskImpl, ok = ImplParallelWALStore, true
}
}
if !ok {
return fmt.Errorf("%w: unrecognized magic %q at %s",
ErrImplKindMismatch, string(magic), path)
@@ -465,6 +477,8 @@ func magicToImpl(magic string) (ImplName, bool) {
return ImplWALStore, true
case "SWAW":
return ImplSmartWAL, true
case "SWPW":
return ImplParallelWALStore, true
default:
return "", false
}
@@ -498,6 +512,12 @@ func (p *DurableProvider) openExisting(volumeID, path string) (*volHandle, error
return nil, fmt.Errorf("durable: smartwal.OpenStore %s: %w", path, err)
}
s = sw
case ImplParallelWALStore:
pw, err := parallelwal.OpenStore(path)
if err != nil {
return nil, fmt.Errorf("durable: parallelwal.OpenStore %s: %w", path, err)
}
s = pw
default:
return nil, fmt.Errorf("durable: unknown impl %q", p.cfg.Impl)
}
@@ -536,6 +556,12 @@ func (p *DurableProvider) createFresh(volumeID, path string) (*volHandle, error)
return nil, fmt.Errorf("durable: smartwal.CreateStore %s: %w", path, err)
}
s = sw
case ImplParallelWALStore:
pw, err := parallelwal.CreateStore(path, p.cfg.NumBlocks, p.cfg.BlockSize)
if err != nil {
return nil, fmt.Errorf("durable: parallelwal.CreateStore %s: %w", path, err)
}
s = pw
default:
return nil, fmt.Errorf("durable: unknown impl %q", p.cfg.Impl)
}
@@ -1,6 +1,6 @@
// T3b Provider tests — mini plan §2 acceptance rows #1-#4, #8.
// Matrix-parameterized per Addendum A #1: every test iterates both
// walstore and smartwal impls.
// Matrix-parameterized per Addendum A #1: every test iterates all
// registered durable implementations.
package durable_test
@@ -17,10 +17,15 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/storage/parallelwal"
)
func implMatrix() []durable.ImplName {
return []durable.ImplName{durable.ImplSmartWAL, durable.ImplWALStore}
return []durable.ImplName{
durable.ImplSmartWAL,
durable.ImplWALStore,
durable.ImplParallelWALStore,
}
}
func TestPhase150_DurableProviderWALMultiBlockOptIn(t *testing.T) {
@@ -240,6 +245,8 @@ func TestT3b_DurableProvider_Open_SelectsImpl_Matrix(t *testing.T) {
expectMagic = "SWBK"
case durable.ImplSmartWAL:
expectMagic = "SWAW"
case durable.ImplParallelWALStore:
expectMagic = "SWPW"
}
if magic != expectMagic {
t.Errorf("on-disk magic=%q want %q (impl=%s)", magic, expectMagic, impl)
@@ -315,6 +322,68 @@ func TestT3b_DurableProvider_Open_ImplKindMismatch_FailsFast(t *testing.T) {
}
}
func TestDurableProviderParallelWALUsesDualHeaderProbe(t *testing.T) {
root := t.TempDir()
path := filepath.Join(root, "v1.bin")
s, err := parallelwal.CreateStoreWithConfig(path, parallelwal.Config{
NumBlocks: 16,
BlockSize: 4096,
LaneCount: 4,
StripeBlocks: 1,
SlotsPerLane: 128,
QueueDepth: 64,
})
if err != nil {
t.Fatal(err)
}
if _, err := s.Write(0, bytes.Repeat([]byte{0x71}, 4096)); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
f, err := os.OpenFile(path, os.O_RDWR, 0o644)
if err != nil {
t.Fatal(err)
}
if _, err := f.WriteAt([]byte("BAD!"), 0); err != nil {
_ = f.Close()
t.Fatal(err)
}
if err := f.Close(); err != nil {
t.Fatal(err)
}
id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplParallelWALStore,
StorageRoot: root,
BlockSize: 4096,
NumBlocks: 16,
}, newStubView(healthyProj(id)))
if err != nil {
t.Fatal(err)
}
defer p.Close()
raw, err := p.EnsureStorage("v1")
if err != nil {
t.Fatalf("EnsureStorage should recover from header slot 1: %v", err)
}
if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil {
t.Fatalf("RecoverVolume should select header slot 1: %v", err)
}
got, err := raw.Read(0)
if err != nil {
t.Fatal(err)
}
if got[0] != 0x71 {
t.Fatalf("recovered byte=%02x want=71", got[0])
}
}
// readFirstMagic reads the first 4 bytes of a file to peek magic.
func readFirstMagic(path string) (string, error) {
f, err := os.Open(path)
@@ -42,6 +42,7 @@ import (
"errors"
"fmt"
"log"
"sort"
"sync"
"sync/atomic"
"time"
@@ -149,11 +150,12 @@ type StorageBackend struct {
operational atomic.Bool
opEvidence atomic.Value // string
mu sync.Mutex
closed bool
observer WriteObserver // optional; nil = no replication fan-out
writeAck WriteAckPolicy
profile writeProfile
mu sync.Mutex
closed bool
observer WriteObserver // optional; nil = no replication fan-out
writeAck WriteAckPolicy
profile writeProfile
lbaWriteLocks [256]sync.Mutex
}
// NewStorageBackend constructs a backend. Starts NON-operational
@@ -556,6 +558,8 @@ func (b *StorageBackend) writeBytes(ctx context.Context, offset int64, p []byte)
chunkLen = available
}
writeLock := &b.lbaWriteLocks[lba%uint32(len(b.lbaWriteLocks))]
writeLock.Lock()
var block []byte
if inBlockOff == 0 && chunkLen == int(bs) {
// Full-block write: skip the read.
@@ -564,6 +568,7 @@ func (b *StorageBackend) writeBytes(ctx context.Context, offset int64, p []byte)
// Partial-block: RMW.
existing, err := b.storage.Read(lba)
if err != nil {
writeLock.Unlock()
return total, fmt.Errorf("durable: RMW read lba=%d: %w", lba, err)
}
block = make([]byte, bs)
@@ -571,10 +576,12 @@ func (b *StorageBackend) writeBytes(ctx context.Context, offset int64, p []byte)
copy(block[inBlockOff:], buf[:chunkLen])
}
if obs == nil && policy == WriteAckRequireObserverAck {
writeLock.Unlock()
return total, fmt.Errorf("%w: no write observer installed", ErrReplicationAckUnavailable)
}
lsn, err := b.storage.Write(lba, block)
writeLock.Unlock()
if err != nil {
return total, fmt.Errorf("durable: write lba=%d: %w", lba, err)
}
@@ -608,7 +615,9 @@ func (b *StorageBackend) writeFullBlockBatch(ctx context.Context, startLBA uint3
for i := range blocks {
blocks[i] = p[i*bs : (i+1)*bs]
}
unlock := b.lockLBARange(startLBA, blockCount)
lsns, err := batcher.WriteBatch(startLBA, blocks)
unlock()
if len(lsns) > 0 {
b.profile.recordBackendStorageWrite(len(lsns), true)
b.profile.recordBackendFullBlockBatch(len(lsns))
@@ -639,6 +648,27 @@ func (b *StorageBackend) writeFullBlockBatch(ctx context.Context, startLBA uint3
return len(p), nil
}
func (b *StorageBackend) lockLBARange(startLBA uint32, blockCount int) func() {
var used [256]bool
indices := make([]int, 0, blockCount)
for i := 0; i < blockCount; i++ {
index := int((startLBA + uint32(i)) % uint32(len(b.lbaWriteLocks)))
if !used[index] {
used[index] = true
indices = append(indices, index)
}
}
sort.Ints(indices)
for _, index := range indices {
b.lbaWriteLocks[index].Lock()
}
return func() {
for i := len(indices) - 1; i >= 0; i-- {
b.lbaWriteLocks[indices[i]].Unlock()
}
}
}
func (b *StorageBackend) observeWrite(ctx context.Context, lba uint32, lsn uint64, block []byte, obs WriteObserver, policy WriteAckPolicy) error {
// Replication fan-out (T4a-6 hook). Error is logged best-effort
// unless the ack policy requires observer acknowledgement.
@@ -1,5 +1,5 @@
// T3a adapter tests — matrix-parameterized per Addendum A #1.
// EVERY test runs against BOTH walstore and smartwal.Store so
// EVERY test runs against walstore, smartwal.Store, and parallelwal.Store so
// variant skew is caught at L1 instead of prod.
//
// Acceptance-criteria mapping (mini plan §2):
@@ -21,10 +21,13 @@ import (
"path/filepath"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/storage/memorywal"
"github.com/seaweedfs/seaweed-block/core/storage/parallelwal"
"github.com/seaweedfs/seaweed-block/core/storage/smartwal"
)
@@ -198,6 +201,180 @@ func logicalStorageFactories() []logicalStorageFactory {
return s
},
},
{
name: "parallelwal",
make: func(t *testing.T, numBlocks uint32, blockSize int) storage.LogicalStorage {
t.Helper()
path := filepath.Join(t.TempDir(), "parallelwal.bin")
s, err := parallelwal.CreateStoreWithConfig(path, parallelwal.Config{
NumBlocks: numBlocks,
BlockSize: blockSize,
LaneCount: 4,
StripeBlocks: 1,
SlotsPerLane: 128,
QueueDepth: 64,
})
if err != nil {
t.Fatalf("parallelwal.CreateStoreWithConfig: %v", err)
}
t.Cleanup(func() { _ = s.Close() })
return s
},
},
}
}
type firstReadGateStorage struct {
storage.LogicalStorage
reads atomic.Int32
entered chan struct{}
release chan struct{}
}
type firstReadGateBatchStorage struct {
*firstReadGateStorage
}
func (s *firstReadGateBatchStorage) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error) {
return s.LogicalStorage.(storage.WriteBatcher).WriteBatch(startLBA, blocks)
}
func (s *firstReadGateStorage) Read(lba uint32) ([]byte, error) {
if s.reads.Add(1) == 1 {
close(s.entered)
<-s.release
}
return s.LogicalStorage.Read(lba)
}
func TestStorageBackend_SerializesPartialRMWPerLBA(t *testing.T) {
base := storage.NewBlockStore(2, 4096)
gated := &firstReadGateStorage{
LogicalStorage: base,
entered: make(chan struct{}),
release: make(chan struct{}),
}
id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}
view := newStubView(healthyProj(id))
b := durable.NewStorageBackend(gated, view, id)
b.SetOperational(true, "test")
results := make(chan error, 2)
go func() {
_, err := b.Write(context.Background(), 0, []byte{0x11})
results <- err
}()
<-gated.entered
go func() {
_, err := b.Write(context.Background(), 1, []byte{0x22})
results <- err
}()
time.Sleep(50 * time.Millisecond)
if got := gated.reads.Load(); got != 1 {
t.Fatalf("partial RMW reads=%d before first write completed; want serialized single read", got)
}
close(gated.release)
for i := 0; i < 2; i++ {
if err := <-results; err != nil {
t.Fatal(err)
}
}
block, err := base.Read(0)
if err != nil {
t.Fatal(err)
}
if block[0] != 0x11 || block[1] != 0x22 {
t.Fatalf("partial RMW lost update: first bytes=%02x %02x", block[0], block[1])
}
}
func TestStorageBackend_SerializesPartialRMWAgainstFullBlockWrite(t *testing.T) {
base := storage.NewBlockStore(2, 4096)
gated := &firstReadGateStorage{
LogicalStorage: base,
entered: make(chan struct{}),
release: make(chan struct{}),
}
id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}
b := durable.NewStorageBackend(gated, newStubView(healthyProj(id)), id)
b.SetOperational(true, "test")
partialDone := make(chan error, 1)
go func() {
_, err := b.Write(context.Background(), 1, []byte{0x22})
partialDone <- err
}()
<-gated.entered
fullDone := make(chan error, 1)
go func() {
_, err := b.Write(context.Background(), 0, bytes.Repeat([]byte{0x55}, 4096))
fullDone <- err
}()
select {
case err := <-fullDone:
t.Fatalf("full-block write bypassed in-flight RMW: %v", err)
case <-time.After(50 * time.Millisecond):
}
close(gated.release)
if err := <-partialDone; err != nil {
t.Fatal(err)
}
if err := <-fullDone; err != nil {
t.Fatal(err)
}
block, err := base.Read(0)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(block, bytes.Repeat([]byte{0x55}, 4096)) {
t.Fatal("stale partial RMW overwrote the later full-block write")
}
}
func TestStorageBackend_SerializesPartialRMWAgainstBatchWrite(t *testing.T) {
base := memorywal.NewStore(4, 4096)
gated := &firstReadGateBatchStorage{firstReadGateStorage: &firstReadGateStorage{
LogicalStorage: base,
entered: make(chan struct{}),
release: make(chan struct{}),
}}
id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}
b := durable.NewStorageBackend(gated, newStubView(healthyProj(id)), id)
b.SetOperational(true, "test")
partialDone := make(chan error, 1)
go func() {
_, err := b.Write(context.Background(), 1, []byte{0x22})
partialDone <- err
}()
<-gated.entered
batchDone := make(chan error, 1)
go func() {
payload := append(bytes.Repeat([]byte{0x55}, 4096), bytes.Repeat([]byte{0x66}, 4096)...)
_, err := b.Write(context.Background(), 0, payload)
batchDone <- err
}()
select {
case err := <-batchDone:
t.Fatalf("batch write bypassed in-flight RMW: %v", err)
case <-time.After(50 * time.Millisecond):
}
close(gated.release)
if err := <-partialDone; err != nil {
t.Fatal(err)
}
if err := <-batchDone; err != nil {
t.Fatal(err)
}
for lba, want := range []byte{0x55, 0x66} {
block, err := base.Read(uint32(lba))
if err != nil {
t.Fatal(err)
}
if block[0] != want {
t.Fatalf("LBA %d byte=%02x want=%02x", lba, block[0], want)
}
}
}
@@ -634,14 +811,14 @@ func TestT3a_StorageBackend_Close_ReturnsErrBackendClosed(t *testing.T) {
}
}
// Stop-rule sanity — ensure every test ran against both impls.
// Stop-rule sanity — ensure every test ran against every registered impl.
func TestT3a_MatrixCoverage(t *testing.T) {
names := []string{}
for _, f := range logicalStorageFactories() {
names = append(names, f.name)
}
got := fmt.Sprint(names)
want := "[walstore smartwal]"
want := "[walstore smartwal parallelwal]"
if got != want {
t.Fatalf("matrix drifted: got %s want %s", got, want)
}
@@ -11,7 +11,7 @@
// 3. LargeSpanningWrite — multi-LBA single-write integrity
//
// All three tests matrix-parameterize via logicalStorageFactories()
// so walstore and smartwal are both exercised.
// so every registered durable implementation is exercised.
package durable_test
@@ -24,6 +24,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/storage/parallelwal"
"github.com/seaweedfs/seaweed-block/core/storage/smartwal"
)
@@ -133,6 +134,16 @@ func TestT3_Durable_RecoverThenServe(t *testing.T) {
create: func(p string) (storage.LogicalStorage, error) { return smartwal.CreateStore(p, numBlocks, blockSize) },
reopen: func(p string) (storage.LogicalStorage, error) { return smartwal.OpenStore(p) },
},
{
name: "parallelwal",
create: func(p string) (storage.LogicalStorage, error) {
return parallelwal.CreateStoreWithConfig(p, parallelwal.Config{
NumBlocks: numBlocks, BlockSize: blockSize, LaneCount: 4,
StripeBlocks: 1, SlotsPerLane: 128, QueueDepth: 64,
})
},
reopen: func(p string) (storage.LogicalStorage, error) { return parallelwal.OpenStore(p) },
},
}
for _, f := range factories {
+2 -2
View File
@@ -58,9 +58,9 @@ func RenderBlockVolumeDeployments(plan lifecycle.BlockVolumeWorkloadPlan, cfg K8
cfg.DurableImpl = "walstore"
}
switch cfg.DurableImpl {
case "walstore", "smartwal":
case "walstore", "smartwal", "parallel-walstore":
default:
return nil, fmt.Errorf("launcher: durable impl %q invalid; want walstore or smartwal", cfg.DurableImpl)
return nil, fmt.Errorf("launcher: durable impl %q invalid; want walstore, smartwal, or parallel-walstore", cfg.DurableImpl)
}
if cfg.StateHostPathBase != "" && path.Clean(cfg.DurableRootBase) != stateMountPath {
return nil, fmt.Errorf("launcher: state hostPath requires durable root base %q, got %q", stateMountPath, cfg.DurableRootBase)
@@ -118,6 +118,19 @@ func TestPhase34_K8sRendererRejectsUnknownDurableImpl(t *testing.T) {
}
}
func TestPhase167_K8sRendererAllowsParallelWALStoreOptIn(t *testing.T) {
manifests, err := RenderBlockVolumeDeployments(sampleWorkloadPlan(), K8sRenderConfig{
MasterAddr: "blockmaster.kube-system.svc.cluster.local:9333",
DurableImpl: "parallel-walstore",
})
if err != nil {
t.Fatal(err)
}
if got := string(manifests[0].YAML); !strings.Contains(got, "--durable-impl=parallel-walstore") {
t.Fatalf("manifest missing parallel-walstore opt-in:\n%s", got)
}
}
func TestG15d_K8sRenderer_RF2UsesDistinctNamesAndPorts(t *testing.T) {
manifests, err := RenderBlockVolumeDeployments(sampleWorkloadPlan(), K8sRenderConfig{MasterAddr: "m:9333"})
if err != nil {
+21
View File
@@ -50,6 +50,7 @@ type Receiver struct {
blocksSinceLastAck uint32
lastAckTime time.Time
baseInstalledUpper uint32 // highest base LBA installed; advisory only in BaseBatchAck
basePrepared bool
}
// NewReceiver constructs a receiver bound to the replica's substrate
@@ -159,6 +160,7 @@ func (r *Receiver) Run() (achievedLSN uint64, err error) {
r.session.SeedWalApplied(s.FromLSN)
r.recvFromLSN = s.FromLSN
r.appliedWalLSN = s.FromLSN
r.basePrepared = false
log.Printf("g7-debug: Receiver.Run frameSessionStart sessionID=%d fromLSN=%d targetLSN=%d numBlocks=%d", s.SessionID, s.FromLSN, s.TargetLSN, s.NumBlocks)
case frameBaseBlock:
@@ -170,6 +172,9 @@ func (r *Receiver) Run() (achievedLSN uint64, err error) {
if decErr != nil {
return 0, newFailure(FailureProtocol, PhaseRecvDispatch, decErr)
}
if prepErr := r.prepareBaseInstall(); prepErr != nil {
return 0, newFailure(FailureSubstrate, PhaseRecvApply, prepErr)
}
if _, applyErr := r.session.ApplyBaseBlock(lba, data); applyErr != nil {
log.Printf("g7-debug: Receiver.Run ApplyBaseBlock err lba=%d err=%v", lba, applyErr)
return 0, newFailure(FailureSubstrate, PhaseRecvApply,
@@ -221,6 +226,9 @@ func (r *Receiver) Run() (achievedLSN uint64, err error) {
return 0, newFailure(FailureProtocol, PhaseRecvDispatch,
errors.New("BaseDone before SessionStart"))
}
if prepErr := r.prepareBaseInstall(); prepErr != nil {
return 0, newFailure(FailureSubstrate, PhaseRecvApply, prepErr)
}
log.Printf("g7-debug: Receiver.Run frameBaseDone baseCount=%d walCount=%d", baseCount, walCount)
r.session.MarkBaseComplete()
// Mandatory final base-lane ack — base done means primary
@@ -282,6 +290,19 @@ func (r *Receiver) Run() (achievedLSN uint64, err error) {
}
}
func (r *Receiver) prepareBaseInstall() error {
if r.basePrepared {
return nil
}
if preparer, ok := r.store.(storage.BaseInstallPreparer); ok {
if err := preparer.BeginBaseInstall(); err != nil {
return fmt.Errorf("prepare BASE install: %w", err)
}
}
r.basePrepared = true
return nil
}
// shouldAck evaluates the cadence rule per docs/recovery-pin-floor-wire.md §3.
// Returns true on the FIRST trigger (K blocks accumulated OR T elapsed since
// last ack). Idempotent: returns false if neither K nor T threshold reached.
@@ -8,7 +8,7 @@ import (
)
func TestReceiver_SessionStart_UsesFromLSNAsBaseFrontierHint(t *testing.T) {
replica := storage.NewBlockStore(0, 4096)
replica := &basePreparingStore{LogicalStorage: storage.NewBlockStore(0, 4096)}
primaryConn, replicaConn := net.Pipe()
defer primaryConn.Close()
defer replicaConn.Close()
@@ -80,6 +80,19 @@ func TestReceiver_SessionStart_UsesFromLSNAsBaseFrontierHint(t *testing.T) {
if st.TargetLSN != basePinLSN {
t.Fatalf("TargetLSN legacy status alias=%d want BaseFrontierHint %d", st.TargetLSN, basePinLSN)
}
if replica.prepareCalls != 1 {
t.Fatalf("BeginBaseInstall calls=%d want=1 for empty BASE", replica.prepareCalls)
}
}
type basePreparingStore struct {
storage.LogicalStorage
prepareCalls int
}
func (s *basePreparingStore) BeginBaseInstall() error {
s.prepareCalls++
return nil
}
func TestReceiver_DurableProgressAck_DoesNotExceedDurableSyncFrontier(t *testing.T) {
@@ -7,6 +7,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/storage/memorywal"
"github.com/seaweedfs/seaweed-block/core/storage/parallelwal"
)
// LogicalStorage is re-aliased for brevity inside this _test package.
@@ -62,6 +63,25 @@ func implementations() []implFactory {
return memorywal.NewStore(numBlocks, blockSize)
},
},
{
name: "ParallelWAL",
fresh: func(t *testing.T, dir string, numBlocks uint32, blockSize int) LogicalStorage {
path := filepath.Join(dir, "parallelwal.bin")
s, err := parallelwal.CreateStoreWithConfig(path, parallelwal.Config{
NumBlocks: numBlocks,
BlockSize: blockSize,
LaneCount: 4,
StripeBlocks: 1,
SlotsPerLane: 128,
QueueDepth: 64,
})
if err != nil {
t.Fatalf("Create parallelwal: %v", err)
}
t.Cleanup(func() { _ = s.Close() })
return s
},
},
}
}
@@ -211,6 +211,13 @@ type LogicalStorage interface {
Close() error
}
// BaseInstallPreparer is an optional rebuild capability for substrates that
// stage BASE snapshots before making them authoritative. Recovery callers
// invoke it once before the first BASE block (or an empty BASE completion).
type BaseInstallPreparer interface {
BeginBaseInstall() error
}
// WriteBatcher is an optional LogicalStorage extension for contiguous
// full-block write batches. Each block still receives its own LSN and recovery
// entry; batching is only an execution optimization and must not change
@@ -0,0 +1,177 @@
# Parallel WAL Candidate
`parallelwal` is the explicit Phase 167 `LogicalStorage` candidate selected
with:
```text
--durable-impl=parallel-walstore
```
It is not the default backend. `smartwal` and `walstore` keep their existing
formats and behavior.
## Problem
The legacy WAL path assigns a global LSN and appends every write through one
whole-volume critical section. That gives simple ordering, but concurrent
independent-LBA writers still contend on one append owner.
This candidate separates physical append ownership from logical publication:
- an LBA maps deterministically to one lane;
- each lane owns a non-overlapping WAL region;
- lanes may execute positioned writes concurrently;
- a global completion ledger publishes only the contiguous LSN prefix.
Physical completion out of order is allowed. Logical success over an LSN hole
is not.
## File Format
One preallocated file contains:
```text
[4 KiB header A]
[4 KiB header B]
[lane 0 WAL ring]
...
[lane N WAL ring]
[block extent A]
[block extent B]
```
Each WAL record contains a 32-byte header followed by one complete block. The
record stores its global LSN, LBA, flags, payload length, data CRC, and record
CRC. Each lane's logical head and tail are monotonic; physical slot selection
uses `sequence % slotsPerLane`.
The alternating headers are CRC protected and include:
- generation;
- block and volume geometry;
- lane count, stripe mapping, record size, and ring capacity;
- global durable and checkpoint LSNs;
- global retained-WAL floor;
- durable head and tail for every lane.
- the currently authoritative extent.
Open chooses the highest valid generation. A damaged latest header may fall
back to the prior valid generation; a torn or CRC-invalid committed record
fails with typed `storage.ErrWALIntegrityFault`.
## Write And Publication
The store allocates global LSN and lane sequence under one short metadata lock.
Execution then moves to the LBA's lane:
1. same-lane requests wait for their exact lane sequence;
2. the owner writes the record to that lane's region;
3. completion enters the global ledger;
4. the ledger publishes consecutive completed LSNs from `H+1`;
5. the caller returns only after its LSN is published.
If LSN `N` fails, the store enters a terminal error state. A physically
completed `N+1` cannot return success or advance `H`.
`WriteBatch` reserves one contiguous global LSN range, groups requests by lane,
and uses at most one dispatcher per active lane. Same-LBA writes always map to
the same lane and remain ordered.
## Sync And Checkpoint
`Sync` first fences the highest LSN admitted when the call acquires the store
lock. It waits until that prefix is contiguously published or a terminal append
failure is known, then snapshots `H` and the per-lane published heads. It then:
1. fsyncs WAL writes;
2. writes the alternate header with `R=H`;
3. fsyncs the header;
4. returns without checkpointing when every lane remains below pressure.
When a lane exceeds its retained-slot threshold, `Sync` additionally:
1. writes only latest blocks with `LSN <= R` to the shared extent;
2. fsyncs the extent;
3. advances checkpoint and lane tails in the alternate header;
4. fsyncs that header;
5. advances `S` to the first LSN still honestly scannable.
No unstable record is copied into the checkpoint. No slot is reused before
the extent is durable and both header slots have been sealed with the recycled
tails, so fallback cannot scan a physical slot after it has been reused.
Rebuild BASE installation uses the inactive extent as a copy-on-write stage.
Before reusing that extent, a guard generation makes both valid headers point
at the current active extent, preserving header fallback. The stage is then
cleared, BASE blocks are written there, and any session-live WAL blocks are
overlaid before durability. The final alternate header switches
`ActiveExtent` only after the staged extent is fsynced. A crash or final-header
failure therefore leaves the prior header and prior acknowledged extent
authoritative. Normal WAL-pressure checkpoints keep using the active extent
because the WAL-first header preserves replay data.
`WriteExtentDirect` remains immediately readable as required by the shared
`LogicalStorage` contract; COW controls which extent recovery treats as
durable, not in-process visibility inside a rebuilding replica. The recovery
and authority layers must keep that replica non-ready until the terminal
barrier succeeds. A failed session is never evidence that the staged extent is
serviceable, and the next session resets it before reuse.
## Recovery
Recovery reads only records inside the durable lane head/tail ranges from the
selected header, validates every retained record, and merges lanes by global
LSN. It rejects:
- record CRC or data CRC mismatch;
- invalid LBA-to-lane mapping;
- duplicate committed LSN;
- record LSN above `R`;
- a hole in the required contiguous interval
`[max(checkpoint + 1, S), R]`.
Extent data supplies checkpointed blocks. Recovery validates all retained WAL
records, but records at or below the checkpoint remain catch-up history only;
they cannot replace newer BASE bytes installed directly into the extent.
Retained records above the checkpoint rebuild the live overlay and all
retained records remain eligible for `ScanLBAs`. Requests below `S` return
typed `storage.ErrWALRecycled`.
`ApplyEntry` honors the source LSN from `LogicalStorage`, including a first
entry above LSN 1. Such a jump is published only after the entry append
succeeds. It advances the retained-WAL floor `S`, not the checkpoint: recovery
still replays every physically retained record, while the unrepresented LSN
interval is not falsely advertised as catch-up history. `AdvanceFrontier` is
reserved for the rebuild path after direct extent installation and moves `S`
beyond that BASE frontier.
## Frontend Concurrency
Removing whole-volume serialization exposed an existing partial-write hazard:
two `Read -> overlay -> Write` operations against different byte ranges of one
block could lose one update. `StorageBackend` therefore serializes every write
to an LBA through striped locks: partial RMW, single full-block writes, and
full-block batches all share the same exclusion boundary. Full-block writes
still skip the read.
## Current Evidence And Limit
Run:
```bash
scripts/run-phase167-parallel-wal-candidate-gate.sh
```
The gate stress-tests header fallback, Sync admission fencing, out-of-order
completion, terminal lower-LSN failure and append drain, source-frontier
jumps, unsynced-tail discard, CRC failure, ring wrap, recovery merge,
BASE-versus-retained-WAL precedence, failed BASE commit rollback, abandoned
BASE-stage reset, direct-frontier retention, and adapter integration. It also
runs the canonical `LogicalStorage` contract and compares 1/2/4/8-writer
throughput against legacy `walstore`.
The current Windows positioned-I/O result does not meet the Phase 167
promotion thresholds. Multiple lanes are active and correctness gates pass,
but `performance_claim_allowed=false`. Do not describe this package as a
performance improvement until the same-run Linux/device gate meets the
single-writer and four-writer acceptance ratios.
@@ -0,0 +1,176 @@
package parallelwal
import (
"fmt"
"path/filepath"
"sort"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func BenchmarkPhase167ParallelWALContention(b *testing.B) {
const (
blockSize = 4096
numBlocks = 16384
)
for _, writers := range []int{1, 2, 4, 8} {
b.Run(fmt.Sprintf("writers_%d", writers), func(b *testing.B) {
s, err := CreateStoreWithConfig(filepath.Join(b.TempDir(), "store.bin"), Config{
NumBlocks: numBlocks,
BlockSize: blockSize,
LaneCount: 4,
StripeBlocks: 1,
SlotsPerLane: 4096,
RetainPerLane: 64,
QueueDepth: 256,
})
if err != nil {
b.Fatal(err)
}
b.Cleanup(func() { _ = s.Close() })
data := make([][]byte, writers)
for i := range data {
data[i] = make([]byte, blockSize)
data[i][0] = byte(i + 1)
}
latencies := make([]int64, b.N)
workerOps := make([]int, writers)
var firstErr error
var errOnce sync.Once
start := make(chan struct{})
var wg sync.WaitGroup
b.SetBytes(blockSize)
b.ResetTimer()
wallStart := time.Now()
for worker := 0; worker < writers; worker++ {
wg.Add(1)
go func(worker int) {
defer wg.Done()
<-start
for idx := worker; idx < b.N; idx += writers {
opStart := time.Now()
_, writeErr := s.Write(uint32(idx%numBlocks), data[worker])
latencies[idx] = time.Since(opStart).Nanoseconds()
if writeErr != nil {
errOnce.Do(func() { firstErr = writeErr })
return
}
workerOps[worker]++
}
}(worker)
}
close(start)
wg.Wait()
if firstErr == nil {
_, firstErr = s.Sync()
}
wallDuration := time.Since(wallStart)
b.StopTimer()
if firstErr != nil {
b.Fatal(firstErr)
}
if b.N >= writers {
for worker, ops := range workerOps {
if ops == 0 {
b.Fatalf("worker %d completed zero writes", worker)
}
}
}
activeLanes := 0
s.mu.RLock()
for laneID := 0; laneID < int(s.hdr.LaneCount); laneID++ {
if s.publishedHeads[laneID] > 0 {
activeLanes++
}
}
s.mu.RUnlock()
_, walTail, _ := s.Boundaries()
reportParallelLatencyPercentiles(b, latencies)
b.ReportMetric(float64(activeLanes), "active_lanes")
b.ReportMetric(float64(walTail), "wal_tail")
b.ReportMetric(float64(b.N)/wallDuration.Seconds(), "write_ops/s")
})
}
}
func BenchmarkPhase167LegacyWALContentionControl(b *testing.B) {
const (
blockSize = 4096
numBlocks = 16384
)
for _, writers := range []int{1, 2, 4, 8} {
b.Run(fmt.Sprintf("writers_%d", writers), func(b *testing.B) {
s, err := storage.CreateWALStore(filepath.Join(b.TempDir(), "store.bin"), numBlocks, blockSize)
if err != nil {
b.Fatal(err)
}
b.Cleanup(func() { _ = s.Close() })
data := make([][]byte, writers)
for i := range data {
data[i] = make([]byte, blockSize)
data[i][0] = byte(i + 1)
}
latencies := make([]int64, b.N)
start := make(chan struct{})
var firstErr error
var errOnce sync.Once
var wg sync.WaitGroup
b.SetBytes(blockSize)
b.ResetTimer()
wallStart := time.Now()
for worker := 0; worker < writers; worker++ {
wg.Add(1)
go func(worker int) {
defer wg.Done()
<-start
for idx := worker; idx < b.N; idx += writers {
opStart := time.Now()
_, writeErr := s.Write(uint32(idx%numBlocks), data[worker])
latencies[idx] = time.Since(opStart).Nanoseconds()
if writeErr != nil {
errOnce.Do(func() { firstErr = writeErr })
return
}
}
}(worker)
}
close(start)
wg.Wait()
if firstErr == nil {
_, firstErr = s.Sync()
}
wallDuration := time.Since(wallStart)
b.StopTimer()
if firstErr != nil {
b.Fatal(firstErr)
}
reportParallelLatencyPercentiles(b, latencies)
b.ReportMetric(float64(b.N)/wallDuration.Seconds(), "write_ops/s")
})
}
}
func reportParallelLatencyPercentiles(b *testing.B, samples []int64) {
b.Helper()
if len(samples) == 0 {
return
}
sort.Slice(samples, func(i, j int) bool { return samples[i] < samples[j] })
at := func(percent int) float64 {
idx := (len(samples)*percent + 99) / 100
if idx > 0 {
idx--
}
return float64(samples[idx])
}
b.ReportMetric(at(50), "p50_ns")
b.ReportMetric(at(95), "p95_ns")
b.ReportMetric(at(99), "p99_ns")
}
@@ -0,0 +1,206 @@
package parallelwal
import (
"encoding/binary"
"errors"
"fmt"
"hash/crc32"
"io"
"os"
)
const (
headerSize = 4096
headerSlots = 2
headerMagic = "SWPW"
headerVersion = 1
maxLaneCount = 16
laneHeadsOffset = 128
laneTailsOffset = laneHeadsOffset + maxLaneCount*8
headerCRCOffset = headerSize - 4
defaultLaneCount = 4
defaultLaneSlots = 4096
)
var (
errBadMagic = errors.New("parallelwal: bad magic")
errBadVersion = errors.New("parallelwal: unsupported version")
errBadHeader = errors.New("parallelwal: invalid header")
errBadGeometry = errors.New("parallelwal: invalid geometry")
)
type fileHeader struct {
Generation uint64
CreatedAt uint64
BlockSize uint32
NumBlocks uint32
LaneCount uint16
StripeBlocks uint16
RecordSize uint32
SlotsPerLane uint64
DurableLSN uint64
CheckpointLSN uint64
WALTail uint64
RetainPerLane uint64
ActiveExtent uint8
LaneHeads [maxLaneCount]uint64
LaneTails [maxLaneCount]uint64
}
func (h fileHeader) validate() error {
if h.BlockSize == 0 || h.NumBlocks == 0 {
return fmt.Errorf("%w: blockSize=%d numBlocks=%d", errBadGeometry, h.BlockSize, h.NumBlocks)
}
if h.LaneCount == 0 || h.LaneCount > maxLaneCount {
return fmt.Errorf("%w: laneCount=%d", errBadGeometry, h.LaneCount)
}
if h.StripeBlocks == 0 || h.SlotsPerLane == 0 {
return fmt.Errorf("%w: stripeBlocks=%d slotsPerLane=%d", errBadGeometry, h.StripeBlocks, h.SlotsPerLane)
}
wantRecordSize := uint64(recordHeaderSize) + uint64(h.BlockSize)
if wantRecordSize > uint64(^uint32(0)) || uint64(h.RecordSize) != wantRecordSize {
return fmt.Errorf("%w: recordSize=%d want=%d", errBadGeometry, h.RecordSize, wantRecordSize)
}
if h.CheckpointLSN > h.DurableLSN {
return fmt.Errorf("%w: checkpoint=%d durable=%d", errBadHeader, h.CheckpointLSN, h.DurableLSN)
}
for i := 0; i < int(h.LaneCount); i++ {
if h.LaneTails[i] > h.LaneHeads[i] || h.LaneHeads[i]-h.LaneTails[i] > h.SlotsPerLane {
return fmt.Errorf("%w: lane=%d tail=%d head=%d slots=%d",
errBadHeader, i, h.LaneTails[i], h.LaneHeads[i], h.SlotsPerLane)
}
}
if h.RetainPerLane == 0 || h.RetainPerLane >= h.SlotsPerLane {
return fmt.Errorf("%w: retainPerLane=%d slotsPerLane=%d", errBadGeometry, h.RetainPerLane, h.SlotsPerLane)
}
if h.ActiveExtent > 1 {
return fmt.Errorf("%w: activeExtent=%d", errBadGeometry, h.ActiveExtent)
}
return nil
}
func encodeHeader(h fileHeader) ([headerSize]byte, error) {
var buf [headerSize]byte
copy(buf[0:4], headerMagic)
binary.LittleEndian.PutUint16(buf[4:6], headerVersion)
binary.LittleEndian.PutUint16(buf[6:8], headerSize)
binary.LittleEndian.PutUint64(buf[8:16], h.Generation)
binary.LittleEndian.PutUint64(buf[16:24], h.CreatedAt)
binary.LittleEndian.PutUint32(buf[24:28], h.BlockSize)
binary.LittleEndian.PutUint32(buf[28:32], h.NumBlocks)
binary.LittleEndian.PutUint16(buf[32:34], h.LaneCount)
binary.LittleEndian.PutUint16(buf[34:36], h.StripeBlocks)
binary.LittleEndian.PutUint32(buf[36:40], h.RecordSize)
binary.LittleEndian.PutUint64(buf[40:48], h.SlotsPerLane)
binary.LittleEndian.PutUint64(buf[48:56], h.DurableLSN)
binary.LittleEndian.PutUint64(buf[56:64], h.CheckpointLSN)
binary.LittleEndian.PutUint64(buf[64:72], h.WALTail)
binary.LittleEndian.PutUint64(buf[72:80], h.RetainPerLane)
buf[80] = h.ActiveExtent
for i := 0; i < maxLaneCount; i++ {
binary.LittleEndian.PutUint64(buf[laneHeadsOffset+i*8:], h.LaneHeads[i])
binary.LittleEndian.PutUint64(buf[laneTailsOffset+i*8:], h.LaneTails[i])
}
if err := h.validate(); err != nil {
return buf, err
}
binary.LittleEndian.PutUint32(buf[headerCRCOffset:], crc32.ChecksumIEEE(buf[:headerCRCOffset]))
return buf, nil
}
func decodeHeader(buf []byte) (fileHeader, error) {
if len(buf) != headerSize {
return fileHeader{}, fmt.Errorf("%w: size=%d", errBadHeader, len(buf))
}
if string(buf[0:4]) != headerMagic {
return fileHeader{}, errBadMagic
}
if got := binary.LittleEndian.Uint16(buf[4:6]); got != headerVersion {
return fileHeader{}, fmt.Errorf("%w: got=%d want=%d", errBadVersion, got, headerVersion)
}
if got := binary.LittleEndian.Uint16(buf[6:8]); got != headerSize {
return fileHeader{}, fmt.Errorf("%w: headerSize=%d", errBadHeader, got)
}
gotCRC := binary.LittleEndian.Uint32(buf[headerCRCOffset:])
wantCRC := crc32.ChecksumIEEE(buf[:headerCRCOffset])
if gotCRC != wantCRC {
return fileHeader{}, fmt.Errorf("%w: CRC got=%08x want=%08x", errBadHeader, gotCRC, wantCRC)
}
h := fileHeader{
Generation: binary.LittleEndian.Uint64(buf[8:16]),
CreatedAt: binary.LittleEndian.Uint64(buf[16:24]),
BlockSize: binary.LittleEndian.Uint32(buf[24:28]),
NumBlocks: binary.LittleEndian.Uint32(buf[28:32]),
LaneCount: binary.LittleEndian.Uint16(buf[32:34]),
StripeBlocks: binary.LittleEndian.Uint16(buf[34:36]),
RecordSize: binary.LittleEndian.Uint32(buf[36:40]),
SlotsPerLane: binary.LittleEndian.Uint64(buf[40:48]),
DurableLSN: binary.LittleEndian.Uint64(buf[48:56]),
CheckpointLSN: binary.LittleEndian.Uint64(buf[56:64]),
WALTail: binary.LittleEndian.Uint64(buf[64:72]),
RetainPerLane: binary.LittleEndian.Uint64(buf[72:80]),
ActiveExtent: buf[80],
}
for i := 0; i < maxLaneCount; i++ {
h.LaneHeads[i] = binary.LittleEndian.Uint64(buf[laneHeadsOffset+i*8:])
h.LaneTails[i] = binary.LittleEndian.Uint64(buf[laneTailsOffset+i*8:])
}
if err := h.validate(); err != nil {
return fileHeader{}, err
}
return h, nil
}
func readBestHeader(f *os.File) (fileHeader, int, error) {
var best fileHeader
bestSlot := -1
var errs [headerSlots]error
for slot := 0; slot < headerSlots; slot++ {
buf := make([]byte, headerSize)
if _, err := f.ReadAt(buf, int64(slot*headerSize)); err != nil && !errors.Is(err, io.EOF) {
errs[slot] = err
continue
}
h, err := decodeHeader(buf)
if err != nil {
errs[slot] = err
continue
}
if bestSlot == -1 || h.Generation > best.Generation {
best = h
bestSlot = slot
}
}
if bestSlot == -1 {
return fileHeader{}, -1, fmt.Errorf("parallelwal: no valid header: slot0=%v slot1=%v", errs[0], errs[1])
}
return best, bestSlot, nil
}
// ProbeStore validates that path has at least one usable parallelwal header.
// It intentionally applies the same dual-header selection as OpenStore.
func ProbeStore(path string) error {
f, err := os.Open(path)
if err != nil {
return fmt.Errorf("parallelwal: probe open %s: %w", path, err)
}
defer f.Close()
if _, _, err := readBestHeader(f); err != nil {
return err
}
return nil
}
func writeHeaderAt(f *os.File, slot int, h fileHeader) error {
if slot < 0 || slot >= headerSlots {
return fmt.Errorf("parallelwal: header slot %d out of range", slot)
}
buf, err := encodeHeader(h)
if err != nil {
return err
}
if _, err := f.WriteAt(buf[:], int64(slot*headerSize)); err != nil {
return fmt.Errorf("parallelwal: write header slot %d: %w", slot, err)
}
return nil
}
@@ -0,0 +1,84 @@
package parallelwal
import (
"encoding/binary"
"fmt"
"hash/crc32"
)
const (
recordHeaderSize = 32
recordMagic = "PWR1"
recordVersion = 1
flagWrite = uint16(1)
)
type walRecord struct {
LSN uint64
LBA uint32
Flags uint16
Data []byte
}
func encodeRecord(rec walRecord, blockSize int) ([]byte, error) {
buf := make([]byte, recordHeaderSize+blockSize)
if err := encodeRecordInto(buf, rec, blockSize); err != nil {
return nil, err
}
return buf, nil
}
func encodeRecordInto(buf []byte, rec walRecord, blockSize int) error {
if len(rec.Data) != blockSize {
return fmt.Errorf("parallelwal: record data size %d != block size %d", len(rec.Data), blockSize)
}
if len(buf) != recordHeaderSize+blockSize {
return fmt.Errorf("parallelwal: encode buffer size %d != record size %d", len(buf), recordHeaderSize+blockSize)
}
clear(buf)
copy(buf[0:4], recordMagic)
binary.LittleEndian.PutUint16(buf[4:6], recordVersion)
binary.LittleEndian.PutUint16(buf[6:8], rec.Flags)
binary.LittleEndian.PutUint64(buf[8:16], rec.LSN)
binary.LittleEndian.PutUint32(buf[16:20], rec.LBA)
binary.LittleEndian.PutUint32(buf[20:24], uint32(blockSize))
binary.LittleEndian.PutUint32(buf[24:28], crc32.ChecksumIEEE(rec.Data))
copy(buf[recordHeaderSize:], rec.Data)
recordCRC := crc32.NewIEEE()
_, _ = recordCRC.Write(buf[:28])
_, _ = recordCRC.Write(buf[recordHeaderSize : recordHeaderSize+blockSize])
binary.LittleEndian.PutUint32(buf[28:32], recordCRC.Sum32())
return nil
}
func decodeRecord(buf []byte, blockSize int) (walRecord, error) {
if len(buf) != recordHeaderSize+blockSize {
return walRecord{}, fmt.Errorf("parallelwal: record size %d != %d", len(buf), recordHeaderSize+blockSize)
}
if string(buf[0:4]) != recordMagic {
return walRecord{}, fmt.Errorf("parallelwal: record bad magic")
}
if version := binary.LittleEndian.Uint16(buf[4:6]); version != recordVersion {
return walRecord{}, fmt.Errorf("parallelwal: record version %d", version)
}
if size := binary.LittleEndian.Uint32(buf[20:24]); size != uint32(blockSize) {
return walRecord{}, fmt.Errorf("parallelwal: record payload size %d != %d", size, blockSize)
}
data := make([]byte, blockSize)
copy(data, buf[recordHeaderSize:recordHeaderSize+blockSize])
if got, want := crc32.ChecksumIEEE(data), binary.LittleEndian.Uint32(buf[24:28]); got != want {
return walRecord{}, fmt.Errorf("parallelwal: data CRC got=%08x want=%08x", got, want)
}
recordCRC := crc32.NewIEEE()
_, _ = recordCRC.Write(buf[:28])
_, _ = recordCRC.Write(data)
if got, want := recordCRC.Sum32(), binary.LittleEndian.Uint32(buf[28:32]); got != want {
return walRecord{}, fmt.Errorf("parallelwal: record CRC got=%08x want=%08x", got, want)
}
return walRecord{
LSN: binary.LittleEndian.Uint64(buf[8:16]),
LBA: binary.LittleEndian.Uint32(buf[16:20]),
Flags: binary.LittleEndian.Uint16(buf[6:8]),
Data: data,
}, nil
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+22
View File
@@ -198,6 +198,19 @@ func (r *ReplicaListener) acceptLoop() {
func (r *ReplicaListener) handleConn(conn net.Conn) {
defer conn.Close()
lane := mutationLaneLive
basePrepared := false
prepareBaseInstall := func() error {
if basePrepared {
return nil
}
if preparer, ok := r.store.(storage.BaseInstallPreparer); ok {
if err := preparer.BeginBaseInstall(); err != nil {
return err
}
}
basePrepared = true
return nil
}
for {
msgType, payload, err := ReadMsg(conn)
@@ -303,8 +316,13 @@ func (r *ReplicaListener) handleConn(conn net.Conn) {
// Rebuild blocks are BASE-lane bytes. They must not enter the
// WAL apply path and must not advance R/S/H per block; the
// frontier is reconciled once, at MsgRebuildDone.
if err := prepareBaseInstall(); err != nil {
log.Printf("replica: prepare rebuild base: %v", err)
return
}
if err := r.store.WriteExtentDirect(lba, data); err != nil {
log.Printf("replica: apply rebuild base block: %v", err)
return
}
case MsgRebuildDone:
@@ -318,6 +336,10 @@ func (r *ReplicaListener) handleConn(conn net.Conn) {
lineage.SessionID, lineage.Epoch, lineage.EndpointVersion)
return
}
if err := prepareBaseInstall(); err != nil {
log.Printf("replica: prepare empty rebuild base: %v", err)
return
}
// The done message carries the engine's frozen base frontier hint.
// Advance the replica's frontier metadata without touching
// any block data — AdvanceFrontier only updates nextLSN/walHead.
@@ -98,6 +98,41 @@ writer and `6.48 MiB/s` for four writers (`0.131x` scaling); ACK wait dominates
the multi-writer path. Linux race, mounted NVMe/TCP, and same-run lab evidence
remain open. D3 parallel local WAL is now the active implementation target.
The first D3 candidate slice is implemented behind the explicit
`parallel-walstore` selector:
- one file contains alternating CRC headers, four fixed WAL rings, and dual
data extents; lane geometry, durable heads/tails, `R`, checkpoint, `S`, and
the authoritative extent are persisted;
- deterministic LBA lanes execute positioned writes independently while a
global ledger publishes only contiguous LSN completion;
- pressure-triggered checkpointing copies only `LSN <= R`, then advances
recyclable lane tails after extent durability;
- recovery merges durable lane records by LSN and fails closed on CRC,
mapping, duplicate, or committed-hole evidence;
- provider, blockvolume flag, launcher rendering, adapter/reopen matrices,
canonical `LogicalStorage`, source-LSN jumps, direct rebuild frontier, ring
wrap, and per-LBA serialization across partial/full/batch writes are covered;
- adversarial review drove explicit Sync admission fencing, terminal append
drain before close/recover, dual-header provider probing, checked persisted
geometry, and protection against retained pre-checkpoint WAL overriding
rebuilt BASE extents;
- rebuild BASE installation now clears and writes an inactive COW extent,
overlays session-live WAL, and switches the authoritative extent only in the
final fsynced header; failed commits retain prior acknowledged data and a new
session cannot inherit an abandoned BASE stage;
- `scripts/run-phase167-parallel-wal-candidate-gate.sh` passes the correctness
stress gate with multiple lanes and steady-state WAL recycle observed.
The candidate has not earned a performance claim. The latest Windows
positioned-I/O control, now including checkpoint/recycle work, measured
`84.02 MiB/s` for one candidate writer and `94.06 MiB/s` for four (`1.119x`
scaling), versus `345.27 MiB/s` and `275.77 MiB/s` for legacy `walstore`. The
gate therefore records
`performance_claim_allowed=false`. D4 Linux/device profiling and execution
redesign are required before RF3 or mounted promotion gates; the default
backend remains unchanged.
## Assumptions And Boundaries
- `walstore` remains the default backend until the candidate passes the full
@@ -174,10 +209,24 @@ remain open. D3 parallel local WAL is now the active implementation target.
- Allocate global LSN ranges centrally with minimal synchronization.
- Track completion in a contiguous frontier ledger so out-of-order lane
completion cannot advance `R` over a hole.
- Persist geometry, lane cursors, checkpoint, and durable frontier through
alternating CRC-protected headers. `Sync` may publish `R=N` only after every
record through `N` is complete and the corresponding lane writes are
durable; a lower-LSN failure terminal-faults the store instead of allowing a
higher lane to publish success.
- Keep one logical shared extent, materialized as two physical COW copies for
rebuild commit safety, and flush only the stable `LSN <= R` prefix. Extent
writeback, checkpoint advance, WAL recycling, `ApplyEntry`, and
`AdvanceFrontier` must preserve the same global ordering contract.
- Merge lane recovery scans by LSN and return the existing typed
`ErrWALRecycled`/recovery failures where the old contract requires them.
- Use a format-specific recovery scanner. Do not reuse legacy recovery logic
that mixes byte-ring cursors with logical LSNs.
- Keep lane count and mapping format on disk so reopen does not reinterpret
existing data.
- Serialize partial-block read-modify-write by LBA (or the same deterministic
stripe owner) so frontend concurrency cannot lose overlapping updates before
they reach the WAL.
### D4. Storage Execution Backend
@@ -0,0 +1,167 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="${1:-$(pwd)}"
ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-${ROOT}/results/phase167-parallel-wal-candidate-gate}"
SUMMARY="${ARTIFACT_DIR}/phase167-parallel-wal-candidate-summary.txt"
BENCH="${ARTIFACT_DIR}/parallel-wal-contention-benchmark.txt"
BENCHTIME="${SW_BLOCK_PHASE167_PARALLEL_WAL_BENCHTIME:-1000x}"
mkdir -p "${ARTIFACT_DIR}"
: >"${SUMMARY}"
write_summary() {
echo "$*" | tee -a "${SUMMARY}" >/dev/null
}
metric() {
local benchmark="$1"
local writers="$2"
local unit="$3"
awk -v prefix="${benchmark}/writers_${writers}-" -v unit="${unit}" '
index($1, prefix) == 1 {
for (i = 2; i <= NF; i++) {
if ($(i + 1) == unit) {
print $i
exit
}
}
}
' "${BENCH}"
}
require_metric() {
local value
value="$(metric "$1" "$2" "$3")"
if [[ -z "${value}" ]]; then
echo "missing metric benchmark=$1 writers=$2 unit=$3" >&2
exit 1
fi
printf '%s' "${value}"
}
ratio() {
awk -v numerator="$1" -v denominator="$2" 'BEGIN {
if (numerator <= 0 || denominator <= 0) exit 1
printf "%.3f", numerator / denominator
}'
}
if [[ ! "${BENCHTIME}" =~ ^[0-9]+x$ ]]; then
echo "SW_BLOCK_PHASE167_PARALLEL_WAL_BENCHTIME must be a fixed iteration count" >&2
exit 1
fi
iterations="${BENCHTIME%x}"
if (( iterations < 512 || iterations > 8192 )); then
echo "benchmark iterations must be between 512 and 8192" >&2
exit 1
fi
write_summary "phase167_parallel_wal_candidate_status=running"
write_summary "candidate=parallel-walstore"
write_summary "candidate_default=false"
write_summary "mounted_nvme_claim_allowed=false"
write_summary "performance_claim_allowed=false"
cd "${ROOT}"
go test ./core/storage ./core/storage/parallelwal ./core/recovery ./core/transport \
./core/frontend/durable ./core/launcher ./cmd/blockvolume ./cmd/blockmaster \
-count=1 >"${ARTIFACT_DIR}/affected-tests.log" 2>&1
write_summary "affected_tests=pass"
if command -v helm >/dev/null 2>&1; then
helm lint charts/seaweed-block \
--set compat.launcherDurableImplFlag=true \
--set blockmaster.durableImpl=parallel-walstore \
>"${ARTIFACT_DIR}/helm-lint.log" 2>&1
write_summary "helm_validation=lint"
else
python - <<'PY' >"${ARTIFACT_DIR}/helm-lint.log"
import json
with open("charts/seaweed-block/values.schema.json", encoding="utf-8") as handle:
schema = json.load(handle)
allowed = schema["properties"]["blockmaster"]["properties"]["durableImpl"]["enum"]
if "parallel-walstore" not in allowed:
raise SystemExit("parallel-walstore is absent from blockmaster.durableImpl enum")
print("schema enum accepts parallel-walstore; helm binary unavailable")
PY
write_summary "helm_validation=schema_only_no_helm"
fi
write_summary "helm_candidate_schema=pass"
go test ./core/storage/parallelwal \
-run 'Test(CreateSyncRecoverAndScan|CrossLaneCompletionPublishesContiguousLSNs|SyncFencesWritesAdmittedBeforeCall|LowerLSNFailureBlocksCompletedHigherLane|CloseDrainsActiveAppenderAfterTerminalFailure|RecoverRejectsActiveAppender|UnsyncedTailIgnoredAfterCrash|OpenFallsBackFromCorruptLatestHeader|CommittedRecordCorruptionFailsClosed|RecoveryRejectsInvalidCommittedRecordSemantics|ApplyEntryAcceptsSourceFrontierJump|FailedApplyEntryDoesNotPublishSourceFrontierJump|SourceFrontierJumpPersistsWithoutFalseCheckpoint|ConcurrentSameLBAWritesRemainOrdered|WriteBatchDispatchesAcrossLanesBeforePublishing|RingWrapRecyclesOnlyCheckpointedPrefix|AdvancedWALTailBeyondHeadSurvivesRecovery|RecoverReplaysDurableWALBeforeCheckpoint|DirectExtentFrontierPersistsWithoutSyntheticWAL|RetainedPreCheckpointWALDoesNotOverrideRebuiltExtent|BaseExtentHeaderFailureKeepsPriorAcknowledgedExtent|BeginBaseInstallClearsAbortedStage|AdvanceFrontierWithoutBaseStageKeepsExistingData|NextBaseStagePreservesHeaderFallbackToCurrentExtent|RecycledSlotsRemainRecoverableThroughHeaderFallback|HeaderValidationRejectsWrappedRecordSize)$' \
-count=50 >"${ARTIFACT_DIR}/correctness-stress.log" 2>&1
write_summary "correctness_stress=pass"
write_summary "dual_crc_header_fallback=pass"
write_summary "sync_admission_fence=pass"
write_summary "contiguous_completion_frontier=pass"
write_summary "lower_lsn_failure_fail_closed=pass"
write_summary "terminal_append_drain=pass"
write_summary "unsynced_tail_ignored=pass"
write_summary "committed_crc_corruption_fail_closed=pass"
write_summary "ring_wrap_retention=pass"
write_summary "stable_prefix_checkpoint=pass"
write_summary "rebuild_extent_precedence=pass"
write_summary "rebuild_cow_extent_commit=pass"
write_summary "failed_rebuild_keeps_acknowledged_extent=pass"
write_summary "aborted_rebuild_stage_reset=pass"
write_summary "reused_extent_header_fallback=pass"
write_summary "recycled_slot_header_fallback=pass"
write_summary "logical_storage_contract=pass"
write_summary "failed_source_jump_not_published=pass"
write_summary "source_jump_retention_floor=pass"
write_summary "record_semantics_validation=pass"
write_summary "persisted_geometry_overflow_validation=pass"
write_summary "partial_rmw_serialized=pass"
go test ./core/storage/parallelwal \
-run '^$' \
-bench '^BenchmarkPhase167(ParallelWALContention|LegacyWALContentionControl)$' \
-benchtime="${BENCHTIME}" \
-count=1 >"${BENCH}" 2>&1
for writers in 1 2 4 8; do
candidate_mibps="$(require_metric BenchmarkPhase167ParallelWALContention "${writers}" MB/s)"
candidate_p99="$(require_metric BenchmarkPhase167ParallelWALContention "${writers}" p99_ns)"
active_lanes="$(require_metric BenchmarkPhase167ParallelWALContention "${writers}" active_lanes)"
wal_tail="$(require_metric BenchmarkPhase167ParallelWALContention "${writers}" wal_tail)"
legacy_mibps="$(require_metric BenchmarkPhase167LegacyWALContentionControl "${writers}" MB/s)"
write_summary "candidate_writers_${writers}_mibps=${candidate_mibps}"
write_summary "candidate_writers_${writers}_p99_ns=${candidate_p99}"
write_summary "candidate_writers_${writers}_active_lanes=${active_lanes}"
write_summary "candidate_writers_${writers}_wal_tail=${wal_tail}"
write_summary "legacy_writers_${writers}_mibps=${legacy_mibps}"
done
active_four="$(require_metric BenchmarkPhase167ParallelWALContention 4 active_lanes)"
awk -v value="${active_four}" 'BEGIN { if (value < 2) exit 1 }'
write_summary "multiple_lanes_observed=true"
wal_tail_four="$(require_metric BenchmarkPhase167ParallelWALContention 4 wal_tail)"
awk -v value="${wal_tail_four}" 'BEGIN { if (value <= 1) exit 1 }'
write_summary "steady_state_recycle_observed=true"
candidate_1="$(require_metric BenchmarkPhase167ParallelWALContention 1 MB/s)"
candidate_4="$(require_metric BenchmarkPhase167ParallelWALContention 4 MB/s)"
legacy_1="$(require_metric BenchmarkPhase167LegacyWALContentionControl 1 MB/s)"
legacy_4="$(require_metric BenchmarkPhase167LegacyWALContentionControl 4 MB/s)"
single_ratio="$(ratio "${candidate_1}" "${legacy_1}")"
four_scaling="$(ratio "${candidate_4}" "${candidate_1}")"
four_vs_legacy="$(ratio "${candidate_4}" "${legacy_4}")"
write_summary "candidate_single_writer_vs_legacy_ratio=${single_ratio}"
write_summary "candidate_four_writer_scaling_ratio=${four_scaling}"
write_summary "candidate_four_writer_vs_legacy_ratio=${four_vs_legacy}"
claim_allowed="$(
awk -v single="${single_ratio}" -v scaling="${four_scaling}" 'BEGIN {
if (single >= 0.90 && scaling >= 1.50) print "true"; else print "false"
}'
)"
write_summary "performance_claim_allowed=${claim_allowed}"
if [[ "${claim_allowed}" == "true" ]]; then
write_summary "next_recommendation=rf3_and_mounted_candidate_gate"
else
write_summary "next_recommendation=local_execution_backend_redesign"
fi
write_summary "phase167_parallel_wal_candidate_status=ok"