From 4bc5803dca82477b5041784c57c3a43672b103ea Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 21:14:24 -0800 Subject: [PATCH 1/4] test(volume): a fenced caught-up peer is healed on its live session (red) A replica already at the primary's end is fenced at the peer's epoch with a session the fence mints, above the live session drawn at the peer's creation; the replica then holds the fence's lineage, and the engine's healthy verdict, a barrier on the live session, is refused as stale: the peer stays degraded. A second test fixes the order: a live session re-drawn before the fence is acknowledged makes the replica refuse the fence. Co-Authored-By: Claude Opus 5.5 --- .../volume/peer_fence_live_session_test.go | 135 ++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100644 seaweed-block/core/host/volume/peer_fence_live_session_test.go diff --git a/seaweed-block/core/host/volume/peer_fence_live_session_test.go b/seaweed-block/core/host/volume/peer_fence_live_session_test.go new file mode 100644 index 0000000000..a092dd484c --- /dev/null +++ b/seaweed-block/core/host/volume/peer_fence_live_session_test.go @@ -0,0 +1,135 @@ +package volume + +import ( + "net" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/replication" + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +// A replica that is already at the primary's end (R = H) is fenced at the +// peer's epoch with a session the fence mints (as the adapter's +// FenceAtEpoch does, from the peer's one session order), above the live +// session the peer drew at its creation. The replica then holds the +// fence's lineage. The engine's healthy verdict sends its barrier on the +// live session: it must be acknowledged and the peer healed, so the live +// session must be re-drawn above the fence's once the fence completes. +// Without that the replica refuses the barrier as stale, forever. +func TestAFencedCaughtUpPeerIsHealedOnItsLiveSession(t *testing.T) { + for _, fence := range []bool{true, false} { + name := map[bool]string{true: "fenced first", false: "control: no fence"}[fence] + t.Run(name, func(t *testing.T) { + peer, exec := fencePeerRig(t) + if fence { + done := make(chan adapter.FenceResult, 1) + exec.SetOnFenceComplete(func(r adapter.FenceResult) { done <- r }) + sid := exec.SessionIDs().Next() // the adapter's FenceAtEpoch mint + if err := exec.Fence("r2", sid, 2, 1); err != nil { + t.Fatal(err) + } + select { + case r := <-done: + if !r.Success { + t.Fatalf("fence failed: %s", r.FailReason) + } + case <-time.After(10 * time.Second): + t.Fatal("the fence did not complete") + } + } + exec.PublishHealthy("r2") + if s := peer.State(); s != replication.ReplicaHealthy { + t.Fatalf("peer %s after the healthy verdict; want healthy (its barrier on the live session must be acknowledged)", s) + } + }) + } +} + +// fencePeerRig is a primary volume with one degraded peer r2 at epoch 2 +// whose replica (a real listener) is already at the primary's end. +func fencePeerRig(t *testing.T) (*replication.ReplicaPeer, *PeerCommandExecutor) { + t.Helper() + const blockSize, n = 4096, 4 + primary := storage.NewBlockStore(64, blockSize) + replica := storage.NewBlockStore(64, blockSize) + for i := 0; i < n; i++ { + data := make([]byte, blockSize) + data[0] = byte(i + 1) + lsn, err := primary.Write(uint32(i), data) + if err != nil { + t.Fatal(err) + } + if err := replica.ApplyEntry(uint32(i), data, lsn); err != nil { + t.Fatal(err) + } + } + own, _ := transport.LoadEpochTable("", "vol1") + _ = own.Replace([]transport.EpochRow{{Epoch: 2, FirstLSN: 1}}) + theirs, _ := transport.LoadEpochTable("", "vol1") + _ = theirs.Replace([]transport.EpochRow{{Epoch: 2, FirstLSN: 1}}) + + // Nothing listens yet: the seed barrier fails and the peer is + // degraded (the rejoining replica is not up). + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := l.Addr().String() + _ = l.Close() + v := replication.NewReplicationVolume("vol1", primary) + v.SetDurabilityMode(replication.DurabilitySyncQuorum) + v.SetEpochTable(own) + t.Cleanup(func() { _ = v.Close() }) + var peer *replication.ReplicaPeer + if err := v.ConfigurePeerLifecycleHook(func(p *replication.ReplicaPeer) { peer = p }, func(string) {}); err != nil { + t.Fatal(err) + } + if err := v.UpdateReplicaSet(1, []replication.ReplicaTarget{{ReplicaID: "r2", DataAddr: addr, ControlAddr: addr, Epoch: 2, EndpointVersion: 1}}); err != nil { + t.Fatal(err) + } + if peer == nil || peer.State() != replication.ReplicaDegraded { + t.Fatalf("peer %v; want degraded after an unanswered seed barrier", peer) + } + + listener, err := transport.NewReplicaListener(addr, replica) + if err != nil { + t.Fatal(err) + } + listener.SetEpochTable(theirs) + listener.Serve() + t.Cleanup(func() { _ = v.Close(); listener.Stop() }) + + return peer, NewPeerCommandExecutor(peer) +} + +// The order of the re-draw: the live session moves above the fence's only +// after the fence's own barrier is acknowledged. Moved before (here: the +// fence's session drawn, the live one re-drawn above it, then the fence +// sent), the replica holds the higher live lineage and refuses the fence. +func TestTheLiveSessionMovesOnlyAfterTheFenceIsAcknowledged(t *testing.T) { + peer, exec := fencePeerRig(t) + done := make(chan adapter.FenceResult, 1) + exec.SetOnFenceComplete(func(r adapter.FenceResult) { done <- r }) + sid := exec.SessionIDs().Next() + if err := peer.RefreshLiveShipSessionAfter(sid, 0, "re-drawn too early"); err != nil { + t.Fatal(err) + } + exec.PublishHealthy("r2") // the replica now holds the live lineage above sid + if s := peer.State(); s != replication.ReplicaHealthy { + t.Fatalf("fixture: peer %s; want healthy on the re-drawn live session", s) + } + if err := exec.Fence("r2", sid, 2, 1); err != nil { + t.Fatal(err) + } + select { + case r := <-done: + if r.Success { + t.Fatal("a fence below the replica's held live lineage was acknowledged; want it refused (which is why the re-draw waits for the fence's ack)") + } + case <-time.After(10 * time.Second): + t.Fatal("the fence did not complete") + } +} From 7483d9634ecaa3873c0f53d09cc8c749d42df4ad Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 21:14:25 -0800 Subject: [PATCH 2/4] fix(volume): re-draw the live ship session above a completed fence A fence mints its own session from the peer's one session order; once the replica acknowledges it, the replica holds the fence's lineage, above the peer's earlier live session, and refuses every later barrier or ship on that live session as stale. A rejoining replica already at the primary's end (no recovery session, so no post-recovery refresh) was never healed. The fence-complete callback now calls the same RefreshLiveShipSessionAfter the recovery close uses, after the fence's barrier was acknowledged and before the engine publishes healthy. The replica's stale-refusal log lines now name their cause (a primary listener, an epoch below the floor, no role yet, below the held lineage, or the same lineage with another frontier hint). Co-Authored-By: Claude Opus 5.5 --- .../core/host/volume/peer_command_executor.go | 25 ++++++-- seaweed-block/core/transport/replica.go | 63 ++++++++++++------- .../transport/replica_refusal_reason_test.go | 50 +++++++++++++++ 3 files changed, 111 insertions(+), 27 deletions(-) create mode 100644 seaweed-block/core/transport/replica_refusal_reason_test.go diff --git a/seaweed-block/core/host/volume/peer_command_executor.go b/seaweed-block/core/host/volume/peer_command_executor.go index c9754e8673..40673542bc 100644 --- a/seaweed-block/core/host/volume/peer_command_executor.go +++ b/seaweed-block/core/host/volume/peer_command_executor.go @@ -104,11 +104,28 @@ func (p *PeerCommandExecutor) SetOnSessionClose(fn adapter.OnSessionClose) { }) } -// SetOnFenceComplete delegates verbatim to the inner executor. -// Fence completion does not directly drive peer state; it advances -// engine Reachability.FencedEpoch which is the ack-gate for Healthy. +// SetOnFenceComplete wraps the adapter-supplied callback so a completed +// fence first re-draws the peer's live session above the fence's, then +// lets the engine advance Reachability.FencedEpoch (the ack-gate for +// Healthy). A fence mints its own session from the peer's one session +// order, and the replica holds the fence's lineage once it acknowledges +// it: the live session, drawn earlier, would be below it, and every later +// barrier or ship on it refused as stale. The re-draw runs only after the +// fence's own barrier was acknowledged (this callback), so the replica +// never holds a live lineage above an in-flight fence. func (p *PeerCommandExecutor) SetOnFenceComplete(fn adapter.OnFenceComplete) { - p.inner.SetOnFenceComplete(fn) + p.inner.SetOnFenceComplete(func(r adapter.FenceResult) { + if r.Success { + if err := p.peer.RefreshLiveShipSessionAfter(r.SessionID, 0, "fence completed"); err != nil { + r.Success = false + r.FailReason = err.Error() + p.peer.Invalidate("live session refresh after fence failed: " + err.Error()) + } + } + if fn != nil { + fn(r) + } + }) } // --- Wire-level command delegation (verbatim to inner) --- diff --git a/seaweed-block/core/transport/replica.go b/seaweed-block/core/transport/replica.go index c47e745d2a..a109a68994 100644 --- a/seaweed-block/core/transport/replica.go +++ b/seaweed-block/core/transport/replica.go @@ -178,12 +178,12 @@ func (r *ReplicaListener) raiseFloor(epoch uint64) error { // then, if the frame's epoch raises the floor, the durable raise before any // effect or ACK (G1). It runs inside the frame's counted section (G2), so a // fence waits for it. -func (r *ReplicaListener) admitMutation(l RecoveryLineage) bool { +func (r *ReplicaListener) admitMutation(l RecoveryLineage) (bool, string) { r.mu.Lock() prev := r.activeLineage - if !r.acceptMutationLineageLocked(l) { + if why := r.mutationLineageRefusalLocked(l); why != "" { r.mu.Unlock() - return false + return false, why } if r.sessionFrames == nil { r.sessionFrames = make(map[uint64]int) @@ -199,14 +199,14 @@ func (r *ReplicaListener) admitMutation(l RecoveryLineage) bool { r.mu.Unlock() r.endSessionFrame(l.SessionID) log.Printf("replica: refuse mutation at epoch %d: %v", l.Epoch, err) - return false + return false, "epoch floor not durable: " + err.Error() } r.mu.Lock() if prev.SessionID != l.SessionID { r.markSessionRetiringLocked(prev.SessionID) } r.mu.Unlock() - return true + return true, "" } // NewReplicaListenerWithApplyHook creates a listener with the @@ -411,8 +411,11 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { var replyType byte var reply []byte var admittedSession uint64 + var refusal string // why the last admit refused (logged by its caller) admit := func(l RecoveryLineage) bool { - if !r.admitMutation(l) { + ok, why := r.admitMutation(l) + if !ok { + refusal = why return false } admittedSession = l.SessionID @@ -427,8 +430,8 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { return true } if !admit(lineage) { - log.Printf("replica: reject stale recovery lane start session=%d epoch=%d endpointVersion=%d", - lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) + log.Printf("replica: reject stale recovery lane start session=%d epoch=%d endpointVersion=%d: %s", + lineage.SessionID, lineage.Epoch, lineage.EndpointVersion, refusal) return true } // The lane ships history whose epochs arrive only at its @@ -469,8 +472,8 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { return true } if !admit(entry.Lineage) { - log.Printf("replica: reject stale ship session=%d epoch=%d endpointVersion=%d", - entry.Lineage.SessionID, entry.Lineage.Epoch, entry.Lineage.EndpointVersion) + log.Printf("replica: reject stale ship session=%d epoch=%d endpointVersion=%d: %s", + entry.Lineage.SessionID, entry.Lineage.Epoch, entry.Lineage.EndpointVersion, refusal) return true } // Live lane: the row first, then the entry, so an entry @@ -587,8 +590,8 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { return true } if !admit(lineage) { - log.Printf("replica: reject stale rebuild block session=%d epoch=%d endpointVersion=%d", - lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) + log.Printf("replica: reject stale rebuild block session=%d epoch=%d endpointVersion=%d: %s", + lineage.SessionID, lineage.Epoch, lineage.EndpointVersion, refusal) return true } // Rebuild blocks are BASE-lane bytes. They must not enter the @@ -611,8 +614,8 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { return true } if !admit(lineage) { - log.Printf("replica: reject stale rebuild done session=%d epoch=%d endpointVersion=%d", - lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) + log.Printf("replica: reject stale rebuild done session=%d epoch=%d endpointVersion=%d: %s", + lineage.SessionID, lineage.Epoch, lineage.EndpointVersion, refusal) return true } // Done (DESIGN 8.7): an empty rebuild begins here; the hint must @@ -679,8 +682,8 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { return true } if !admit(lineage) { - log.Printf("replica: reject stale barrier session=%d epoch=%d endpointVersion=%d", - lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) + log.Printf("replica: reject stale barrier session=%d epoch=%d endpointVersion=%d: %s", + lineage.SessionID, lineage.Epoch, lineage.EndpointVersion, refusal) return true } frontier, syncErr := r.store.Sync() @@ -1000,31 +1003,45 @@ func (r *ReplicaListener) acceptMutationLineage(incoming RecoveryLineage) bool { } func (r *ReplicaListener) acceptMutationLineageLocked(incoming RecoveryLineage) bool { + return r.mutationLineageRefusalLocked(incoming) == "" +} +// mutationLineageRefusalLocked admits incoming (taking it as the active +// lineage when newer) and returns "", or returns why it is refused, one +// reason per cause, for the caller's log line. +func (r *ReplicaListener) mutationLineageRefusalLocked(incoming RecoveryLineage) string { if incoming.SessionID == 0 || incoming.Epoch == 0 || incoming.EndpointVersion == 0 { - return false + return "incomplete lineage" } // G2: a primary applies no inbound replication, and no host applies // any below the epoch it has taken a role at. G1: a production listener // applies nothing before its role is known. - if r.primary || incoming.Epoch < r.epochFloor || (r.requireRole && !r.assigned) { - return false + switch { + case r.primary: + return "this listener is a primary" + case incoming.Epoch < r.epochFloor: + return fmt.Sprintf("epoch below the floor %d", r.epochFloor) + case r.requireRole && !r.assigned: + return "no role assigned yet" } active := r.activeLineage if active.SessionID == 0 { r.activeLineage = incoming - return true + return "" } switch compareLineage(incoming, active) { case 1: r.activeLineage = incoming - return true + return "" case 0: - return incoming.EffectiveFrontierHint() == active.EffectiveFrontierHint() + if incoming.EffectiveFrontierHint() == active.EffectiveFrontierHint() { + return "" + } + return fmt.Sprintf("same lineage with another frontier hint (%d, held %d)", incoming.EffectiveFrontierHint(), active.EffectiveFrontierHint()) default: - return false + return fmt.Sprintf("below the held lineage session=%d epoch=%d endpointVersion=%d", active.SessionID, active.Epoch, active.EndpointVersion) } } diff --git a/seaweed-block/core/transport/replica_refusal_reason_test.go b/seaweed-block/core/transport/replica_refusal_reason_test.go new file mode 100644 index 0000000000..d4c4b246ad --- /dev/null +++ b/seaweed-block/core/transport/replica_refusal_reason_test.go @@ -0,0 +1,50 @@ +package transport + +import ( + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Each cause of a refused mutation lineage has its own reason, so a refusal +// log line says which one it was: a primary listener, an epoch below the +// floor, no role yet, a lineage below the held one, and the same lineage +// with another frontier hint. An admitted lineage has none. +func TestMutationRefusalNamesItsCause(t *testing.T) { + held := RecoveryLineage{SessionID: 5, Epoch: 2, EndpointVersion: 1, TargetLSN: 1} + for _, c := range []struct { + name string + setup func(r *ReplicaListener) + incoming RecoveryLineage + want string + }{ + {"primary", func(r *ReplicaListener) { r.primary = true }, RecoveryLineage{SessionID: 6, Epoch: 2, EndpointVersion: 1, TargetLSN: 1}, "is a primary"}, + {"below the floor", func(r *ReplicaListener) { r.epochFloor = 3 }, RecoveryLineage{SessionID: 6, Epoch: 2, EndpointVersion: 1, TargetLSN: 1}, "below the floor 3"}, + {"no role", func(r *ReplicaListener) { r.requireRole, r.assigned = true, false }, RecoveryLineage{SessionID: 6, Epoch: 2, EndpointVersion: 1, TargetLSN: 1}, "no role assigned"}, + {"below the held lineage", func(r *ReplicaListener) { r.activeLineage = held }, RecoveryLineage{SessionID: 1, Epoch: 2, EndpointVersion: 1, TargetLSN: 66}, "below the held lineage session=5"}, + {"same lineage, another hint", func(r *ReplicaListener) { r.activeLineage = held }, RecoveryLineage{SessionID: 5, Epoch: 2, EndpointVersion: 1, TargetLSN: 66}, "another frontier hint"}, + {"admitted", func(r *ReplicaListener) { r.activeLineage = held }, RecoveryLineage{SessionID: 6, Epoch: 2, EndpointVersion: 1, TargetLSN: 66}, ""}, + } { + t.Run(c.name, func(t *testing.T) { + l, err := NewReplicaListener("127.0.0.1:0", storage.NewBlockStore(8, 4096)) + if err != nil { + t.Fatal(err) + } + defer l.Stop() + l.mu.Lock() + c.setup(l) + why := l.mutationLineageRefusalLocked(c.incoming) + l.mu.Unlock() + if c.want == "" { + if why != "" { + t.Fatalf("refused %q; want admitted", why) + } + return + } + if !strings.Contains(why, c.want) { + t.Fatalf("reason %q; want it to name %q", why, c.want) + } + }) + } +} From de6a56b45326ec845b0bd3217e9779997e173f78 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 21:29:44 -0800 Subject: [PATCH 3/4] fix(volume): re-draw the live session above a session whatever its outcome The replica takes a session's lineage when it admits it; the sender saw only the exchange's result. A fence the replica admitted whose reply was lost, or a recovery session whose close failed, left the replica above the live session with no re-draw. The fence-complete and session-close callbacks now re-draw the live session above the session on any outcome (a completed recovery still advances the cursor and heals). A guard test over the adapter's draw switch lists every command kind that draws a session and what re-draws after it; the refresh's log line names the session and the reason instead of 'after recovery='. Co-Authored-By: Claude Opus 5.5 --- .../core/host/volume/peer_command_executor.go | 70 +++++++++----- .../volume/peer_fence_live_session_test.go | 95 +++++++++++++++++++ seaweed-block/core/replication/peer.go | 4 +- 3 files changed, 145 insertions(+), 24 deletions(-) diff --git a/seaweed-block/core/host/volume/peer_command_executor.go b/seaweed-block/core/host/volume/peer_command_executor.go index 40673542bc..27a2b5a54c 100644 --- a/seaweed-block/core/host/volume/peer_command_executor.go +++ b/seaweed-block/core/host/volume/peer_command_executor.go @@ -81,18 +81,8 @@ func (p *PeerCommandExecutor) SetOnSessionStart(fn adapter.OnSessionStart) { // session ID. func (p *PeerCommandExecutor) SetOnSessionClose(fn adapter.OnSessionClose) { p.inner.SetOnSessionClose(func(r adapter.SessionCloseResult) { - if r.Success { - if err := p.peer.RefreshLiveShipSessionAfter(r.SessionID, r.AchievedLSN, "recovery session completed"); err != nil { - r.Success = false - r.FailReason = err.Error() - p.peer.Invalidate("live session refresh failed: " + err.Error()) - } else { - ctx, cancel := context.WithTimeout(context.Background(), healReconcileTimeout) - p.peer.HealIfInSync(ctx, "recovery session completed") - cancel() - } - } - // Failure path: the adapter feeds engine + r = p.afterSessionClose(r) + // Failure path (after the re-draw above): the adapter feeds engine // SessionClosedFailed which (per FailureKind) may emit // PublishDegraded; that lands at our PublishDegraded // override and calls peer.Invalidate. We do NOT @@ -104,30 +94,66 @@ func (p *PeerCommandExecutor) SetOnSessionClose(fn adapter.OnSessionClose) { }) } +// afterSessionClose re-draws the peer's live session above the closed +// recovery session, whatever its outcome: a session the replica admitted +// moved its held lineage even when its close failed (a lost final ack), +// and a live frame below it would be refused as stale. A completed one +// also advances the cursor and heals the peer when it is in sync. +func (p *PeerCommandExecutor) afterSessionClose(r adapter.SessionCloseResult) adapter.SessionCloseResult { + if !r.Success { + if err := p.peer.RefreshLiveShipSessionAfter(r.SessionID, 0, "recovery session failed"); err != nil { + p.peer.Invalidate("live session refresh failed: " + err.Error()) + } + return r + } + if err := p.peer.RefreshLiveShipSessionAfter(r.SessionID, r.AchievedLSN, "recovery session completed"); err != nil { + r.Success = false + r.FailReason = err.Error() + p.peer.Invalidate("live session refresh failed: " + err.Error()) + return r + } + ctx, cancel := context.WithTimeout(context.Background(), healReconcileTimeout) + p.peer.HealIfInSync(ctx, "recovery session completed") + cancel() + return r +} + // SetOnFenceComplete wraps the adapter-supplied callback so a completed // fence first re-draws the peer's live session above the fence's, then // lets the engine advance Reachability.FencedEpoch (the ack-gate for // Healthy). A fence mints its own session from the peer's one session // order, and the replica holds the fence's lineage once it acknowledges // it: the live session, drawn earlier, would be below it, and every later -// barrier or ship on it refused as stale. The re-draw runs only after the -// fence's own barrier was acknowledged (this callback), so the replica -// never holds a live lineage above an in-flight fence. +// barrier or ship on it refused as stale. The re-draw runs only once the +// fence's exchange is over (this callback), so the replica never holds a +// live lineage above an in-flight fence; and it runs on a failed fence too, +// since the replica may have admitted the fence and only its reply was lost. func (p *PeerCommandExecutor) SetOnFenceComplete(fn adapter.OnFenceComplete) { p.inner.SetOnFenceComplete(func(r adapter.FenceResult) { - if r.Success { - if err := p.peer.RefreshLiveShipSessionAfter(r.SessionID, 0, "fence completed"); err != nil { - r.Success = false - r.FailReason = err.Error() - p.peer.Invalidate("live session refresh after fence failed: " + err.Error()) - } - } + r = p.afterFence(r) if fn != nil { fn(r) } }) } +// afterFence re-draws the peer's live session above the fence's session, +// whatever the fence's outcome. +func (p *PeerCommandExecutor) afterFence(r adapter.FenceResult) adapter.FenceResult { + reason := "fence completed" + if !r.Success { + reason = "fence failed" + } + if err := p.peer.RefreshLiveShipSessionAfter(r.SessionID, 0, reason); err != nil { + p.peer.Invalidate("live session refresh after fence failed: " + err.Error()) + if r.Success { + r.Success = false + r.FailReason = err.Error() + } + } + return r +} + // --- Wire-level command delegation (verbatim to inner) --- func (p *PeerCommandExecutor) Probe(replicaID, dataAddr, ctrlAddr string, sessionID, epoch, endpointVersion uint64) adapter.ProbeResult { diff --git a/seaweed-block/core/host/volume/peer_fence_live_session_test.go b/seaweed-block/core/host/volume/peer_fence_live_session_test.go index a092dd484c..dfece663b0 100644 --- a/seaweed-block/core/host/volume/peer_fence_live_session_test.go +++ b/seaweed-block/core/host/volume/peer_fence_live_session_test.go @@ -1,7 +1,12 @@ package volume import ( + "context" + "go/ast" + "go/parser" + "go/token" "net" + "path/filepath" "testing" "time" @@ -133,3 +138,93 @@ func TestTheLiveSessionMovesOnlyAfterTheFenceIsAcknowledged(t *testing.T) { t.Fatal("the fence did not complete") } } + +// The lost acknowledgement: the replica admits a session (it holds that +// lineage from then on) but the sender sees the exchange fail, its reply +// lost. The live session is re-drawn above it all the same, so the next +// live frame is not refused as stale. Both cases are driven here: a fence +// the replica admitted whose result is a failure, and a recovery session +// (standing in: the replica holds its lineage) whose close failed. +func TestAnAdmittedSessionWhoseReplyIsLostStillMovesTheLiveSession(t *testing.T) { + for _, kind := range []string{"fence", "recovery session"} { + t.Run(kind, func(t *testing.T) { + peer, exec := fencePeerRig(t) + sid := exec.SessionIDs().Next() + // The replica admits a barrier at sid: it now holds sid's lineage. + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := peer.Fence(ctx, transport.RecoveryLineage{SessionID: sid, Epoch: 2, EndpointVersion: 1, TargetLSN: 1}); err != nil { + t.Fatalf("fixture: the replica did not admit the session: %v", err) + } + // The sender saw it fail (the reply lost). + if kind == "fence" { + exec.afterFence(adapter.FenceResult{ReplicaID: "r2", SessionID: sid, Epoch: 2, EndpointVersion: 1, Success: false, FailReason: "reply lost"}) + } else { + exec.afterSessionClose(adapter.SessionCloseResult{ReplicaID: "r2", SessionID: sid, Success: false, FailReason: "final ack lost"}) + } + exec.PublishHealthy("r2") + if s := peer.State(); s != replication.ReplicaHealthy { + t.Fatalf("peer %s after the healthy verdict; want healthy: the live session must be above the admitted %d", s, sid) + } + }) + } +} + +// Every command kind for which the adapter draws a session from the peer's +// order is listed with what keeps the live session above it: recovery +// sessions re-draw at their close and fences at their completion, both on +// any outcome; a probe does not move the replica's held lineage. A new +// drawing kind fails here until it is classified. +func TestEverySessionDrawIsFollowedByALiveRedraw(t *testing.T) { + want := map[string]string{ + "StartCatchUp": "recovery session: afterSessionClose re-draws", + "StartRebuild": "recovery session: afterSessionClose re-draws", + "StartRecovery": "recovery session: afterSessionClose re-draws", + "FenceAtEpoch": "fence: afterFence re-draws", + "ProbeReplica": "non-moving: the replica validates a probe without taking its lineage", + } + fset := token.NewFileSet() + f, err := parser.ParseFile(fset, filepath.Join("..", "..", "adapter", "adapter.go"), nil, 0) + if err != nil { + t.Fatal(err) + } + got := map[string]bool{} + ast.Inspect(f, func(n ast.Node) bool { + cc, ok := n.(*ast.CaseClause) + if !ok { + return true + } + draws := false + for _, st := range cc.Body { + ast.Inspect(st, func(m ast.Node) bool { + if call, ok := m.(*ast.CallExpr); ok { + if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "Next" || sel.Sel.Name == "NextAfter") { + if inner, ok := sel.X.(*ast.SelectorExpr); ok && inner.Sel.Name == "sessionIDs" { + draws = true + } + } + } + return true + }) + } + if !draws { + return true + } + for _, e := range cc.List { + if sel, ok := e.(*ast.SelectorExpr); ok { + got[sel.Sel.Name] = true + } + } + return true + }) + for kind := range got { + if _, ok := want[kind]; !ok { + t.Errorf("the adapter draws a session for %s, which is not classified: re-draw the live session above it, or declare it non-moving", kind) + } + } + for kind, why := range want { + if !got[kind] { + t.Errorf("listed drawing kind %s (%s) no longer draws a session; update the list", kind, why) + } + } +} diff --git a/seaweed-block/core/replication/peer.go b/seaweed-block/core/replication/peer.go index 0f8e462c32..56e35bb3ba 100644 --- a/seaweed-block/core/replication/peer.go +++ b/seaweed-block/core/replication/peer.go @@ -266,8 +266,8 @@ func (p *ReplicaPeer) RefreshLiveShipSessionAfter(completedSessionID, achievedLS p.executor.InvalidateSession(p.target.ReplicaID, oldSessionID, reason) p.sessionID = newSessionID p.lineage = newLineage - log.Printf("replication: peer %s refreshed live session old=%d new=%d after recovery=%d", - p.target.ReplicaID, oldSessionID, newSessionID, completedSessionID) + log.Printf("replication: peer %s refreshed live session old=%d new=%d after session=%d (%s)", + p.target.ReplicaID, oldSessionID, newSessionID, completedSessionID, reason) return nil } From 2b55f615790638a9b4f912f82424b31fdade830b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 21:45:27 -0800 Subject: [PATCH 4/4] test(volume): the live re-draw through the real callbacks; R < H control; wider census The lost-reply tests now run through the executor's registered callbacks: a proxy forwards every frame to the replica (which admits and acts on it) and discards its replies, so the fence and the catch-up really fail at the sender; the failure is forwarded and the healthy verdict that follows heals the peer, and live traffic is acknowledged. A behind peer (R < H) is not healed by the healthy verdict, heals only through a catch-up's registered close (every block equal to the primary's), and then takes live traffic. The census now covers every reference to the session order in the adapter's production source (constructor binding and each draw by case), with helper, alias and outside-a-case controls. Each control is red against its mutant: no afterFence wiring, no afterSessionClose wiring, no re-draw on failure. Co-Authored-By: Claude Opus 5.5 --- .../volume/peer_fence_live_session_test.go | 541 +++++++++++++----- 1 file changed, 389 insertions(+), 152 deletions(-) diff --git a/seaweed-block/core/host/volume/peer_fence_live_session_test.go b/seaweed-block/core/host/volume/peer_fence_live_session_test.go index dfece663b0..350d5ea40d 100644 --- a/seaweed-block/core/host/volume/peer_fence_live_session_test.go +++ b/seaweed-block/core/host/volume/peer_fence_live_session_test.go @@ -1,12 +1,18 @@ package volume import ( + "bytes" "context" "go/ast" "go/parser" "go/token" + "io" + "io/fs" "net" "path/filepath" + "strings" + "sync" + "sync/atomic" "testing" "time" @@ -16,6 +22,216 @@ import ( "github.com/seaweedfs/seaweed-block/core/transport" ) +// replyDropProxy sits between the primary and a replica. In drop mode a +// new connection forwards the primary's frames to the replica (which +// admits and applies them) but discards the replica's replies: the +// primary's exchange times out although the replica acted on every frame. +type replyDropProxy struct { + ln net.Listener + upstream string + drop atomic.Bool + mu sync.Mutex + conns []net.Conn + wg sync.WaitGroup +} + +func startReplyDropProxy(t *testing.T, addr, upstream string) *replyDropProxy { + t.Helper() + ln, err := net.Listen("tcp", addr) + if err != nil { + t.Fatal(err) + } + p := &replyDropProxy{ln: ln, upstream: upstream} + p.wg.Add(1) + go func() { + defer p.wg.Done() + for { + c, err := ln.Accept() + if err != nil { + return + } + u, err := net.Dial("tcp", upstream) + if err != nil { + _ = c.Close() + continue + } + p.mu.Lock() + p.conns = append(p.conns, c, u) + p.mu.Unlock() + dropping := p.drop.Load() + p.wg.Add(2) + go func() { defer p.wg.Done(); _, _ = io.Copy(u, c); _ = u.Close() }() + go func() { + defer p.wg.Done() + if dropping { + // The replica acts on every frame; its replies are + // discarded, so the sender times out waiting for them. + _, _ = io.Copy(io.Discard, u) + } else { + _, _ = io.Copy(c, u) + } + _ = c.Close() + _ = u.Close() + }() + } + }() + t.Cleanup(func() { + _ = ln.Close() + p.mu.Lock() + for _, c := range p.conns { + _ = c.Close() + } + p.mu.Unlock() + p.wg.Wait() + }) + return p +} + +// fenceRig is a primary volume with one degraded peer r2 at epoch 2 and a +// real replica listener, either at the primary's end or `behind` entries +// short of it, optionally reached through a replyDropProxy. +type fenceRig struct { + peer *replication.ReplicaPeer + exec *PeerCommandExecutor + v *replication.ReplicationVolume + primary, replica *storage.BlockStore + proxy *replyDropProxy +} + +func newFenceRig(t *testing.T, behind int, proxied bool) *fenceRig { + t.Helper() + const blockSize, n = 4096, 4 + r := &fenceRig{primary: storage.NewBlockStore(64, blockSize), replica: storage.NewBlockStore(64, blockSize)} + for i := 0; i < n; i++ { + data := bytes.Repeat([]byte{byte(i + 1)}, blockSize) + lsn, err := r.primary.Write(uint32(i), data) + if err != nil { + t.Fatal(err) + } + if i < n-behind { + if err := r.replica.ApplyEntry(uint32(i), data, lsn); err != nil { + t.Fatal(err) + } + } + } + own, _ := transport.LoadEpochTable("", "vol1") + _ = own.Replace([]transport.EpochRow{{Epoch: 2, FirstLSN: 1}}) + theirs, _ := transport.LoadEpochTable("", "vol1") + _ = theirs.Replace([]transport.EpochRow{{Epoch: 2, FirstLSN: 1}}) + + // Nothing listens yet: the seed barrier fails and the peer is degraded + // (the rejoining replica is not up). + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := l.Addr().String() + _ = l.Close() + r.v = replication.NewReplicationVolume("vol1", r.primary) + r.v.SetDurabilityMode(replication.DurabilitySyncQuorum) + r.v.SetEpochTable(own) + t.Cleanup(func() { _ = r.v.Close() }) + if err := r.v.ConfigurePeerLifecycleHook(func(p *replication.ReplicaPeer) { r.peer = p }, func(string) {}); err != nil { + t.Fatal(err) + } + if err := r.v.UpdateReplicaSet(1, []replication.ReplicaTarget{{ReplicaID: "r2", DataAddr: addr, ControlAddr: addr, Epoch: 2, EndpointVersion: 1}}); err != nil { + t.Fatal(err) + } + if r.peer == nil || r.peer.State() != replication.ReplicaDegraded { + t.Fatalf("peer %v; want degraded after an unanswered seed barrier", r.peer) + } + listenAt := addr + if proxied { + listenAt = "127.0.0.1:0" + } + listener, err := transport.NewReplicaListener(listenAt, r.replica) + if err != nil { + t.Fatal(err) + } + listener.SetEpochTable(theirs) + listener.Serve() + if proxied { + r.proxy = startReplyDropProxy(t, addr, listener.Addr()) + } + // The primary's connection closes first, or Stop waits for it. + t.Cleanup(func() { _ = r.v.Close(); listener.Stop() }) + r.exec = NewPeerCommandExecutor(r.peer) + r.exec.SetOnSessionStart(func(adapter.SessionStartResult) {}) + return r +} + +// fencePeerRig is the caught-up rig, reached directly. +func fencePeerRig(t *testing.T) (*replication.ReplicaPeer, *PeerCommandExecutor) { + t.Helper() + r := newFenceRig(t, 0, false) + return r.peer, r.exec +} + +// fence runs a fence through the executor's registered callback and +// returns its result. +func (r *fenceRig) fence(t *testing.T) adapter.FenceResult { + t.Helper() + done := make(chan adapter.FenceResult, 1) + r.exec.SetOnFenceComplete(func(res adapter.FenceResult) { done <- res }) + if err := r.exec.Fence("r2", r.exec.SessionIDs().Next(), 2, 1); err != nil { + t.Fatal(err) + } + select { + case res := <-done: + return res + case <-time.After(10 * time.Second): + t.Fatal("the fence did not complete") + return adapter.FenceResult{} + } +} + +// catchUp runs a catch-up from the replica's end to the primary's through +// the executor's registered close callback and returns its result. +func (r *fenceRig) catchUp(t *testing.T) adapter.SessionCloseResult { + t.Helper() + closed := make(chan adapter.SessionCloseResult, 1) + r.exec.SetOnSessionClose(func(res adapter.SessionCloseResult) { closed <- res }) + end, _ := r.replica.Sync() + _, _, head := r.primary.Boundaries() + // The catch-up states the LSN it starts after: the replica's durable end. + if err := r.exec.StartCatchUp("r2", r.exec.SessionIDs().Next(), 2, 1, end, head); err != nil { + t.Fatal(err) + } + select { + case res := <-closed: + return res + case <-time.After(15 * time.Second): + t.Fatal("the catch-up never closed") + return adapter.SessionCloseResult{} + } +} + +// requireLiveTraffic writes one more block on the primary and requires it +// to be shipped and acknowledged on the live session (the replica's end +// reaches its LSN). +func (r *fenceRig) requireLiveTraffic(t *testing.T) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + data := bytes.Repeat([]byte{0x7C}, 4096) + lsn, err := r.primary.Write(9, data) + if err != nil { + t.Fatal(err) + } + if err := r.v.Observe(ctx, 9, lsn, data); err != nil { + t.Fatalf("live ship: %v", err) + } + if err := r.v.Sync(ctx, lsn); err != nil { + t.Fatalf("live barrier: %v", err) + } + // The live session's frames were admitted and acknowledged: the + // replica's durable end reached the write. + if R, _, _ := r.replica.Boundaries(); R < lsn { + t.Fatalf("the live write (LSN %d) was not acknowledged on the replica (end %d)", lsn, R) + } + +} + // A replica that is already at the primary's end (R = H) is fenced at the // peer's epoch with a session the fence mints (as the adapter's // FenceAtEpoch does, from the peer's one session order), above the live @@ -28,92 +244,25 @@ func TestAFencedCaughtUpPeerIsHealedOnItsLiveSession(t *testing.T) { for _, fence := range []bool{true, false} { name := map[bool]string{true: "fenced first", false: "control: no fence"}[fence] t.Run(name, func(t *testing.T) { - peer, exec := fencePeerRig(t) + r := newFenceRig(t, 0, false) if fence { - done := make(chan adapter.FenceResult, 1) - exec.SetOnFenceComplete(func(r adapter.FenceResult) { done <- r }) - sid := exec.SessionIDs().Next() // the adapter's FenceAtEpoch mint - if err := exec.Fence("r2", sid, 2, 1); err != nil { - t.Fatal(err) - } - select { - case r := <-done: - if !r.Success { - t.Fatalf("fence failed: %s", r.FailReason) - } - case <-time.After(10 * time.Second): - t.Fatal("the fence did not complete") + if res := r.fence(t); !res.Success { + t.Fatalf("fence failed: %s", res.FailReason) } } - exec.PublishHealthy("r2") - if s := peer.State(); s != replication.ReplicaHealthy { + r.exec.PublishHealthy("r2") + if s := r.peer.State(); s != replication.ReplicaHealthy { t.Fatalf("peer %s after the healthy verdict; want healthy (its barrier on the live session must be acknowledged)", s) } + r.requireLiveTraffic(t) }) } } -// fencePeerRig is a primary volume with one degraded peer r2 at epoch 2 -// whose replica (a real listener) is already at the primary's end. -func fencePeerRig(t *testing.T) (*replication.ReplicaPeer, *PeerCommandExecutor) { - t.Helper() - const blockSize, n = 4096, 4 - primary := storage.NewBlockStore(64, blockSize) - replica := storage.NewBlockStore(64, blockSize) - for i := 0; i < n; i++ { - data := make([]byte, blockSize) - data[0] = byte(i + 1) - lsn, err := primary.Write(uint32(i), data) - if err != nil { - t.Fatal(err) - } - if err := replica.ApplyEntry(uint32(i), data, lsn); err != nil { - t.Fatal(err) - } - } - own, _ := transport.LoadEpochTable("", "vol1") - _ = own.Replace([]transport.EpochRow{{Epoch: 2, FirstLSN: 1}}) - theirs, _ := transport.LoadEpochTable("", "vol1") - _ = theirs.Replace([]transport.EpochRow{{Epoch: 2, FirstLSN: 1}}) - - // Nothing listens yet: the seed barrier fails and the peer is - // degraded (the rejoining replica is not up). - l, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatal(err) - } - addr := l.Addr().String() - _ = l.Close() - v := replication.NewReplicationVolume("vol1", primary) - v.SetDurabilityMode(replication.DurabilitySyncQuorum) - v.SetEpochTable(own) - t.Cleanup(func() { _ = v.Close() }) - var peer *replication.ReplicaPeer - if err := v.ConfigurePeerLifecycleHook(func(p *replication.ReplicaPeer) { peer = p }, func(string) {}); err != nil { - t.Fatal(err) - } - if err := v.UpdateReplicaSet(1, []replication.ReplicaTarget{{ReplicaID: "r2", DataAddr: addr, ControlAddr: addr, Epoch: 2, EndpointVersion: 1}}); err != nil { - t.Fatal(err) - } - if peer == nil || peer.State() != replication.ReplicaDegraded { - t.Fatalf("peer %v; want degraded after an unanswered seed barrier", peer) - } - - listener, err := transport.NewReplicaListener(addr, replica) - if err != nil { - t.Fatal(err) - } - listener.SetEpochTable(theirs) - listener.Serve() - t.Cleanup(func() { _ = v.Close(); listener.Stop() }) - - return peer, NewPeerCommandExecutor(peer) -} - // The order of the re-draw: the live session moves above the fence's only -// after the fence's own barrier is acknowledged. Moved before (here: the -// fence's session drawn, the live one re-drawn above it, then the fence -// sent), the replica holds the higher live lineage and refuses the fence. +// once the fence's exchange is over. Moved before (here: the fence's +// session drawn, the live one re-drawn above it, then the fence sent), the +// replica holds the higher live lineage and refuses the fence. func TestTheLiveSessionMovesOnlyAfterTheFenceIsAcknowledged(t *testing.T) { peer, exec := fencePeerRig(t) done := make(chan adapter.FenceResult, 1) @@ -132,99 +281,187 @@ func TestTheLiveSessionMovesOnlyAfterTheFenceIsAcknowledged(t *testing.T) { select { case r := <-done: if r.Success { - t.Fatal("a fence below the replica's held live lineage was acknowledged; want it refused (which is why the re-draw waits for the fence's ack)") + t.Fatal("a fence below the replica's held live lineage was acknowledged; want it refused (which is why the re-draw waits for the fence's exchange)") } case <-time.After(10 * time.Second): t.Fatal("the fence did not complete") } } -// The lost acknowledgement: the replica admits a session (it holds that -// lineage from then on) but the sender sees the exchange fail, its reply -// lost. The live session is re-drawn above it all the same, so the next -// live frame is not refused as stale. Both cases are driven here: a fence -// the replica admitted whose result is a failure, and a recovery session -// (standing in: the replica holds its lineage) whose close failed. +// The lost acknowledgement, through the executor's registered callbacks: +// the replica admits a session (it holds that lineage from then on) and +// acts on it, but its reply never reaches the primary, which sees the +// exchange fail. The failure is forwarded to the engine's callback, and +// the live session is re-drawn above the session all the same: the +// healthy verdict that follows is acknowledged and live traffic lands. +// Cases: a fence of a caught-up replica, and a catch-up of a behind one +// whose close fails. func TestAnAdmittedSessionWhoseReplyIsLostStillMovesTheLiveSession(t *testing.T) { - for _, kind := range []string{"fence", "recovery session"} { - t.Run(kind, func(t *testing.T) { - peer, exec := fencePeerRig(t) - sid := exec.SessionIDs().Next() - // The replica admits a barrier at sid: it now holds sid's lineage. - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - if err := peer.Fence(ctx, transport.RecoveryLineage{SessionID: sid, Epoch: 2, EndpointVersion: 1, TargetLSN: 1}); err != nil { - t.Fatalf("fixture: the replica did not admit the session: %v", err) - } - // The sender saw it fail (the reply lost). - if kind == "fence" { - exec.afterFence(adapter.FenceResult{ReplicaID: "r2", SessionID: sid, Epoch: 2, EndpointVersion: 1, Success: false, FailReason: "reply lost"}) - } else { - exec.afterSessionClose(adapter.SessionCloseResult{ReplicaID: "r2", SessionID: sid, Success: false, FailReason: "final ack lost"}) - } - exec.PublishHealthy("r2") - if s := peer.State(); s != replication.ReplicaHealthy { - t.Fatalf("peer %s after the healthy verdict; want healthy: the live session must be above the admitted %d", s, sid) - } - }) - } + t.Run("fence", func(t *testing.T) { + r := newFenceRig(t, 0, true) + r.proxy.drop.Store(true) + if res := r.fence(t); res.Success { + t.Fatal("fixture: the fence succeeded; its reply was to be lost") + } + r.proxy.drop.Store(false) + r.exec.PublishHealthy("r2") + if s := r.peer.State(); s != replication.ReplicaHealthy { + t.Fatalf("peer %s after the healthy verdict; want healthy: the live session must be above the admitted fence", s) + } + r.requireLiveTraffic(t) + }) + t.Run("recovery session", func(t *testing.T) { + r := newFenceRig(t, 2, true) + r.proxy.drop.Store(true) + if res := r.catchUp(t); res.Success { + t.Fatal("fixture: the catch-up closed successfully; its replies were to be lost") + } + r.proxy.drop.Store(false) + r.exec.PublishHealthy("r2") + if s := r.peer.State(); s != replication.ReplicaHealthy { + t.Fatalf("peer %s after the healthy verdict; want healthy: the live session must be above the admitted recovery session", s) + } + r.requireLiveTraffic(t) + }) } -// Every command kind for which the adapter draws a session from the peer's -// order is listed with what keeps the live session above it: recovery -// sessions re-draw at their close and fences at their completion, both on -// any outcome; a probe does not move the replica's held lineage. A new -// drawing kind fails here until it is classified. +// The R < H control: a peer behind the primary is not healed by the +// engine's healthy verdict while it lags; a catch-up through the +// registered close callback brings it to the primary's end (every block +// equal, nothing skipped or rewound), heals it, and live traffic then +// lands on the re-drawn live session. +func TestABehindPeerHealsOnlyThroughItsRecovery(t *testing.T) { + r := newFenceRig(t, 2, false) + r.exec.PublishHealthy("r2") + if s := r.peer.State(); s == replication.ReplicaHealthy { + t.Fatal("a peer two entries behind was healed by the healthy verdict") + } + if res := r.catchUp(t); !res.Success { + t.Fatalf("the catch-up failed: %s", res.FailReason) + } + if s := r.peer.State(); s != replication.ReplicaHealthy { + t.Fatalf("peer %s after a completed catch-up; want healthy", s) + } + for lba := uint32(0); lba < 4; lba++ { + want, _ := r.primary.Read(lba) + if got, err := r.replica.Read(lba); err != nil || !bytes.Equal(got, want) { + t.Fatalf("after the catch-up LBA %d differs from the primary (err %v)", lba, err) + } + } + r.requireLiveTraffic(t) +} + +// sessionOrderSites counts every reference to the peer's session order in +// the given files (the sessionIDs field, a SessionIDs() call, or a draw +// from either), keyed by the enclosing function and, inside a type switch, +// its case: "prepareQueuedCommands/FenceAtEpoch". +func sessionOrderSites(files []*ast.File) map[string]int { + sites := map[string]int{} + isRef := func(n ast.Node) bool { + switch x := n.(type) { + case *ast.SelectorExpr: + return x.Sel.Name == "sessionIDs" + case *ast.CallExpr: + if sel, ok := x.Fun.(*ast.SelectorExpr); ok { + return sel.Sel.Name == "SessionIDs" + } + } + return false + } + for _, f := range files { + for _, decl := range f.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + var walk func(n ast.Node, site string) + walk = func(n ast.Node, site string) { + ast.Inspect(n, func(m ast.Node) bool { + if cc, ok := m.(*ast.CaseClause); ok && m != n { + name := site + for _, e := range cc.List { + if sel, ok := e.(*ast.SelectorExpr); ok { + name = fn.Name.Name + "/" + sel.Sel.Name + } + } + for _, st := range cc.Body { + walk(st, name) + } + return false + } + if isRef(m) { + sites[site]++ + } + return true + }) + } + walk(fn.Body, fn.Name.Name) + } + } + return sites +} + +// Every reference to the peer's session order in the adapter's production +// source is a listed site: the constructor binds the executor's order, and +// each command kind that draws a session is listed with what keeps the +// live session above it (recovery sessions re-draw at their close and +// fences at their completion, on any outcome, covered by the tests above; +// a probe does not move the replica's held lineage). A helper that draws, +// an alias of the order, or a draw outside these cases fails here until it +// is classified. func TestEverySessionDrawIsFollowedByALiveRedraw(t *testing.T) { - want := map[string]string{ - "StartCatchUp": "recovery session: afterSessionClose re-draws", - "StartRebuild": "recovery session: afterSessionClose re-draws", - "StartRecovery": "recovery session: afterSessionClose re-draws", - "FenceAtEpoch": "fence: afterFence re-draws", - "ProbeReplica": "non-moving: the replica validates a probe without taking its lineage", + want := map[string]int{ + "NewVolumeReplicaAdapter": 3, // binds the executor's order (a.sessionIDs = src.SessionIDs()) + "prepareQueuedCommands/StartCatchUp": 1, // recovery session: afterSessionClose re-draws + "prepareQueuedCommands/StartRebuild": 1, // recovery session: afterSessionClose re-draws + "prepareQueuedCommands/StartRecovery": 1, // recovery session: afterSessionClose re-draws + "prepareQueuedCommands/FenceAtEpoch": 1, // fence: afterFence re-draws + "prepareQueuedCommands/ProbeReplica": 1, // non-moving: the replica validates a probe without taking its lineage } fset := token.NewFileSet() - f, err := parser.ParseFile(fset, filepath.Join("..", "..", "adapter", "adapter.go"), nil, 0) + pkgs, err := parser.ParseDir(fset, filepath.Join("..", "..", "adapter"), func(fi fs.FileInfo) bool { return !strings.HasSuffix(fi.Name(), "_test.go") }, 0) if err != nil { t.Fatal(err) } - got := map[string]bool{} - ast.Inspect(f, func(n ast.Node) bool { - cc, ok := n.(*ast.CaseClause) - if !ok { - return true - } - draws := false - for _, st := range cc.Body { - ast.Inspect(st, func(m ast.Node) bool { - if call, ok := m.(*ast.CallExpr); ok { - if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "Next" || sel.Sel.Name == "NextAfter") { - if inner, ok := sel.X.(*ast.SelectorExpr); ok && inner.Sel.Name == "sessionIDs" { - draws = true - } - } - } - return true - }) - } - if !draws { - return true - } - for _, e := range cc.List { - if sel, ok := e.(*ast.SelectorExpr); ok { - got[sel.Sel.Name] = true - } - } - return true - }) - for kind := range got { - if _, ok := want[kind]; !ok { - t.Errorf("the adapter draws a session for %s, which is not classified: re-draw the live session above it, or declare it non-moving", kind) + var files []*ast.File + for _, p := range pkgs { + for _, f := range p.Files { + files = append(files, f) } } - for kind, why := range want { - if !got[kind] { - t.Errorf("listed drawing kind %s (%s) no longer draws a session; update the list", kind, why) + got := sessionOrderSites(files) + for site, n := range got { + if want[site] != n { + t.Errorf("%s references the session order %d time(s), listed %d: classify it (re-draw the live session after it, or declare it non-moving)", site, n, want[site]) + } + } + for site := range want { + if got[site] == 0 { + t.Errorf("listed site %s no longer references the session order; update the list", site) + } + } + + // Negative controls: a helper that draws, an alias drawn from, and a + // draw outside any case are each a site of their own. + src := `package adapter +func (a *A) helperDraw() uint64 { return a.sessionIDs.Next() } +func (a *A) aliasDraw() uint64 { ids := a.sessionIDs; return ids.Next() } +func (a *A) prepareQueuedCommands(cmds []any) { + _ = a.sessionIDs.Next() + for _, c := range cmds { + switch c.(type) { + case engine.FenceAtEpoch: + _ = a.sessionIDs.Next() } } } +` + f, err := parser.ParseFile(token.NewFileSet(), "control.go", src, 0) + if err != nil { + t.Fatal(err) + } + c := sessionOrderSites([]*ast.File{f}) + if c["helperDraw"] != 1 || c["aliasDraw"] != 1 || c["prepareQueuedCommands"] != 1 || c["prepareQueuedCommands/FenceAtEpoch"] != 1 { + t.Fatalf("the census missed or misattributed a control site: %v", c) + } +}