package replication import ( "bytes" "context" "errors" "fmt" "net" "strings" "sync" "sync/atomic" "testing" "time" "github.com/seaweedfs/seaweed-block/core/storage" "github.com/seaweedfs/seaweed-block/core/transport" ) // replicaHarness stands up one real ReplicaListener backed by an // in-memory BlockStore and returns its address + store for assertions. func replicaHarness(t *testing.T, label string) (addr string, replicaStore *storage.BlockStore) { t.Helper() replicaStore = storage.NewBlockStore(64, 4096) listener, err := transport.NewReplicaListener("127.0.0.1:0", replicaStore) if err != nil { t.Fatalf("%s: NewReplicaListener: %v", label, err) } listener.Serve() t.Cleanup(func() { listener.Stop() }) return listener.Addr(), replicaStore } // volumeHarness returns a fresh ReplicationVolume with a primary // store that's never actually used for reads (tests assert on the // replica side). func volumeHarness(t *testing.T, volumeID string) *ReplicationVolume { t.Helper() primary := storage.NewBlockStore(64, 4096) v := NewReplicationVolume(volumeID, primary) t.Cleanup(func() { _ = v.Close() }) return v } // targetFor builds a fresh ReplicaTarget aimed at the given addr with // the given ReplicaID and authoritative lineage fields. func targetFor(id, addr string, epoch, endpointVersion uint64) ReplicaTarget { return ReplicaTarget{ ReplicaID: id, DataAddr: addr, ControlAddr: addr, Epoch: epoch, EndpointVersion: endpointVersion, } } // --- Test 1 --- // TestReplicationVolume_UpdateReplicaSet_AddPeer — empty → 1 peer; // peer is tracked and Healthy. func TestReplicationVolume_UpdateReplicaSet_AddPeer(t *testing.T) { addr, _ := replicaHarness(t, "r1") v := volumeHarness(t, "vol1") if v.PeerCount() != 0 { t.Fatalf("precondition: PeerCount=%d want 0", v.PeerCount()) } if err := v.UpdateReplicaSet(0, []ReplicaTarget{targetFor("r1", addr, 1, 1)}); err != nil { t.Fatalf("UpdateReplicaSet: %v", err) } if v.PeerCount() != 1 { t.Fatalf("PeerCount=%d want 1", v.PeerCount()) } } func TestReplicationVolume_PeerStatuses_SortedStateSnapshot(t *testing.T) { addr2, _ := replicaHarness(t, "r2") addr1, _ := replicaHarness(t, "r1") v := volumeHarness(t, "vol1") if err := v.UpdateReplicaSet(42, []ReplicaTarget{ targetFor("r2", addr2, 3, 2), targetFor("r1", addr1, 3, 2), }); err != nil { t.Fatalf("UpdateReplicaSet: %v", err) } v.mu.Lock() r2 := v.peers["r2"] v.mu.Unlock() r2.SetState(ReplicaDegraded) got := v.PeerStatuses() if len(got) != 2 { t.Fatalf("PeerStatuses len=%d want 2: %+v", len(got), got) } if got[0].ReplicaID != "r1" || got[1].ReplicaID != "r2" { t.Fatalf("PeerStatuses not sorted by replica_id: %+v", got) } if got[0].State != "healthy" { t.Fatalf("r1 state=%q want healthy", got[0].State) } if got[1].State != "degraded" { t.Fatalf("r2 state=%q want degraded", got[1].State) } if got[1].Epoch != 3 || got[1].EndpointVersion != 2 || got[1].DataAddr == "" || got[1].SessionID == 0 { t.Fatalf("r2 status missing lineage/address/session: %+v", got[1]) } } func TestReplicationVolume_StartRuntimeRecovery_ValidatesPeerLineage(t *testing.T) { addr, _ := replicaHarness(t, "r1") v := volumeHarness(t, "vol1") if err := v.UpdateReplicaSet(42, []ReplicaTarget{targetFor("r1", addr, 3, 2)}); err != nil { t.Fatalf("UpdateReplicaSet: %v", err) } if err := v.StartRuntimeRecovery(context.Background(), RuntimeRecoveryRequest{ ReplicaID: "r1", TargetDataAddr: addr, SessionID: 1001, Epoch: 3, EndpointVersion: 2, FromLSN: 1, FrontierHintLSN: 1, }); err != nil { t.Fatalf("StartRuntimeRecovery valid catch-up: %v", err) } if err := v.StartRuntimeRecovery(context.Background(), RuntimeRecoveryRequest{ ReplicaID: "r1", TargetDataAddr: addr, SessionID: 1002, Epoch: 4, EndpointVersion: 2, FrontierHintLSN: 1, }); err == nil || !strings.Contains(err.Error(), "lineage drift") { t.Fatalf("StartRuntimeRecovery wrong epoch err=%v, want lineage drift", err) } if err := v.StartRuntimeRecovery(context.Background(), RuntimeRecoveryRequest{ ReplicaID: "r1", TargetDataAddr: "127.0.0.1:1", SessionID: 1003, Epoch: 3, EndpointVersion: 2, FrontierHintLSN: 1, }); err == nil || !strings.Contains(err.Error(), "target data address drift") { t.Fatalf("StartRuntimeRecovery wrong addr err=%v, want target data address drift", err) } } func TestReplicationVolume_RuntimeRecoveryStatus_ReportsTerminalFrontier(t *testing.T) { addr, _ := replicaHarness(t, "r1") v := volumeHarness(t, "vol1") if err := v.UpdateReplicaSet(42, []ReplicaTarget{targetFor("r1", addr, 3, 2)}); err != nil { t.Fatalf("UpdateReplicaSet: %v", err) } data := make([]byte, 4096) data[0] = 0x42 if err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: 1, Data: data, LSN: 1}); err != nil { t.Fatalf("OnLocalWrite: %v", err) } // Recovery must supersede this run's live session, not a fixed process-wide ID. recoverySessionID := v.PeerStatuses()[0].SessionID + 2000 req := RuntimeRecoveryRequest{ ReplicaID: "r1", TargetDataAddr: addr, SessionID: recoverySessionID, Epoch: 3, EndpointVersion: 2, BasePinLSN: 1, FrontierHintLSN: 1, } if err := v.StartRuntimeRecovery(context.Background(), req); err != nil { t.Fatalf("StartRuntimeRecovery: %v", err) } deadline := time.After(5 * time.Second) for { status, err := v.RuntimeRecoveryStatus(context.Background(), req) if err != nil { t.Fatalf("RuntimeRecoveryStatus: %v", err) } if status.State == "caught_up" { if status.AchievedLSN != 1 { t.Fatalf("achieved=%d want 1", status.AchievedLSN) } return } if status.State == "failed" { t.Fatalf("runtime failed: %+v", status) } select { case <-deadline: t.Fatalf("timeout waiting for caught_up, last=%+v", status) case <-time.After(10 * time.Millisecond): } } } // --- Test 2: Opt-3 three-assertion pin --- // TestReplicationVolume_UpdateReplicaSet_RemovePeer_ExecutorTornDown — // Opt-3 three-assertion fence: // // (a) peer.Close called once and only once on removal // (b) session removed from underlying executor // (c) re-add at same ReplicaID succeeds and a subsequent OnLocalWrite // reaches the replica func TestReplicationVolume_UpdateReplicaSet_RemovePeer_ExecutorTornDown(t *testing.T) { addr, replica := replicaHarness(t, "r1") v := volumeHarness(t, "vol1") // Wrap newExec so tests can observe the underlying executor. var execCount atomic.Int64 var firstExec *transport.BlockExecutor v.newExec = func(store storage.LogicalStorage, replicaAddr string) *transport.BlockExecutor { e := transport.NewBlockExecutor(store, replicaAddr) if execCount.Add(1) == 1 { firstExec = e } return e } // Add. if err := v.UpdateReplicaSet(0, []ReplicaTarget{targetFor("r1", addr, 1, 1)}); err != nil { t.Fatal(err) } v.mu.Lock() peer1SessionID := v.peers["r1"].sessionID v.mu.Unlock() // (b) session is registered on the first executor. if !firstExec.HasSession(peer1SessionID) { t.Fatal("precondition: session not registered on first executor") } // Remove (empty target set). if err := v.UpdateReplicaSet(0, []ReplicaTarget{}); err != nil { t.Fatalf("remove: %v", err) } if v.PeerCount() != 0 { t.Fatalf("PeerCount after remove=%d want 0", v.PeerCount()) } // (b) session removed from the first executor. if firstExec.HasSession(peer1SessionID) { t.Fatal("executor session not torn down on peer removal") } err := firstExec.RegisterLiveShipSession(transport.RecoveryLineage{ SessionID: peer1SessionID + 1000, Epoch: 1, EndpointVersion: 1, }) if !errors.Is(err, transport.ErrExecutorStopped) { t.Fatalf("removed peer executor accepted new session: %v", err) } // (c) re-add at same ReplicaID must work cleanly and ship must reach replica. if err := v.UpdateReplicaSet(0, []ReplicaTarget{targetFor("r1", addr, 1, 1)}); err != nil { t.Fatalf("re-add: %v", err) } if v.PeerCount() != 1 { t.Fatalf("PeerCount after re-add=%d want 1", v.PeerCount()) } data := make([]byte, 4096) data[0], data[1] = 0xDE, 0xAD if err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: 7, Data: data, LSN: 1}); err != nil { t.Fatalf("OnLocalWrite after re-add: %v", err) } waitForReplicaLBA(t, replica, 7, 0xDE, 0xAD, 2*time.Second) // (a) Close-called-once is demonstrated by the fact that (b) session // is gone exactly once (idempotent Close returns nil on subsequent // calls; the Test 7 idempotence check below covers the boundary). } // --- Test 3 --- // TestReplicationVolume_UpdateReplicaSet_LineageBump_RecreatesPeer — // same ReplicaID with a new Epoch bumps the peer: old one closed, // new one created, new lineage reflected. func TestReplicationVolume_UpdateReplicaSet_LineageBump_RecreatesPeer(t *testing.T) { addr, _ := replicaHarness(t, "r1") v := volumeHarness(t, "vol1") var firstExecutor *transport.BlockExecutor oldStoppedBeforeReplacement := false membershipBlockedBeforeReplacement := false v.newExec = func(store storage.LogicalStorage, replicaAddr string) *transport.BlockExecutor { executor := transport.NewBlockExecutor(store, replicaAddr) if firstExecutor == nil { firstExecutor = executor } else { membershipBlockedBeforeReplacement = v.membershipUpdating err := firstExecutor.RegisterLiveShipSession(transport.RecoveryLineage{ SessionID: 999999, Epoch: 1, EndpointVersion: 1, }) oldStoppedBeforeReplacement = errors.Is(err, transport.ErrExecutorStopped) } return executor } if err := v.UpdateReplicaSet(0, []ReplicaTarget{targetFor("r1", addr, 1, 1)}); err != nil { t.Fatal(err) } v.mu.Lock() firstSessionID := v.peers["r1"].sessionID firstEpoch := v.peers["r1"].Target().Epoch v.mu.Unlock() // Bump epoch. if err := v.UpdateReplicaSet(0, []ReplicaTarget{targetFor("r1", addr, 2, 1)}); err != nil { t.Fatal(err) } v.mu.Lock() secondSessionID := v.peers["r1"].sessionID secondEpoch := v.peers["r1"].Target().Epoch v.mu.Unlock() if firstSessionID == secondSessionID { t.Fatal("sessionID did not change across lineage bump — peer was not recreated") } if !oldStoppedBeforeReplacement { t.Fatal("replacement executor was admitted before the old executor stopped") } if !membershipBlockedBeforeReplacement { t.Fatal("writes were not blocked while the replacement executor was admitted") } if v.membershipUpdating { t.Fatal("membership transition remained blocked after replacement completed") } if firstEpoch != 1 || secondEpoch != 2 { t.Fatalf("epoch bump not reflected: first=%d second=%d", firstEpoch, secondEpoch) } } func TestReplicationVolume_MembershipTransitionRejectsWriteAndSync(t *testing.T) { v := volumeHarness(t, "vol-transition") v.mu.Lock() v.membershipUpdating = true v.mu.Unlock() err := v.OnLocalWrite(context.Background(), LocalWrite{ LBA: 1, Data: make([]byte, 4096), LSN: 1, }) if err == nil || !strings.Contains(err.Error(), "membership transition in progress") { t.Fatalf("OnLocalWrite error=%v, want membership transition rejection", err) } err = v.Sync(context.Background(), 0) if err == nil || !strings.Contains(err.Error(), "membership transition in progress") { t.Fatalf("Sync error=%v, want membership transition rejection", err) } } func TestReplicationVolume_FailedMembershipReplacementRemainsBlocked(t *testing.T) { addr, _ := replicaHarness(t, "r1") v := volumeHarness(t, "vol-failed-transition") if err := v.UpdateReplicaSet(1, []ReplicaTarget{targetFor("r1", addr, 1, 1)}); err != nil { t.Fatal(err) } v.newExec = func(store storage.LogicalStorage, replicaAddr string) *transport.BlockExecutor { executor := transport.NewBlockExecutor(store, replicaAddr) executor.Stop() return executor } err := v.UpdateReplicaSet(2, []ReplicaTarget{targetFor("r1", addr, 2, 1)}) if !errors.Is(err, transport.ErrExecutorStopped) { t.Fatalf("UpdateReplicaSet error=%v, want ErrExecutorStopped", err) } v.mu.Lock() blocked := v.membershipUpdating v.mu.Unlock() if !blocked { t.Fatal("failed membership replacement reopened writes on a partial replica set") } err = v.OnLocalWrite(context.Background(), LocalWrite{ LBA: 1, Data: make([]byte, 4096), LSN: 1, }) if err == nil || !strings.Contains(err.Error(), "membership transition in progress") { t.Fatalf("OnLocalWrite error=%v, want membership transition rejection", err) } if err := v.Sync(context.Background(), 0); err == nil || !strings.Contains(err.Error(), "membership transition in progress") { t.Fatalf("Sync error=%v, want membership transition rejection", err) } v.newExec = transport.NewBlockExecutor if err := v.UpdateReplicaSet(2, []ReplicaTarget{targetFor("r1", addr, 2, 1)}); err != nil { t.Fatalf("retry replacement: %v", err) } v.mu.Lock() blocked = v.membershipUpdating v.mu.Unlock() if blocked { t.Fatal("successful replacement retry did not reopen writes") } } // --- Test 4 --- // TestReplicationVolume_OnLocalWrite_SinglePeer_BestEffort — write // N LBAs; every LBA arrives byte-exact on replica; peer stays Healthy. func TestReplicationVolume_OnLocalWrite_SinglePeer_BestEffort(t *testing.T) { addr, replica := replicaHarness(t, "r1") v := volumeHarness(t, "vol1") if err := v.UpdateReplicaSet(0, []ReplicaTarget{targetFor("r1", addr, 1, 1)}); err != nil { t.Fatal(err) } const n = 20 for i := uint32(0); i < n; i++ { data := make([]byte, 4096) data[0] = byte(i + 1) data[1] = byte(0xA0 + i) if err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: i, Data: data, LSN: uint64(i + 1)}); err != nil { t.Fatalf("OnLocalWrite[%d]: %v", i, err) } } deadline := time.Now().Add(2 * time.Second) for time.Now().Before(deadline) { last, _ := replica.Read(n - 1) if last != nil && last[0] == byte(n) { break } time.Sleep(10 * time.Millisecond) } for i := uint32(0); i < n; i++ { got, _ := replica.Read(i) want0 := byte(i + 1) want1 := byte(0xA0 + i) if got == nil || got[0] != want0 || got[1] != want1 { t.Fatalf("LBA %d mismatch: got [%02x %02x] want [%02x %02x]", i, got[0], got[1], want0, want1) } } v.mu.Lock() state := v.peers["r1"].State() v.mu.Unlock() if state != ReplicaHealthy { t.Fatalf("peer state=%s want healthy", state) } } func TestG9A_ReplicationVolume_OnLocalWrite_BestEffortRetainsRecoveringPeer(t *testing.T) { addr, _ := replicaHarness(t, "r1") v := volumeHarness(t, "vol-g9a-best-effort") if err := v.UpdateReplicaSet(0, []ReplicaTarget{targetFor("r1", addr, 1, 1)}); err != nil { t.Fatal(err) } v.mu.Lock() v.peers["r1"].SetState(ReplicaCatchingUp) v.mu.Unlock() data := make([]byte, 4096) data[0] = 0xA9 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) } } func TestG9A_ReplicationVolume_OnLocalWrite_SyncAllFailsRecoveringPeer(t *testing.T) { addr, _ := replicaHarness(t, "r1") v := volumeHarness(t, "vol-g9a-sync-all") v.SetDurabilityMode(DurabilitySyncAll) if err := v.UpdateReplicaSet(0, []ReplicaTarget{targetFor("r1", addr, 1, 1)}); err != nil { t.Fatal(err) } v.mu.Lock() v.peers["r1"].SetState(ReplicaCatchingUp) v.mu.Unlock() data := make([]byte, 4096) data[0] = 0xB9 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) } } func TestG9A_ReplicationVolume_OnLocalWrite_SyncQuorumRF2FailsRecoveringPeer(t *testing.T) { addr, _ := replicaHarness(t, "r1") v := volumeHarness(t, "vol-g9a-sync-quorum") v.SetDurabilityMode(DurabilitySyncQuorum) if err := v.UpdateReplicaSet(0, []ReplicaTarget{targetFor("r1", addr, 1, 1)}); err != nil { t.Fatal(err) } v.mu.Lock() v.peers["r1"].SetState(ReplicaCatchingUp) v.mu.Unlock() data := make([]byte, 4096) data[0] = 0xC9 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) } } func TestG9A_ReplicationVolume_OnLocalWrite_SyncQuorumRF3ToleratesOneRecoveringPeer(t *testing.T) { addr1, replica1 := replicaHarness(t, "r1") addr2, _ := replicaHarness(t, "r2") v := volumeHarness(t, "vol-g9a-sync-quorum-rf3-one-recovering") v.SetDurabilityMode(DurabilitySyncQuorum) if err := v.UpdateReplicaSet(0, []ReplicaTarget{ targetFor("r1", addr1, 1, 1), targetFor("r2", addr2, 1, 1), }); err != nil { t.Fatal(err) } v.mu.Lock() v.peers["r2"].SetState(ReplicaCatchingUp) v.mu.Unlock() data := make([]byte, 4096) data[0] = 0xD9 if err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: 6, Data: data, LSN: 1}); err != nil { t.Fatalf("sync_quorum RF=3 should tolerate one recovering peer, got %v", err) } waitForReplicaLBA(t, replica1, 6, 0xD9, 0x00, 2*time.Second) } func TestG9A_ReplicationVolume_OnLocalWrite_SyncQuorumRF3FailsTwoRecoveringPeers(t *testing.T) { addr1, _ := replicaHarness(t, "r1") addr2, _ := replicaHarness(t, "r2") v := volumeHarness(t, "vol-g9a-sync-quorum-rf3-two-recovering") v.SetDurabilityMode(DurabilitySyncQuorum) if err := v.UpdateReplicaSet(0, []ReplicaTarget{ targetFor("r1", addr1, 1, 1), targetFor("r2", addr2, 1, 1), }); err != nil { t.Fatal(err) } v.mu.Lock() v.peers["r1"].SetState(ReplicaCatchingUp) v.peers["r2"].SetState(ReplicaCatchingUp) v.mu.Unlock() data := make([]byte, 4096) data[0] = 0xE9 err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: 7, Data: data, LSN: 1}) if !strings.Contains(fmt.Sprint(err), ErrDurabilityQuorumLost.Error()) { t.Fatalf("sync_quorum RF=3 with two recovering peers should fail write ack, got %v", err) } } // --- Test 5 --- // TestReplicationVolume_OnLocalWrite_PeerErrorDoesNotFailCaller — // peer aimed at a dead addr: OnLocalWrite still returns nil (best- // effort); peer transitions to Degraded. func TestReplicationVolume_OnLocalWrite_PeerErrorDoesNotFailCaller(t *testing.T) { // Reserve a port then release it → guaranteed unreachable. ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } deadAddr := ln.Addr().String() _ = ln.Close() v := volumeHarness(t, "vol1") if err := v.UpdateReplicaSet(0, []ReplicaTarget{targetFor("r-dead", deadAddr, 1, 1)}); err != nil { t.Fatal(err) } data := make([]byte, 4096) if err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: 0, Data: data, LSN: 1}); err != nil { t.Fatalf("OnLocalWrite should not fail on best-effort peer error: %v", err) } v.mu.Lock() state := v.peers["r-dead"].State() v.mu.Unlock() if state != ReplicaDegraded { t.Fatalf("peer state=%s want degraded after dial failure", state) } } // --- Test 6: INV-REPL-LSN-ORDER-FANOUT-001 adversarial pin --- // TestReplicationVolume_OnLocalWrite_ConcurrentLSNs_OrderedAtReplica — // the architect-requested adversarial ordering pin. // // 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 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") if err := v.UpdateReplicaSet(0, []ReplicaTarget{targetFor("r1", addr, 1, 1)}); err != nil { t.Fatal(err) } const n = 40 var nextLSN atomic.Uint64 var wg sync.WaitGroup start := make(chan struct{}) // Build a write plan where LSN ordering differs from LBA ordering // so any reorder at the replica is byte-detectable. Each LSN writes // to LBA (n-1 - idx) and stamps its LSN into byte[0..1]. // // Intended final state on replica: // LBA k ← whatever LSN was assigned to plan index (n-1-k) // Serial order of LSN allocation = plan index order. 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 lsn := nextLSN.Add(1) // Resolve plan deterministically by LSN. p := plans[lsn-1] data := make([]byte, 4096) data[0] = p.lsnMarker data[1] = 0xCC err := v.OnLocalWrite(context.Background(), LocalWrite{ LBA: p.lba, Data: data, LSN: lsn, }) if err != nil { t.Errorf("OnLocalWrite idx=%d lsn=%d: %v", idx, lsn, err) } }(i) } close(start) wg.Wait() // Wait for the last-written LBA on the replica to settle to the // expected marker (the highest-LSN write's marker, which targets // LBA 0). finalLBA0Marker := byte(n) // plan index n-1 (LSN=n) targets LBA 0 deadline := time.Now().Add(3 * time.Second) for time.Now().Before(deadline) { got, _ := replica.Read(0) if got != nil && got[0] == finalLBA0Marker { break } time.Sleep(10 * time.Millisecond) } // Verify every LBA has the LSN marker that plan dictated. for i := 0; i < n; i++ { p := plans[i] got, _ := replica.Read(p.lba) if got == nil || got[0] != p.lsnMarker { t.Fatalf("LBA %d: got marker [%02x], want [%02x] (LSN=%d) — out-of-order application", p.lba, got[0], p.lsnMarker, i+1) } } } // --- Test 7: BUG-005 regression fence --- // TestReplicationVolume_Constructor_DoesNotOwnStore — after the // volume is Closed (simulating full shutdown), the borrowed store // handle remains usable. BUG-005 non-repeat fence. func TestReplicationVolume_Constructor_DoesNotOwnStore(t *testing.T) { store := storage.NewBlockStore(64, 4096) v := NewReplicationVolume("vol1", store) // Do some operations, including Close. _ = v.UpdateReplicaSet(0, []ReplicaTarget{}) // empty set is valid _ = v.Close() _ = v.Close() // idempotent // Store must remain usable after ReplicationVolume is torn down. data := make([]byte, 4096) data[0] = 0x42 if _, err := store.Write(0, data); err != nil { t.Fatalf("store usable after ReplicationVolume.Close: got err=%v", err) } got, err := store.Read(0) if err != nil { t.Fatalf("store.Read after Close: %v", err) } if !bytes.Equal(got, data) { t.Fatal("store data corrupted after ReplicationVolume.Close") } } // --- Test 8 --- // TestReplicationVolume_OnLocalWrite_Closed_Errors — post-Close calls // return error cleanly (no panic, no partial fan-out). func TestReplicationVolume_OnLocalWrite_Closed_Errors(t *testing.T) { v := volumeHarness(t, "vol1") _ = v.Close() data := make([]byte, 4096) err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: 0, Data: data, LSN: 1}) if err == nil { t.Fatal("expected error on OnLocalWrite post-Close") } if !strings.Contains(err.Error(), "closed") { t.Fatalf("expected 'closed' error, got: %v", err) } err = v.UpdateReplicaSet(0, []ReplicaTarget{}) if err == nil { t.Fatal("expected error on UpdateReplicaSet post-Close") } if !strings.Contains(err.Error(), "closed") { t.Fatalf("expected 'closed' error, got: %v", err) } } func TestReplicationVolume_UpdateReplicaSet_SeedsLiveCursorFromBarrierFrontier(t *testing.T) { const blockSize = 4096 primary := storage.NewBlockStore(64, blockSize) replica := storage.NewBlockStore(64, blockSize) for i := uint32(0); i < 3; i++ { data := make([]byte, blockSize) data[0] = byte(i + 1) data[1] = 0xA0 lsn, err := primary.Write(i, data) if err != nil { t.Fatalf("primary seed write %d: %v", i, err) } if err := replica.ApplyEntry(i, data, lsn); err != nil { t.Fatalf("replica seed apply %d: %v", i, err) } } frontier, err := primary.Sync() if err != nil { t.Fatalf("primary seed sync: %v", err) } if got, err := replica.Sync(); err != nil || got != frontier { t.Fatalf("replica seed sync=(%d,%v), want frontier %d", got, err, frontier) } listener, err := transport.NewReplicaListener("127.0.0.1:0", replica) if err != nil { t.Fatal(err) } listener.Serve() t.Cleanup(func() { listener.Stop() }) v := NewReplicationVolume("vol-promoted", primary) v.SetDurabilityMode(DurabilitySyncQuorum) t.Cleanup(func() { _ = v.Close() }) if err := v.UpdateReplicaSet(1, []ReplicaTarget{targetFor("r3", listener.Addr(), 2, 1)}); err != nil { t.Fatalf("UpdateReplicaSet: %v", err) } next := make([]byte, blockSize) next[0] = 0x44 next[1] = 0x55 lsn, err := primary.Write(9, next) if err != nil { t.Fatalf("primary post-promotion write: %v", err) } if lsn != frontier+1 { t.Fatalf("post-promotion lsn=%d want frontier+1=%d", lsn, frontier+1) } if err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: 9, Data: next, LSN: lsn}); err != nil { t.Fatalf("OnLocalWrite after promoted peer install: %v", err) } waitForReplicaLBA(t, replica, 9, 0x44, 0x55, 2*time.Second) } func TestReplicationVolume_UpdateReplicaSet_DegradesPeerBelowLocalFrontier(t *testing.T) { const blockSize = 4096 primary := storage.NewBlockStore(64, blockSize) replica := storage.NewBlockStore(64, blockSize) for i := uint32(0); i < 3; i++ { data := make([]byte, blockSize) data[0] = byte(i + 1) data[1] = 0xB0 lsn, err := primary.Write(i, data) if err != nil { t.Fatalf("primary seed write %d: %v", i, err) } if i < 2 { if err := replica.ApplyEntry(i, data, lsn); err != nil { t.Fatalf("replica partial apply %d: %v", i, err) } } } frontier, err := primary.Sync() if err != nil { t.Fatalf("primary seed sync: %v", err) } if got, err := replica.Sync(); err != nil || got >= frontier { t.Fatalf("replica partial sync=(%d,%v), want below frontier %d", got, err, frontier) } listener, err := transport.NewReplicaListener("127.0.0.1:0", replica) if err != nil { t.Fatal(err) } listener.Serve() t.Cleanup(func() { listener.Stop() }) v := NewReplicationVolume("vol-promoted", primary) v.SetDurabilityMode(DurabilitySyncQuorum) t.Cleanup(func() { _ = v.Close() }) if err := v.UpdateReplicaSet(1, []ReplicaTarget{targetFor("r3", listener.Addr(), 2, 1)}); err != nil { t.Fatalf("UpdateReplicaSet: %v", err) } v.mu.Lock() state := v.peers["r3"].State() v.mu.Unlock() if state != ReplicaDegraded { t.Fatalf("peer state=%s want degraded for below-frontier survivor", state) } next := make([]byte, blockSize) next[0] = 0x66 next[1] = 0x77 lsn, err := primary.Write(9, next) if err != nil { t.Fatalf("primary post-promotion write: %v", err) } err = v.OnLocalWrite(context.Background(), LocalWrite{LBA: 9, Data: next, LSN: lsn}) if err == nil || !strings.Contains(err.Error(), ErrDurabilityQuorumLost.Error()) { t.Fatalf("OnLocalWrite err=%v, want quorum loss for below-frontier survivor", err) } } // --- Small helpers --- func waitForReplicaLBA(t *testing.T, replica *storage.BlockStore, lba uint32, want0, want1 byte, timeout time.Duration) { t.Helper() deadline := time.Now().Add(timeout) for time.Now().Before(deadline) { got, _ := replica.Read(lba) if got != nil && got[0] == want0 && got[1] == want1 { return } time.Sleep(10 * time.Millisecond) } got, _ := replica.Read(lba) t.Fatalf("replica LBA %d did not settle to [%02x %02x] within %v (got [%02x %02x])", lba, want0, want1, timeout, got[0], got[1]) } // Silence unused-import warnings in some build configs where the test // files reference fmt only in the error paths. var _ = fmt.Sprintf // --- Test 9: Q1 monotonic-guard pin --- // TestReplicationVolume_UpdateReplicaSet_Generation_MonotonicGuard — // Q1/Q2 pin (T4a-5.0 §9.4 rule). Apply a sequence of increasing // generations, then a stale one (gen <= lastApplied). Stale apply // must: // - return nil (idempotent replay is success, not an error) // - NOT mutate the peer map // - advance replayedGens counter (Q1 binding) // // Also exercises the Q2 "differing peers" log path by making the // stale-replay set differ from the live set. func TestReplicationVolume_UpdateReplicaSet_Generation_MonotonicGuard(t *testing.T) { addr1, _ := replicaHarness(t, "r1") addr2, _ := replicaHarness(t, "r2") v := volumeHarness(t, "vol1") // gen=1 → apply r1 if err := v.UpdateReplicaSet(1, []ReplicaTarget{targetFor("r1", addr1, 1, 1)}); err != nil { t.Fatal(err) } // gen=2 → apply r1+r2 if err := v.UpdateReplicaSet(2, []ReplicaTarget{ targetFor("r1", addr1, 1, 1), targetFor("r2", addr2, 1, 1), }); err != nil { t.Fatal(err) } // gen=3 → apply r2 only (r1 removed) if err := v.UpdateReplicaSet(3, []ReplicaTarget{targetFor("r2", addr2, 1, 1)}); err != nil { t.Fatal(err) } if v.PeerCount() != 1 { t.Fatalf("after gen=3 PeerCount=%d want 1", v.PeerCount()) } preReplayed := v.replayedGens.Load() // Stale replay at gen=2 with the ORIGINAL r1+r2 set. Must not // mutate peers (still r2 only); must increment replayedGens. err := v.UpdateReplicaSet(2, []ReplicaTarget{ targetFor("r1", addr1, 1, 1), targetFor("r2", addr2, 1, 1), }) if err != nil { t.Fatalf("stale-gen replay should return nil, got %v", err) } if v.PeerCount() != 1 { t.Fatalf("stale-gen replay mutated peer map: PeerCount=%d want 1", v.PeerCount()) } if v.replayedGens.Load() != preReplayed+1 { t.Fatalf("replayedGens counter: got %d want %d", v.replayedGens.Load(), preReplayed+1) } // Also stale at gen=3 (equal is stale per the rule: gen <= lastApplied). if err := v.UpdateReplicaSet(3, []ReplicaTarget{}); err != nil { t.Fatal(err) } if v.PeerCount() != 1 { t.Fatalf("gen==lastApplied must be stale no-op: PeerCount=%d want 1", v.PeerCount()) } if v.replayedGens.Load() != preReplayed+2 { t.Fatalf("replayedGens counter after second replay: got %d want %d", v.replayedGens.Load(), preReplayed+2) } // Forward progress to gen=4 works after stale replays. if err := v.UpdateReplicaSet(4, []ReplicaTarget{}); err != nil { t.Fatal(err) } if v.PeerCount() != 0 { t.Fatalf("gen=4 apply should remove all peers: got %d", v.PeerCount()) } } // --- Test 10: Q1 unversioned-apply pin --- // TestReplicationVolume_UpdateReplicaSet_GenerationZero_DoesNotAdvanceGuard // — gen=0 applies peer mutations but MUST NOT advance lastApplied. // Pinning this means test-harness uses of gen=0 cannot accidentally // poison the monotonic guard (the original MaxUint64 sentinel // hazard that QA caught and this rule replaces). func TestReplicationVolume_UpdateReplicaSet_GenerationZero_DoesNotAdvanceGuard(t *testing.T) { addr, _ := replicaHarness(t, "r1") v := volumeHarness(t, "vol1") // gen=5 → apply r1. lastApplied=5. if err := v.UpdateReplicaSet(5, []ReplicaTarget{targetFor("r1", addr, 1, 1)}); err != nil { t.Fatal(err) } v.mu.Lock() last := v.lastAppliedGeneration v.mu.Unlock() if last != 5 { t.Fatalf("lastApplied after gen=5: got %d want 5", last) } // gen=0 → unversioned apply (remove r1). Peer mutation happens // but lastApplied MUST stay at 5. if err := v.UpdateReplicaSet(0, []ReplicaTarget{}); err != nil { t.Fatal(err) } if v.PeerCount() != 0 { t.Fatalf("gen=0 did not mutate peer map: PeerCount=%d want 0", v.PeerCount()) } v.mu.Lock() last = v.lastAppliedGeneration v.mu.Unlock() if last != 5 { t.Fatalf("gen=0 advanced lastApplied: got %d want 5 (monotonic guard would be poisoned)", last) } // gen=3 now arrives — still stale vs lastApplied=5. Must be // rejected. If the guard had been poisoned by gen=0 (e.g., reset // to 0), gen=3 would have been accepted. preReplayed := v.replayedGens.Load() if err := v.UpdateReplicaSet(3, []ReplicaTarget{targetFor("r1", addr, 1, 1)}); err != nil { t.Fatal(err) } if v.PeerCount() != 0 { t.Fatalf("gen=3 (stale vs lastApplied=5) was not rejected: PeerCount=%d", v.PeerCount()) } if v.replayedGens.Load() != preReplayed+1 { t.Fatal("gen=3 should have been counted as stale replay") } } // --- Test 11: Q3 empty-peer-set with lifecycle teardown --- // TestReplicationVolume_UpdateReplicaSet_EmptyPeerSet_AppliesWithTeardown // — Q3 binding: UpdateReplicaSet(gen, []) MUST go through the normal // teardown path, NOT a special "clear the map" fast-path. Assertions: // // (a) PeerCount() == 0 after apply // (b) every formerly-present peer's executor session is invalidated // (c) next OnLocalWrite succeeds as a zero-fanout no-op func TestReplicationVolume_UpdateReplicaSet_EmptyPeerSet_AppliesWithTeardown(t *testing.T) { addr1, _ := replicaHarness(t, "r1") addr2, _ := replicaHarness(t, "r2") v := volumeHarness(t, "vol1") // Wrap newExec to collect per-peer executors so we can assert // session invalidation. var execs []*transport.BlockExecutor var execMu sync.Mutex v.newExec = func(store storage.LogicalStorage, replicaAddr string) *transport.BlockExecutor { e := transport.NewBlockExecutor(store, replicaAddr) execMu.Lock() execs = append(execs, e) execMu.Unlock() return e } // Apply gen=1 with r1+r2 → two peers, two executors, two sessions. if err := v.UpdateReplicaSet(1, []ReplicaTarget{ targetFor("r1", addr1, 1, 1), targetFor("r2", addr2, 1, 1), }); err != nil { t.Fatal(err) } // Snapshot the session IDs before teardown. v.mu.Lock() sessionID1 := v.peers["r1"].sessionID sessionID2 := v.peers["r2"].sessionID v.mu.Unlock() execMu.Lock() snapshotExecs := append([]*transport.BlockExecutor(nil), execs...) execMu.Unlock() if len(snapshotExecs) < 2 { t.Fatalf("expected >=2 executors after 2-peer apply, got %d", len(snapshotExecs)) } // Apply gen=2 with [] → N→0 teardown. if err := v.UpdateReplicaSet(2, []ReplicaTarget{}); err != nil { t.Fatal(err) } // (a) PeerCount == 0 if v.PeerCount() != 0 { t.Fatalf("PeerCount after empty-set apply=%d want 0", v.PeerCount()) } // (b) both sessions invalidated. Scan all executors recorded for // this volume and confirm neither session is still registered. for _, e := range snapshotExecs { if e.HasSession(sessionID1) { t.Fatal("r1's session not invalidated after empty-set apply") } if e.HasSession(sessionID2) { t.Fatal("r2's session not invalidated after empty-set apply") } } // (c) next OnLocalWrite succeeds as zero-fanout no-op. data := make([]byte, 4096) data[0] = 0x7E err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: 0, Data: data, LSN: 1}) if err != nil { t.Fatalf("OnLocalWrite after empty-set teardown: %v", err) } }