T4b-5: ReplicationVolume.Sync + WriteObserver.Sync seam

Wires DurabilityCoordinator (T4b-4) into the per-volume Sync path.
Host-side FLUSH / SYNCHRONIZE_CACHE now drives the full local fsync
+ per-peer barrier closure in parallel with mode-dependent arithmetic.

Changes:

  core/frontend/durable/storage_adapter.go
    WriteObserver interface extended: Sync(ctx, targetLSN) joins the
    existing Observe(ctx, lba, lsn, data) method. Contract documented
    inline — observer.Sync OWNS the full sync job (both local
    fsync and peer barriers) when installed; StorageBackend delegates
    rather than calling storage.Sync locally.
    StorageBackend.Sync branches: observer==nil preserves the
    pre-T4b behavior (local storage.Sync only); observer!=nil reads
    walHead from LogicalStorage.Boundaries() and calls observer.Sync
    with that as targetLSN. The observer (ReplicationVolume) then
    invokes DurabilityCoordinator.SyncLocalAndReplicas which runs
    local + barriers in parallel inside its own goroutines.

  core/replication/volume.go
    ReplicationVolume gains:
      - coord field set to NewDurabilityCoordinator at construction
      - durabilityMode field, SetDurabilityMode setter +
        DurabilityMode accessor. Default BestEffort (zero value).
        Per mini-plan §5, T4b does not support per-Sync-call mode
        override — mode is a per-volume setting.
      - Sync(ctx, targetLSN) method — snapshots peers under v.mu,
        builds a localSync closure around v.store.Sync, delegates
        to coord.SyncLocalAndReplicas, returns error verbatim.

    Lock scope: v.mu held across the FULL Sync call. Matches the
    T4a-4 round-15 Condition A discipline — concurrent Sync +
    OnLocalWrite calls are serialized on v.mu, preserving the V2
    shipMu semantics extended from ship-only into ship+barrier.
    Accepted correctness-first trade-off: a slow peer barrier stalls
    other writers on the same volume; async-queue optimization
    (Option Z) is deferred post-T4.

Tests (2 required per mini-plan §2 T4b-5):

  - TestReplicationVolume_Sync_BestEffort_E2E — full end-to-end
    smoke: StorageBackend.Write 10 LBAs → Observe → ship → replica
    applies. StorageBackend.Sync → observer.Sync →
    DurabilityCoordinator → local fsync + peer barrier in parallel.
    Replica's R-boundary (durable frontier) must reach primary's
    H (walHead) after Sync returns. Peer stays Healthy throughout.

  - TestReplicationVolume_Sync_PreservesLSNOrderUnderConcurrency —
    forward-carry fence for INV-REPL-LSN-ORDER-FANOUT-001 under
    the new Sync code path. 40 goroutines, caller-side serialized
    LSN allocation + OnLocalWrite, periodic Sync calls interleaved
    every 4th iteration. LBA ordering is inverted from LSN order so
    any reorder is byte-detectable. All 40 LBAs must settle to the
    correct LSN marker at the replica.

Forward-carry verification: T4a-4's
TestReplicationVolume_OnLocalWrite_ConcurrentLSNs_OrderedAtReplica
continues to pass — the existing ordering invariant is not regressed
by the new Sync code path that shares v.mu.

Verification: full 21-package repo suite green including the
extended WriteObserver interface not breaking core/frontend/durable
tests. G-2 tri-line godoc on SetDurabilityMode, DurabilityMode
accessor, Sync method, extended WriteObserver.Sync contract. G-3
cumulative.

Fifth task in T4b batch. Next: T4b-6 L2 subprocess integration
matrix closes the batch.
This commit is contained in:
pingqiu committed 2026-04-24 01:14:38 -07:00
1 parent e79ec9e952
commit 44f87603fd
3 files changed
+378 -11

No files matched your search

@@ -50,12 +50,13 @@ import (
)
// WriteObserver is the narrow seam StorageBackend uses to notify the
// replication layer of each successfully-applied local write. The
// ReplicationVolume (core/replication) satisfies this interface via
// its Observe method; the indirection keeps core/frontend/durable
// from importing replication directly and lets tests inject mocks.
// replication layer of each successfully-applied local write and to
// delegate Sync durability closure. The ReplicationVolume
// (core/replication) satisfies this interface; the indirection keeps
// core/frontend/durable from importing replication directly and lets
// tests inject mocks.
//
// Contract (matches V2 BlockVol.shipMu → ShipAll invariant):
// Observe contract (matches V2 BlockVol.shipMu → ShipAll invariant):
// - StorageBackend calls Observe AFTER LogicalStorage.Write
// returns successfully, with the LBA + block data + LSN the
// storage layer just assigned.
@@ -66,8 +67,23 @@ import (
// ReplicationVolume's own mutex then serializes fan-out per
// volume (V2 shipMu equivalent; closes
// INV-REPL-LSN-ORDER-FANOUT-001 at the replication seam).
//
// 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.
// - targetLSN is the primary's current walHead at the moment the
// host requested Sync; caller (StorageBackend) reads it from
// LogicalStorage.Boundaries().
// - Observer.Sync returns error iff the mode-dependent durability
// arithmetic declared failure (ErrDurabilityBarrierFailed /
// ErrDurabilityQuorumLost / local fsync error). StorageBackend
// surfaces the error verbatim so the host sees the real
// durability outcome.
type WriteObserver interface {
Observe(ctx context.Context, lba uint32, lsn uint64, data []byte) error
Sync(ctx context.Context, targetLSN uint64) error
}
// errInvalidOffset is returned for negative byte offsets. Callers
@@ -180,6 +196,28 @@ func (b *StorageBackend) Sync(ctx context.Context) error {
if err := b.gate(); err != nil {
return err
}
// 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
// local sync would run twice (once here, once inside the
// coordinator) 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
// intent for what must be durable. Local sync's achieved LSN
// should meet or exceed this; per-peer barriers carry the
// session lineage (TargetLSN fixed per session per peer.Barrier
// godoc).
b.mu.Lock()
obs := b.observer
b.mu.Unlock()
if obs != nil {
_, _, walHead := b.storage.Boundaries()
return obs.Sync(ctx, walHead)
}
// No observer installed — observer-free path runs local sync only
// (T0 / bootstrap / single-replica dev configurations).
if _, err := b.storage.Sync(); err != nil {
return fmt.Errorf("durable: storage sync: %w", err)
}
+84 -6
View File
@@ -37,11 +37,13 @@ type ReplicationVolume struct {
volumeID string
store storage.LogicalStorage // borrowed, NEVER closed by us
newExec executorFactory // test seam; default dials real TCP
coord *DurabilityCoordinator // used by Sync; stateless
mu sync.Mutex // serializes UpdateReplicaSet + OnLocalWrite entry AND fan-out
mu sync.Mutex // serializes UpdateReplicaSet + OnLocalWrite entry AND fan-out AND Sync
peers map[string]*ReplicaPeer
closed bool
lastAppliedGeneration uint64 // monotonic guard; 0 means "no generation applied yet"
lastAppliedGeneration uint64 // monotonic guard; 0 means "no generation applied yet"
durabilityMode DurabilityMode // set via SetDurabilityMode; default is BestEffort
// replayedGens counts UpdateReplicaSet calls dropped as stale
// (generation > 0 && generation <= lastAppliedGeneration). Exposed
@@ -68,13 +70,89 @@ type executorFactory func(store storage.LogicalStorage, replicaAddr string) *tra
// ReplicationVolume MUST NOT call store.Close() (BUG-005).
func NewReplicationVolume(volumeID string, store storage.LogicalStorage) *ReplicationVolume {
return &ReplicationVolume{
volumeID: volumeID,
store: store,
newExec: transport.NewBlockExecutor,
peers: make(map[string]*ReplicaPeer),
volumeID: volumeID,
store: store,
newExec: transport.NewBlockExecutor,
coord: NewDurabilityCoordinator(),
peers: make(map[string]*ReplicaPeer),
durabilityMode: DurabilityBestEffort, // zero value; explicit for clarity
}
}
// SetDurabilityMode configures the per-volume durability semantic
// that Sync uses. Safe to call at any time; effect applies from the
// next Sync call forward. Per mini-plan §5, T4b does not support
// per-Sync-call mode override — mode is a per-volume setting.
//
// Called by: Host / Provider composition root at volume lifecycle
// start, or on operator reconfiguration.
// Owns: durabilityMode field under v.mu.
// Borrows: nothing.
func (v *ReplicationVolume) SetDurabilityMode(mode DurabilityMode) {
v.mu.Lock()
v.durabilityMode = mode
v.mu.Unlock()
}
// DurabilityMode returns the currently-configured mode. Read-only
// accessor for tests and diagnostics.
func (v *ReplicationVolume) DurabilityMode() DurabilityMode {
v.mu.Lock()
defer v.mu.Unlock()
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 (architect T4a-4 round-15
// Condition A): LSN-order fan-out serialization at the replication
// layer. Concurrent Sync and OnLocalWrite calls are thus serialized
// on v.mu, matching V2's shipMu semantics extended from ship-only
// into ship+barrier. Accepted correctness-first trade-off: a slow
// peer barrier stalls other writers on the same volume; async-queue
// optimization (Option Z) is deferred post-T4 per mini-plan §6.
//
// Forward-carry: INV-REPL-LSN-ORDER-FANOUT-001 (T4a-4) must
// continue to pass under the new code path; the adversarial
// TestReplicationVolume_OnLocalWrite_ConcurrentLSNs_OrderedAtReplica
// test and the new TestReplicationVolume_Sync_PreservesLSNOrder
// UnderConcurrency pin verify no regression.
//
// 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.
func (v *ReplicationVolume) Sync(ctx context.Context, targetLSN uint64) error {
if err := ctx.Err(); err != nil {
return err
}
v.mu.Lock()
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
}
// UpdateReplicaSet applies the authoritative replica set from a master
// assignment event. Adds new peers, removes deleted ones, and tears
// down + recreates peers whose lineage (Epoch / EndpointVersion) has
@@ -0,0 +1,251 @@
package replication
import (
"bytes"
"context"
"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"
)
// --- Test 1: BestEffort E2E smoke ---
// TestReplicationVolume_Sync_BestEffort_E2E verifies the full
// StorageBackend.Sync → observer.Sync → DurabilityCoordinator →
// peer.Barrier → replica path end-to-end in best_effort mode.
//
// Flow: primary writes N LBAs through StorageBackend.Write; those
// fan out to the replica via the existing T4a-6 Observe hook. Host
// then calls StorageBackend.Sync which delegates to the observer.
// Observer calls DurabilityCoordinator which runs local fsync +
// per-peer barrier in parallel. Replica's LogicalStorage.Boundaries()
// must reflect the synced frontier after the call returns.
func TestReplicationVolume_Sync_BestEffort_E2E(t *testing.T) {
const blockSize = 4096
replicaStore := storage.NewBlockStore(64, blockSize)
listener, err := transport.NewReplicaListener("127.0.0.1:0", replicaStore)
if err != nil {
t.Fatal(err)
}
listener.Serve()
t.Cleanup(func() { listener.Stop() })
// Primary setup: LogicalStorage + StorageBackend + ReplicationVolume.
primaryStore := storage.NewBlockStore(64, blockSize)
id := frontend.Identity{
VolumeID: "vol-sync",
ReplicaID: "primary-sync",
Epoch: 1,
EndpointVersion: 1,
}
view := &alwaysHealthySyncView{proj: frontend.Projection{
VolumeID: id.VolumeID, ReplicaID: id.ReplicaID,
Epoch: id.Epoch, EndpointVersion: id.EndpointVersion, Healthy: true,
}}
backend := durable.NewStorageBackend(primaryStore, view, id)
backend.SetOperational(true, "test harness ready")
repVol := NewReplicationVolume(id.VolumeID, primaryStore)
repVol.SetDurabilityMode(DurabilityBestEffort)
backend.SetWriteObserver(repVol)
t.Cleanup(func() {
_ = backend.Close()
_ = repVol.Close()
})
// Add one replica peer via the fake-master path.
if err := repVol.UpdateReplicaSet(1, []ReplicaTarget{{
ReplicaID: "r1",
DataAddr: listener.Addr(),
ControlAddr: listener.Addr(),
Epoch: 1,
EndpointVersion: 1,
}}); err != nil {
t.Fatalf("UpdateReplicaSet: %v", err)
}
// Write N LBAs through StorageBackend (host-style byte Write).
const n = 10
for i := 0; i < n; i++ {
data := make([]byte, blockSize)
data[0] = byte(i + 1)
data[1] = byte(0xA0 + i)
offset := int64(i) * int64(blockSize)
if _, err := backend.Write(context.Background(), offset, data); err != nil {
t.Fatalf("Write[%d]: %v", i, err)
}
}
// Wait for last ship to land so Sync sees the expected walHead.
waitForReplicaLBA(t, replicaStore, n-1, byte(n), byte(0xA0+n-1), 2*time.Second)
// Host-side Sync → observer path.
if err := backend.Sync(context.Background()); err != nil {
t.Fatalf("Sync: %v", err)
}
// Replica frontier must have advanced. R/S/H from Boundaries():
// after the primary syncs + barrier, R on the replica should
// reflect that the replica has applied + fsynced.
_, _, pH := primaryStore.Boundaries()
rR, _, _ := replicaStore.Boundaries()
if rR < pH {
t.Fatalf("replica R=%d < primary H=%d after Sync — barrier did not drive replica frontier",
rR, pH)
}
// Byte-exact cross-check.
for i := uint32(0); i < n; i++ {
pri, _ := primaryStore.Read(i)
rep, _ := replicaStore.Read(i)
if !bytes.Equal(pri, rep) {
t.Fatalf("LBA %d byte mismatch: primary[0]=%d replica[0]=%d", i, pri[0], rep[0])
}
}
// Peer must still be Healthy — best_effort with no failures.
repVol.mu.Lock()
state := repVol.peers["r1"].State()
repVol.mu.Unlock()
if state != ReplicaHealthy {
t.Fatalf("peer state after happy-path Sync: got %s want healthy", state)
}
}
// --- Test 2: Forward-carry fence for INV-REPL-LSN-ORDER-FANOUT-001 ---
// TestReplicationVolume_Sync_PreservesLSNOrderUnderConcurrency is
// the T4b-4/T4b-5 forward-carry fence for the T4a-4 LSN-order
// invariant. Concurrent OnLocalWrite and Sync calls must not
// interleave in a way that lets a later-LSN message reach the
// replica before an earlier-LSN one.
//
// Pattern mirrors TestReplicationVolume_OnLocalWrite_ConcurrentLSNs_
// OrderedAtReplica (T4a-4 test #6): N goroutines, each pre-assigned
// a unique LSN under a caller-side mutex, call OnLocalWrite and
// sometimes Sync concurrently. LBAs are interleaved with LSN
// ordering so any reorder is byte-detectable at the replica.
func TestReplicationVolume_Sync_PreservesLSNOrderUnderConcurrency(t *testing.T) {
const blockSize = 4096
replicaStore := storage.NewBlockStore(64, blockSize)
listener, err := transport.NewReplicaListener("127.0.0.1:0", replicaStore)
if err != nil {
t.Fatal(err)
}
listener.Serve()
t.Cleanup(func() { listener.Stop() })
primary := storage.NewBlockStore(64, blockSize)
v := NewReplicationVolume("vol-ordering", primary)
v.SetDurabilityMode(DurabilityBestEffort)
t.Cleanup(func() { _ = v.Close() })
if err := v.UpdateReplicaSet(1, []ReplicaTarget{{
ReplicaID: "r1",
DataAddr: listener.Addr(),
ControlAddr: listener.Addr(),
Epoch: 1,
EndpointVersion: 1,
}}); err != nil {
t.Fatal(err)
}
const n = 40
var callerMu sync.Mutex
var nextLSN atomic.Uint64
var wg sync.WaitGroup
start := make(chan struct{})
// Build a write plan where LSN ordering differs from LBA ordering
// (same shape as T4a-4 test #6). LSN i writes to LBA (n-1-i).
type plan struct {
lba uint32
lsnMarker byte
}
plans := make([]plan, n)
for i := 0; i < n; i++ {
plans[i] = plan{lba: uint32(n - 1 - i), lsnMarker: byte(i + 1)}
}
for i := 0; i < n; i++ {
wg.Add(1)
go func(idx int) {
defer wg.Done()
<-start
// Caller-side serialized section: LSN allocation + write.
// Sync may be requested randomly mid-stream to exercise
// the write + sync interleave on v.mu.
callerMu.Lock()
lsn := nextLSN.Add(1)
p := plans[lsn-1]
data := make([]byte, blockSize)
data[0] = p.lsnMarker
data[1] = 0xCC
err := v.OnLocalWrite(context.Background(), LocalWrite{
LBA: p.lba,
Data: data,
LSN: lsn,
})
callerMu.Unlock()
if err != nil {
t.Errorf("OnLocalWrite[%d] lsn=%d: %v", idx, lsn, err)
return
}
// Periodically request a Sync — this is the new T4b-5
// code path that must coexist with OnLocalWrite without
// breaking LSN ordering.
if idx%4 == 0 {
if err := v.Sync(context.Background(), lsn); err != nil {
t.Errorf("Sync[%d] lsn=%d: %v", idx, lsn, err)
}
}
}(i)
}
close(start)
wg.Wait()
// Final sync to drain any in-flight ships.
if err := v.Sync(context.Background(), uint64(n)); err != nil {
t.Fatalf("final Sync: %v", err)
}
// Wait for last-written LBA to settle on replica.
finalLBA0Marker := byte(n)
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
got, _ := replicaStore.Read(0)
if got != nil && got[0] == finalLBA0Marker {
break
}
time.Sleep(10 * time.Millisecond)
}
// Every LBA must carry the LSN marker that plan dictated. Any
// reorder (later-LSN arriving before earlier-LSN on the same
// LBA) would leave a stale marker and fail here.
for i := 0; i < n; i++ {
p := plans[i]
got, _ := replicaStore.Read(p.lba)
if got == nil || got[0] != p.lsnMarker {
t.Fatalf("LBA %d: got marker %02x, want %02x (LSN=%d) — out-of-order under concurrent Sync (INV-REPL-LSN-ORDER-FANOUT-001 regression)",
p.lba, got[0], p.lsnMarker, i+1)
}
}
}
// --- helpers ---
type alwaysHealthySyncView struct {
proj frontend.Projection
}
func (v *alwaysHealthySyncView) Projection() frontend.Projection { return v.proj }