diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index f6bacf4ebd..53aebc9adc 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -91,15 +91,14 @@ var ErrReplicationAckUnavailable = errors.New("durable: replication ack unavaila // RF=2/full-ack seam: a recovering/down replica must not be // silently treated as a full-sync peer. // - StorageBackend calls Observe from within writeBytes; the -// ReplicationVolume's own mutex then serializes fan-out per -// volume (V2 shipMu equivalent; closes -// INV-REPL-LSN-ORDER-FANOUT-001 at the replication seam). +// ReplicationVolume resequences callbacks by storage-assigned LSN, +// then dispatches through one ordered queue per peer lineage. // // Sync contract (T4b-5 — matches V2 BlockVol.MakeDistributedSync): // - When an observer is installed, StorageBackend.Sync DELEGATES // the full sync job to observer.Sync — the observer owns both -// the local LogicalStorage.Sync call and the peer barriers, -// fanned out in parallel by DurabilityCoordinator. +// the local LogicalStorage.Sync call and the peer barriers, with +// barriers ordered behind prior writes in each peer queue. // - targetLSN is the primary's current walHead at the moment the // host requested Sync; caller (StorageBackend) reads it from // LogicalStorage.Boundaries(). @@ -113,6 +112,15 @@ type WriteObserver interface { Sync(ctx context.Context, targetLSN uint64) error } +// BatchWriteObserver lets a replication observer accept a contiguous batch of +// locally-committed blocks before waiting for acknowledgement. StorageBackend +// only enables strict-ACK WriteBatch when the installed observer implements +// this interface. +type BatchWriteObserver interface { + WriteObserver + ObserveBatch(ctx context.Context, startLBA uint32, lsns []uint64, blocks [][]byte) error +} + // errInvalidOffset is returned for negative byte offsets. Callers // should never produce these; both iSCSI and NVMe clamp LBA before // it reaches the backend. Kept as a distinct sentinel so the cause @@ -349,9 +357,9 @@ func (b *StorageBackend) Sync(ctx context.Context) error { // T4b-5: if an observer is installed, delegate the FULL sync // job — the observer (ReplicationVolume) owns both the local // LogicalStorage.Sync call and the peer barriers fanned out - // in parallel by DurabilityCoordinator. Without this branch the + // through the peer queues. Without this branch the // local sync would run twice (once here, once inside the - // coordinator) which is both wasteful and semantically wrong + // observer) which is both wasteful and semantically wrong // (primary would be "durable" before peers were even queried). // // targetLSN is the primary's current walHead — the replica-facing @@ -526,7 +534,7 @@ func (b *StorageBackend) writeBytes(ctx context.Context, offset int64, p []byte) obs := b.observer policy := b.writeAck b.mu.Unlock() - if _, ok := b.storage.(storage.WriteBatcher); ok && inBlockOff == 0 && len(buf) >= int(bs) && canBatchFullBlockRun(policy) { + if _, ok := b.storage.(storage.WriteBatcher); ok && inBlockOff == 0 && len(buf) >= int(bs) && canBatchFullBlockRun(policy, obs) { fullBlocks := len(buf) / int(bs) if fullBlocks > maxFullBlockBatchBlocks { fullBlocks = maxFullBlockBatchBlocks @@ -581,8 +589,12 @@ func (b *StorageBackend) writeBytes(ctx context.Context, offset int64, p []byte) return total, nil } -func canBatchFullBlockRun(policy WriteAckPolicy) bool { - return policy != WriteAckRequireObserverAck +func canBatchFullBlockRun(policy WriteAckPolicy, obs WriteObserver) bool { + if policy != WriteAckRequireObserverAck { + return true + } + _, ok := obs.(BatchWriteObserver) + return ok } func (b *StorageBackend) writeFullBlockBatch(ctx context.Context, startLBA uint32, p []byte, obs WriteObserver, policy WriteAckPolicy) (int, error) { @@ -601,11 +613,21 @@ func (b *StorageBackend) writeFullBlockBatch(ctx context.Context, startLBA uint3 b.profile.recordBackendStorageWrite(len(lsns), true) b.profile.recordBackendFullBlockBatch(len(lsns)) } - for i, lsn := range lsns { - block := blocks[i] - lba := startLBA + uint32(i) - if obsErr := b.observeWrite(ctx, lba, lsn, block, obs, policy); obsErr != nil { - return (i + 1) * bs, obsErr + if batchObserver, ok := obs.(BatchWriteObserver); ok && len(lsns) > 0 { + if obsErr := batchObserver.ObserveBatch(ctx, startLBA, lsns, blocks[:len(lsns)]); obsErr != nil { + log.Printf("durable: replication batch fan-out failed lba=%d blocks=%d: %v", + startLBA, len(lsns), obsErr) + if policy == WriteAckRequireObserverAck { + return len(lsns) * bs, fmt.Errorf("%w: %w", ErrReplicationAckUnavailable, obsErr) + } + } + } else { + for i, lsn := range lsns { + block := blocks[i] + lba := startLBA + uint32(i) + if obsErr := b.observeWrite(ctx, lba, lsn, block, obs, policy); obsErr != nil { + return (i + 1) * bs, obsErr + } } } if err != nil { diff --git a/seaweed-block/core/frontend/durable/storage_adapter_test.go b/seaweed-block/core/frontend/durable/storage_adapter_test.go index 72919a8274..8d01461a51 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter_test.go +++ b/seaweed-block/core/frontend/durable/storage_adapter_test.go @@ -47,6 +47,116 @@ func (f writeObserverFunc) Sync(ctx context.Context, targetLSN uint64) error { return nil } +type batchWriteObserverFunc struct { + writeObserverFunc + observeBatch func(context.Context, uint32, []uint64, [][]byte) error +} + +type partialBatchStorage struct { + storage.LogicalStorage + err error +} + +func (s partialBatchStorage) WriteBatch(_ uint32, _ [][]byte) ([]uint64, error) { + return []uint64{1}, s.err +} + +func (f batchWriteObserverFunc) ObserveBatch( + ctx context.Context, + startLBA uint32, + lsns []uint64, + blocks [][]byte, +) error { + if f.observeBatch != nil { + return f.observeBatch(ctx, startLBA, lsns, blocks) + } + return nil +} + +func TestStorageBackend_StrictAckUsesBatchObserver(t *testing.T) { + b, _, s := newTestBackend(t, logicalStorageFactories()[0], 16, 4096) + b.SetWriteAckPolicy(durable.WriteAckRequireObserverAck) + + var singleCalls atomic.Int64 + var batchCalls atomic.Int64 + b.SetWriteObserver(batchWriteObserverFunc{ + writeObserverFunc: writeObserverFunc{ + observe: func(context.Context, uint32, uint64, []byte) error { + singleCalls.Add(1) + return nil + }, + }, + observeBatch: func(_ context.Context, startLBA uint32, lsns []uint64, blocks [][]byte) error { + batchCalls.Add(1) + if startLBA != 0 || len(lsns) != 2 || len(blocks) != 2 { + t.Fatalf("batch start=%d lsns=%v blocks=%d", startLBA, lsns, len(blocks)) + } + if lsns[0]+1 != lsns[1] { + t.Fatalf("batch LSNs are not contiguous: %v", lsns) + } + return nil + }, + }) + + payload := make([]byte, 2*4096) + payload[0] = 0x41 + payload[4096] = 0x42 + n, err := b.Write(context.Background(), 0, payload) + if err != nil { + t.Fatal(err) + } + if n != len(payload) { + t.Fatalf("Write n=%d want %d", n, len(payload)) + } + if batchCalls.Load() != 1 || singleCalls.Load() != 0 { + t.Fatalf("batch calls=%d single calls=%d want 1/0", batchCalls.Load(), singleCalls.Load()) + } + for lba, marker := range []byte{0x41, 0x42} { + block, readErr := s.Read(uint32(lba)) + if readErr != nil { + t.Fatal(readErr) + } + if block[0] != marker { + t.Fatalf("LBA %d marker=%x want %x", lba, block[0], marker) + } + } +} + +func TestStorageBackend_PartialBatchObservesOnlyCommittedPrefix(t *testing.T) { + _, view, base := newTestBackend(t, logicalStorageFactories()[0], 16, 4096) + batchErr := errors.New("partial batch failure") + s := partialBatchStorage{LogicalStorage: base, err: batchErr} + id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1} + b := durable.NewStorageBackend(s, view, id) + b.SetOperational(true, "test") + b.SetWriteAckPolicy(durable.WriteAckRequireObserverAck) + + var observedLSNs []uint64 + var observedBlocks int + b.SetWriteObserver(batchWriteObserverFunc{ + observeBatch: func(_ context.Context, startLBA uint32, lsns []uint64, blocks [][]byte) error { + if startLBA != 0 { + t.Fatalf("startLBA=%d want 0", startLBA) + } + observedLSNs = append(observedLSNs, lsns...) + observedBlocks = len(blocks) + return nil + }, + }) + + payload := make([]byte, 2*4096) + n, err := b.Write(context.Background(), 0, payload) + if !errors.Is(err, batchErr) { + t.Fatalf("error=%v want partial batch failure", err) + } + if n != 4096 { + t.Fatalf("written=%d want committed prefix 4096", n) + } + if len(observedLSNs) != 1 || observedLSNs[0] != 1 || observedBlocks != 1 { + t.Fatalf("observed LSNs=%v blocks=%d want committed prefix [1]/1", observedLSNs, observedBlocks) + } +} + // ------- Matrix factory (Addendum A #1) ------- // logicalStorageFactory is the shared factory contract; every diff --git a/seaweed-block/core/replication/async_ack.go b/seaweed-block/core/replication/async_ack.go new file mode 100644 index 0000000000..44a090961e --- /dev/null +++ b/seaweed-block/core/replication/async_ack.go @@ -0,0 +1,149 @@ +package replication + +import ( + "context" + "errors" + "fmt" +) + +func waitForPeerAcks( + ctx context.Context, + mode DurabilityMode, + rf int, + peerCount int, + results <-chan peerWorkResult, + operation string, +) error { + if peerCount == 0 { + return nil + } + requiredPeerSuccesses := peerCount + if mode == DurabilitySyncQuorum { + requiredPeerSuccesses = rf / 2 + } + + successes := 0 + failures := 0 + var firstErr error + var terminalErr error + for received := 0; received < peerCount; received++ { + select { + case <-ctx.Done(): + return ctx.Err() + case result := <-results: + if result.err == nil && result.eligible { + successes++ + } else { + failures++ + if firstErr == nil { + if result.err != nil { + firstErr = result.err + } else { + firstErr = fmt.Errorf("replication: peer %s was not write-ack eligible", result.peerID) + } + } + if terminalErr == nil && isPeerQueueTerminalError(result.err) { + terminalErr = result.err + } + } + } + + remaining := peerCount - received - 1 + if mode == DurabilitySyncQuorum { + if successes >= requiredPeerSuccesses { + return nil + } + if successes+remaining < requiredPeerSuccesses { + return durabilityAckError(ErrDurabilityQuorumLost, operation, successes+1, rf/2+1, firstErr) + } + } + } + + switch mode { + case DurabilitySyncAll: + if failures > 0 { + return durabilityAckError(ErrDurabilityBarrierFailed, operation, successes+1, rf, firstErr) + } + case DurabilityBestEffort: + if terminalErr != nil { + return terminalErr + } + } + return nil +} + +func waitForSyncAcks( + ctx context.Context, + mode DurabilityMode, + targetLSN uint64, + peerCount int, + localResult <-chan localSyncResult, + results <-chan peerWorkResult, +) error { + rf := peerCount + 1 + requiredPeerSuccesses := peerCount + if mode == DurabilitySyncQuorum { + requiredPeerSuccesses = rf / 2 + } + + localDone := false + peerReceived := 0 + peerSuccesses := 0 + var firstPeerErr error + for !localDone || peerReceived < peerCount { + select { + case <-ctx.Done(): + return ctx.Err() + case result := <-localResult: + localDone = true + if result.err != nil { + return result.err + } + case result := <-results: + peerReceived++ + if result.err == nil { + peerSuccesses++ + } else if firstPeerErr == nil { + firstPeerErr = result.err + } + } + + if mode == DurabilitySyncQuorum { + if localDone && peerSuccesses >= requiredPeerSuccesses { + return nil + } + remaining := peerCount - peerReceived + if localDone && peerSuccesses+remaining < requiredPeerSuccesses { + return durabilityAckError( + ErrDurabilityQuorumLost, + fmt.Sprintf("sync target LSN %d", targetLSN), + peerSuccesses+1, + rf/2+1, + firstPeerErr, + ) + } + } + } + + if mode == DurabilitySyncAll && firstPeerErr != nil { + return durabilityAckError( + ErrDurabilityBarrierFailed, + fmt.Sprintf("sync target LSN %d", targetLSN), + peerSuccesses+1, + rf, + firstPeerErr, + ) + } + return nil +} + +func durabilityAckError(kind error, operation string, got, required int, cause error) error { + if cause != nil { + return fmt.Errorf("%w: %s acknowledgements %d/%d: %w", kind, operation, got, required, cause) + } + return fmt.Errorf("%w: %s acknowledgements %d/%d", kind, operation, got, required) +} + +func isPeerQueueTerminalError(err error) bool { + return errors.Is(err, ErrPeerQueueSaturated) || errors.Is(err, ErrPeerQueueClosed) +} diff --git a/seaweed-block/core/replication/async_ack_test.go b/seaweed-block/core/replication/async_ack_test.go new file mode 100644 index 0000000000..8f4665129e --- /dev/null +++ b/seaweed-block/core/replication/async_ack_test.go @@ -0,0 +1,70 @@ +package replication + +import ( + "context" + "errors" + "strings" + "testing" +) + +func TestWaitForPeerAcks_BestEffortPreservesTerminalQueueError(t *testing.T) { + results := make(chan peerWorkResult, 2) + results <- peerWorkResult{peerID: "ordinary", err: errors.New("transport unavailable")} + results <- peerWorkResult{peerID: "terminal", err: ErrPeerQueueSaturated} + + err := waitForPeerAcks( + context.Background(), + DurabilityBestEffort, + 3, + 2, + results, + "write", + ) + if !errors.Is(err, ErrPeerQueueSaturated) { + t.Fatalf("error=%v want ErrPeerQueueSaturated", err) + } +} + +func TestWaitForPeerAcks_SyncAllReportsSuccessfulAcknowledgements(t *testing.T) { + results := make(chan peerWorkResult, 2) + results <- peerWorkResult{peerID: "r1", eligible: true} + results <- peerWorkResult{peerID: "r2", err: errors.New("write failed")} + + err := waitForPeerAcks( + context.Background(), + DurabilitySyncAll, + 3, + 2, + results, + "write", + ) + if !errors.Is(err, ErrDurabilityBarrierFailed) { + t.Fatalf("error=%v want ErrDurabilityBarrierFailed", err) + } + if !strings.Contains(err.Error(), "acknowledgements 2/3") { + t.Fatalf("error=%q want actual successful acknowledgement count 2/3", err) + } +} + +func TestWaitForSyncAcks_SyncAllReportsSuccessfulAcknowledgements(t *testing.T) { + local := make(chan localSyncResult, 1) + local <- localSyncResult{} + results := make(chan peerWorkResult, 2) + results <- peerWorkResult{peerID: "r1"} + results <- peerWorkResult{peerID: "r2", err: errors.New("barrier failed")} + + err := waitForSyncAcks( + context.Background(), + DurabilitySyncAll, + 7, + 2, + local, + results, + ) + if !errors.Is(err, ErrDurabilityBarrierFailed) { + t.Fatalf("error=%v want ErrDurabilityBarrierFailed", err) + } + if !strings.Contains(err.Error(), "acknowledgements 2/3") { + t.Fatalf("error=%q want actual successful acknowledgement count 2/3", err) + } +} diff --git a/seaweed-block/core/replication/durability.go b/seaweed-block/core/replication/durability.go index 887e66f87e..b74eaa2619 100644 --- a/seaweed-block/core/replication/durability.go +++ b/seaweed-block/core/replication/durability.go @@ -120,7 +120,8 @@ func NewDurabilityCoordinator() *DurabilityCoordinator { // (Invalidate + Degraded) already happened inside peer.Barrier // — see INV-REPL-BARRIER-FAILURE-DEGRADES-PEER pinned at T4b-3. // -// Called by: ReplicationVolume.Sync (T4b-5). +// Called by: synchronous durability contract tests. ReplicationVolume.Sync +// uses lineage-scoped ordered queues so barriers cannot overtake writes. // Owns: parallel fan-out; DurabilityResult construction; FailedPeers // slice assembly. // Borrows: localSync closure from caller; peers slice from caller @@ -257,4 +258,3 @@ func collectFailedPeerIDs(peers []*ReplicaPeer, errs []error) []string { } return failed } - diff --git a/seaweed-block/core/replication/peer.go b/seaweed-block/core/replication/peer.go index d260ded865..ffe01ab003 100644 --- a/seaweed-block/core/replication/peer.go +++ b/seaweed-block/core/replication/peer.go @@ -161,6 +161,9 @@ type ReplicaPeer struct { mu sync.Mutex state ReplicaState closed bool + // onHealthy lets the owning ReplicationVolume reopen a terminal work + // queue only after recovery has returned this peer to Healthy. + onHealthy func() // Probe cooldown / in-flight state. All fields read+written // under p.mu only. @@ -654,8 +657,8 @@ func (p *ReplicaPeer) ShipEntry(ctx context.Context, lineage transport.RecoveryL // Caller uses targetLSN at the coordinator layer (comparing against // ack.AchievedLSN) to decide per-mode durability arithmetic. // -// Called by: DurabilityCoordinator.SyncLocalAndReplicas per-peer -// fan-out. +// Called by: peerWorkQueue for the production ordered barrier path, and by +// DurabilityCoordinator.SyncLocalAndReplicas in synchronous contract tests. // Owns: the error → Invalidate translation (peer state mutation). // Borrows: ctx + targetLSN from caller; lineage is read from peer's // own registered state. @@ -755,8 +758,18 @@ func (p *ReplicaPeer) SetState(next ReplicaState) { return } p.state = next + onHealthy := p.onHealthy p.mu.Unlock() log.Printf("replication: peer %s state %s → %s", p.target.ReplicaID, prev, next) + if prev != ReplicaHealthy && next == ReplicaHealthy && onHealthy != nil { + onHealthy() + } +} + +func (p *ReplicaPeer) setOnHealthy(fn func()) { + p.mu.Lock() + p.onHealthy = fn + p.mu.Unlock() } // replicaStateTransitionAllowed is the table-driven transition gate. diff --git a/seaweed-block/core/replication/peer_work_queue.go b/seaweed-block/core/replication/peer_work_queue.go new file mode 100644 index 0000000000..c38076c776 --- /dev/null +++ b/seaweed-block/core/replication/peer_work_queue.go @@ -0,0 +1,213 @@ +package replication + +import ( + "context" + "errors" + "fmt" + "sync" + + "github.com/seaweedfs/seaweed-block/core/transport" +) + +var ( + ErrPeerQueueSaturated = errors.New("replication: peer work queue saturated") + ErrPeerQueueClosed = errors.New("replication: peer work queue closed") + ErrBarrierBelowTargetLSN = errors.New("replication: barrier acknowledgement below target LSN") +) + +type peerWorkKind uint8 + +const ( + peerWorkWrite peerWorkKind = iota + 1 + peerWorkBarrier +) + +type peerWorkResult struct { + peerID string + eligible bool + ackLSN uint64 + err error +} + +type peerWork struct { + kind peerWorkKind + write LocalWrite + targetLSN uint64 + result chan<- peerWorkResult +} + +type peerWorkQueueOps struct { + ship func(context.Context, LocalWrite) (bool, error) + barrier func(context.Context, uint64) (uint64, error) + invalidate func(string) +} + +// peerWorkQueue is one lineage-scoped, bounded FIFO. Writes and barriers share +// the same worker so a barrier can never overtake an earlier write. +type peerWorkQueue struct { + peerID string + ops peerWorkQueueOps + + ctx context.Context + cancel context.CancelFunc + jobs chan peerWork + done chan struct{} + + mu sync.Mutex + closed bool + terminalErr error +} + +func newPeerWorkQueue(peer *ReplicaPeer, depth int) *peerWorkQueue { + return newPeerWorkQueueWithOps(peer.Target().ReplicaID, depth, peerWorkQueueOps{ + ship: func(ctx context.Context, write LocalWrite) (bool, error) { + eligible := peer.State() == ReplicaHealthy + err := peer.ShipEntry(ctx, transport.RecoveryLineage{}, write.LBA, write.LSN, write.Data) + return eligible, err + }, + barrier: func(ctx context.Context, targetLSN uint64) (uint64, error) { + ack, err := peer.Barrier(ctx, targetLSN) + if err != nil { + return 0, err + } + if ack.AchievedLSN < targetLSN { + err := fmt.Errorf("%w: peer %s achieved %d, required %d", + ErrBarrierBelowTargetLSN, peer.Target().ReplicaID, ack.AchievedLSN, targetLSN) + peer.Invalidate(err.Error()) + return ack.AchievedLSN, err + } + return ack.AchievedLSN, nil + }, + invalidate: peer.Invalidate, + }) +} + +func newPeerWorkQueueWithOps(peerID string, depth int, ops peerWorkQueueOps) *peerWorkQueue { + if depth < 1 { + depth = 1 + } + ctx, cancel := context.WithCancel(context.Background()) + q := &peerWorkQueue{ + peerID: peerID, + ops: ops, + ctx: ctx, + cancel: cancel, + jobs: make(chan peerWork, depth), + done: make(chan struct{}), + } + go q.run() + return q +} + +func (q *peerWorkQueue) enqueueWrite(write LocalWrite, result chan<- peerWorkResult) (int, error) { + return q.enqueue(peerWork{kind: peerWorkWrite, write: write, result: result}) +} + +func (q *peerWorkQueue) enqueueBarrier(targetLSN uint64, result chan<- peerWorkResult) (int, error) { + return q.enqueue(peerWork{kind: peerWorkBarrier, targetLSN: targetLSN, result: result}) +} + +func (q *peerWorkQueue) enqueue(work peerWork) (int, error) { + q.mu.Lock() + if q.closed { + err := q.closedErrorLocked() + q.mu.Unlock() + return 0, err + } + select { + case q.jobs <- work: + depth := len(q.jobs) + q.mu.Unlock() + return depth, nil + default: + err := fmt.Errorf("%w: peer %s depth %d", ErrPeerQueueSaturated, q.peerID, cap(q.jobs)) + q.closed = true + q.terminalErr = err + q.cancel() + q.mu.Unlock() + if q.ops.invalidate != nil { + q.ops.invalidate(err.Error()) + } + return 0, err + } +} + +func (q *peerWorkQueue) closeAndWait() { + q.mu.Lock() + if !q.closed { + q.closed = true + q.terminalErr = fmt.Errorf("%w: peer %s", ErrPeerQueueClosed, q.peerID) + q.cancel() + } + q.mu.Unlock() + <-q.done +} + +func (q *peerWorkQueue) isTerminal() bool { + q.mu.Lock() + defer q.mu.Unlock() + return q.closed +} + +func (q *peerWorkQueue) run() { + defer close(q.done) + defer q.failPending() + for { + select { + case <-q.ctx.Done(): + return + default: + } + + select { + case <-q.ctx.Done(): + return + case work := <-q.jobs: + if err := q.ctx.Err(); err != nil { + q.complete(work, peerWorkResult{peerID: q.peerID, err: q.closedError()}) + return + } + result := peerWorkResult{peerID: q.peerID} + switch work.kind { + case peerWorkWrite: + result.eligible, result.err = q.ops.ship(q.ctx, work.write) + case peerWorkBarrier: + result.ackLSN, result.err = q.ops.barrier(q.ctx, work.targetLSN) + default: + result.err = fmt.Errorf("replication: peer %s unknown queue work kind %d", q.peerID, work.kind) + } + q.complete(work, result) + } + } +} + +func (q *peerWorkQueue) failPending() { + err := q.closedError() + for { + select { + case work := <-q.jobs: + q.complete(work, peerWorkResult{peerID: q.peerID, err: err}) + default: + return + } + } +} + +func (q *peerWorkQueue) complete(work peerWork, result peerWorkResult) { + if work.result != nil { + work.result <- result + } +} + +func (q *peerWorkQueue) closedError() error { + q.mu.Lock() + defer q.mu.Unlock() + return q.closedErrorLocked() +} + +func (q *peerWorkQueue) closedErrorLocked() error { + if q.terminalErr != nil { + return q.terminalErr + } + return fmt.Errorf("%w: peer %s", ErrPeerQueueClosed, q.peerID) +} diff --git a/seaweed-block/core/replication/peer_work_queue_test.go b/seaweed-block/core/replication/peer_work_queue_test.go new file mode 100644 index 0000000000..06d6a33a78 --- /dev/null +++ b/seaweed-block/core/replication/peer_work_queue_test.go @@ -0,0 +1,223 @@ +package replication + +import ( + "context" + "errors" + "sync" + "testing" +) + +func TestPeerWorkQueue_PreservesWriteBarrierOrder(t *testing.T) { + var ( + mu sync.Mutex + order []uint64 + ) + q := newPeerWorkQueueWithOps("r1", 8, peerWorkQueueOps{ + ship: func(_ context.Context, write LocalWrite) (bool, error) { + mu.Lock() + order = append(order, write.LSN) + mu.Unlock() + return true, nil + }, + barrier: func(_ context.Context, targetLSN uint64) (uint64, error) { + mu.Lock() + order = append(order, 1000+targetLSN) + mu.Unlock() + return targetLSN, nil + }, + }) + t.Cleanup(q.closeAndWait) + + results := make(chan peerWorkResult, 3) + if _, err := q.enqueueWrite(LocalWrite{LSN: 1}, results); err != nil { + t.Fatal(err) + } + if _, err := q.enqueueWrite(LocalWrite{LSN: 2}, results); err != nil { + t.Fatal(err) + } + if _, err := q.enqueueBarrier(2, results); err != nil { + t.Fatal(err) + } + for i := 0; i < 3; i++ { + if result := <-results; result.err != nil { + t.Fatal(result.err) + } + } + + mu.Lock() + defer mu.Unlock() + want := []uint64{1, 2, 1002} + if len(order) != len(want) { + t.Fatalf("order=%v want %v", order, want) + } + for i := range want { + if order[i] != want[i] { + t.Fatalf("order=%v want %v", order, want) + } + } +} + +func TestPeerWorkQueue_SaturationFailsClosed(t *testing.T) { + started := make(chan struct{}) + release := make(chan struct{}) + invalidated := make(chan string, 1) + q := newPeerWorkQueueWithOps("slow", 1, peerWorkQueueOps{ + ship: func(_ context.Context, _ LocalWrite) (bool, error) { + select { + case <-started: + default: + close(started) + } + <-release + return true, nil + }, + barrier: func(_ context.Context, targetLSN uint64) (uint64, error) { + return targetLSN, nil + }, + invalidate: func(reason string) { + invalidated <- reason + }, + }) + + results := make(chan peerWorkResult, 3) + if _, err := q.enqueueWrite(LocalWrite{LSN: 1}, results); err != nil { + t.Fatal(err) + } + <-started + if _, err := q.enqueueWrite(LocalWrite{LSN: 2}, results); err != nil { + t.Fatal(err) + } + if _, err := q.enqueueWrite(LocalWrite{LSN: 3}, results); !errors.Is(err, ErrPeerQueueSaturated) { + t.Fatalf("saturation error=%v", err) + } + if _, err := q.enqueueWrite(LocalWrite{LSN: 4}, results); !errors.Is(err, ErrPeerQueueSaturated) { + t.Fatalf("post-saturation error=%v", err) + } + if reason := <-invalidated; reason == "" { + t.Fatal("empty invalidation reason") + } + close(release) + q.closeAndWait() +} + +func TestPeerWorkQueue_CloseFailsPendingWork(t *testing.T) { + started := make(chan struct{}) + release := make(chan struct{}) + q := newPeerWorkQueueWithOps("r1", 2, peerWorkQueueOps{ + ship: func(_ context.Context, _ LocalWrite) (bool, error) { + select { + case <-started: + default: + close(started) + } + <-release + return false, errors.New("stopped") + }, + }) + + results := make(chan peerWorkResult, 2) + if _, err := q.enqueueWrite(LocalWrite{LSN: 1}, results); err != nil { + t.Fatal(err) + } + <-started + if _, err := q.enqueueWrite(LocalWrite{LSN: 2}, results); err != nil { + t.Fatal(err) + } + closed := make(chan struct{}) + go func() { + q.closeAndWait() + close(closed) + }() + for { + q.mu.Lock() + queueClosed := q.closed + q.mu.Unlock() + if queueClosed { + break + } + } + close(release) + <-closed + + first := <-results + second := <-results + if first.err == nil { + t.Fatal("in-flight work unexpectedly succeeded") + } + if !errors.Is(second.err, ErrPeerQueueClosed) { + t.Fatalf("pending close error=%v", second.err) + } +} + +func TestPeerWorkQueue_BarrierBelowTargetDegradesPeer(t *testing.T) { + addr, _ := replicaHarness(t, "below-target") + v := volumeHarness(t, "below-target-volume") + if err := v.UpdateReplicaSet(1, []ReplicaTarget{targetFor("r1", addr, 1, 1)}); err != nil { + t.Fatal(err) + } + + v.mu.Lock() + q := v.peerQueues["r1"] + peer := v.peers["r1"] + v.mu.Unlock() + results := make(chan peerWorkResult, 1) + if _, err := q.enqueueBarrier(1, results); err != nil { + t.Fatal(err) + } + result := <-results + if !errors.Is(result.err, ErrBarrierBelowTargetLSN) { + t.Fatalf("barrier error=%v", result.err) + } + if peer.State() != ReplicaDegraded { + t.Fatalf("peer state=%s want degraded", peer.State()) + } +} + +func TestReplicationVolume_LineageReplacementWaitsForOldQueue(t *testing.T) { + addr, _ := replicaHarness(t, "lineage-replace") + v := volumeHarness(t, "lineage-replace-volume") + if err := v.UpdateReplicaSet(1, []ReplicaTarget{targetFor("r1", addr, 1, 1)}); err != nil { + t.Fatal(err) + } + + started := make(chan struct{}) + finished := make(chan struct{}) + oldQueue := newPeerWorkQueueWithOps("r1", 1, peerWorkQueueOps{ + ship: func(ctx context.Context, _ LocalWrite) (bool, error) { + close(started) + <-ctx.Done() + close(finished) + return false, ctx.Err() + }, + }) + v.mu.Lock() + v.closePeerQueueLocked("r1") + v.peerQueues["r1"] = oldQueue + oldPeer := v.peers["r1"] + v.mu.Unlock() + + results := make(chan peerWorkResult, 1) + if _, err := oldQueue.enqueueWrite(LocalWrite{LSN: 1}, results); err != nil { + t.Fatal(err) + } + <-started + if err := v.UpdateReplicaSet(2, []ReplicaTarget{targetFor("r1", addr, 1, 2)}); err != nil { + t.Fatal(err) + } + select { + case <-finished: + default: + t.Fatal("lineage replacement returned before old in-flight queue work stopped") + } + if result := <-results; result.err == nil { + t.Fatal("old-lineage in-flight write unexpectedly succeeded") + } + + v.mu.Lock() + newPeer := v.peers["r1"] + newQueue := v.peerQueues["r1"] + v.mu.Unlock() + if newPeer == oldPeer || newQueue == oldQueue { + t.Fatal("lineage replacement reused old peer or queue") + } +} diff --git a/seaweed-block/core/replication/volume.go b/seaweed-block/core/replication/volume.go index 9cec9329d6..49511625e9 100644 --- a/seaweed-block/core/replication/volume.go +++ b/seaweed-block/core/replication/volume.go @@ -36,13 +36,15 @@ 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. +// VolumeStats is a read-only contention and queue snapshot for write-path +// gates. The counters do not affect acknowledgement or ordering semantics. type VolumeStats struct { WriteOps uint64 WriteLockWaitNanos uint64 WriteFanoutNanos uint64 + WriteAckWaitNanos uint64 + PeerQueueMaxDepth uint64 + PeerQueueSaturated uint64 SyncOps uint64 SyncOrderWaitNanos uint64 SyncLockWaitNanos uint64 @@ -54,6 +56,10 @@ type orderedLocalWrite struct { result chan error } +type localSyncResult struct { + err error +} + type RuntimeRecoveryStatus struct { State string ReplicaID string @@ -66,10 +72,10 @@ type RuntimeRecoveryStatus struct { // ReplicationVolume is the per-volume fan-out owner. It: // - tracks the authoritative replica set (peers) from master // assignments; -// - serializes per-write fan-out so the LSN-order invariant -// V2 enforced via BlockVol.shipMu survives into V3 even though -// the LSN allocation seam (LogicalStorage.Write) is now split -// from the ship seam (this type). +// - resequences concurrent local callbacks by global LSN; +// - dispatches writes and barriers through one bounded FIFO per peer +// lineage, preserving wire order without holding a whole-volume network +// lock. // // Lifecycle: borrowed LogicalStorage — Provider owns the engine; // ReplicationVolume must NEVER call store.Close() (BUG-005 discipline). @@ -78,10 +84,11 @@ type ReplicationVolume struct { store storage.LogicalStorage // borrowed, NEVER closed by us newExec executorFactory // test seam; default dials real TCP newDualExec dualLaneExecutorFactory // optional dual-lane override; nil = use newExec - coord *DurabilityCoordinator // used by Sync; stateless - mu sync.Mutex // serializes UpdateReplicaSet + OnLocalWrite entry AND fan-out AND Sync + mu sync.Mutex // protects membership, lineage, and lifecycle snapshots peers map[string]*ReplicaPeer + peerQueues map[string]*peerWorkQueue + peerQueueDepth int closed bool lastAppliedGeneration uint64 // monotonic guard; 0 means "no generation applied yet" durabilityMode DurabilityMode // set via SetDurabilityMode; default is BestEffort @@ -90,10 +97,13 @@ type ReplicationVolume struct { // (generation > 0 && generation <= lastAppliedGeneration). replayedGens atomic.Uint64 - // Write/sync counters expose the current whole-volume serialization cost. + // Write/sync counters expose snapshot, dispatch, queue, and ACK costs. writeOps atomic.Uint64 writeWait atomic.Uint64 writeFanout atomic.Uint64 + writeAckWait atomic.Uint64 + queueMaxDepth atomic.Uint64 + queueFull atomic.Uint64 syncOps atomic.Uint64 syncOrderWait atomic.Uint64 syncWait atomic.Uint64 @@ -128,6 +138,7 @@ type ReplicationVolume struct { } const promotionSeedBarrierTimeout = 5 * time.Second +const defaultPeerWorkQueueDepth = 1024 // executorFactory lets tests inject a BlockExecutor constructor that // binds to a specific replica address. Production uses the real @@ -152,7 +163,7 @@ type dualLaneExecutorFactory func(store storage.LogicalStorage, replicaAddr, rep // Called by: DurableProvider / Host composition root at volume // lifecycle start, after LogicalStorage is recovered and ready. // Owns: the peers map; all *ReplicaPeer lifecycles (Close on remove); -// the volume-level serialization mutex. +// the LSN resequencer and lineage-scoped work queues. // Borrows: store (LogicalStorage). Provider owns engine lifecycle; // ReplicationVolume MUST NOT call store.Close() (BUG-005). func NewReplicationVolume(volumeID string, store storage.LogicalStorage) *ReplicationVolume { @@ -161,8 +172,9 @@ func NewReplicationVolume(volumeID string, store storage.LogicalStorage) *Replic volumeID: volumeID, store: store, newExec: transport.NewBlockExecutor, - coord: NewDurabilityCoordinator(), peers: make(map[string]*ReplicaPeer), + peerQueues: make(map[string]*peerWorkQueue), + peerQueueDepth: defaultPeerWorkQueueDepth, durabilityMode: DurabilityBestEffort, // zero value; explicit for clarity nextShipLSN: store.NextLSN(), pending: make(map[uint64]*orderedLocalWrite), @@ -198,10 +210,9 @@ func (v *ReplicationVolume) SetDualLaneExecutorFactory(f func(store storage.Logi v.newDualExec = f } -// SetDurabilityMode configures the per-volume durability semantic -// that Sync uses. Safe to call at any time; effect applies from the -// next Sync call forward. There is no per-Sync-call mode override — -// mode is a per-volume setting. +// SetDurabilityMode configures the per-volume write and Sync +// acknowledgement semantic. Safe to call at any time; each operation uses the +// mode captured with its membership snapshot. // // Called by: Host / Provider composition root at volume lifecycle // start, or on operator reconfiguration. @@ -221,26 +232,11 @@ func (v *ReplicationVolume) DurabilityMode() DurabilityMode { return v.durabilityMode } -// Sync runs the per-volume durability closure for host-requested -// cache flushes. Delegates to DurabilityCoordinator.SyncLocalAndReplicas -// with the volume's configured mode + current peer set + a localSync -// closure that wraps LogicalStorage.Sync. -// -// Lock scope: v.mu is held across the FULL call. This preserves the -// same discipline as OnLocalWrite — LSN-order fan-out serialization -// at the replication layer. Concurrent Sync and OnLocalWrite calls -// are thus serialized on v.mu. Accepted correctness-first trade-off: -// a slow peer barrier stalls other writers on the same volume; -// async-queue optimization is a future refinement. -// -// Pinned by: INV-REPL-LSN-ORDER-FANOUT-001 + -// TestReplicationVolume_Sync_PreservesLSNOrder_UnderConcurrency. -// -// Called by: StorageBackend.Sync (when a WriteObserver is installed) -// per host-side FLUSH / SYNCHRONIZE_CACHE. -// Owns: v.mu across the full SyncLocalAndReplicas call; peer snapshot -// assembly. -// Borrows: ctx + targetLSN from caller. +// Sync queues one barrier behind every write through targetLSN, runs the local +// fsync in parallel, and applies the configured acknowledgement policy. The +// membership mutex is held only long enough to snapshot lineage-scoped queues. +// A sync-quorum call may return after the local fsync plus enough peer barriers +// succeed; queued work for a slow non-quorum peer continues in its own FIFO. func (v *ReplicationVolume) Sync(ctx context.Context, targetLSN uint64) error { if err := ctx.Err(); err != nil { return err @@ -255,28 +251,33 @@ func (v *ReplicationVolume) Sync(ctx context.Context, targetLSN uint64) error { v.mu.Lock() v.syncOps.Add(1) v.syncWait.Add(replicationDurationNanos(time.Since(lockStart))) + if v.closed { + v.mu.Unlock() + return fmt.Errorf("replication: Sync: volume %s closed", v.volumeID) + } + mode := v.durabilityMode + localResult := make(chan localSyncResult, 1) + go func() { + _, err := v.store.Sync() + localResult <- localSyncResult{err: err} + }() + + peerCount := len(v.peerQueues) + results := make(chan peerWorkResult, peerCount) + for _, q := range v.peerQueues { + depth, err := q.enqueueBarrier(targetLSN, results) + v.observeQueueDepth(depth) + if err != nil { + v.observeQueueError(err) + results <- peerWorkResult{peerID: q.peerID, err: err} + v.replaceTerminalPeerQueueLocked(q.peerID, q) + } + } + v.mu.Unlock() 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) - } - - // Snapshot the peers under v.mu — DurabilityCoordinator reads - // them from a slice so no further lock coordination is needed. - peers := make([]*ReplicaPeer, 0, len(v.peers)) - for _, p := range v.peers { - peers = append(peers, p) - } - - mode := v.durabilityMode - localSync := func(ctx context.Context) (uint64, error) { - return v.store.Sync() - } - - _, err := v.coord.SyncLocalAndReplicas(ctx, mode, targetLSN, localSync, peers) - return err + return waitForSyncAcks(ctx, mode, targetLSN, peerCount, localResult, results) } // UpdateReplicaSet applies the authoritative replica set from a master @@ -347,6 +348,7 @@ func (v *ReplicationVolume) UpdateReplicaSet(generation uint64, targets []Replic // path is used for N → 0 (empty targets) — no special branch. for id, peer := range v.peers { if _, keep := want[id]; !keep { + v.closePeerQueueLocked(id) _ = peer.Close() delete(v.peers, id) // Notify peer-lifecycle hook AFTER peer.Close to mirror @@ -367,6 +369,7 @@ func (v *ReplicationVolume) UpdateReplicaSet(generation uint64, targets []Replic continue } // Lineage or address bumped → tear down + recreate. + v.closePeerQueueLocked(id) _ = existing.Close() delete(v.peers, id) // Lineage-bump teardown also notifies the hook so the @@ -386,6 +389,9 @@ func (v *ReplicationVolume) UpdateReplicaSet(generation uint64, targets []Replic if err != nil { return fmt.Errorf("replication: UpdateReplicaSet: add peer %s: %w", id, err) } + peer.setOnHealthy(func() { + v.resetTerminalPeerQueue(peer) + }) // Push the volume-level probe cooldown config onto the fresh // peer. A new peer (whether first add or post-lineage-bump // recreate) starts with cooldown reset to defaults; the prior @@ -399,6 +405,7 @@ func (v *ReplicationVolume) UpdateReplicaSet(generation uint64, targets []Replic }) } v.peers[id] = peer + v.peerQueues[id] = newPeerWorkQueue(peer, v.peerQueueDepth) // Notify peer-lifecycle hook AFTER the peer is installed in // the map so the host's registry can construct the per-peer // adapter and prime it with the peer's identity. @@ -417,6 +424,38 @@ func (v *ReplicationVolume) UpdateReplicaSet(generation uint64, targets []Replic return nil } +func (v *ReplicationVolume) closePeerQueueLocked(replicaID string) { + if q := v.peerQueues[replicaID]; q != nil { + q.closeAndWait() + delete(v.peerQueues, replicaID) + } +} + +func (v *ReplicationVolume) resetTerminalPeerQueue(peer *ReplicaPeer) { + id := peer.Target().ReplicaID + v.mu.Lock() + defer v.mu.Unlock() + if v.closed || v.peers[id] != peer { + return + } + v.replaceTerminalPeerQueueLocked(id, v.peerQueues[id]) +} + +func (v *ReplicationVolume) replaceTerminalPeerQueueLocked(id string, old *peerWorkQueue) *peerWorkQueue { + if old == nil || v.peerQueues[id] != old || !old.isTerminal() { + return v.peerQueues[id] + } + old.closeAndWait() + peer := v.peers[id] + if peer == nil || v.closed { + delete(v.peerQueues, id) + return nil + } + replacement := newPeerWorkQueue(peer, v.peerQueueDepth) + v.peerQueues[id] = replacement + return replacement +} + // seedNewPeerLiveCursorsLocked verifies that newly installed peers have // durably reached this node's local frontier, then seeds their live // ship cursor so the first post-promotion write starts at frontier+1. @@ -513,9 +552,9 @@ func formatIDSet(s map[string]struct{}) string { // // 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. +// The resequencer retains owned buffers until every preceding LSN has been +// dispatched to the lineage-scoped peer queues. Each queue then preserves the +// same order independently. // // Best-effort semantics: per-peer ship errors are logged and the // offending peer is marked Degraded (by ReplicaPeer.ShipEntry's own @@ -523,18 +562,27 @@ func formatIDSet(s map[string]struct{}) string { // call — the remaining peers still receive the entry. Stricter // durability closure (sync_all / sync_quorum) is layered above this. // -// Accepted trade-off: this is a correctness-first serialized design. -// Throughput may be reduced or peer slowness may amplify into writer -// latency when a peer's dial / write is slow. Async-queue -// optimization is a future refinement. -// // Called by: Backend.Write wrapper immediately after // LogicalStorage.Write returns with the assigned LSN. // 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 { + req, err := v.enqueueLocalWrite(w) + if err != nil { + return err + } + + select { + case err := <-req.result: + return err + case <-ctx.Done(): + return ctx.Err() + } +} + +func (v *ReplicationVolume) enqueueLocalWrite(w LocalWrite) (*orderedLocalWrite, error) { if w.LSN == 0 { - return errors.New("replication: OnLocalWrite: LSN must be nonzero") + return nil, errors.New("replication: OnLocalWrite: LSN must be nonzero") } owned := append([]byte(nil), w.Data...) req := &orderedLocalWrite{ @@ -545,20 +593,20 @@ func (v *ReplicationVolume) OnLocalWrite(ctx context.Context, w LocalWrite) erro v.orderMu.Lock() if v.orderClosed { v.orderMu.Unlock() - return fmt.Errorf("replication: OnLocalWrite: volume %s closed", v.volumeID) + return nil, 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) + return nil, 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) + return nil, fmt.Errorf("replication: OnLocalWrite: duplicate pending LSN %d", w.LSN) } if w.LSN == v.inflightLSN { v.orderMu.Unlock() - return fmt.Errorf("replication: OnLocalWrite: duplicate in-flight LSN %d", w.LSN) + return nil, fmt.Errorf("replication: OnLocalWrite: duplicate in-flight LSN %d", w.LSN) } v.pending[w.LSN] = req leader := !v.draining @@ -570,13 +618,7 @@ func (v *ReplicationVolume) OnLocalWrite(ctx context.Context, w LocalWrite) erro if leader { go v.drainOrderedWrites() } - - select { - case err := <-req.result: - return err - case <-ctx.Done(): - return ctx.Err() - } + return req, nil } func (v *ReplicationVolume) drainOrderedWrites() { @@ -597,8 +639,7 @@ func (v *ReplicationVolume) drainOrderedWrites() { v.inflightLSN = req.write.LSN v.orderMu.Unlock() - err := v.shipLocalWrite(v.lifecycle, req.write) - req.result <- err + acks := v.dispatchLocalWrite(req.write) v.orderMu.Lock() v.inflightLSN = 0 @@ -608,6 +649,10 @@ func (v *ReplicationVolume) drainOrderedWrites() { v.progress = make(chan struct{}) } v.orderMu.Unlock() + + go func(req *orderedLocalWrite, acks writeAckSet) { + req.result <- v.waitForWriteAcks(v.lifecycle, acks) + }(req, acks) } } @@ -633,78 +678,73 @@ func (v *ReplicationVolume) waitUntilShipped(ctx context.Context, targetLSN uint } } -func (v *ReplicationVolume) shipLocalWrite(ctx context.Context, w LocalWrite) error { +type writeAckSet struct { + mode DurabilityMode + rf int + peerCount int + results <-chan peerWorkResult + directErr error +} + +func (v *ReplicationVolume) dispatchLocalWrite(w LocalWrite) writeAckSet { 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) + v.mu.Unlock() + return writeAckSet{directErr: fmt.Errorf("replication: OnLocalWrite: volume %s closed", v.volumeID)} } - // Log entry with peer count so we can disambiguate - // "OnLocalWrite never called" vs "called but peers map is empty" - // vs "called and fans out". - log.Printf("replication: OnLocalWrite volume=%s lba=%d lsn=%d peers=%d", - v.volumeID, w.LBA, w.LSN, len(v.peers)) - mode := v.durabilityMode - rf := len(v.peers) + 1 - successes := 0 - failures := 0 + peerCount := len(v.peerQueues) + results := make(chan peerWorkResult, peerCount) + for _, q := range v.peerQueues { + depth, err := q.enqueueWrite(w, results) + v.observeQueueDepth(depth) + if err != nil { + v.observeQueueError(err) + results <- peerWorkResult{peerID: q.peerID, err: err} + replacement := v.replaceTerminalPeerQueueLocked(q.peerID, q) + if replacement != nil && replacement != q { + shadowDepth, shadowErr := replacement.enqueueWrite(w, nil) + v.observeQueueDepth(shadowDepth) + if shadowErr != nil { + v.observeQueueError(shadowErr) + log.Printf("replication: retained write enqueue failed peer=%s lsn=%d: %v", + q.peerID, w.LSN, shadowErr) + } + } + } + } + v.mu.Unlock() - // Fan out under the mutex — LSN-order invariant. Lineage is - // informational; each peer uses its own registered lineage for - // authority framing. - informational := transport.RecoveryLineage{} - for _, peer := range v.peers { - eligible := peer.State() == ReplicaHealthy - if err := peer.ShipEntry(ctx, informational, w.LBA, w.LSN, w.Data); err != nil { - log.Printf("replication: volume %s peer %s ship failed lsn=%d: %v", - v.volumeID, peer.Target().ReplicaID, w.LSN, err) - // Best-effort: continue iterating peers. Peer is already - // marked Degraded inside ShipEntry. - failures++ - continue - } - if eligible { - successes++ - } else { - failures++ - } + log.Printf("replication: OnLocalWrite volume=%s lba=%d lsn=%d peers=%d", + v.volumeID, w.LBA, w.LSN, peerCount) + + v.writeFanout.Add(replicationDurationNanos(time.Since(start))) + return writeAckSet{ + mode: mode, + rf: peerCount + 1, + peerCount: peerCount, + results: results, } - if err := evaluateWriteAck(mode, rf, successes, failures); err != nil { - return err - } - return nil } -func evaluateWriteAck(mode DurabilityMode, rf, peerSuccesses, peerFailures int) error { - switch mode { - case DurabilitySyncAll: - if peerFailures > 0 { - return fmt.Errorf("%w: %d of %d write acknowledgements unavailable", - ErrDurabilityBarrierFailed, peerFailures, rf-1) - } - case DurabilitySyncQuorum: - quorum := rf/2 + 1 - durableNodes := 1 + peerSuccesses // local primary write already succeeded before Observe. - if durableNodes < quorum { - return fmt.Errorf("%w: %d durable of %d needed for write acknowledgement", - ErrDurabilityQuorumLost, durableNodes, quorum) - } +func (v *ReplicationVolume) waitForWriteAcks(ctx context.Context, acks writeAckSet) error { + if acks.directErr != nil { + return acks.directErr } - return nil + start := time.Now() + defer func() { + v.writeAckWait.Add(replicationDurationNanos(time.Since(start))) + }() + return waitForPeerAcks(ctx, acks.mode, acks.rf, acks.peerCount, acks.results, "write") } // Stop is the canonical lifecycle entry point. Tears down all peers -// (their executor sessions are invalidated), serializes against -// concurrent OnLocalWrite/Sync via the volume mutex, and is -// idempotent. Does NOT close the borrowed store +// (their executor sessions are invalidated), closes ordered work queues, +// and is idempotent. Does NOT close the borrowed store // (`INV-REPL-LIFECYCLE-HANDLE-BORROWED-001`). // // Stop and Close are equivalent (Stop delegates to Close); the @@ -767,6 +807,9 @@ func (v *ReplicationVolume) Close() error { return nil } v.closed = true + for id := range v.peerQueues { + v.closePeerQueueLocked(id) + } for id, peer := range v.peers { _ = peer.Close() delete(v.peers, id) @@ -783,12 +826,57 @@ func (v *ReplicationVolume) Close() error { // // Called by: core/frontend/durable.StorageBackend.writeBytes // after a successful LogicalStorage.Write. -// Owns: same serialization and fan-out semantics as OnLocalWrite. +// Owns: same resequencing and fan-out semantics as OnLocalWrite. // Borrows: data slice; see OnLocalWrite for the full contract. func (v *ReplicationVolume) Observe(ctx context.Context, lba uint32, lsn uint64, data []byte) error { return v.OnLocalWrite(ctx, LocalWrite{LBA: lba, Data: data, LSN: lsn}) } +// ObserveBatch submits a contiguous storage batch to the LSN resequencer +// before waiting for any individual acknowledgement. This preserves storage +// batching while each peer FIFO retains the wire-order invariant. +func (v *ReplicationVolume) ObserveBatch(ctx context.Context, startLBA uint32, lsns []uint64, blocks [][]byte) error { + if len(lsns) != len(blocks) { + return fmt.Errorf("replication: ObserveBatch: %d LSNs for %d blocks", len(lsns), len(blocks)) + } + if len(lsns) == 0 { + return nil + } + for i, lsn := range lsns { + if lsn == 0 { + return fmt.Errorf("replication: ObserveBatch: zero LSN at index %d", i) + } + if i > 0 && lsn != lsns[i-1]+1 { + return fmt.Errorf("replication: ObserveBatch: non-contiguous LSN %d after %d", lsn, lsns[i-1]) + } + } + + requests := make([]*orderedLocalWrite, 0, len(lsns)) + for i, lsn := range lsns { + req, err := v.enqueueLocalWrite(LocalWrite{ + LBA: startLBA + uint32(i), + LSN: lsn, + Data: blocks[i], + }) + if err != nil { + return err + } + requests = append(requests, req) + } + + for _, req := range requests { + select { + case err := <-req.result: + if err != nil { + return err + } + case <-ctx.Done(): + return ctx.Err() + } + } + return nil +} + // PeerCount returns the current number of tracked peers. Test helper // and diagnostic accessor. func (v *ReplicationVolume) PeerCount() int { @@ -803,6 +891,9 @@ func (v *ReplicationVolume) Stats() VolumeStats { WriteOps: v.writeOps.Load(), WriteLockWaitNanos: v.writeWait.Load(), WriteFanoutNanos: v.writeFanout.Load(), + WriteAckWaitNanos: v.writeAckWait.Load(), + PeerQueueMaxDepth: v.queueMaxDepth.Load(), + PeerQueueSaturated: v.queueFull.Load(), SyncOps: v.syncOps.Load(), SyncOrderWaitNanos: v.syncOrderWait.Load(), SyncLockWaitNanos: v.syncWait.Load(), @@ -810,6 +901,25 @@ func (v *ReplicationVolume) Stats() VolumeStats { } } +func (v *ReplicationVolume) observeQueueDepth(depth int) { + if depth <= 0 { + return + } + value := uint64(depth) + for { + current := v.queueMaxDepth.Load() + if value <= current || v.queueMaxDepth.CompareAndSwap(current, value) { + return + } + } +} + +func (v *ReplicationVolume) observeQueueError(err error) { + if errors.Is(err, ErrPeerQueueSaturated) { + v.queueFull.Add(1) + } +} + func replicationDurationNanos(d time.Duration) uint64 { if d <= 0 { return 1 diff --git a/seaweed-block/core/replication/volume_async_queue_test.go b/seaweed-block/core/replication/volume_async_queue_test.go new file mode 100644 index 0000000000..dca94dba6a --- /dev/null +++ b/seaweed-block/core/replication/volume_async_queue_test.go @@ -0,0 +1,337 @@ +package replication + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestReplicationVolume_ObserveBatchSyncQuorumDoesNotWaitForSlowNonQuorumPeer(t *testing.T) { + v := NewReplicationVolume("batch-quorum", storage.NewBlockStore(64, 4096)) + v.SetDurabilityMode(DurabilitySyncQuorum) + + var ( + fastMu sync.Mutex + fastLSNs []uint64 + slowMu sync.Mutex + slowLSNs []uint64 + ) + slowStarted := make(chan struct{}) + slowDrained := make(chan struct{}) + releaseSlow := make(chan struct{}) + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(releaseSlow) }) } + + fast := newPeerWorkQueueWithOps("fast", 16, peerWorkQueueOps{ + ship: func(_ context.Context, write LocalWrite) (bool, error) { + fastMu.Lock() + fastLSNs = append(fastLSNs, write.LSN) + fastMu.Unlock() + return true, nil + }, + barrier: func(_ context.Context, targetLSN uint64) (uint64, error) { + return targetLSN, nil + }, + }) + slow := newPeerWorkQueueWithOps("slow", 16, peerWorkQueueOps{ + ship: func(_ context.Context, write LocalWrite) (bool, error) { + if write.LSN == 1 { + select { + case <-slowStarted: + default: + close(slowStarted) + } + <-releaseSlow + } + slowMu.Lock() + slowLSNs = append(slowLSNs, write.LSN) + if len(slowLSNs) == 4 { + close(slowDrained) + } + slowMu.Unlock() + return true, nil + }, + barrier: func(_ context.Context, targetLSN uint64) (uint64, error) { + return targetLSN, nil + }, + }) + v.mu.Lock() + v.peerQueues["fast"] = fast + v.peerQueues["slow"] = slow + v.mu.Unlock() + t.Cleanup(func() { _ = v.Close() }) + t.Cleanup(release) + + blocks := make([][]byte, 4) + for i := range blocks { + blocks[i] = make([]byte, 4096) + blocks[i][0] = byte(i + 1) + } + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + if err := v.ObserveBatch(ctx, 0, []uint64{1, 2, 3, 4}, blocks); err != nil { + t.Fatal(err) + } + select { + case <-slowStarted: + case <-time.After(250 * time.Millisecond): + t.Fatal("slow peer never received the first queued write") + } + + fastMu.Lock() + if len(fastLSNs) != 4 { + fastMu.Unlock() + t.Fatalf("fast peer LSNs=%v want [1 2 3 4]", fastLSNs) + } + for i, lsn := range fastLSNs { + if lsn != uint64(i+1) { + fastMu.Unlock() + t.Fatalf("fast peer LSNs=%v want [1 2 3 4]", fastLSNs) + } + } + fastMu.Unlock() + + release() + select { + case <-slowDrained: + case <-time.After(time.Second): + t.Fatal("slow peer did not drain all queued writes") + } + slowMu.Lock() + defer slowMu.Unlock() + if len(slowLSNs) != 4 { + t.Fatalf("slow peer LSNs=%v want [1 2 3 4]", slowLSNs) + } + for i, lsn := range slowLSNs { + if lsn != uint64(i+1) { + t.Fatalf("slow peer LSNs=%v want [1 2 3 4]", slowLSNs) + } + } +} + +func TestReplicationVolume_SyncQuorumDoesNotWaitForSlowNonQuorumBarrier(t *testing.T) { + v, releaseSlow, slowStarted := volumeWithControlledBarrierQueues(t, DurabilitySyncQuorum) + defer releaseSlow() + + if err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: 0, LSN: 1, Data: make([]byte, 4096)}); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + if err := v.Sync(ctx, 1); err != nil { + t.Fatal(err) + } + select { + case <-slowStarted: + case <-time.After(250 * time.Millisecond): + t.Fatal("slow peer barrier was not queued") + } +} + +func TestReplicationVolume_SyncAllWaitsForSlowBarrier(t *testing.T) { + v, releaseSlow, slowStarted := volumeWithControlledBarrierQueues(t, DurabilitySyncAll) + if err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: 0, LSN: 1, Data: make([]byte, 4096)}); err != nil { + t.Fatal(err) + } + + done := make(chan error, 1) + go func() { + done <- v.Sync(context.Background(), 1) + }() + <-slowStarted + select { + case err := <-done: + t.Fatalf("sync_all returned before slow barrier release: %v", err) + case <-time.After(25 * time.Millisecond): + } + releaseSlow() + if err := <-done; err != nil { + t.Fatal(err) + } +} + +func TestReplicationVolume_QueueSaturationIsTypedAndCounted(t *testing.T) { + v := NewReplicationVolume("queue-saturation", storage.NewBlockStore(64, 4096)) + started := make(chan struct{}) + releaseCh := make(chan struct{}) + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(releaseCh) }) } + q := newPeerWorkQueueWithOps("slow", 1, peerWorkQueueOps{ + ship: func(ctx context.Context, _ LocalWrite) (bool, error) { + select { + case <-started: + default: + close(started) + } + select { + case <-releaseCh: + return true, nil + case <-ctx.Done(): + return false, ctx.Err() + } + }, + }) + v.mu.Lock() + v.peerQueues["slow"] = q + v.mu.Unlock() + t.Cleanup(func() { _ = v.Close() }) + t.Cleanup(release) + + first, err := v.enqueueLocalWrite(LocalWrite{LBA: 0, LSN: 1, Data: make([]byte, 4096)}) + if err != nil { + t.Fatal(err) + } + <-started + second, err := v.enqueueLocalWrite(LocalWrite{LBA: 1, LSN: 2, Data: make([]byte, 4096)}) + if err != nil { + t.Fatal(err) + } + third, err := v.enqueueLocalWrite(LocalWrite{LBA: 2, LSN: 3, Data: make([]byte, 4096)}) + if err != nil { + t.Fatal(err) + } + select { + case err := <-third.result: + if !errors.Is(err, ErrPeerQueueSaturated) { + t.Fatalf("third write error=%v", err) + } + case <-time.After(time.Second): + t.Fatal("saturated write did not complete") + } + if got := v.Stats().PeerQueueSaturated; got != 1 { + t.Fatalf("PeerQueueSaturated=%d want 1", got) + } + release() + <-first.result + <-second.result +} + +func TestReplicationVolume_HealthyRecoveryReplacesTerminalPeerQueue(t *testing.T) { + addr, _ := replicaHarness(t, "queue-recovery") + v := volumeHarness(t, "queue-recovery-volume") + if err := v.UpdateReplicaSet(1, []ReplicaTarget{targetFor("r1", addr, 1, 1)}); err != nil { + t.Fatal(err) + } + + v.mu.Lock() + oldQueue := v.peerQueues["r1"] + peer := v.peers["r1"] + v.mu.Unlock() + oldQueue.closeAndWait() + peer.SetState(ReplicaDegraded) + peer.SetState(ReplicaHealthy) + + v.mu.Lock() + newQueue := v.peerQueues["r1"] + v.mu.Unlock() + if newQueue == nil || newQueue == oldQueue { + t.Fatal("healthy recovery did not replace terminal peer queue") + } + results := make(chan peerWorkResult, 1) + if _, err := newQueue.enqueueWrite(LocalWrite{LBA: 0, LSN: 1, Data: make([]byte, 4096)}, results); err != nil { + t.Fatalf("replacement queue rejected write: %v", err) + } + if result := <-results; result.err != nil { + t.Fatalf("replacement queue write failed: %v", result.err) + } +} + +func TestReplicationVolume_RecoveryQueueResetCannotLoseConcurrentWrite(t *testing.T) { + addr, replicaStore := replicaHarness(t, "queue-reset-race") + v := volumeHarness(t, "queue-reset-race-volume") + if err := v.UpdateReplicaSet(1, []ReplicaTarget{targetFor("r1", addr, 1, 1)}); err != nil { + t.Fatal(err) + } + + v.mu.Lock() + oldQueue := v.peerQueues["r1"] + peer := v.peers["r1"] + v.mu.Unlock() + oldQueue.closeAndWait() + peer.SetState(ReplicaDegraded) + + callbackStarted := make(chan struct{}) + releaseCallback := make(chan struct{}) + peer.setOnHealthy(func() { + close(callbackStarted) + <-releaseCallback + v.resetTerminalPeerQueue(peer) + }) + stateDone := make(chan struct{}) + go func() { + peer.SetState(ReplicaHealthy) + close(stateDone) + }() + <-callbackStarted + + data := make([]byte, 4096) + data[0] = 0x7a + acks := v.dispatchLocalWrite(LocalWrite{LBA: 0, LSN: 1, Data: data}) + if err := v.waitForWriteAcks(context.Background(), acks); !errors.Is(err, ErrPeerQueueClosed) { + t.Fatalf("write error=%v want old terminal queue evidence", err) + } + close(releaseCallback) + <-stateDone + + deadline := time.Now().Add(time.Second) + for { + got, err := replicaStore.Read(0) + if err == nil && len(got) > 0 && got[0] == 0x7a { + break + } + if time.Now().After(deadline) { + t.Fatal("concurrent write was not delivered through the replacement queue") + } + time.Sleep(time.Millisecond) + } + + v.mu.Lock() + newQueue := v.peerQueues["r1"] + v.mu.Unlock() + if newQueue == nil || newQueue == oldQueue { + t.Fatal("terminal queue was not replaced") + } +} + +func volumeWithControlledBarrierQueues( + t *testing.T, + mode DurabilityMode, +) (*ReplicationVolume, func(), <-chan struct{}) { + t.Helper() + v := NewReplicationVolume("controlled-barrier", storage.NewBlockStore(64, 4096)) + v.SetDurabilityMode(mode) + + slowStarted := make(chan struct{}) + releaseCh := make(chan struct{}) + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(releaseCh) }) } + newQueue := func(peerID string, slow bool) *peerWorkQueue { + return newPeerWorkQueueWithOps(peerID, 16, peerWorkQueueOps{ + ship: func(_ context.Context, _ LocalWrite) (bool, error) { + return true, nil + }, + barrier: func(_ context.Context, targetLSN uint64) (uint64, error) { + if slow { + select { + case <-slowStarted: + default: + close(slowStarted) + } + <-releaseCh + } + return targetLSN, nil + }, + }) + } + v.mu.Lock() + v.peerQueues["fast"] = newQueue("fast", false) + v.peerQueues["slow"] = newQueue("slow", true) + v.mu.Unlock() + t.Cleanup(func() { _ = v.Close() }) + t.Cleanup(release) + return v, release, slowStarted +} diff --git a/seaweed-block/core/replication/volume_contention_bench_test.go b/seaweed-block/core/replication/volume_contention_bench_test.go index 6409849ef4..4f95e1e356 100644 --- a/seaweed-block/core/replication/volume_contention_bench_test.go +++ b/seaweed-block/core/replication/volume_contention_bench_test.go @@ -153,9 +153,16 @@ func BenchmarkPhase167RF3SyncQuorumContention(b *testing.B) { } } for replicaIndex, replicaStore := range replicaStores { - _, _, head := replicaStore.Boundaries() - if head != uint64(b.N) { - b.Fatalf("replica %d head=%d want %d", replicaIndex, head, b.N) + deadline := time.Now().Add(3 * time.Second) + for { + _, _, head := replicaStore.Boundaries() + if head == uint64(b.N) { + break + } + if time.Now().After(deadline) { + b.Fatalf("replica %d head=%d want %d after queued-work drain", replicaIndex, head, b.N) + } + time.Sleep(time.Millisecond) } if b.N <= numBlocks { for idx := 0; idx < b.N; idx++ { @@ -174,6 +181,9 @@ func BenchmarkPhase167RF3SyncQuorumContention(b *testing.B) { 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(stats.WriteAckWaitNanos)/float64(stats.WriteOps), "repl_ack_wait_ns/op") + b.ReportMetric(float64(stats.PeerQueueMaxDepth), "peer_queue_max_depth") + b.ReportMetric(float64(stats.PeerQueueSaturated), "peer_queue_saturated") b.ReportMetric(float64(b.N)/wallDuration.Seconds(), "write_ops/s") }) } diff --git a/seaweed-block/core/transport/executor.go b/seaweed-block/core/transport/executor.go index 7d78e8f16b..9d4b0332e9 100644 --- a/seaweed-block/core/transport/executor.go +++ b/seaweed-block/core/transport/executor.go @@ -446,8 +446,8 @@ func (e *BlockExecutor) doFence(replicaID string, lineage RecoveryLineage) { // A future optimization MUST NOT weaken this to epoch-only; the // full-lineage rule is load-bearing for the durability gate. // -// Called by: DurabilityCoordinator.SyncLocalAndReplicas per-peer -// fan-out. +// Called by: replication's per-peer ordered work queue and by the legacy +// synchronous durability coordinator contract. // Owns: per-call conn deadline (recoveryConnTimeout); lineage binding; // ack validation against the session's registered lineage. // Borrows: session by replicaID + lineage.SessionID; BarrierAck diff --git a/seaweed-block/internal/docs/current-plan.md b/seaweed-block/internal/docs/current-plan.md index 10100a13fc..716560b776 100644 --- a/seaweed-block/internal/docs/current-plan.md +++ b/seaweed-block/internal/docs/current-plan.md @@ -64,10 +64,39 @@ The D1 local baseline slice is implemented and repeatable through - 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. +The D2 ordered asynchronous replication slice is implemented and repeatable +through `scripts/run-phase167-ordered-async-replication-gate.sh`: + +- each replica lineage owns one bounded FIFO shared by writes and barriers, so + per-peer LSN order is retained without holding the whole-volume mutex across + network I/O; +- the global resequencer dispatches every contiguous committed LSN before + waiting for individual acknowledgements, allowing multiple writes and + independent peers to remain in flight; +- sync-quorum returns after local durability plus the required peer frontier, + while a slow non-quorum queue continues independently; sync-all still waits + for every peer; +- queue saturation fails closed with typed evidence and degrades that peer + lineage rather than skipping one LSN and sending later writes; +- terminal queue failures cannot be hidden by an earlier ordinary transport + error; terminal replacement and enqueue are atomic with queue identity, and + the failed committed write is retained on the replacement queue so the + recovery boundary cannot lose its first LSN; +- write and barrier queues are closed before a removed or replaced peer + lineage is torn down; the gate verifies an in-flight old-lineage write has + stopped before replacement returns; +- strict observer-ack mode now retains full-block storage batching through an + explicit batch observer seam, including correct observation of a partially + committed batch prefix; +- repeated slow-peer, sync-all, saturation, ordering, and batch tests pass, + and the real-TCP RF3 gate verifies eventual frontier and byte agreement on + both replicas with zero normal-path queue saturation. + +D2 is a correctness and slow-peer isolation improvement, not yet a throughput +win. The latest same-host result measured about `49.38 MiB/s` for one RF3 +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. ## Assumptions And Boundaries diff --git a/seaweed-block/scripts/run-phase167-ordered-async-replication-gate.sh b/seaweed-block/scripts/run-phase167-ordered-async-replication-gate.sh new file mode 100755 index 0000000000..9863170e58 --- /dev/null +++ b/seaweed-block/scripts/run-phase167-ordered-async-replication-gate.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT="${1:-$(pwd)}" +ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-${ROOT}/results/phase167-ordered-async-replication-gate}" +SUMMARY="${ARTIFACT_DIR}/phase167-ordered-async-replication-summary.txt" +CONTENT_DIR="${ARTIFACT_DIR}/contention" +mkdir -p "${ARTIFACT_DIR}" +: >"${SUMMARY}" + +write_summary() { + echo "$*" | tee -a "${SUMMARY}" >/dev/null +} + +write_summary "phase167_ordered_async_replication_status=running" +write_summary "scope=local_component_and_real_tcp_rf3" +write_summary "mounted_nvme_claim_allowed=false" + +cd "${ROOT}" +go test ./core/replication \ + -run 'Test(WaitFor|PeerWorkQueue|ReplicationVolume_(ObserveBatchSyncQuorumDoesNotWaitForSlowNonQuorumPeer|SyncQuorumDoesNotWaitForSlowNonQuorumBarrier|SyncAllWaitsForSlowBarrier|QueueSaturationIsTypedAndCounted|HealthyRecoveryReplacesTerminalPeerQueue|RecoveryQueueResetCannotLoseConcurrentWrite|LineageReplacementWaitsForOldQueue))' \ + -count=25 \ + >"${ARTIFACT_DIR}/ordered-queue-tests.log" 2>&1 +write_summary "ordered_queue_tests=pass" + +go test ./core/frontend/durable \ + -run '^TestStorageBackend_(StrictAckUsesBatchObserver|PartialBatchObservesOnlyCommittedPrefix)$' \ + -count=25 \ + >"${ARTIFACT_DIR}/batch-observer-tests.log" 2>&1 +write_summary "strict_batch_observer_tests=pass" + +SW_BLOCK_ARTIFACT_DIR="${CONTENT_DIR}" \ + "${ROOT}/scripts/run-phase167-parallel-write-engine-local-baseline-gate.sh" + +BASELINE_SUMMARY="${CONTENT_DIR}/phase167-parallel-write-engine-local-baseline-summary.txt" +grep -q '^phase167_parallel_write_engine_local_baseline_status=ok$' "${BASELINE_SUMMARY}" +for writers in 1 2 4 8; do + grep -q "^rf3_writers_${writers}_queue_saturated=0$" "${BASELINE_SUMMARY}" +done + +write_summary "real_tcp_rf3_contention_gate=pass" +write_summary "normal_path_queue_saturation=0" +write_summary "slow_non_quorum_progress=pass" +write_summary "sync_all_waits_all_peers=pass" +write_summary "queue_saturation_fail_closed=pass" +write_summary "terminal_queue_error_precedence=pass" +write_summary "healthy_recovery_queue_reset=pass" +write_summary "recovery_queue_reset_race=pass" +write_summary "lineage_replacement_drain=pass" +write_summary "batch_observer_path=pass" +write_summary "partial_batch_prefix_observed=pass" +write_summary "next_recommendation=parallel_local_wal_candidate" +write_summary "phase167_ordered_async_replication_status=ok" diff --git a/seaweed-block/scripts/run-phase167-parallel-write-engine-local-baseline-gate.sh b/seaweed-block/scripts/run-phase167-parallel-write-engine-local-baseline-gate.sh index fa4b0bf79a..6799440be4 100644 --- a/seaweed-block/scripts/run-phase167-parallel-write-engine-local-baseline-gate.sh +++ b/seaweed-block/scripts/run-phase167-parallel-write-engine-local-baseline-gate.sh @@ -119,6 +119,13 @@ for writers in 1 2 4 8; do 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)" + rf3_ack_wait="$(require_metric "${RF3_BENCH}" BenchmarkPhase167RF3SyncQuorumContention "${writers}" repl_ack_wait_ns/op)" + rf3_queue_depth="$(require_metric "${RF3_BENCH}" BenchmarkPhase167RF3SyncQuorumContention "${writers}" peer_queue_max_depth)" + rf3_queue_saturated="$(require_metric "${RF3_BENCH}" BenchmarkPhase167RF3SyncQuorumContention "${writers}" peer_queue_saturated)" + if [[ "${rf3_queue_saturated}" != "0" ]]; then + echo "writers_${writers} peer queue saturated ${rf3_queue_saturated} times" >&2 + exit 1 + fi write_summary "wal_writers_${writers}_mibps=${wal_mibps}" write_summary "wal_writers_${writers}_p99_ns=${wal_p99}" @@ -127,6 +134,9 @@ for writers in 1 2 4 8; do 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}" + write_summary "rf3_writers_${writers}_ack_wait_ns_per_op=${rf3_ack_wait}" + write_summary "rf3_writers_${writers}_queue_max_depth=${rf3_queue_depth}" + write_summary "rf3_writers_${writers}_queue_saturated=${rf3_queue_saturated}" done wal_1="$(require_metric "${WAL_BENCH}" BenchmarkPhase167WALStoreContention 1 MB/s)"