phase167: establish concurrent write baseline

This commit is contained in:
pingqiu committed 2026-07-29 16:36:32 -07:00
1 parent 19cce945e5
commit d84ca10bdd
12 files changed
+827 -29

No files matched your search

@@ -251,6 +251,8 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus
writeProfile.WALAppendOps = storageProfile.WALAppendOps
writeProfile.WALAppendBytes = storageProfile.WALAppendBytes
writeProfile.WALAppendDurationNanos = storageProfile.WALAppendDurationNanos
writeProfile.WALAppendLockWaitOps = storageProfile.WALAppendLockWaitOps
writeProfile.WALAppendLockWaitNanos = storageProfile.WALAppendLockWaitNanos
writeProfile.WALAppendWriteAtCalls = storageProfile.WALAppendWriteAtCalls
writeProfile.WALAppendWriteAtBytes = storageProfile.WALAppendWriteAtBytes
writeProfile.WALAppendWriteAtMaxBytes = storageProfile.WALAppendWriteAtMaxBytes
@@ -38,6 +38,8 @@ type WriteProfileStatus struct {
WALAppendOps uint64
WALAppendBytes uint64
WALAppendDurationNanos uint64
WALAppendLockWaitOps uint64
WALAppendLockWaitNanos uint64
WALAppendWriteAtCalls uint64
WALAppendWriteAtBytes uint64
WALAppendWriteAtMaxBytes uint64
+195 -12
View File
@@ -2,6 +2,7 @@ package replication
import (
"context"
"errors"
"fmt"
"log"
"sort"
@@ -35,6 +36,25 @@ type RuntimeRecoveryRequest struct {
BasePinLSN uint64
}
// VolumeStats is a read-only contention snapshot for write-path gates. These
// counters describe the current serialized implementation; they do not affect
// acknowledgement or ordering semantics.
type VolumeStats struct {
WriteOps uint64
WriteLockWaitNanos uint64
WriteFanoutNanos uint64
SyncOps uint64
SyncOrderWaitNanos uint64
SyncLockWaitNanos uint64
SyncDurationNanos uint64
}
type orderedLocalWrite struct {
ctx context.Context
write LocalWrite
result chan error
}
type RuntimeRecoveryStatus struct {
State string
ReplicaID string
@@ -68,11 +88,25 @@ type ReplicationVolume struct {
durabilityMode DurabilityMode // set via SetDurabilityMode; default is BestEffort
// replayedGens counts UpdateReplicaSet calls dropped as stale
// (generation > 0 && generation <= lastAppliedGeneration). Exposed
// only to same-package tests for now; a public Stats() or
// Prometheus hook is a future observability pass.
// (generation > 0 && generation <= lastAppliedGeneration).
replayedGens atomic.Uint64
// Write/sync counters expose the current whole-volume serialization cost.
writeOps atomic.Uint64
writeWait atomic.Uint64
writeFanout atomic.Uint64
syncOps atomic.Uint64
syncOrderWait atomic.Uint64
syncWait atomic.Uint64
syncDuration atomic.Uint64
orderMu sync.Mutex
nextShipLSN uint64
pending map[uint64]*orderedLocalWrite
draining bool
orderClosed bool
progress chan struct{}
// Probe loop integration. Set once via ConfigureProbeLoop;
// started via StartProbeLoop after primary admit; stopped FIRST
// during Close (before peer teardown) so an in-flight probe
@@ -127,6 +161,9 @@ func NewReplicationVolume(volumeID string, store storage.LogicalStorage) *Replic
coord: NewDurabilityCoordinator(),
peers: make(map[string]*ReplicaPeer),
durabilityMode: DurabilityBestEffort, // zero value; explicit for clarity
nextShipLSN: store.NextLSN(),
pending: make(map[uint64]*orderedLocalWrite),
progress: make(chan struct{}),
}
}
@@ -203,7 +240,19 @@ func (v *ReplicationVolume) Sync(ctx context.Context, targetLSN uint64) error {
if err := ctx.Err(); err != nil {
return err
}
start := time.Now()
orderStart := time.Now()
if err := v.waitUntilShipped(ctx, targetLSN); err != nil {
return err
}
v.syncOrderWait.Add(replicationDurationNanos(time.Since(orderStart)))
lockStart := time.Now()
v.mu.Lock()
v.syncOps.Add(1)
v.syncWait.Add(replicationDurationNanos(time.Since(lockStart)))
defer func() {
v.syncDuration.Add(replicationDurationNanos(time.Since(start)))
}()
defer v.mu.Unlock()
if v.closed {
return fmt.Errorf("replication: Sync: volume %s closed", v.volumeID)
@@ -454,13 +503,14 @@ func formatIDSet(s map[string]struct{}) string {
return "{" + strings.Join(ids, ",") + "}"
}
// OnLocalWrite fans out one acked local write to every tracked peer.
// OnLocalWrite orders one acked local write by its storage-assigned LSN and
// fans it out to every tracked peer.
//
// Contract: OnLocalWrite serializes fan-out in LSN order for a given
// volume. Caller order is NOT trusted as the correctness mechanism —
// the volume-level mutex v.mu is held across the entire fan-out loop.
// A future refactor that releases v.mu before issuing per-peer Ship
// calls silently reintroduces an out-of-order-ship hazard.
// Caller arrival order is not trusted: concurrent StorageBackend writes can
// allocate LSN N before LSN N+1 but reach this method in the opposite order.
// The resequencer retains owned buffers until every preceding LSN has shipped.
// The current fan-out remains serialized; Phase 167 replaces that execution
// step with per-peer ordered queues without removing this ordering boundary.
//
// Best-effort semantics: per-peer ship errors are logged and the
// offending peer is marked Degraded (by ReplicaPeer.ShipEntry's own
@@ -475,14 +525,116 @@ func formatIDSet(s map[string]struct{}) string {
//
// Called by: Backend.Write wrapper immediately after
// LogicalStorage.Write returns with the assigned LSN.
// Owns: the per-write mutex hold across fan-out (LSN-order lock
// scope); per-peer error aggregation and logging.
// Borrows: w.Data slice — caller retains; fan-out must not mutate.
// Owns: an immutable copy of w.Data while queued; per-peer error aggregation
// and logging.
func (v *ReplicationVolume) OnLocalWrite(ctx context.Context, w LocalWrite) error {
if err := ctx.Err(); err != nil {
return err
}
if w.LSN == 0 {
return errors.New("replication: OnLocalWrite: LSN must be nonzero")
}
owned := append([]byte(nil), w.Data...)
req := &orderedLocalWrite{
ctx: ctx,
write: LocalWrite{LBA: w.LBA, Data: owned, LSN: w.LSN},
result: make(chan error, 1),
}
v.orderMu.Lock()
if v.orderClosed {
v.orderMu.Unlock()
return fmt.Errorf("replication: OnLocalWrite: volume %s closed", v.volumeID)
}
if w.LSN < v.nextShipLSN {
next := v.nextShipLSN
v.orderMu.Unlock()
return fmt.Errorf("replication: OnLocalWrite: stale LSN %d below next ship LSN %d", w.LSN, next)
}
if _, exists := v.pending[w.LSN]; exists {
v.orderMu.Unlock()
return fmt.Errorf("replication: OnLocalWrite: duplicate pending LSN %d", w.LSN)
}
v.pending[w.LSN] = req
leader := !v.draining
if leader {
v.draining = true
}
v.orderMu.Unlock()
if leader {
v.drainOrderedWrites()
}
select {
case err := <-req.result:
return err
case <-ctx.Done():
return ctx.Err()
}
}
func (v *ReplicationVolume) drainOrderedWrites() {
for {
v.orderMu.Lock()
if v.orderClosed {
v.draining = false
v.orderMu.Unlock()
return
}
req := v.pending[v.nextShipLSN]
if req == nil {
v.draining = false
v.orderMu.Unlock()
return
}
delete(v.pending, v.nextShipLSN)
v.orderMu.Unlock()
err := v.shipLocalWrite(context.WithoutCancel(req.ctx), req.write)
req.result <- err
v.orderMu.Lock()
v.nextShipLSN++
if !v.orderClosed {
close(v.progress)
v.progress = make(chan struct{})
}
v.orderMu.Unlock()
}
}
func (v *ReplicationVolume) waitUntilShipped(ctx context.Context, targetLSN uint64) error {
for {
v.orderMu.Lock()
if targetLSN < v.nextShipLSN {
v.orderMu.Unlock()
return nil
}
if v.orderClosed {
v.orderMu.Unlock()
return fmt.Errorf("replication: Sync: volume %s closed", v.volumeID)
}
progress := v.progress
v.orderMu.Unlock()
select {
case <-progress:
case <-ctx.Done():
return ctx.Err()
}
}
}
func (v *ReplicationVolume) shipLocalWrite(ctx context.Context, w LocalWrite) error {
start := time.Now()
lockStart := time.Now()
v.mu.Lock()
v.writeOps.Add(1)
v.writeWait.Add(replicationDurationNanos(time.Since(lockStart)))
defer func() {
v.writeFanout.Add(replicationDurationNanos(time.Since(start)))
}()
defer v.mu.Unlock()
if v.closed {
return fmt.Errorf("replication: OnLocalWrite: volume %s closed", v.volumeID)
@@ -573,6 +725,17 @@ func (v *ReplicationVolume) Stop() error {
// (via peer.Close()).
// Borrows: nothing.
func (v *ReplicationVolume) Close() error {
v.orderMu.Lock()
if !v.orderClosed {
v.orderClosed = true
close(v.progress)
for lsn, req := range v.pending {
req.result <- fmt.Errorf("replication: OnLocalWrite: volume %s closed before LSN %d shipped", v.volumeID, lsn)
delete(v.pending, lsn)
}
}
v.orderMu.Unlock()
// Ordering: stop the
// probe loop FIRST, before acquiring v.mu and tearing down
// peers. This ensures any in-flight probe callback completes /
@@ -626,6 +789,26 @@ func (v *ReplicationVolume) PeerCount() int {
return len(v.peers)
}
// Stats returns a stable diagnostic snapshot without exposing mutable state.
func (v *ReplicationVolume) Stats() VolumeStats {
return VolumeStats{
WriteOps: v.writeOps.Load(),
WriteLockWaitNanos: v.writeWait.Load(),
WriteFanoutNanos: v.writeFanout.Load(),
SyncOps: v.syncOps.Load(),
SyncOrderWaitNanos: v.syncOrderWait.Load(),
SyncLockWaitNanos: v.syncWait.Load(),
SyncDurationNanos: v.syncDuration.Load(),
}
}
func replicationDurationNanos(d time.Duration) uint64 {
if d <= 0 {
return 1
}
return uint64(d.Nanoseconds())
}
// PeerStatuses returns a stable, sorted diagnostic snapshot of all
// currently tracked peers. This is intentionally a status surface, not
// a control surface: callers cannot mutate the returned peer state.
@@ -0,0 +1,172 @@
package replication
import (
"context"
"fmt"
"io"
"log"
"os"
"path/filepath"
"sort"
"sync"
"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/transport"
)
type phase167HealthyView struct {
projection frontend.Projection
}
func (v *phase167HealthyView) Projection() frontend.Projection {
return v.projection
}
func BenchmarkPhase167RF3SyncQuorumContention(b *testing.B) {
const (
blockSize = 4096
numBlocks = 16384
)
if os.Getenv("SW_BLOCK_BENCH_VERBOSE") == "" {
oldLogWriter := log.Writer()
log.SetOutput(io.Discard)
b.Cleanup(func() { log.SetOutput(oldLogWriter) })
}
for _, writers := range []int{1, 2, 4, 8} {
b.Run(fmt.Sprintf("writers_%d", writers), func(b *testing.B) {
primary, err := storage.CreateWALStore(filepath.Join(b.TempDir(), "primary.bin"), numBlocks, blockSize)
if err != nil {
b.Fatal(err)
}
b.Cleanup(func() { _ = primary.Close() })
targets := make([]ReplicaTarget, 0, 2)
for i := 0; i < 2; i++ {
replicaStore := storage.NewBlockStore(numBlocks, blockSize)
listener, listenErr := transport.NewReplicaListener("127.0.0.1:0", replicaStore)
if listenErr != nil {
b.Fatal(listenErr)
}
listener.Serve()
b.Cleanup(listener.Stop)
targets = append(targets, ReplicaTarget{
ReplicaID: fmt.Sprintf("r%d", i+1),
DataAddr: listener.Addr(),
ControlAddr: listener.Addr(),
Epoch: 1,
EndpointVersion: 1,
})
}
id := frontend.Identity{
VolumeID: "phase167",
ReplicaID: "primary",
Epoch: 1,
EndpointVersion: 1,
}
view := &phase167HealthyView{projection: frontend.Projection{
VolumeID: id.VolumeID,
ReplicaID: id.ReplicaID,
Epoch: id.Epoch,
EndpointVersion: id.EndpointVersion,
Healthy: true,
}}
backend := durable.NewStorageBackend(primary, view, id)
backend.SetOperational(true, "phase167 contention baseline")
backend.SetWriteAckPolicy(durable.WriteAckRequireObserverAck)
repVolume := NewReplicationVolume(id.VolumeID, primary)
repVolume.SetDurabilityMode(DurabilitySyncQuorum)
if err := repVolume.UpdateReplicaSet(1, targets); err != nil {
b.Fatal(err)
}
backend.SetWriteObserver(repVolume)
b.Cleanup(func() {
_ = backend.Close()
_ = repVolume.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)
var next atomic.Int64
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 := int(next.Add(1) - 1)
if idx >= b.N {
return
}
opStart := time.Now()
_, writeErr := backend.Write(
context.Background(),
int64(idx%numBlocks)*blockSize,
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 = backend.Sync(context.Background())
}
wallDuration := time.Since(wallStart)
b.StopTimer()
if firstErr != nil {
b.Fatal(firstErr)
}
stats := repVolume.Stats()
if stats.WriteOps != uint64(b.N) {
b.Fatalf("replication write ops=%d want %d", stats.WriteOps, b.N)
}
reportReplicationLatencyPercentiles(b, latencies)
b.ReportMetric(float64(stats.WriteLockWaitNanos)/float64(stats.WriteOps), "repl_lock_wait_ns/op")
b.ReportMetric(float64(stats.WriteFanoutNanos)/float64(stats.WriteOps), "repl_fanout_ns/op")
b.ReportMetric(float64(b.N)/wallDuration.Seconds(), "write_ops/s")
})
}
}
func reportReplicationLatencyPercentiles(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,126 @@
package replication
import (
"context"
"errors"
"strings"
"testing"
"time"
)
func TestReplicationVolume_ResequencesConcurrentArrivalByLSN(t *testing.T) {
addr, replica := replicaHarness(t, "resequence")
v := volumeHarness(t, "vol-resequence")
if err := v.UpdateReplicaSet(1, []ReplicaTarget{targetFor("r1", addr, 1, 1)}); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
lsn2Done := make(chan error, 1)
go func() {
data := make([]byte, 4096)
data[0] = 0x22
lsn2Done <- v.OnLocalWrite(ctx, LocalWrite{LBA: 2, Data: data, LSN: 2})
}()
deadline := time.Now().Add(time.Second)
for {
v.orderMu.Lock()
_, pending := v.pending[2]
v.orderMu.Unlock()
if pending {
break
}
if time.Now().After(deadline) {
t.Fatal("LSN 2 did not enter the resequencer")
}
time.Sleep(time.Millisecond)
}
data1 := make([]byte, 4096)
data1[0] = 0x11
if err := v.OnLocalWrite(ctx, LocalWrite{LBA: 1, Data: data1, LSN: 1}); err != nil {
t.Fatalf("LSN 1: %v", err)
}
if err := <-lsn2Done; err != nil {
t.Fatalf("LSN 2: %v", err)
}
waitForReplicaLBA(t, replica, 1, 0x11, 0, time.Second)
waitForReplicaLBA(t, replica, 2, 0x22, 0, time.Second)
_, _, head := replica.Boundaries()
if head != 2 {
t.Fatalf("replica head=%d want 2", head)
}
}
func TestReplicationVolume_CloseUnblocksWriteWaitingForMissingLSN(t *testing.T) {
v := volumeHarness(t, "vol-close-pending")
done := make(chan error, 1)
go func() {
done <- v.OnLocalWrite(context.Background(), LocalWrite{
LBA: 2,
Data: make([]byte, 4096),
LSN: 2,
})
}()
waitForPendingLSN(t, v, 2)
if err := v.Close(); err != nil {
t.Fatal(err)
}
select {
case err := <-done:
if err == nil || !strings.Contains(err.Error(), "closed before LSN 2 shipped") {
t.Fatalf("pending write error=%v", err)
}
case <-time.After(time.Second):
t.Fatal("pending write remained blocked after Close")
}
}
func TestReplicationVolume_SyncWaitingForMissingLSNHonorsContext(t *testing.T) {
v := volumeHarness(t, "vol-sync-missing")
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
err := v.Sync(ctx, 1)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("Sync error=%v want context deadline exceeded", err)
}
}
func TestReplicationVolume_OnLocalWriteRejectsPreCanceledContext(t *testing.T) {
v := volumeHarness(t, "vol-canceled")
ctx, cancel := context.WithCancel(context.Background())
cancel()
err := v.OnLocalWrite(ctx, LocalWrite{LBA: 1, Data: make([]byte, 4096), LSN: 1})
if !errors.Is(err, context.Canceled) {
t.Fatalf("OnLocalWrite error=%v want context canceled", err)
}
v.orderMu.Lock()
defer v.orderMu.Unlock()
if len(v.pending) != 0 {
t.Fatalf("pending writes=%d want 0", len(v.pending))
}
}
func waitForPendingLSN(t *testing.T, v *ReplicationVolume, lsn uint64) {
t.Helper()
deadline := time.Now().Add(time.Second)
for {
v.orderMu.Lock()
_, pending := v.pending[lsn]
v.orderMu.Unlock()
if pending {
return
}
if time.Now().After(deadline) {
t.Fatalf("LSN %d did not enter the resequencer", lsn)
}
time.Sleep(time.Millisecond)
}
}
@@ -0,0 +1,35 @@
package replication
import (
"context"
"testing"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func TestReplicationVolume_StatsCountWriteAndSyncContention(t *testing.T) {
store := storage.NewBlockStore(8, 4096)
v := NewReplicationVolume("stats", store)
t.Cleanup(func() { _ = v.Close() })
data := make([]byte, 4096)
lsn, err := store.Write(0, data)
if err != nil {
t.Fatal(err)
}
if err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: 0, LSN: lsn, Data: data}); err != nil {
t.Fatal(err)
}
if err := v.Sync(context.Background(), lsn); err != nil {
t.Fatal(err)
}
got := v.Stats()
if got.WriteOps != 1 || got.SyncOps != 1 {
t.Fatalf("stats counts=%+v want one write and one sync", got)
}
if got.WriteLockWaitNanos == 0 || got.WriteFanoutNanos == 0 ||
got.SyncLockWaitNanos == 0 || got.SyncDurationNanos == 0 {
t.Fatalf("stats missing duration evidence: %+v", got)
}
}
+10 -17
View File
@@ -351,7 +351,7 @@ func TestG9A_ReplicationVolume_OnLocalWrite_BestEffortRetainsRecoveringPeer(t *t
data := make([]byte, 4096)
data[0] = 0xA9
if err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: 3, Data: data, LSN: 9}); err != nil {
if err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: 3, Data: data, LSN: 1}); err != nil {
t.Fatalf("best-effort recovering peer should retain/feed without failing Write observer: %v", err)
}
}
@@ -369,7 +369,7 @@ func TestG9A_ReplicationVolume_OnLocalWrite_SyncAllFailsRecoveringPeer(t *testin
data := make([]byte, 4096)
data[0] = 0xB9
err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: 4, Data: data, LSN: 10})
err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: 4, Data: data, LSN: 1})
if !strings.Contains(fmt.Sprint(err), ErrDurabilityBarrierFailed.Error()) {
t.Fatalf("sync_all recovering peer should fail write ack, got %v", err)
}
@@ -388,7 +388,7 @@ func TestG9A_ReplicationVolume_OnLocalWrite_SyncQuorumRF2FailsRecoveringPeer(t *
data := make([]byte, 4096)
data[0] = 0xC9
err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: 5, Data: data, LSN: 11})
err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: 5, Data: data, LSN: 1})
if !strings.Contains(fmt.Sprint(err), ErrDurabilityQuorumLost.Error()) {
t.Fatalf("sync_quorum RF=2 recovering peer should fail write ack, got %v", err)
}
@@ -477,21 +477,19 @@ func TestReplicationVolume_OnLocalWrite_PeerErrorDoesNotFailCaller(t *testing.T)
// TestReplicationVolume_OnLocalWrite_ConcurrentLSNs_OrderedAtReplica —
// the architect-requested adversarial ordering pin.
//
// Shape: N goroutines, each pre-assigned a unique LSN. Calls are
// funneled through a caller-side serialization primitive that
// mimics how Backend.Write will work in production (hold a lock
// across LSN allocation + OnLocalWrite invocation). Under the
// architect-approved Option X design, ReplicationVolume.OnLocalWrite
// preserves LSN order through fan-out AS LONG AS the caller path
// is serialized.
// Shape: N goroutines allocate unique LSNs and call OnLocalWrite
// without a caller-side lock. ReplicationVolume must tolerate the
// callback for LSN N+1 arriving before LSN N and still ship a
// contiguous stream to the replica.
//
// Test schedules N writes where LSN order and LBA order are distinct
// (LSN 1 writes to LBA 9, LSN 2 writes to LBA 8, ...) so any
// out-of-order application would produce detectable final-state
// corruption.
//
// Proves: V2 shipMu semantic is preserved by V3's Option X pattern
// when the system-level caller contract is honored.
// Proves: V2 shipMu ordering is preserved inside ReplicationVolume;
// callers do not need to serialize storage allocation and observer
// dispatch as one critical section.
func TestReplicationVolume_OnLocalWrite_ConcurrentLSNs_OrderedAtReplica(t *testing.T) {
addr, replica := replicaHarness(t, "r1")
v := volumeHarness(t, "vol1")
@@ -500,7 +498,6 @@ func TestReplicationVolume_OnLocalWrite_ConcurrentLSNs_OrderedAtReplica(t *testi
}
const n = 40
var callerMu sync.Mutex
var nextLSN atomic.Uint64
var wg sync.WaitGroup
start := make(chan struct{})
@@ -527,9 +524,6 @@ func TestReplicationVolume_OnLocalWrite_ConcurrentLSNs_OrderedAtReplica(t *testi
defer wg.Done()
<-start
// Caller-side serialized section: mimics Backend.Write holding
// a volume-level mutex across LSN allocation + OnLocalWrite.
callerMu.Lock()
lsn := nextLSN.Add(1)
// Resolve plan deterministically by LSN.
p := plans[lsn-1]
@@ -541,7 +535,6 @@ func TestReplicationVolume_OnLocalWrite_ConcurrentLSNs_OrderedAtReplica(t *testi
Data: data,
LSN: lsn,
})
callerMu.Unlock()
if err != nil {
t.Errorf("OnLocalWrite idx=%d lsn=%d: %v", idx, lsn, err)
}
+8
View File
@@ -64,7 +64,11 @@ func (w *walWriter) append(entry *walEntry) (walRelOffset uint64, err error) {
return 0, fmt.Errorf("walWriter.append: encode: %w", err)
}
lockStart := time.Now()
w.mu.Lock()
if w.instr != nil {
w.instr.recordWALAppendLockWait(time.Since(lockStart))
}
defer w.mu.Unlock()
entryLen := uint64(len(buf))
@@ -124,7 +128,11 @@ func (w *walWriter) appendBatch(entries []walEntry) ([]uint64, error) {
}
pendingCapacity := boundedPendingCapacity(lengths)
lockStart := time.Now()
w.mu.Lock()
if w.instr != nil {
w.instr.recordWALAppendLockWait(time.Since(lockStart))
}
defer w.mu.Unlock()
offsets, finalHead, err := w.planAppendBatchLengths(lengths)
@@ -0,0 +1,120 @@
package storage
import (
"fmt"
"path/filepath"
"sort"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestWALStore_WriteInstrumentationCountsAppendLockWait(t *testing.T) {
s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 64, 4096)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
block := make([]byte, 4096)
if _, err := s.Write(0, block); err != nil {
t.Fatal(err)
}
if _, err := s.WriteBatch(1, [][]byte{block, block}); err != nil {
t.Fatal(err)
}
got := s.WriteInstrumentation()
if got.WALAppendLockWaitOps != 2 {
t.Fatalf("WALAppendLockWaitOps=%d want 2", got.WALAppendLockWaitOps)
}
if got.WALAppendLockWaitNanos == 0 {
t.Fatal("WALAppendLockWaitNanos=0 want diagnostic evidence")
}
}
func BenchmarkPhase167WALStoreContention(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 := 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)
var next atomic.Int64
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 := int(next.Add(1) - 1)
if idx >= b.N {
return
}
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)
}
status := s.WriteInstrumentation()
reportLatencyPercentiles(b, latencies)
b.ReportMetric(float64(status.WALAppendLockWaitNanos)/float64(status.WALAppendLockWaitOps), "wal_lock_wait_ns/op")
b.ReportMetric(float64(b.N)/wallDuration.Seconds(), "write_ops/s")
})
}
}
func reportLatencyPercentiles(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")
}
@@ -20,6 +20,8 @@ type WriteInstrumentationStatus struct {
WALAppendOps uint64
WALAppendBytes uint64
WALAppendDurationNanos uint64
WALAppendLockWaitOps uint64
WALAppendLockWaitNanos uint64
WALAppendWriteAtCalls uint64
WALAppendWriteAtBytes uint64
WALAppendWriteAtMaxBytes uint64
@@ -48,6 +50,8 @@ type writeInstrumentation struct {
walAppendOps atomic.Uint64
walAppendBytes atomic.Uint64
walAppendDurationNanos atomic.Uint64
walAppendLockWaitOps atomic.Uint64
walAppendLockWaitNanos atomic.Uint64
walAppendWriteAtCalls atomic.Uint64
walAppendWriteAtBytes atomic.Uint64
walAppendWriteAtMaxBytes atomic.Uint64
@@ -101,6 +105,14 @@ func (i *writeInstrumentation) recordWALAppend(bytes int, d time.Duration) {
i.recordWALAppendWriteAt(bytes)
}
func (i *writeInstrumentation) recordWALAppendLockWait(d time.Duration) {
if i == nil {
return
}
i.walAppendLockWaitOps.Add(1)
i.walAppendLockWaitNanos.Add(storageDurationNanos(d))
}
func (i *writeInstrumentation) recordWALAppendWriteAt(bytes int) {
if i == nil || bytes <= 0 {
return
@@ -149,6 +161,8 @@ func (i *writeInstrumentation) snapshot() WriteInstrumentationStatus {
WALAppendOps: i.walAppendOps.Load(),
WALAppendBytes: i.walAppendBytes.Load(),
WALAppendDurationNanos: i.walAppendDurationNanos.Load(),
WALAppendLockWaitOps: i.walAppendLockWaitOps.Load(),
WALAppendLockWaitNanos: i.walAppendLockWaitNanos.Load(),
WALAppendWriteAtCalls: i.walAppendWriteAtCalls.Load(),
WALAppendWriteAtBytes: i.walAppendWriteAtBytes.Load(),
WALAppendWriteAtMaxBytes: i.walAppendWriteAtMaxBytes.Load(),
@@ -33,6 +33,31 @@ This is one large milestone. Its implementation may use several reviewable
commits or PR slices, but individual lock, counter, queue, and syscall changes
do not become separate phases.
## Current Progress
The D1 local baseline slice is implemented and repeatable through
`scripts/run-phase167-parallel-write-engine-local-baseline-gate.sh`:
- direct WAL and real TCP RF3 sync-quorum benchmarks cover 1, 2, 4, and 8
writers with throughput, p99, WAL-lock wait, and replication-fanout timing;
- the benchmark asserts the replication observer processed every accepted
write, so a detached observer cannot produce a false performance PASS;
- the first same-run Windows baseline measured WAL four-writer scaling at
`0.882x`, while RF3 four-writer scaling was `0.167x`;
- concurrent RF3 execution exposed a real pre-existing ordering gap: storage
could assign LSN N before N+1 while observer callbacks arrived in the
opposite order, causing the replica ship cursor to reject the gap;
- `ReplicationVolume` now resequences concurrent callbacks by storage-assigned
LSN, owns queued buffers, makes `Sync(targetLSN)` wait for the ordered ship
frontier, and unblocks pending work safely on shutdown;
- five repeated RF3 benchmark runs and the storage/frontend/replication test
suites passed without another cursor gap.
This is evidence and a correctness prerequisite, not a parallel-engine
performance claim. Linux race, CPU/queue-depth evidence, mounted NVMe/TCP, and
same-run lab comparison remain open. D2 ordered asynchronous replication is
the active implementation target.
## Assumptions And Boundaries
- `walstore` remains the default backend until the candidate passes the full
@@ -0,0 +1,118 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="${1:-$(pwd)}"
ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-${ROOT}/results/phase167-parallel-write-engine-local-baseline-gate}"
SUMMARY="${ARTIFACT_DIR}/phase167-parallel-write-engine-local-baseline-summary.txt"
WAL_BENCH="${ARTIFACT_DIR}/walstore-contention-benchmark.txt"
RF3_BENCH="${ARTIFACT_DIR}/rf3-sync-quorum-contention-benchmark.txt"
WAL_BENCHTIME="${SW_BLOCK_PHASE167_WAL_BENCHTIME:-1000x}"
RF3_BENCHTIME="${SW_BLOCK_PHASE167_RF3_BENCHTIME:-500x}"
mkdir -p "${ARTIFACT_DIR}"
: >"${SUMMARY}"
write_summary() {
echo "$*" | tee -a "${SUMMARY}" >/dev/null
}
benchmark_metric() {
local file="$1"
local benchmark="$2"
local writers="$3"
local metric="$4"
awk -v prefix="${benchmark}/writers_${writers}-" -v metric="${metric}" '
index($1, prefix) == 1 {
for (i = 2; i <= NF; i++) {
if ($(i + 1) == metric) {
print $i
exit
}
}
}
' "${file}"
}
require_metric() {
local file="$1"
local benchmark="$2"
local writers="$3"
local metric="$4"
local value
value="$(benchmark_metric "${file}" "${benchmark}" "${writers}" "${metric}")"
if [[ -z "${value}" ]]; then
echo "missing ${benchmark}/writers_${writers} metric ${metric} in ${file}" >&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
}'
}
write_summary "phase167_parallel_write_engine_local_baseline_status=running"
write_summary "scope=local_engine_and_real_tcp_rf3"
write_summary "mounted_nvme_claim_allowed=false"
write_summary "parallel_engine_performance_claim_allowed=false"
cd "${ROOT}"
go test ./core/storage ./core/frontend/durable ./core/replication -count=1 \
>"${ARTIFACT_DIR}/go-test.log" 2>&1
write_summary "unit_component_tests=pass"
if [[ "$(go env CGO_ENABLED)" == "1" ]]; then
go test -race ./core/replication -count=1 \
>"${ARTIFACT_DIR}/go-test-race.log" 2>&1
write_summary "replication_race_test=pass"
else
write_summary "replication_race_test=not_run_cgo_disabled"
fi
go test ./core/storage \
-run '^$' \
-bench '^BenchmarkPhase167WALStoreContention$' \
-benchtime="${WAL_BENCHTIME}" \
-count=1 \
>"${WAL_BENCH}" 2>&1
go test ./core/replication \
-run '^$' \
-bench '^BenchmarkPhase167RF3SyncQuorumContention$' \
-benchtime="${RF3_BENCHTIME}" \
-count=1 \
>"${RF3_BENCH}" 2>&1
for writers in 1 2 4 8; do
wal_mibps="$(require_metric "${WAL_BENCH}" BenchmarkPhase167WALStoreContention "${writers}" MB/s)"
wal_p99="$(require_metric "${WAL_BENCH}" BenchmarkPhase167WALStoreContention "${writers}" p99_ns)"
wal_wait="$(require_metric "${WAL_BENCH}" BenchmarkPhase167WALStoreContention "${writers}" wal_lock_wait_ns/op)"
rf3_mibps="$(require_metric "${RF3_BENCH}" BenchmarkPhase167RF3SyncQuorumContention "${writers}" MB/s)"
rf3_p99="$(require_metric "${RF3_BENCH}" BenchmarkPhase167RF3SyncQuorumContention "${writers}" p99_ns)"
rf3_fanout="$(require_metric "${RF3_BENCH}" BenchmarkPhase167RF3SyncQuorumContention "${writers}" repl_fanout_ns/op)"
write_summary "wal_writers_${writers}_mibps=${wal_mibps}"
write_summary "wal_writers_${writers}_p99_ns=${wal_p99}"
write_summary "wal_writers_${writers}_lock_wait_ns_per_op=${wal_wait}"
write_summary "rf3_writers_${writers}_mibps=${rf3_mibps}"
write_summary "rf3_writers_${writers}_p99_ns=${rf3_p99}"
write_summary "rf3_writers_${writers}_fanout_ns_per_op=${rf3_fanout}"
done
wal_1="$(require_metric "${WAL_BENCH}" BenchmarkPhase167WALStoreContention 1 MB/s)"
wal_4="$(require_metric "${WAL_BENCH}" BenchmarkPhase167WALStoreContention 4 MB/s)"
rf3_1="$(require_metric "${RF3_BENCH}" BenchmarkPhase167RF3SyncQuorumContention 1 MB/s)"
rf3_4="$(require_metric "${RF3_BENCH}" BenchmarkPhase167RF3SyncQuorumContention 4 MB/s)"
wal_scaling_ratio="$(ratio "${wal_4}" "${wal_1}")"
rf3_scaling_ratio="$(ratio "${rf3_4}" "${rf3_1}")"
write_summary "wal_four_writer_scaling_ratio=${wal_scaling_ratio}"
write_summary "rf3_four_writer_scaling_ratio=${rf3_scaling_ratio}"
write_summary "strict_replication_write_count=true"
write_summary "lsn_resequencing_gate=pass"
write_summary "next_recommendation=ordered_async_replication"
write_summary "phase167_parallel_write_engine_local_baseline_status=ok"