From 0a069427a5495960ed0a85356546cd9e80f90353 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 05:35:40 -0800 Subject: [PATCH 01/11] volume: a failed replica role call is retried until it succeeds A replica whose floor could not be persisted (a full or read-only disk) latched its role failure and stayed out of the volume until an operator restarted it. The host now re-applies the current replica role with backoff and clears the latch on success; a refusal that a retry cannot change (ErrRoleRefused: the ingress is closed, or the volume refuses replica peers) keeps its reason and is not retried. Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/replication_ingress.go | 6 +- seaweed-block/core/host/volume/host.go | 53 ++++++++++- .../core/host/volume/role_retry_test.go | 90 +++++++++++++++++++ 3 files changed, 146 insertions(+), 3 deletions(-) create mode 100644 seaweed-block/core/host/volume/role_retry_test.go diff --git a/seaweed-block/cmd/blockvolume/replication_ingress.go b/seaweed-block/cmd/blockvolume/replication_ingress.go index b7457d5e50..45790fcf45 100644 --- a/seaweed-block/cmd/blockvolume/replication_ingress.go +++ b/seaweed-block/cmd/blockvolume/replication_ingress.go @@ -6,6 +6,7 @@ import ( "net" "sync" + "github.com/seaweedfs/seaweed-block/core/host/volume" "github.com/seaweedfs/seaweed-block/core/recovery" "github.com/seaweedfs/seaweed-block/core/replication" "github.com/seaweedfs/seaweed-block/core/storage" @@ -131,16 +132,17 @@ func (r *replicationIngress) AdmitAsReplica(epoch uint64) error { r.mu.Lock() defer r.mu.Unlock() if r.closed { - return fmt.Errorf("replication ingress closed") + return fmt.Errorf("replication ingress closed: %w", volume.ErrRoleRefused) } if r.rf1Only != "" { - return fmt.Errorf("volume %s refuses a replica role at epoch %d: %s", r.volumeID, epoch, r.rf1Only) + return fmt.Errorf("volume %s refuses a replica role at epoch %d: %s: %w", r.volumeID, epoch, r.rf1Only, volume.ErrRoleRefused) } if r.epochsErr != nil { return fmt.Errorf("volume %s epoch table: %w", r.volumeID, r.epochsErr) } return r.roleLocked(epoch, false) } + // FenceFloor is a fencing round's promise on this replica: the listener // makes epoch its durable floor (refusing every frame and ACK below it) // before the round is answered. Without a listener (no replica role yet) diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 6493014b85..8e20d55078 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -4,6 +4,7 @@ import ( "context" "crypto/rand" "encoding/hex" + "errors" "fmt" "io" "log" @@ -170,6 +171,11 @@ type Host struct { // storesAwaited: the primary fact's (awaited<<32 | initial) replica // store count (ReplicaStoresAwaited). storesAwaited atomic.Uint64 + // roleRetry: the last replica role call failed with an error a retry + // may outlast (a floor that could not be persisted); runRoleRetry + // re-applies the current role until it succeeds or is refused for good. + // Under selfFenceMu. + roleRetry bool // RF1Only admission state, one unit under rf1Mu (field access only, no // calls): the highest refused epoch with its reason ("" = cleared), and the // highest epoch an RF1 fact was admitted at. A clear removes only the @@ -472,6 +478,7 @@ func (h *Host) SetSelfFence(f selfFencer) error { // latch (projection not Healthy); a success clears it. Caller holds // selfFenceMu. func (h *Host) latchRoleAdmission(role selfRole, epoch uint64, err error) { + h.roleRetry = role == selfRoleReplica && err != nil && !errors.Is(err, ErrRoleRefused) if role == selfRoleNone { return } @@ -482,6 +489,49 @@ func (h *Host) latchRoleAdmission(role selfRole, epoch uint64, err error) { h.roleAdmissionFailed.Store("") } +// ErrRoleRefused marks a role call refused for good (the listener is closed, +// or the volume refuses replica peers): retrying cannot succeed, so the +// latch stays with its reason and no retry runs. +var ErrRoleRefused = errors.New("role refused") + +// roleRetryMin and roleRetryMax bound the backoff between retries of a +// failed replica role call. +var roleRetryMin, roleRetryMax = 250 * time.Millisecond, 10 * time.Second + +// runRoleRetry re-applies a failed replica role call with backoff, so a +// replica whose floor could not be persisted (a full or read-only disk) +// rejoins once it can, with no operator: the latch clears on success and +// the primary's probe of degraded peers finds it ready again. +func (h *Host) runRoleRetry(ctx context.Context) { + defer h.wg.Done() + delay := roleRetryMin + for { + select { + case <-ctx.Done(): + return + case <-time.After(delay): + } + h.selfFenceMu.Lock() + if !h.roleRetry || h.selfFence == nil || h.selfRole != selfRoleReplica { + h.selfFenceMu.Unlock() + delay = roleRetryMin + continue + } + role, epoch := h.selfRole, h.selfEpoch + err := applySelfRoleWithPeers(h.selfFence, role, epoch, h.selfHasPeers) + h.latchRoleAdmission(role, epoch, err) + h.selfFenceMu.Unlock() + if err == nil { + h.log.Printf("blockvolume: replica role at epoch %d admitted on retry", epoch) + delay = roleRetryMin + continue + } + if delay *= 2; delay > roleRetryMax { + delay = roleRetryMax + } + } +} + // RoleAdmissionFailure reports the G1 admission latch: whether the last role // call on this host's replica listener failed, and why. The projection view // treats a failure as not Healthy. @@ -617,10 +667,11 @@ func (h *Host) Start() context.Context { ctx, cancel := context.WithCancel(context.Background()) h.cancel = cancel - h.wg.Add(3) + h.wg.Add(4) go h.runHeartbeat(ctx) go h.runSubscribe(ctx) go h.runProbeRounds(ctx) + go h.runRoleRetry(ctx) return ctx } diff --git a/seaweed-block/core/host/volume/role_retry_test.go b/seaweed-block/core/host/volume/role_retry_test.go new file mode 100644 index 0000000000..9e0875483d --- /dev/null +++ b/seaweed-block/core/host/volume/role_retry_test.go @@ -0,0 +1,90 @@ +package volume + +import ( + "context" + "errors" + "fmt" + "sync" + "testing" + "time" +) + +// flakyListener fails its replica role call with err until fails is used up. +type flakyListener struct { + mu sync.Mutex + fails int + err error + calls int +} + +func (f *flakyListener) FenceAsPrimary(uint64) error { return nil } +func (f *flakyListener) AdmitAsReplica(uint64) error { + f.mu.Lock() + defer f.mu.Unlock() + f.calls++ + if f.fails > 0 { + f.fails-- + return f.err + } + return nil +} + +func (f *flakyListener) count() int { + f.mu.Lock() + defer f.mu.Unlock() + return f.calls +} + +// A replica role call that failed (its floor could not be persisted) is +// retried until it succeeds, which clears the latch; a call refused for good +// (ErrRoleRefused) is not retried and keeps its reason. +func TestReplicaRoleCallIsRetriedUntilItSucceeds(t *testing.T) { + min, max := roleRetryMin, roleRetryMax + roleRetryMin, roleRetryMax = time.Millisecond, 5*time.Millisecond + t.Cleanup(func() { roleRetryMin, roleRetryMax = min, max }) + + for name, c := range map[string]struct { + err error + recovered bool + }{ + "floor not persisted, then the disk recovers": {errors.New("replica floor record write: permission denied"), true}, + "refused for good": {fmt.Errorf("replication ingress closed: %w", ErrRoleRefused), false}, + } { + t.Run(name, func(t *testing.T) { + h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "s3", VolumeID: "v1", ReplicaID: "r3", DataAddr: "127.0.0.1:19403", CtrlAddr: "127.0.0.1:19404"}) + if err != nil { + t.Fatal(err) + } + ln := &flakyListener{fails: 2, err: c.err} + if err := h.SetSelfFence(ln); err != nil { + t.Fatal(err) + } + if err := h.fenceSelfWithPeers(selfRoleReplica, 2, true); err == nil { + t.Fatal("the first role call did not fail") + } + ctx, cancel := context.WithCancel(context.Background()) + h.wg.Add(1) + go h.runRoleRetry(ctx) + defer func() { cancel(); h.wg.Wait() }() + + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if failed, _ := h.RoleAdmissionFailure(); !failed { + break + } + time.Sleep(5 * time.Millisecond) + } + failed, reason := h.RoleAdmissionFailure() + if c.recovered { + if failed || ln.count() != 3 { + t.Fatalf("latch %t (%s) after %d calls; want cleared on the 3rd", failed, reason, ln.count()) + } + return + } + time.Sleep(50 * time.Millisecond) + if !failed || ln.count() != 1 { + t.Fatalf("a refused role call: latch %t, %d calls; want latched and never retried", failed, ln.count()) + } + }) + } +} From 70ef2786711a8386b7eb4cd13f9226326ccebdfb Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 06:10:49 -0800 Subject: [PATCH 02/11] volume: the per-peer adapter never opens sessions on a healthy peer; degraded-peer re-probe on by default With the degraded-peer probe loop on, the per-peer adapter registry primed each new peer's engine at the add, and the engine's assignment probe and fence ran on the replica with sessions of their own while the volume's seed barrier and live ship owned it. The replica keeps the newest session, so it refused the volume's own barrier as stale and the next write missed quorum. The registry now records the identity at the add and primes the adapter only on the probe loop's first dispatch for the peer, which comes only once the peer is degraded (its live session failed and was invalidated); that first dispatch is the adapter's own probe, not a second one. With the race gone, --degraded-probe-interval defaults to 5s, so a replica that fell out of the volume rejoins without an operator. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/main.go | 8 +- .../peer_adapter_divergent_tail_test.go | 5 + .../core/host/volume/peer_adapter_registry.go | 52 ++++++++- .../host/volume/peer_adapter_registry_test.go | 20 +++- .../volume/peer_adapter_session_race_test.go | 100 ++++++++++++++++++ .../core/host/volume/probe_loop_wiring.go | 12 +++ 6 files changed, 188 insertions(+), 9 deletions(-) create mode 100644 seaweed-block/core/host/volume/peer_adapter_session_race_test.go diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index c37a7da141..c27f0be44a 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -248,9 +248,9 @@ func parseFlags(args []string) (flags, error) { "smartwal (fixed-size ring) bounds retention via --durable-blocks instead "+ "and ignores this flag. Recommended starting value for sustained-write "+ "workloads on walstore: 10000 LSNs (sized to expected replica lag).") - fs.DurationVar(&f.degradedProbeInterval, "degraded-probe-interval", 0, - "primary-side degraded-peer probe loop interval; 0 = OFF (default). "+ - "Recommended production value: 5s. Distinct from --degraded-probe-cooldown-base: this is how often "+ + fs.DurationVar(&f.degradedProbeInterval, "degraded-probe-interval", 5*time.Second, + "primary-side degraded-peer probe loop interval; 0 = OFF. "+ + "On by default: a replica that fell out of the volume rejoins without an operator. Distinct from --degraded-probe-cooldown-base: this is how often "+ "the loop wakes up; cooldown-base is how long a single peer is gated AFTER a probe attempt.") fs.DurationVar(&f.degradedProbeCooldownBase, "degraded-probe-cooldown-base", 5*time.Second, "per-peer cooldown after a probe attempt (also the reset value after a successful probe). "+ @@ -1000,7 +1000,7 @@ func runVolume(f flags, exits *processExit) int { CooldownBase: f.degradedProbeCooldownBase, CooldownCap: f.degradedProbeCooldownCap, } - probeFn := volume.ProductionProbeFn(peerRegistry.AdapterFor) + probeFn := volume.ProductionProbeFnWithPrime(peerRegistry.AdapterFor, peerRegistry.PrimePending) if err := replVolume.ConfigureProbeLoop(loopCfg, probeFn, time.Now); err != nil { fmt.Fprintln(os.Stderr, "blockvolume: probe loop configure:", err) _ = replVolume.Close() diff --git a/seaweed-block/core/host/volume/peer_adapter_divergent_tail_test.go b/seaweed-block/core/host/volume/peer_adapter_divergent_tail_test.go index 4e9da7ac71..a0cbfd6678 100644 --- a/seaweed-block/core/host/volume/peer_adapter_divergent_tail_test.go +++ b/seaweed-block/core/host/volume/peer_adapter_divergent_tail_test.go @@ -24,6 +24,11 @@ func TestPeerAdapterRegistry_DivergentTailAboveTheFrontierAtAddIsRebuilt(t *test reg := NewPeerAdapterRegistry("vol1", "r1") reg.SetFrontier(c.frontier) reg.OnPeerAdded(newPeerForRegistryTest(t, "r2", 2, 1)) + // The frontier was read at the add; the probe loop primes the + // adapter when the peer is first degraded. + if !reg.PrimePending("r2") { + t.Fatal("r2 was not pending") + } adpt := reg.AdapterFor("r2") if adpt == nil { t.Fatal("no adapter for r2") diff --git a/seaweed-block/core/host/volume/peer_adapter_registry.go b/seaweed-block/core/host/volume/peer_adapter_registry.go index 467b525e17..a3979bcad3 100644 --- a/seaweed-block/core/host/volume/peer_adapter_registry.go +++ b/seaweed-block/core/host/volume/peer_adapter_registry.go @@ -38,7 +38,10 @@ type PeerAdapterRegistry struct { mu sync.Mutex adapters map[string]*adapter.VolumeReplicaAdapter // keyed by ReplicaID - closed bool + // pending: the identity each adapter is primed with on the probe + // loop's first dispatch for its peer (PrimePending), not at the add. + pending map[string]adapter.AssignmentInfo + closed bool } // SetFrontier installs the local durable frontier read at each peer add @@ -58,12 +61,21 @@ func NewPeerAdapterRegistry(volumeID, selfReplicaID string) *PeerAdapterRegistry volumeID: volumeID, selfReplicaID: selfReplicaID, adapters: make(map[string]*adapter.VolumeReplicaAdapter), + pending: make(map[string]adapter.AssignmentInfo), } } // OnPeerAdded constructs a per-peer adapter wired to a // PeerCommandExecutor over the peer's transport.BlockExecutor, and -// primes the engine with the peer's identity via OnAssignment. +// records the peer's identity to prime it with later (PrimePending). +// +// It does not prime here: priming emits the engine's probe and fence, +// which run on the replica with sessions of their own, while a new peer +// is healthy and owned by the volume's live session (its seed barrier and +// live ship). The replica keeps the newest session, so an adapter acting +// on a healthy peer makes the replica refuse the volume's own barrier. +// The adapter is primed only once the probe loop dispatches for the +// peer, which it does only for a degraded peer (see PrimePending). // // Idempotent: repeated calls for the same peer (same ReplicaID + same // lineage) are a no-op. Lineage-bump recreate (the PeerRemoved → @@ -113,7 +125,7 @@ func (r *PeerAdapterRegistry) OnPeerAdded(peer *replication.ReplicaPeer) { log.Printf("PeerAdapterRegistry: peer=%s frontier unknown (%v): no divergent-tail check", target.ReplicaID, err) } } - adpt.OnAssignment(adapter.AssignmentInfo{ + r.pending[target.ReplicaID] = adapter.AssignmentInfo{ VolumeID: r.volumeID, ReplicaID: target.ReplicaID, Epoch: target.Epoch, @@ -121,7 +133,7 @@ func (r *PeerAdapterRegistry) OnPeerAdded(peer *replication.ReplicaPeer) { DataAddr: target.DataAddr, CtrlAddr: target.ControlAddr, PrimaryStartLSN: start, - }) + } r.adapters[target.ReplicaID] = adpt log.Printf("PeerAdapterRegistry: registered peer=%s epoch=%d EV=%d", target.ReplicaID, target.Epoch, target.EndpointVersion) @@ -141,9 +153,40 @@ func (r *PeerAdapterRegistry) OnPeerRemoved(replicaID string) { return } delete(r.adapters, replicaID) + delete(r.pending, replicaID) log.Printf("PeerAdapterRegistry: unregistered peer=%s", replicaID) } +// PrimePending primes replicaID's adapter with the identity recorded at +// its add (OnAssignment: the engine's own probe, then fence or recovery), +// once: it reports whether this call primed it. The probe loop calls it +// on its first dispatch for the peer. +// +// Lock graph: the pending entry is taken under r.mu, and OnAssignment runs +// after r.mu is released (its commands run the peer's executor). The probe +// loop dispatches only for a peer ProbeIfDegraded admitted under peer.mu +// (state Degraded, no probe in flight). A peer is created Healthy inside +// the volume's UpdateReplicaSet (under the volume's mu, which also runs its +// seed barrier) and turns Degraded only after its own live session failed +// and was invalidated; a degraded peer is not shipped to. So the adapter's +// first session starts only after the volume's session on that peer has +// ended: there is no window in which both act on the replica. +func (r *PeerAdapterRegistry) PrimePending(replicaID string) bool { + if r == nil { + return false + } + r.mu.Lock() + info, ok := r.pending[replicaID] + delete(r.pending, replicaID) + adpt := r.adapters[replicaID] + r.mu.Unlock() + if !ok || adpt == nil { + return false + } + adpt.OnAssignment(info) + return true +} + // AdapterFor returns the per-peer adapter for replicaID, or nil if // no adapter is registered. Safe to call from any goroutine. // @@ -182,4 +225,5 @@ func (r *PeerAdapterRegistry) Close() { } r.closed = true r.adapters = nil + r.pending = nil } diff --git a/seaweed-block/core/host/volume/peer_adapter_registry_test.go b/seaweed-block/core/host/volume/peer_adapter_registry_test.go index b46439ff70..2ffb5b9a47 100644 --- a/seaweed-block/core/host/volume/peer_adapter_registry_test.go +++ b/seaweed-block/core/host/volume/peer_adapter_registry_test.go @@ -9,7 +9,7 @@ import ( ) // G5-5C Batch #7 PeerAdapterRegistry tests: -// - OnPeerAdded constructs adapter and primes identity +// - OnPeerAdded constructs the adapter; PrimePending primes its identity once // - AdapterFor returns the right adapter (per-peer routing) // - OnPeerRemoved drops the adapter // - Self-replicaID guard refuses host-own-slot registration @@ -49,6 +49,17 @@ func TestPeerAdapterRegistry_OnPeerAdded_RegistersAndPrimes(t *testing.T) { if adpt == nil { t.Fatal("AdapterFor(r2) returned nil after OnPeerAdded") } + // The add does not prime: the new peer is healthy and owned by the + // volume's live session, so its adapter has issued nothing. + if log := adpt.CommandLog(); len(log) != 0 || adpt.Projection().Epoch != 0 { + t.Fatalf("the adapter acted at the add: commands %v, epoch %d", log, adpt.Projection().Epoch) + } + if !reg.PrimePending("r2") { + t.Fatal("PrimePending(r2) did not prime the added peer") + } + if reg.PrimePending("r2") { + t.Fatal("PrimePending(r2) primed twice") + } // Adapter must have received OnAssignment to prime engine identity // for r2 — projection's Epoch = 1 confirms the AssignmentObserved // event applied (engine state's Identity.Epoch advances on @@ -123,12 +134,16 @@ func TestPeerAdapterRegistry_LineageBumpTeardown(t *testing.T) { if oldAdpt == nil { t.Fatal("setup: oldAdpt nil") } + reg.PrimePending("r2") if oldAdpt.Projection().Epoch != 1 { t.Fatalf("old projection Epoch = %d, want 1", oldAdpt.Projection().Epoch) } // Lineage bump: teardown then add at epoch=2. reg.OnPeerRemoved("r2") + if reg.PrimePending("r2") { + t.Fatal("a removed peer was still pending") + } newPeer := newPeerForRegistryTest(t, "r2", 2, 1) reg.OnPeerAdded(newPeer) @@ -139,6 +154,9 @@ func TestPeerAdapterRegistry_LineageBumpTeardown(t *testing.T) { if newAdpt == oldAdpt { t.Fatal("lineage bump should produce a fresh adapter pointer") } + if !reg.PrimePending("r2") { + t.Fatal("the re-added peer was not pending") + } if newAdpt.Projection().Epoch != 2 { t.Errorf("new projection Epoch = %d, want 2", newAdpt.Projection().Epoch) } diff --git a/seaweed-block/core/host/volume/peer_adapter_session_race_test.go b/seaweed-block/core/host/volume/peer_adapter_session_race_test.go new file mode 100644 index 0000000000..6457507e77 --- /dev/null +++ b/seaweed-block/core/host/volume/peer_adapter_session_race_test.go @@ -0,0 +1,100 @@ +package volume + +import ( + "context" + "net" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/replication" + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +// A new peer is healthy and owned by the volume's live session: its seed +// barrier, then its live ship. The per-peer adapter (with the degraded-probe +// loop running) must not open sessions of its own on that replica, or the +// replica keeps the newest session and refuses the volume's barrier as +// stale. Each lineage bump adds a fresh peer while the loop ticks; the +// volume's own barrier on it must succeed every time. +func TestPeerAdapterNeverTakesAHealthyPeersSession(t *testing.T) { + 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) + } + } + frontier, err := primary.Sync() + if err != nil { + t.Fatal(err) + } + if _, err := replica.Sync(); err != nil { + t.Fatal(err) + } + + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := l.Addr().String() + _ = l.Close() + listener, err := transport.NewReplicaListener(addr, replica) + if err != nil { + t.Fatal(err) + } + listener.Serve() + + v := replication.NewReplicationVolume("vol1", primary) + v.SetDurabilityMode(replication.DurabilitySyncQuorum) + reg := NewPeerAdapterRegistry("vol1", "r1") + reg.SetFrontier(primary.Sync) + var added *replication.ReplicaPeer // under v's lifecycle hook, read after UpdateReplicaSet + if err := v.ConfigurePeerLifecycleHook(func(p *replication.ReplicaPeer) { added = p; reg.OnPeerAdded(p) }, reg.OnPeerRemoved); err != nil { + t.Fatal(err) + } + cfg := replication.ProbeLoopConfig{Interval: time.Millisecond, MaxConcurrent: 1, CooldownBase: time.Millisecond, CooldownCap: 10 * time.Millisecond} + if err := v.ConfigureProbeLoop(cfg, ProductionProbeFnWithPrime(reg.AdapterFor, reg.PrimePending), time.Now); err != nil { + t.Fatal(err) + } + if err := v.StartProbeLoop(); err != nil { + t.Fatal(err) + } + // The primary's connections close first, or Stop waits for them. + t.Cleanup(func() { _ = v.Close(); reg.Close(); listener.Stop() }) + + for epoch := uint64(1); epoch <= 8; epoch++ { + if err := v.UpdateReplicaSet(epoch, []replication.ReplicaTarget{{ReplicaID: "r2", DataAddr: addr, ControlAddr: addr, Epoch: epoch, EndpointVersion: 1}}); err != nil { + t.Fatal(err) + } + peer := added + if peer == nil || peer.Target().Epoch != epoch { + t.Fatalf("epoch %d: no peer r2", epoch) + } + if s := peer.State(); s != replication.ReplicaHealthy { + t.Fatalf("epoch %d: the seed left r2 %s; want healthy", epoch, s) + } + // Give an adapter that acted at the add time to run its probe + // and fence, while the loop keeps ticking. + time.Sleep(100 * time.Millisecond) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + ack, err := peer.Barrier(ctx, frontier) + cancel() + if err != nil { + t.Fatalf("epoch %d: the volume's own barrier on its healthy peer failed: %v", epoch, err) + } + if ack.AchievedLSN < frontier { + t.Fatalf("epoch %d: barrier achieved %d, want %d", epoch, ack.AchievedLSN, frontier) + } + if s := peer.State(); s != replication.ReplicaHealthy { + t.Fatalf("epoch %d: r2 %s after its barrier; want healthy", epoch, s) + } + } +} diff --git a/seaweed-block/core/host/volume/probe_loop_wiring.go b/seaweed-block/core/host/volume/probe_loop_wiring.go index d35e53bd5d..86e1ff57d5 100644 --- a/seaweed-block/core/host/volume/probe_loop_wiring.go +++ b/seaweed-block/core/host/volume/probe_loop_wiring.go @@ -76,6 +76,15 @@ type AdapterRouter func(replicaID string) *adapter.VolumeReplicaAdapter // Borrows: AdapterRouter — caller retains; lifetime must outlive // the probe loop's lifetime. func ProductionProbeFn(router AdapterRouter) replication.ProbeFn { + return ProductionProbeFnWithPrime(router, nil) +} + +// ProductionProbeFnWithPrime is ProductionProbeFn with the registry's +// deferred priming: on the first dispatch for a peer, prime(replicaID) +// primes its adapter, whose own assignment-driven probe is this attempt +// (no second wire probe with another session); later dispatches probe as +// ProductionProbeFn does. +func ProductionProbeFnWithPrime(router AdapterRouter, prime func(replicaID string) bool) replication.ProbeFn { if router == nil { // Fail-closed shim: if no router is wired, return a probeFn // that ALWAYS reports failure (so cooldown progresses + log @@ -129,6 +138,9 @@ func ProductionProbeFn(router AdapterRouter) replication.ProbeFn { if adpt == nil { return fmt.Errorf("ProductionProbeFn: no adapter registered for peer=%s (PeerAdapterRegistry not synced?)", t.ReplicaID) } + if prime != nil && prime(t.ReplicaID) { + return nil + } result := exec.Probe(t.ReplicaID, t.DataAddr, t.ControlAddr, sessionID, t.Epoch, t.EndpointVersion) From 88a03a40bb0a8956e5bf058b2f7f9e539ecbf2a8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 07:09:38 -0800 Subject: [PATCH 03/11] component: the apply-failure recovery test follows deferred priming The test waited for its registry adapter to probe the new peer right after the add, which is the adapter acting on a healthy peer the volume's live session owns. It now checks the adapter has issued nothing at the add and wires the probe loop as the binary does (priming on the first dispatch for a degraded peer); its degrade, recover and replay assertions are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../replica_apply_failure_recovery_test.go | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/replication/component/replica_apply_failure_recovery_test.go b/seaweed-block/core/replication/component/replica_apply_failure_recovery_test.go index f8f142cb92..c37f545648 100644 --- a/seaweed-block/core/replication/component/replica_apply_failure_recovery_test.go +++ b/seaweed-block/core/replication/component/replica_apply_failure_recovery_test.go @@ -112,7 +112,7 @@ func TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN(t *testi if err := c.primary.RepVol.ConfigurePeerLifecycleHook(registry.OnPeerAdded, registry.OnPeerRemoved); err != nil { t.Fatalf("ConfigurePeerLifecycleHook: %v", err) } - waitAdmitted(t, registry) + waitRegisteredIdle(t, registry) ctx := context.Background() for i := 0; i < 2; i++ { @@ -153,7 +153,7 @@ func TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN(t *testi t.Fatalf("WAL replay fixture retired failed LSN %d (retained=%d)", failedLSN, retained) } cfg := replication.ProbeLoopConfig{Interval: 30 * time.Millisecond, MaxConcurrent: 1, CooldownBase: 20 * time.Millisecond, CooldownCap: 200 * time.Millisecond} - if err := c.primary.RepVol.ConfigureProbeLoop(cfg, volume.ProductionProbeFn(registry.AdapterFor), time.Now); err != nil { + if err := c.primary.RepVol.ConfigureProbeLoop(cfg, volume.ProductionProbeFnWithPrime(registry.AdapterFor, registry.PrimePending), time.Now); err != nil { t.Fatalf("ConfigureProbeLoop: %v", err) } if err := c.primary.RepVol.StartProbeLoop(); err != nil { @@ -207,20 +207,23 @@ func TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN(t *testi } // waitAdmitted waits for the registry adapter's assignment probe to succeed. -func waitAdmitted(t *testing.T, registry *volume.PeerAdapterRegistry) { +// waitRegisteredIdle waits for replica-0's registry adapter and checks it has +// issued nothing: a healthy peer belongs to the volume's live session, and +// its adapter is primed only when the probe loop first dispatches for it +// (once it is degraded). +func waitRegisteredIdle(t *testing.T, registry *volume.PeerAdapterRegistry) { t.Helper() deadline := time.Now().Add(2 * time.Second) for time.Now().Before(deadline) { if a := registry.AdapterFor("replica-0"); a != nil { - for _, entry := range a.Trace() { - if entry.Step == "event" && entry.Detail == "ProbeSucceeded" { - return - } + if cmds := a.CommandLog(); len(cmds) != 0 { + t.Fatalf("replica-0's adapter acted on a healthy peer: %v", cmds) } + return } time.Sleep(10 * time.Millisecond) } - t.Fatal("replica-0 was not admitted: no ProbeSucceeded on its registry adapter") + t.Fatal("replica-0 has no registry adapter") } func firstByte(b []byte) byte { From 314b79bff1319a8b636e40bbf9716fb325f44ee1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 08:06:02 -0800 Subject: [PATCH 04/11] volume: a probe dispatch acts only for the peer it was admitted for Priming and the adapter lookup were keyed by ReplicaID. A dispatch the loop admitted for an old degraded peer, delayed while a lineage bump replaced the peer under the same ReplicaID, then primed the new healthy peer's adapter, whose probe raced the volume's live session again. The registry now keeps the exact peer each adapter was added for; PrimePendingFor and AdapterForPeer compare it under the registry lock, and a mismatch primes nothing and sends no wire probe. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/main.go | 2 +- .../core/host/volume/peer_adapter_registry.go | 55 +++++++++++++- .../peer_adapter_replaced_dispatch_test.go | 75 +++++++++++++++++++ .../volume/peer_adapter_session_race_test.go | 2 +- .../core/host/volume/probe_loop_wiring.go | 24 +++++- .../replica_apply_failure_recovery_test.go | 2 +- 6 files changed, 151 insertions(+), 9 deletions(-) create mode 100644 seaweed-block/core/host/volume/peer_adapter_replaced_dispatch_test.go diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index c27f0be44a..8aa2d12663 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -1000,7 +1000,7 @@ func runVolume(f flags, exits *processExit) int { CooldownBase: f.degradedProbeCooldownBase, CooldownCap: f.degradedProbeCooldownCap, } - probeFn := volume.ProductionProbeFnWithPrime(peerRegistry.AdapterFor, peerRegistry.PrimePending) + probeFn := volume.ProductionProbeFnWithPrime(peerRegistry.AdapterForPeer, peerRegistry.PrimePendingFor) if err := replVolume.ConfigureProbeLoop(loopCfg, probeFn, time.Now); err != nil { fmt.Fprintln(os.Stderr, "blockvolume: probe loop configure:", err) _ = replVolume.Close() diff --git a/seaweed-block/core/host/volume/peer_adapter_registry.go b/seaweed-block/core/host/volume/peer_adapter_registry.go index a3979bcad3..3197065b1b 100644 --- a/seaweed-block/core/host/volume/peer_adapter_registry.go +++ b/seaweed-block/core/host/volume/peer_adapter_registry.go @@ -41,7 +41,11 @@ type PeerAdapterRegistry struct { // pending: the identity each adapter is primed with on the probe // loop's first dispatch for its peer (PrimePending), not at the add. pending map[string]adapter.AssignmentInfo - closed bool + // peers: the exact peer each adapter was added for. A dispatch acts + // only for the peer it was admitted for (AdapterForPeer, PrimePendingFor): + // a lineage bump replaces the peer under the same ReplicaID. + peers map[string]*replication.ReplicaPeer + closed bool } // SetFrontier installs the local durable frontier read at each peer add @@ -62,6 +66,7 @@ func NewPeerAdapterRegistry(volumeID, selfReplicaID string) *PeerAdapterRegistry selfReplicaID: selfReplicaID, adapters: make(map[string]*adapter.VolumeReplicaAdapter), pending: make(map[string]adapter.AssignmentInfo), + peers: make(map[string]*replication.ReplicaPeer), } } @@ -136,6 +141,7 @@ func (r *PeerAdapterRegistry) OnPeerAdded(peer *replication.ReplicaPeer) { } r.adapters[target.ReplicaID] = adpt + r.peers[target.ReplicaID] = peer log.Printf("PeerAdapterRegistry: registered peer=%s epoch=%d EV=%d", target.ReplicaID, target.Epoch, target.EndpointVersion) } @@ -154,6 +160,7 @@ func (r *PeerAdapterRegistry) OnPeerRemoved(replicaID string) { } delete(r.adapters, replicaID) delete(r.pending, replicaID) + delete(r.peers, replicaID) log.Printf("PeerAdapterRegistry: unregistered peer=%s", replicaID) } @@ -170,12 +177,55 @@ func (r *PeerAdapterRegistry) OnPeerRemoved(replicaID string) { // seed barrier) and turns Degraded only after its own live session failed // and was invalidated; a degraded peer is not shipped to. So the adapter's // first session starts only after the volume's session on that peer has -// ended: there is no window in which both act on the replica. +// ended: there is no window in which both act on the replica. A dispatch +// acts only for the exact peer the loop admitted (PrimePendingFor, +// AdapterForPeer compare the *ReplicaPeer under r.mu): a dispatch admitted +// for an old degraded peer and resumed after a lineage bump replaced it +// under the same ReplicaID finds nothing, so it never primes or probes the +// healthy successor. func (r *PeerAdapterRegistry) PrimePending(replicaID string) bool { if r == nil { return false } r.mu.Lock() + return r.primeLocked(replicaID) +} + +// PrimePendingFor is PrimePending for the exact peer a probe dispatch was +// admitted for: if that peer has since been replaced under its ReplicaID +// (a lineage bump), it primes nothing, so a delayed dispatch for an old +// degraded peer never acts on its healthy successor. +func (r *PeerAdapterRegistry) PrimePendingFor(peer *replication.ReplicaPeer) bool { + if r == nil || peer == nil { + return false + } + id := peer.Target().ReplicaID + r.mu.Lock() + if r.peers[id] != peer { + r.mu.Unlock() + return false + } + return r.primeLocked(id) +} + +// AdapterForPeer is AdapterFor for the exact peer a probe dispatch was +// admitted for (nil once that peer was replaced). +func (r *PeerAdapterRegistry) AdapterForPeer(peer *replication.ReplicaPeer) *adapter.VolumeReplicaAdapter { + if r == nil || peer == nil { + return nil + } + id := peer.Target().ReplicaID + r.mu.Lock() + defer r.mu.Unlock() + if r.peers[id] != peer { + return nil + } + return r.adapters[id] +} + +// primeLocked takes replicaID's pending identity (r.mu held; released +// here) and primes its adapter outside the lock. +func (r *PeerAdapterRegistry) primeLocked(replicaID string) bool { info, ok := r.pending[replicaID] delete(r.pending, replicaID) adpt := r.adapters[replicaID] @@ -226,4 +276,5 @@ func (r *PeerAdapterRegistry) Close() { r.closed = true r.adapters = nil r.pending = nil + r.peers = nil } diff --git a/seaweed-block/core/host/volume/peer_adapter_replaced_dispatch_test.go b/seaweed-block/core/host/volume/peer_adapter_replaced_dispatch_test.go new file mode 100644 index 0000000000..ee5d6975f1 --- /dev/null +++ b/seaweed-block/core/host/volume/peer_adapter_replaced_dispatch_test.go @@ -0,0 +1,75 @@ +package volume + +import ( + "context" + "net" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/replication" + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +// A probe dispatch admitted for an old degraded peer, held while the peer +// is replaced under the same ReplicaID (lineage bump), then resumed: it acts +// for the peer it was admitted for, never for the new healthy one. The new +// peer's adapter issues nothing, stays pending, and no wire probe reaches +// the new peer's address. +func TestPeerAdapterAReplacedPeersDispatchNeverActsOnItsSuccessor(t *testing.T) { + // The new peer's address counts every connection made to it. + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + var dials atomic.Int32 + go func() { + for { + c, err := l.Accept() + if err != nil { + return + } + dials.Add(1) + _ = c.Close() + } + }() + t.Cleanup(func() { _ = l.Close() }) + + peerAt := func(addr string, epoch uint64) *replication.ReplicaPeer { + exec := transport.NewBlockExecutor(storage.NewBlockStore(8, 4096), addr) + p, err := replication.NewReplicaPeer(replication.ReplicaTarget{ReplicaID: "r2", DataAddr: addr, ControlAddr: addr, Epoch: epoch, EndpointVersion: 1}, exec) + if err != nil { + t.Fatal(err) + } + return p + } + + reg := NewPeerAdapterRegistry("vol1", "r1") + old := peerAt("127.0.0.1:1", 1) + reg.OnPeerAdded(old) + old.Invalidate("its live session failed") + if !old.ProbeIfDegraded(time.Now()) { // the loop admits the dispatch + t.Fatal("the degraded old peer was not admitted") + } + + // The dispatch is held here; the peer is replaced under the same id. + reg.OnPeerRemoved("r2") + fresh := peerAt(l.Addr().String(), 2) + reg.OnPeerAdded(fresh) + + // The held dispatch resumes, for the peer it was admitted for. + fn := ProductionProbeFnWithPrime(reg.AdapterForPeer, reg.PrimePendingFor) + _ = fn(context.Background(), old) + + time.Sleep(300 * time.Millisecond) // an adapter probe runs asynchronously + if a := reg.AdapterFor("r2"); a == nil || len(a.CommandLog()) != 0 { + t.Fatalf("the new healthy peer's adapter acted for the old peer's dispatch: %v", a.CommandLog()) + } + if n := dials.Load(); n != 0 { + t.Fatalf("%d connections reached the new healthy peer from the old peer's dispatch", n) + } + if !reg.PrimePending("r2") { + t.Fatal("the new peer is no longer pending: the old dispatch primed it") + } +} diff --git a/seaweed-block/core/host/volume/peer_adapter_session_race_test.go b/seaweed-block/core/host/volume/peer_adapter_session_race_test.go index 6457507e77..f28ca77823 100644 --- a/seaweed-block/core/host/volume/peer_adapter_session_race_test.go +++ b/seaweed-block/core/host/volume/peer_adapter_session_race_test.go @@ -61,7 +61,7 @@ func TestPeerAdapterNeverTakesAHealthyPeersSession(t *testing.T) { t.Fatal(err) } cfg := replication.ProbeLoopConfig{Interval: time.Millisecond, MaxConcurrent: 1, CooldownBase: time.Millisecond, CooldownCap: 10 * time.Millisecond} - if err := v.ConfigureProbeLoop(cfg, ProductionProbeFnWithPrime(reg.AdapterFor, reg.PrimePending), time.Now); err != nil { + if err := v.ConfigureProbeLoop(cfg, ProductionProbeFnWithPrime(reg.AdapterForPeer, reg.PrimePendingFor), time.Now); err != nil { t.Fatal(err) } if err := v.StartProbeLoop(); err != nil { diff --git a/seaweed-block/core/host/volume/probe_loop_wiring.go b/seaweed-block/core/host/volume/probe_loop_wiring.go index 86e1ff57d5..0fe58fab41 100644 --- a/seaweed-block/core/host/volume/probe_loop_wiring.go +++ b/seaweed-block/core/host/volume/probe_loop_wiring.go @@ -76,15 +76,31 @@ type AdapterRouter func(replicaID string) *adapter.VolumeReplicaAdapter // Borrows: AdapterRouter — caller retains; lifetime must outlive // the probe loop's lifetime. func ProductionProbeFn(router AdapterRouter) replication.ProbeFn { - return ProductionProbeFnWithPrime(router, nil) + if router == nil { + return productionProbeFn(nil, nil) + } + return productionProbeFn(func(p *replication.ReplicaPeer) *adapter.VolumeReplicaAdapter { return router(p.Target().ReplicaID) }, nil) } +// PeerAdapterRouter is the per-peer adapter lookup for the exact peer a +// dispatch was admitted for: nil when that peer was replaced since. +type PeerAdapterRouter func(peer *replication.ReplicaPeer) *adapter.VolumeReplicaAdapter + // ProductionProbeFnWithPrime is ProductionProbeFn with the registry's // deferred priming: on the first dispatch for a peer, prime(replicaID) // primes its adapter, whose own assignment-driven probe is this attempt // (no second wire probe with another session); later dispatches probe as // ProductionProbeFn does. -func ProductionProbeFnWithPrime(router AdapterRouter, prime func(replicaID string) bool) replication.ProbeFn { +// +// Both lookups are by the exact peer the dispatch was admitted for +// (PeerAdapterRegistry.AdapterForPeer, PrimePendingFor): a dispatch held +// while its peer was replaced under the same ReplicaID finds no adapter, +// primes nothing and sends no wire probe. +func ProductionProbeFnWithPrime(router PeerAdapterRouter, prime func(peer *replication.ReplicaPeer) bool) replication.ProbeFn { + return productionProbeFn(router, prime) +} + +func productionProbeFn(router PeerAdapterRouter, prime func(peer *replication.ReplicaPeer) bool) replication.ProbeFn { if router == nil { // Fail-closed shim: if no router is wired, return a probeFn // that ALWAYS reports failure (so cooldown progresses + log @@ -134,11 +150,11 @@ func ProductionProbeFnWithPrime(router AdapterRouter, prime func(replicaID strin // peer (registry misconfigured / peer added before registry // caught up), fail the probe so backoff advances and the // log is loud. - adpt := router(t.ReplicaID) + adpt := router(peer) if adpt == nil { return fmt.Errorf("ProductionProbeFn: no adapter registered for peer=%s (PeerAdapterRegistry not synced?)", t.ReplicaID) } - if prime != nil && prime(t.ReplicaID) { + if prime != nil && prime(peer) { return nil } diff --git a/seaweed-block/core/replication/component/replica_apply_failure_recovery_test.go b/seaweed-block/core/replication/component/replica_apply_failure_recovery_test.go index c37f545648..e32a6f24be 100644 --- a/seaweed-block/core/replication/component/replica_apply_failure_recovery_test.go +++ b/seaweed-block/core/replication/component/replica_apply_failure_recovery_test.go @@ -153,7 +153,7 @@ func TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN(t *testi t.Fatalf("WAL replay fixture retired failed LSN %d (retained=%d)", failedLSN, retained) } cfg := replication.ProbeLoopConfig{Interval: 30 * time.Millisecond, MaxConcurrent: 1, CooldownBase: 20 * time.Millisecond, CooldownCap: 200 * time.Millisecond} - if err := c.primary.RepVol.ConfigureProbeLoop(cfg, volume.ProductionProbeFnWithPrime(registry.AdapterFor, registry.PrimePending), time.Now); err != nil { + if err := c.primary.RepVol.ConfigureProbeLoop(cfg, volume.ProductionProbeFnWithPrime(registry.AdapterForPeer, registry.PrimePendingFor), time.Now); err != nil { t.Fatalf("ConfigureProbeLoop: %v", err) } if err := c.primary.RepVol.StartProbeLoop(); err != nil { From 663c745d89000495654f5801326e34df31519526 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 08:31:04 -0800 Subject: [PATCH 05/11] volume: pin the window between the prime check and the adapter's first command After PrimePendingFor's identity check the registry lock is released before OnAssignment, so the peer can be replaced in between. That window is closed by the executor: every command the adapter issues runs through the old peer's BlockExecutor and enters through beginAsyncOperation, and UpdateReplicaSet stops a replaced peer's executor (stopped under its lock, then in-flight work drained) before it installs the replacement and seeds it. The lock graph on PrimePending now says so, and a test holds the dispatch in that window (a package-private hook), replaces the peer at the same lineage on another address of the same replica, and checks that no late connection reaches the replica and the replacement keeps its session. Co-Authored-By: Claude Opus 5.5 --- .../volume/peer_adapter_prime_window_test.go | 149 ++++++++++++++++++ .../core/host/volume/peer_adapter_registry.go | 29 +++- 2 files changed, 176 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/core/host/volume/peer_adapter_prime_window_test.go diff --git a/seaweed-block/core/host/volume/peer_adapter_prime_window_test.go b/seaweed-block/core/host/volume/peer_adapter_prime_window_test.go new file mode 100644 index 0000000000..f5e351f9da --- /dev/null +++ b/seaweed-block/core/host/volume/peer_adapter_prime_window_test.go @@ -0,0 +1,149 @@ +package volume + +import ( + "context" + "io" + "net" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/replication" + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +// The window between the identity check and the adapter's first command: +// a dispatch for an old degraded peer passes PrimePendingFor, is held after +// the registry's lock is released, and the peer is replaced under the same +// ReplicaID meanwhile, its replacement seeded on the same replica. When the +// dispatch resumes, its commands run through the old peer's executor, which +// the volume stopped before installing the replacement: they are refused, +// so no connection reaches the replica through the old peer's address after +// the replacement, and the replica keeps the replacement's live session +// (its barrier succeeds). +// +// The replacement keeps the lineage (epoch 1, endpoint version 1) and only +// moves the data address: the old peer reaches the same replica through a +// relay. With an older lineage the replica itself would refuse the old +// adapter's fence, so this is the case in which only the stopped executor +// keeps the late command off the replica. +func TestPeerAdapterPrimeAfterUnlockNeverReachesTheReplacedReplica(t *testing.T) { + 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) + } + } + frontier, err := primary.Sync() + if err != nil { + t.Fatal(err) + } + if _, err := replica.Sync(); err != nil { + t.Fatal(err) + } + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := l.Addr().String() + _ = l.Close() + listener, err := transport.NewReplicaListener(addr, replica) + if err != nil { + t.Fatal(err) + } + listener.Serve() + relay, relayed := relayTo(t, addr) // a second address of the same replica + + v := replication.NewReplicationVolume("vol1", primary) + v.SetDurabilityMode(replication.DurabilitySyncQuorum) + reg := NewPeerAdapterRegistry("vol1", "r1") + reg.SetFrontier(primary.Sync) + entered, release := make(chan struct{}), make(chan struct{}) + reg.afterPrimeUnlock = func() { close(entered); <-release } + var added *replication.ReplicaPeer + if err := v.ConfigurePeerLifecycleHook(func(p *replication.ReplicaPeer) { added = p; reg.OnPeerAdded(p) }, reg.OnPeerRemoved); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = v.Close(); reg.Close(); listener.Stop() }) + target := func(at string) []replication.ReplicaTarget { + return []replication.ReplicaTarget{{ReplicaID: "r2", DataAddr: at, ControlAddr: at, Epoch: 1, EndpointVersion: 1}} + } + + if err := v.UpdateReplicaSet(1, target(relay)); err != nil { + t.Fatal(err) + } + old := added + old.Invalidate("its live session failed") + if !old.ProbeIfDegraded(time.Now()) { + t.Fatal("the degraded old peer was not admitted") + } + fn := ProductionProbeFnWithPrime(reg.AdapterForPeer, reg.PrimePendingFor) + done := make(chan struct{}) + go func() { _ = fn(context.Background(), old); close(done) }() + <-entered // checked, unlocked, not yet acted + + if err := v.UpdateReplicaSet(2, target(addr)); err != nil { + t.Fatal(err) + } + fresh := added + if fresh == old || fresh.State() != replication.ReplicaHealthy { + t.Fatalf("the replacement is %s; want a new healthy peer", fresh.State()) + } + before := relayed() + close(release) + <-done + time.Sleep(300 * time.Millisecond) // the old adapter's probe runs asynchronously + if n := relayed() - before; n != 0 { + t.Fatalf("%d connections reached the replica through the replaced peer's address after the dispatch resumed", n) + } + + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + if _, err := fresh.Barrier(ctx, frontier); err != nil { + t.Fatalf("the replacement's own barrier failed after the old dispatch resumed: %v", err) + } + if s := fresh.State(); s != replication.ReplicaHealthy { + t.Fatalf("the replacement is %s after the old dispatch resumed; want healthy", s) + } + if a := reg.AdapterForPeer(fresh); a == nil || len(a.CommandLog()) != 0 { + t.Fatal("the replacement's adapter acted") + } +} + +// relayTo serves a second local address that forwards every connection to +// addr, and counts them. +func relayTo(t *testing.T, addr string) (string, func() int32) { + t.Helper() + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = l.Close() }) + var n atomic.Int32 + go func() { + for { + in, err := l.Accept() + if err != nil { + return + } + n.Add(1) + out, err := net.Dial("tcp", addr) + if err != nil { + _ = in.Close() + continue + } + go func() { _, _ = io.Copy(out, in); _ = out.Close() }() + go func() { _, _ = io.Copy(in, out); _ = in.Close() }() + } + }() + return l.Addr().String(), n.Load +} diff --git a/seaweed-block/core/host/volume/peer_adapter_registry.go b/seaweed-block/core/host/volume/peer_adapter_registry.go index 3197065b1b..85a293042f 100644 --- a/seaweed-block/core/host/volume/peer_adapter_registry.go +++ b/seaweed-block/core/host/volume/peer_adapter_registry.go @@ -46,6 +46,11 @@ type PeerAdapterRegistry struct { // a lineage bump replaces the peer under the same ReplicaID. peers map[string]*replication.ReplicaPeer closed bool + + // afterPrimeUnlock, when set (tests only), runs between the release of + // mu and the adapter's OnAssignment: the window in which the peer can + // be replaced after the identity check. + afterPrimeUnlock func() } // SetFrontier installs the local durable frontier read at each peer add @@ -177,8 +182,20 @@ func (r *PeerAdapterRegistry) OnPeerRemoved(replicaID string) { // seed barrier) and turns Degraded only after its own live session failed // and was invalidated; a degraded peer is not shipped to. So the adapter's // first session starts only after the volume's session on that peer has -// ended: there is no window in which both act on the replica. A dispatch -// acts only for the exact peer the loop admitted (PrimePendingFor, +// ended: there is no window in which both act on the replica. +// +// After the check, mu is released before OnAssignment, so the peer can be +// replaced in between. That window is closed by the executor, not by this +// lock: every command the adapter issues (probe, fence, catch-up, rebuild, +// recovery session) runs through the peer's own BlockExecutor and enters +// through beginAsyncOperation, which checks stopped and joins asyncWG under +// the executor's mu. UpdateReplicaSet detaches a replaced peer's executor +// and Stop()s it (stopped set under that mu, then asyncWG drained) before it +// creates the replacement and runs its seed barrier. A late command is +// therefore refused (ErrExecutorStopped), or it finished before the +// replacement existed. +// +// A dispatch acts only for the exact peer the loop admitted (PrimePendingFor, // AdapterForPeer compare the *ReplicaPeer under r.mu): a dispatch admitted // for an old degraded peer and resumed after a lineage bump replaced it // under the same ReplicaID finds nothing, so it never primes or probes the @@ -229,10 +246,18 @@ func (r *PeerAdapterRegistry) primeLocked(replicaID string) bool { info, ok := r.pending[replicaID] delete(r.pending, replicaID) adpt := r.adapters[replicaID] + hook := r.afterPrimeUnlock r.mu.Unlock() if !ok || adpt == nil { return false } + if hook != nil { + hook() + } + // The peer may be replaced from here on. The adapter's commands all run + // through the peer's own executor, which the volume stops before it + // installs the replacement (see the lock graph on PrimePending), so a + // command issued late is refused, never sent to the replica. adpt.OnAssignment(info) return true } From e69c2af879b862c95ac0b0c51642c92b81d210d8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 09:10:35 -0800 Subject: [PATCH 06/11] volume: a role-call retry completes the supporting assignment the failure skipped When a supporting fact's replica role call failed, the fact returned before the adapter took the line's identity and before the supporting admission was recorded. The retry cleared the latch but never applied those, so with no new fact the engine stayed at the old line. The skipped assignment is now kept (pendingSupport) and the retry completes it once its role call succeeds at that epoch, with the same steps as the assignment path. A new mutex serialises applyFact with that completion (order: it, then selfFenceMu), and every applied fact supersedes a pending one. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/volume/host.go | 65 ++++++++++-- .../host/volume/role_retry_support_test.go | 98 +++++++++++++++++++ 2 files changed, 153 insertions(+), 10 deletions(-) create mode 100644 seaweed-block/core/host/volume/role_retry_support_test.go diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 8e20d55078..94aa661f71 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -176,6 +176,15 @@ type Host struct { // re-applies the current role until it succeeds or is refused for good. // Under selfFenceMu. roleRetry bool + // factMu serialises applyFact (the subscription stream, the readiness + // replay) with runRoleRetry's completion of a skipped supporting + // assignment. Lock order: factMu, then selfFenceMu. + factMu sync.Mutex + // pendingSupport (under factMu): the supporting assignment the last + // fact skipped because its replica role call failed with an error a + // retry may outlast. runRoleRetry completes it once the role call + // succeeds at its epoch; any later fact supersedes it. + pendingSupport *pendingSupport // RF1Only admission state, one unit under rf1Mu (field access only, no // calls): the highest refused epoch with its reason ("" = cleared), and the // highest epoch an RF1 fact was admitted at. A clear removes only the @@ -489,6 +498,12 @@ func (h *Host) latchRoleAdmission(role selfRole, epoch uint64, err error) { h.roleAdmissionFailed.Store("") } +// pendingSupport is a supporting assignment waiting for its role call. +type pendingSupport struct { + info adapter.AssignmentInfo + primary string +} + // ErrRoleRefused marks a role call refused for good (the listener is closed, // or the volume refuses replica peers): retrying cannot succeed, so the // latch stays with its reason and no retry runs. @@ -511,9 +526,11 @@ func (h *Host) runRoleRetry(ctx context.Context) { return case <-time.After(delay): } + h.factMu.Lock() h.selfFenceMu.Lock() if !h.roleRetry || h.selfFence == nil || h.selfRole != selfRoleReplica { h.selfFenceMu.Unlock() + h.factMu.Unlock() delay = roleRetryMin continue } @@ -523,15 +540,37 @@ func (h *Host) runRoleRetry(ctx context.Context) { h.selfFenceMu.Unlock() if err == nil { h.log.Printf("blockvolume: replica role at epoch %d admitted on retry", epoch) + // Finish what the fact skipped when its role call failed, as the + // assignment path would have after a successful one (factMu held: + // no fact can be applied in between). + if p := h.pendingSupport; p != nil && p.info.Epoch == epoch { + h.pendingSupport = nil + h.completeSupporting(p.info, p.primary) + } + h.factMu.Unlock() delay = roleRetryMin continue } + h.factMu.Unlock() if delay *= 2; delay > roleRetryMax { delay = roleRetryMax } } } +// completeSupporting applies a supporting assignment once its replica role +// call succeeded: the adapter's identity, the watchdog, the ready marker. +func (h *Host) completeSupporting(info adapter.AssignmentInfo, primary string) { + h.adpt.OnAssignment(info) + h.wd.supportingAdmitted(info.Epoch) + h.log.Printf("blockvolume: volume %s admitted as SUPPORTING replica %s at epoch=%d EV=%d behind primary %s; frontend remains gated", + h.cfg.VolumeID, info.ReplicaID, info.Epoch, info.EndpointVersion, primary) + // Supporting replicas need durable lineage latching for promotion-readiness, + // but this must not consume the primary readyOnce. A later promotion to + // PRIMARY has to emit its own marker for the promoted lineage. + h.emitSupportingReadyMarker(info) +} + // RoleAdmissionFailure reports the G1 admission latch: whether the last role // call on this host's replica listener failed, and why. The projection view // treats a failure as not Healthy. @@ -952,6 +991,15 @@ func (h *Host) streamOnce(ctx context.Context) error { // OnAssignment could flip the projection Healthy before peers were // installed, admitting local-only writes with zero fan-out. func (h *Host) applyFact(fact *control.AssignmentFact) { + h.factMu.Lock() + defer h.factMu.Unlock() + // A newer fact supersedes a supporting assignment still waiting for + // its role call. + h.pendingSupport = nil + h.applyFactLocked(fact) +} + +func (h *Host) applyFactLocked(fact *control.AssignmentFact) { // INV-AUTH-HOLDER-IDENTITY-001: matching r1 and loopback endpoints do not identify a host. if h.refusePrimaryAssignment(fact) { return @@ -974,20 +1022,17 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { return } if err := h.fenceSelf(selfRoleReplica, info.Epoch); err != nil { - // G1: fail closed, as for the primary path; stream replay - // redelivers the fact and a later success clears the latch. + // G1: fail closed, as for the primary path. The role call is + // retried (runRoleRetry), which completes this assignment + // once it succeeds; a later fact supersedes it. h.log.Printf("blockvolume: volume %s could not admit its replica listener at epoch %d: %v — NOT admitting supporting replica (fail-closed)", h.cfg.VolumeID, info.Epoch, err) + if !errors.Is(err, ErrRoleRefused) { + h.pendingSupport = &pendingSupport{info: info, primary: fact.ReplicaId} + } return } - h.adpt.OnAssignment(info) - h.wd.supportingAdmitted(info.Epoch) - h.log.Printf("blockvolume: volume %s admitted as SUPPORTING replica %s at epoch=%d EV=%d behind primary %s; frontend remains gated", - h.cfg.VolumeID, info.ReplicaID, info.Epoch, info.EndpointVersion, fact.ReplicaId) - // Supporting replicas need durable lineage latching for promotion-readiness, - // but this must not consume the primary readyOnce. A later promotion to - // PRIMARY has to emit its own marker for the promoted lineage. - h.emitSupportingReadyMarker(info) + h.completeSupporting(info, fact.ReplicaId) return } // The new authoritative set excludes us: close assignment-gated diff --git a/seaweed-block/core/host/volume/role_retry_support_test.go b/seaweed-block/core/host/volume/role_retry_support_test.go new file mode 100644 index 0000000000..62c682659b --- /dev/null +++ b/seaweed-block/core/host/volume/role_retry_support_test.go @@ -0,0 +1,98 @@ +package volume + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" +) + +// assignedEpochs records the assignments the host applied to its adapter. +type assignedEpochs struct { + mu sync.Mutex + epochs []uint64 +} + +func (a *assignedEpochs) OnAssignment(info adapter.AssignmentInfo) adapter.ApplyLog { + a.mu.Lock() + defer a.mu.Unlock() + a.epochs = append(a.epochs, info.Epoch) + return adapter.ApplyLog{} +} + +func (a *assignedEpochs) last() uint64 { + a.mu.Lock() + defer a.mu.Unlock() + if len(a.epochs) == 0 { + return 0 + } + return a.epochs[len(a.epochs)-1] +} + +func supportingEpoch(h *Host) uint64 { + h.wd.mu.Lock() + defer h.wd.mu.Unlock() + return h.wd.supportingEpoch +} + +// A supporting fact whose replica role call failed is completed when the +// retry succeeds, with no new fact delivered: the adapter takes the line's +// identity and the supporting admission is recorded. A newer fact delivered +// while the role call still fails supersedes the pending one. +func TestRoleRetryCompletesTheSkippedSupportingAssignment(t *testing.T) { + min, max := roleRetryMin, roleRetryMax + roleRetryMin, roleRetryMax = time.Millisecond, 5*time.Millisecond + t.Cleanup(func() { roleRetryMin, roleRetryMax = min, max }) + + for name, c := range map[string]struct { + facts []uint64 // supporting facts delivered while the role call fails + want uint64 + }{ + "one fact, then the retry succeeds": {[]uint64{2}, 2}, + "a newer fact supersedes the pending one": {[]uint64{2, 3}, 3}, + } { + t.Run(name, func(t *testing.T) { + h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "sB", VolumeID: "vol1", ReplicaID: "rB", DataAddr: "127.0.0.1:5", CtrlAddr: "127.0.0.1:6"}) + if err != nil { + t.Fatal(err) + } + adpt := &assignedEpochs{} + h.adpt = adpt + ln := &flakyListener{fails: len(c.facts), err: errors.New("replica floor record write: permission denied")} + if err := h.SetSelfFence(ln); err != nil { + t.Fatal(err) + } + for _, e := range c.facts { + h.applyFact(supportingFact(e)) + } + if got := adpt.last(); got != 0 { + t.Fatalf("the adapter took epoch %d while the role call failed", got) + } + if failed, _ := h.RoleAdmissionFailure(); !failed { + t.Fatal("the failed role call was not latched") + } + + ctx, cancel := context.WithCancel(context.Background()) + h.wg.Add(1) + go h.runRoleRetry(ctx) + defer func() { cancel(); h.wg.Wait() }() + + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) && supportingEpoch(h) != c.want { + time.Sleep(5 * time.Millisecond) + } + if got := supportingEpoch(h); got != c.want { + t.Fatalf("supporting admission at epoch %d after the retry; want %d (no new fact delivered)", got, c.want) + } + if got := adpt.last(); got != c.want { + t.Fatalf("adapter epoch %d after the retry; want %d", got, c.want) + } + if failed, reason := h.RoleAdmissionFailure(); failed { + t.Fatalf("latch still set: %s", reason) + } + }) + } +} From a0b6a5da17bd4ceb82245ab508ad1faea0b30c44 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 09:26:49 -0800 Subject: [PATCH 07/11] volume: order the supporting completion with a narrow lock, not around applyFact A mutex around all of applyFact deadlocked facts applied concurrently by design (a replay worker beside the stream, a fact applied from inside another's hook). supportMu now spans only the completion of a supporting assignment, in the fact path after its role call released selfFenceMu and in the retry (supportMu, then selfFenceMu), so an older epoch's completion never lands after a newer one's. The retry completes the pending assignment only while the host still wants the replica role at its epoch; a newer fact moves that epoch or replaces the pending entry. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/volume/host.go | 46 +++++++++++++------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 94aa661f71..9bff5abffa 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -176,14 +176,17 @@ type Host struct { // re-applies the current role until it succeeds or is refused for good. // Under selfFenceMu. roleRetry bool - // factMu serialises applyFact (the subscription stream, the readiness - // replay) with runRoleRetry's completion of a skipped supporting - // assignment. Lock order: factMu, then selfFenceMu. - factMu sync.Mutex - // pendingSupport (under factMu): the supporting assignment the last - // fact skipped because its replica role call failed with an error a - // retry may outlast. runRoleRetry completes it once the role call - // succeeds at its epoch; any later fact supersedes it. + // supportMu orders the completion of a supporting assignment: the fact + // path's (after its role call) and runRoleRetry's (after a retried role + // call), so an older epoch's completion never lands after a newer one's. + // Lock order: supportMu, then selfFenceMu; the fact path takes it only + // after fenceSelf released selfFenceMu. Nothing under it applies a fact. + supportMu sync.Mutex + // pendingSupport (under supportMu): the supporting assignment a fact + // skipped because its replica role call failed with an error a retry + // may outlast. runRoleRetry completes it once the role call succeeds + // while this host still wants the replica role at that epoch; a newer + // fact supersedes it (it moves selfEpoch or the role, or replaces it). pendingSupport *pendingSupport // RF1Only admission state, one unit under rf1Mu (field access only, no // calls): the highest refused epoch with its reason ("" = cleared), and the @@ -526,11 +529,11 @@ func (h *Host) runRoleRetry(ctx context.Context) { return case <-time.After(delay): } - h.factMu.Lock() + h.supportMu.Lock() h.selfFenceMu.Lock() if !h.roleRetry || h.selfFence == nil || h.selfRole != selfRoleReplica { h.selfFenceMu.Unlock() - h.factMu.Unlock() + h.supportMu.Unlock() delay = roleRetryMin continue } @@ -541,17 +544,17 @@ func (h *Host) runRoleRetry(ctx context.Context) { if err == nil { h.log.Printf("blockvolume: replica role at epoch %d admitted on retry", epoch) // Finish what the fact skipped when its role call failed, as the - // assignment path would have after a successful one (factMu held: - // no fact can be applied in between). + // assignment path would have after a successful one. supportMu is + // held: a newer fact's completion waits for this one. if p := h.pendingSupport; p != nil && p.info.Epoch == epoch { h.pendingSupport = nil h.completeSupporting(p.info, p.primary) } - h.factMu.Unlock() + h.supportMu.Unlock() delay = roleRetryMin continue } - h.factMu.Unlock() + h.supportMu.Unlock() if delay *= 2; delay > roleRetryMax { delay = roleRetryMax } @@ -991,15 +994,6 @@ func (h *Host) streamOnce(ctx context.Context) error { // OnAssignment could flip the projection Healthy before peers were // installed, admitting local-only writes with zero fan-out. func (h *Host) applyFact(fact *control.AssignmentFact) { - h.factMu.Lock() - defer h.factMu.Unlock() - // A newer fact supersedes a supporting assignment still waiting for - // its role call. - h.pendingSupport = nil - h.applyFactLocked(fact) -} - -func (h *Host) applyFactLocked(fact *control.AssignmentFact) { // INV-AUTH-HOLDER-IDENTITY-001: matching r1 and loopback endpoints do not identify a host. if h.refusePrimaryAssignment(fact) { return @@ -1027,12 +1021,18 @@ func (h *Host) applyFactLocked(fact *control.AssignmentFact) { // once it succeeds; a later fact supersedes it. h.log.Printf("blockvolume: volume %s could not admit its replica listener at epoch %d: %v — NOT admitting supporting replica (fail-closed)", h.cfg.VolumeID, info.Epoch, err) + h.supportMu.Lock() + h.pendingSupport = nil if !errors.Is(err, ErrRoleRefused) { h.pendingSupport = &pendingSupport{info: info, primary: fact.ReplicaId} } + h.supportMu.Unlock() return } + h.supportMu.Lock() + h.pendingSupport = nil // this fact supersedes any skipped one h.completeSupporting(info, fact.ReplicaId) + h.supportMu.Unlock() return } // The new authoritative set excludes us: close assignment-gated From 49dcf2d22ebb612af3027f77c48dd65c4f45ff01 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 10:33:33 -0800 Subject: [PATCH 08/11] volume: note why the role-call retry does not touch shipPrepared Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/volume/host.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 9bff5abffa..9214863741 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -538,6 +538,9 @@ func (h *Host) runRoleRetry(ctx context.Context) { continue } role, epoch := h.selfRole, h.selfEpoch + // Re-applied directly, not through fenceSelfWithPeers: the desired + // role is unchanged, and shipPrepared was already cleared when this + // replica role was first taken there. err := applySelfRoleWithPeers(h.selfFence, role, epoch, h.selfHasPeers) h.latchRoleAdmission(role, epoch, err) h.selfFenceMu.Unlock() From a292f142ccdd9cc57b85ed3affb38f73a248381c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 10:51:04 -0800 Subject: [PATCH 09/11] volume: an old supporting completion never lands after a newer transition The retry released selfFenceMu before completing a skipped supporting assignment, and only supporting completions took the lock that ordered it, so a newer self-primary or excluding fact could act in between; the retry then ran supportingAdmitted for the old epoch (clearing the primary watchdog) and emitted an old ready marker. The retry now completes under selfFenceMu, and every fact records its epoch under that lock at the very start of applyFact, before it acts at all (the watchdog runs before the role call); the retry completes only while no newer epoch was seen. A newer fact waits at that record until the completion is done. Only the record is under the lock, so facts applied concurrently by design do not nest it. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/volume/host.go | 56 +++--- .../core/host/volume/role_retry_order_test.go | 164 ++++++++++++++++++ 2 files changed, 197 insertions(+), 23 deletions(-) create mode 100644 seaweed-block/core/host/volume/role_retry_order_test.go diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 9214863741..63bc2fdd89 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -176,18 +176,22 @@ type Host struct { // re-applies the current role until it succeeds or is refused for good. // Under selfFenceMu. roleRetry bool - // supportMu orders the completion of a supporting assignment: the fact - // path's (after its role call) and runRoleRetry's (after a retried role - // call), so an older epoch's completion never lands after a newer one's. - // Lock order: supportMu, then selfFenceMu; the fact path takes it only - // after fenceSelf released selfFenceMu. Nothing under it applies a fact. - supportMu sync.Mutex - // pendingSupport (under supportMu): the supporting assignment a fact + // pendingSupport (under selfFenceMu): the supporting assignment a fact // skipped because its replica role call failed with an error a retry - // may outlast. runRoleRetry completes it once the role call succeeds - // while this host still wants the replica role at that epoch; a newer - // fact supersedes it (it moves selfEpoch or the role, or replaces it). + // may outlast. runRoleRetry completes it, under selfFenceMu, once the + // role call succeeds while the desired role is still replica at that + // epoch and no newer fact has been seen (factEpochSeen). pendingSupport *pendingSupport + // factEpochSeen (under selfFenceMu): the highest epoch of any fact + // applyFact has started on, recorded at its very start, before the fact + // acts in any way (the watchdog, the role call, the adapter). The retry + // completes a pending assignment, under selfFenceMu, only while no newer + // epoch was seen; a newer fact arriving meanwhile waits at that record + // until the completion is done, so none of its actions precede it and no + // older completion lands after a newer transition. The record is the + // only part of applyFact under the lock: facts applied concurrently (a + // replay beside the stream, one inside another's hook) do not nest it. + factEpochSeen uint64 // RF1Only admission state, one unit under rf1Mu (field access only, no // calls): the highest refused epoch with its reason ("" = cleared), and the // highest epoch an RF1 fact was admitted at. A clear removes only the @@ -529,11 +533,9 @@ func (h *Host) runRoleRetry(ctx context.Context) { return case <-time.After(delay): } - h.supportMu.Lock() h.selfFenceMu.Lock() if !h.roleRetry || h.selfFence == nil || h.selfRole != selfRoleReplica { h.selfFenceMu.Unlock() - h.supportMu.Unlock() delay = roleRetryMin continue } @@ -543,21 +545,23 @@ func (h *Host) runRoleRetry(ctx context.Context) { // replica role was first taken there. err := applySelfRoleWithPeers(h.selfFence, role, epoch, h.selfHasPeers) h.latchRoleAdmission(role, epoch, err) - h.selfFenceMu.Unlock() if err == nil { h.log.Printf("blockvolume: replica role at epoch %d admitted on retry", epoch) // Finish what the fact skipped when its role call failed, as the - // assignment path would have after a successful one. supportMu is - // held: a newer fact's completion waits for this one. - if p := h.pendingSupport; p != nil && p.info.Epoch == epoch { + // assignment path would have after a successful one, still under + // selfFenceMu: the desired role and epoch read above cannot move + // until it is done, so no newer transition lands in between. + // (The completion takes no host lock: the adapter's executor is + // local, the watchdog and the marker have their own.) + if p := h.pendingSupport; p != nil && p.info.Epoch == epoch && h.factEpochSeen <= epoch { h.pendingSupport = nil h.completeSupporting(p.info, p.primary) } - h.supportMu.Unlock() + h.selfFenceMu.Unlock() delay = roleRetryMin continue } - h.supportMu.Unlock() + h.selfFenceMu.Unlock() if delay *= 2; delay > roleRetryMax { delay = roleRetryMax } @@ -997,6 +1001,12 @@ func (h *Host) streamOnce(ctx context.Context) error { // OnAssignment could flip the projection Healthy before peers were // installed, admitting local-only writes with zero fan-out. func (h *Host) applyFact(fact *control.AssignmentFact) { + // Record the fact's epoch before it acts (see factEpochSeen). + h.selfFenceMu.Lock() + if fact.GetEpoch() > h.factEpochSeen { + h.factEpochSeen = fact.GetEpoch() + } + h.selfFenceMu.Unlock() // INV-AUTH-HOLDER-IDENTITY-001: matching r1 and loopback endpoints do not identify a host. if h.refusePrimaryAssignment(fact) { return @@ -1024,18 +1034,18 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { // once it succeeds; a later fact supersedes it. h.log.Printf("blockvolume: volume %s could not admit its replica listener at epoch %d: %v — NOT admitting supporting replica (fail-closed)", h.cfg.VolumeID, info.Epoch, err) - h.supportMu.Lock() + h.selfFenceMu.Lock() h.pendingSupport = nil - if !errors.Is(err, ErrRoleRefused) { + if !errors.Is(err, ErrRoleRefused) && h.selfRole == selfRoleReplica && h.selfEpoch == info.Epoch { h.pendingSupport = &pendingSupport{info: info, primary: fact.ReplicaId} } - h.supportMu.Unlock() + h.selfFenceMu.Unlock() return } - h.supportMu.Lock() + h.selfFenceMu.Lock() h.pendingSupport = nil // this fact supersedes any skipped one + h.selfFenceMu.Unlock() h.completeSupporting(info, fact.ReplicaId) - h.supportMu.Unlock() return } // The new authoritative set excludes us: close assignment-gated diff --git a/seaweed-block/core/host/volume/role_retry_order_test.go b/seaweed-block/core/host/volume/role_retry_order_test.go new file mode 100644 index 0000000000..1743d27802 --- /dev/null +++ b/seaweed-block/core/host/volume/role_retry_order_test.go @@ -0,0 +1,164 @@ +package volume + +import ( + "context" + "errors" + "fmt" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +// orderLog is one sequence of the host's role calls and adapter assignments. +type orderLog struct { + mu sync.Mutex + seq []string +} + +func (o *orderLog) add(s string) { o.mu.Lock(); o.seq = append(o.seq, s); o.mu.Unlock() } +func (o *orderLog) snapshot() []string { + o.mu.Lock() + defer o.mu.Unlock() + return append([]string(nil), o.seq...) +} +func (o *orderLog) index(s string) int { + for i, e := range o.snapshot() { + if e == s { + return i + } + } + return -1 +} + +// orderListener fails its first replica role call, then records every role +// call it admits. +type orderListener struct { + log *orderLog + mu sync.Mutex + fails int +} + +func (l *orderListener) FenceAsPrimary(e uint64) error { + l.log.add(fmt.Sprintf("primary@%d", e)) + return nil +} +func (l *orderListener) AdmitAsReplica(e uint64) error { + l.mu.Lock() + defer l.mu.Unlock() + if l.fails > 0 { + l.fails-- + return errors.New("replica floor record write: permission denied") + } + l.log.add(fmt.Sprintf("replica@%d", e)) + return nil +} + +// heldAdapter records each assignment when it returns; the one at holdAt +// waits in OnAssignment until release is closed. +type heldAdapter struct { + log *orderLog + holdAt uint64 + entered, release chan struct{} +} + +func (a *heldAdapter) OnAssignment(info adapter.AssignmentInfo) adapter.ApplyLog { + if info.Epoch == a.holdAt { + close(a.entered) + <-a.release + } + a.log.add(fmt.Sprintf("assign@%d", info.Epoch)) + return adapter.ApplyLog{} +} + +// The retry's completion of a skipped supporting assignment at epoch 2 is +// held in its first step while a newer fact at epoch 3 arrives: this host's +// own primary line, or a line that excludes it. The completion must finish +// before the newer transition takes its role, so no older completion lands +// after it: the adapter does not go back to epoch 2, the primary watchdog +// keeps epoch 3, and no supporting admission or marker for 2 follows. +func TestRoleRetryCompletionNeverLandsAfterANewerTransition(t *testing.T) { + min, max := roleRetryMin, roleRetryMax + roleRetryMin, roleRetryMax = time.Millisecond, 5*time.Millisecond + t.Cleanup(func() { roleRetryMin, roleRetryMax = min, max }) + + selfPrimary := func() *control.AssignmentFact { + return &control.AssignmentFact{ServerId: "sB", VolumeId: "vol1", ReplicaId: "rB", Epoch: 3, EndpointVersion: 1, DataAddr: "127.0.0.1:5", CtrlAddr: "127.0.0.1:6", PeerSetGeneration: 3} + } + excluding := func() *control.AssignmentFact { + return &control.AssignmentFact{VolumeId: "vol1", ReplicaId: "rA", Epoch: 3, EndpointVersion: 1, DataAddr: "127.0.0.1:3", CtrlAddr: "127.0.0.1:4", PeerSetGeneration: 3, + Peers: []*control.ReplicaDescriptor{{ReplicaId: "rC", Epoch: 3, EndpointVersion: 1, DataAddr: "127.0.0.1:7", CtrlAddr: "127.0.0.1:8"}}} + } + for name, newer := range map[string]func() *control.AssignmentFact{"self-primary": selfPrimary, "excluding": excluding} { + t.Run(name, func(t *testing.T) { + markers := make(chan adapter.AssignmentInfo, 8) + h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "sB", VolumeID: "vol1", ReplicaID: "rB", DataAddr: "127.0.0.1:5", CtrlAddr: "127.0.0.1:6", ReadyMarker: markers}) + if err != nil { + t.Fatal(err) + } + log := &orderLog{} + adpt := &heldAdapter{log: log, holdAt: 2, entered: make(chan struct{}), release: make(chan struct{})} + h.adpt = adpt + if err := h.SetSelfFence(&orderListener{log: log, fails: 1}); err != nil { + t.Fatal(err) + } + h.applyFact(supportingFact(2)) // its role call fails: the assignment waits for the retry + + ctx, cancel := context.WithCancel(context.Background()) + h.wg.Add(1) + go h.runRoleRetry(ctx) + defer func() { cancel(); h.wg.Wait() }() + + select { + case <-adpt.entered: // the retry's role call succeeded; its completion is held + case <-time.After(2 * time.Second): + t.Fatal("the retry never completed the skipped assignment") + } + done := make(chan struct{}) + go func() { h.applyFact(newer()); close(done) }() + time.Sleep(100 * time.Millisecond) // the newer fact runs as far as it can + close(adpt.release) + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("the newer fact never finished") + } + + deadline := time.Now().Add(2 * time.Second) + for log.index("assign@2") < 0 && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + seq := log.snapshot() + old, newerRole := log.index("assign@2"), log.index("primary@3") + if old < 0 || newerRole < 0 { + t.Fatalf("sequence %v; want the completion at 2 and the newer role call at 3", seq) + } + if old > newerRole { + t.Fatalf("sequence %v: the completion for epoch 2 landed after the newer transition at 3", seq) + } + if name == "self-primary" { + if last := seq[len(seq)-1]; last != "assign@3" { + t.Fatalf("sequence %v: the adapter ended at %s; want assign@3", seq, last) + } + h.wd.mu.Lock() + pe := h.wd.primaryEpoch + h.wd.mu.Unlock() + if pe != 3 { + t.Fatalf("primary watchdog epoch %d after the primary line at 3; want 3 (an old supporting admission cleared it)", pe) + } + } + close(markers) + var order []uint64 + for m := range markers { + order = append(order, m.Epoch) + } + for i := 1; i < len(order); i++ { + if order[i] < order[i-1] { + t.Fatalf("ready markers %v: an old marker followed a newer one", order) + } + } + }) + } +} From 5244dc366394bffa8c4eef359b873b47d121a225 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 11:07:22 -0800 Subject: [PATCH 10/11] volume: both supporting completions run through one guarded function The fact's own successful role call released selfFenceMu before it completed the supporting assignment, and facts run concurrently by design, so a newer self-primary or excluding fact could cross: the old admission then cleared that fact's primary watchdog or emitted an old marker. The direct path and the retry now both complete through completeSupportingIfCurrentLocked, which checks and completes without releasing selfFenceMu: only while the desired role is still replica at that epoch and no newer fact was seen. A newer fact records its epoch under the lock before it acts, so it waits for the completion or supersedes it. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/volume/host.go | 26 +++++- .../core/host/volume/role_retry_order_test.go | 81 +++++++++++++++++++ 2 files changed, 104 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 63bc2fdd89..64ef083dde 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -553,9 +553,9 @@ func (h *Host) runRoleRetry(ctx context.Context) { // until it is done, so no newer transition lands in between. // (The completion takes no host lock: the adapter's executor is // local, the watchdog and the marker have their own.) - if p := h.pendingSupport; p != nil && p.info.Epoch == epoch && h.factEpochSeen <= epoch { + if p := h.pendingSupport; p != nil && p.info.Epoch == epoch { h.pendingSupport = nil - h.completeSupporting(p.info, p.primary) + h.completeSupportingIfCurrentLocked(p.info, p.primary) } h.selfFenceMu.Unlock() delay = roleRetryMin @@ -568,8 +568,28 @@ func (h *Host) runRoleRetry(ctx context.Context) { } } +// completeSupportingIfCurrentLocked is the one completion of a supporting +// assignment, for the fact's own successful role call and for the retry's: +// it completes only while the desired role is still replica at info's epoch +// and no newer fact has been seen (factEpochSeen), checked and completed +// without releasing selfFenceMu (held by the caller). A newer fact records +// its epoch under that lock before it acts at all, so it either was seen +// here (nothing old is completed) or waits until this completion is done: +// no older admission, watchdog step or marker lands after it. Facts run +// concurrently by design (a replay beside the stream); only this and the +// record at applyFact's start are under the lock. +func (h *Host) completeSupportingIfCurrentLocked(info adapter.AssignmentInfo, primary string) { + if h.selfRole != selfRoleReplica || h.selfEpoch != info.Epoch || h.factEpochSeen > info.Epoch { + h.log.Printf("blockvolume: volume %s supporting assignment at epoch %d superseded before its completion (desired %v@%d, newest fact %d)", + h.cfg.VolumeID, info.Epoch, h.selfRole, h.selfEpoch, h.factEpochSeen) + return + } + h.completeSupporting(info, primary) +} + // completeSupporting applies a supporting assignment once its replica role // call succeeded: the adapter's identity, the watchdog, the ready marker. +// Called only through completeSupportingIfCurrentLocked. func (h *Host) completeSupporting(info adapter.AssignmentInfo, primary string) { h.adpt.OnAssignment(info) h.wd.supportingAdmitted(info.Epoch) @@ -1044,8 +1064,8 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { } h.selfFenceMu.Lock() h.pendingSupport = nil // this fact supersedes any skipped one + h.completeSupportingIfCurrentLocked(info, fact.ReplicaId) h.selfFenceMu.Unlock() - h.completeSupporting(info, fact.ReplicaId) return } // The new authoritative set excludes us: close assignment-gated diff --git a/seaweed-block/core/host/volume/role_retry_order_test.go b/seaweed-block/core/host/volume/role_retry_order_test.go index 1743d27802..c79eb44d4c 100644 --- a/seaweed-block/core/host/volume/role_retry_order_test.go +++ b/seaweed-block/core/host/volume/role_retry_order_test.go @@ -162,3 +162,84 @@ func TestRoleRetryCompletionNeverLandsAfterANewerTransition(t *testing.T) { }) } } + +// The direct path: a supporting fact at epoch 2 whose own role call +// succeeds has its completion held in its first step while a newer fact at +// epoch 3 is applied concurrently (facts run concurrently by design: a +// replay beside the stream): this host's own primary line, or a line that +// excludes it. The old completion must not land after the newer +// transition: no adapter step back to 2, no supporting admission clearing +// the primary watchdog at 3, no old marker after a newer one. +func TestDirectSupportingCompletionNeverLandsAfterANewerTransition(t *testing.T) { + selfPrimary := func() *control.AssignmentFact { + return &control.AssignmentFact{ServerId: "sB", VolumeId: "vol1", ReplicaId: "rB", Epoch: 3, EndpointVersion: 1, DataAddr: "127.0.0.1:5", CtrlAddr: "127.0.0.1:6", PeerSetGeneration: 3} + } + excluding := func() *control.AssignmentFact { + return &control.AssignmentFact{VolumeId: "vol1", ReplicaId: "rA", Epoch: 3, EndpointVersion: 1, DataAddr: "127.0.0.1:3", CtrlAddr: "127.0.0.1:4", PeerSetGeneration: 3, + Peers: []*control.ReplicaDescriptor{{ReplicaId: "rC", Epoch: 3, EndpointVersion: 1, DataAddr: "127.0.0.1:7", CtrlAddr: "127.0.0.1:8"}}} + } + for name, newer := range map[string]func() *control.AssignmentFact{"self-primary": selfPrimary, "excluding": excluding} { + t.Run(name, func(t *testing.T) { + markers := make(chan adapter.AssignmentInfo, 8) + h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "sB", VolumeID: "vol1", ReplicaID: "rB", DataAddr: "127.0.0.1:5", CtrlAddr: "127.0.0.1:6", ReadyMarker: markers}) + if err != nil { + t.Fatal(err) + } + log := &orderLog{} + adpt := &heldAdapter{log: log, holdAt: 2, entered: make(chan struct{}), release: make(chan struct{})} + h.adpt = adpt + if err := h.SetSelfFence(&orderListener{log: log}); err != nil { + t.Fatal(err) + } + + first := make(chan struct{}) + go func() { h.applyFact(supportingFact(2)); close(first) }() + select { + case <-adpt.entered: // its role call succeeded; its completion is held + case <-time.After(2 * time.Second): + t.Fatal("the supporting fact never reached its completion") + } + second := make(chan struct{}) + go func() { h.applyFact(newer()); close(second) }() + time.Sleep(100 * time.Millisecond) // the newer fact runs as far as it can + close(adpt.release) + for _, c := range []chan struct{}{first, second} { + select { + case <-c: + case <-time.After(2 * time.Second): + t.Fatal("a fact never finished") + } + } + + seq := log.snapshot() + old, newerRole := log.index("assign@2"), log.index("primary@3") + if old < 0 || newerRole < 0 { + t.Fatalf("sequence %v; want the completion at 2 and the newer role call at 3", seq) + } + if old > newerRole { + t.Fatalf("sequence %v: the completion for epoch 2 landed after the newer transition at 3", seq) + } + if name == "self-primary" { + if last := seq[len(seq)-1]; last != "assign@3" { + t.Fatalf("sequence %v: the adapter ended at %s; want assign@3", seq, last) + } + h.wd.mu.Lock() + pe := h.wd.primaryEpoch + h.wd.mu.Unlock() + if pe != 3 { + t.Fatalf("primary watchdog epoch %d after the primary line at 3; want 3 (an old supporting admission cleared it)", pe) + } + } + close(markers) + var order []uint64 + for m := range markers { + order = append(order, m.Epoch) + } + for i := 1; i < len(order); i++ { + if order[i] < order[i-1] { + t.Fatalf("ready markers %v: an old marker followed a newer one", order) + } + } + }) + } +} From 5a6048a218f61f839be3f20d88a4ae8780f6a345 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 11:24:46 -0800 Subject: [PATCH 11/11] volume: a late older fact never clears a newer pending supporting assignment A supporting fact cleared pendingSupport unconditionally, so a late replay of an older line (its role call refused as stale) wiped the assignment a newer fact left pending; the retry then admitted the newer listener but never completed its assignment. A fact now clears or replaces the pending assignment only when its epoch is the same or newer. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/volume/host.go | 21 +++++++-- .../host/volume/role_retry_support_test.go | 47 +++++++++++++++++++ 2 files changed, 64 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 64ef083dde..2f9a20e04a 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -568,6 +568,13 @@ func (h *Host) runRoleRetry(ctx context.Context) { } } +// supersedesPendingLocked reports whether a supporting fact at epoch may +// clear or replace the pending assignment: only one at its epoch or below +// (selfFenceMu held). +func (h *Host) supersedesPendingLocked(epoch uint64) bool { + return h.pendingSupport == nil || h.pendingSupport.info.Epoch <= epoch +} + // completeSupportingIfCurrentLocked is the one completion of a supporting // assignment, for the fact's own successful role call and for the retry's: // it completes only while the desired role is still replica at info's epoch @@ -1055,15 +1062,21 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { h.log.Printf("blockvolume: volume %s could not admit its replica listener at epoch %d: %v — NOT admitting supporting replica (fail-closed)", h.cfg.VolumeID, info.Epoch, err) h.selfFenceMu.Lock() - h.pendingSupport = nil - if !errors.Is(err, ErrRoleRefused) && h.selfRole == selfRoleReplica && h.selfEpoch == info.Epoch { - h.pendingSupport = &pendingSupport{info: info, primary: fact.ReplicaId} + // An older fact (a late replay) never touches a newer + // pending assignment: it neither clears nor replaces it. + if h.supersedesPendingLocked(info.Epoch) { + h.pendingSupport = nil + if !errors.Is(err, ErrRoleRefused) && h.selfRole == selfRoleReplica && h.selfEpoch == info.Epoch { + h.pendingSupport = &pendingSupport{info: info, primary: fact.ReplicaId} + } } h.selfFenceMu.Unlock() return } h.selfFenceMu.Lock() - h.pendingSupport = nil // this fact supersedes any skipped one + if h.supersedesPendingLocked(info.Epoch) { + h.pendingSupport = nil // this fact supersedes a skipped one at its epoch or below + } h.completeSupportingIfCurrentLocked(info, fact.ReplicaId) h.selfFenceMu.Unlock() return diff --git a/seaweed-block/core/host/volume/role_retry_support_test.go b/seaweed-block/core/host/volume/role_retry_support_test.go index 62c682659b..18b9c07132 100644 --- a/seaweed-block/core/host/volume/role_retry_support_test.go +++ b/seaweed-block/core/host/volume/role_retry_support_test.go @@ -96,3 +96,50 @@ func TestRoleRetryCompletesTheSkippedSupportingAssignment(t *testing.T) { }) } } + +// A late older fact never clears a newer pending assignment: the fact at 3 +// fails its role call (pending at 3), a late replay at 2 arrives (its role +// call is refused as stale), and the retry then completes epoch 3 (the +// adapter takes 3, the supporting admission is at 3, its marker is sent). +func TestALateOlderFactNeverClearsANewerPendingAssignment(t *testing.T) { + min, max := roleRetryMin, roleRetryMax + roleRetryMin, roleRetryMax = time.Millisecond, 5*time.Millisecond + t.Cleanup(func() { roleRetryMin, roleRetryMax = min, max }) + + markers := make(chan adapter.AssignmentInfo, 8) + h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "sB", VolumeID: "vol1", ReplicaID: "rB", DataAddr: "127.0.0.1:5", CtrlAddr: "127.0.0.1:6", ReadyMarker: markers}) + if err != nil { + t.Fatal(err) + } + adpt := &assignedEpochs{} + h.adpt = adpt + if err := h.SetSelfFence(&flakyListener{fails: 1, err: errors.New("replica floor record write: permission denied")}); err != nil { + t.Fatal(err) + } + h.applyFact(supportingFact(3)) // its role call fails: pending at 3 + h.applyFact(supportingFact(2)) // a late replay of an older line + + ctx, cancel := context.WithCancel(context.Background()) + h.wg.Add(1) + go h.runRoleRetry(ctx) + defer func() { cancel(); h.wg.Wait() }() + + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) && supportingEpoch(h) != 3 { + time.Sleep(5 * time.Millisecond) + } + if got := supportingEpoch(h); got != 3 { + t.Fatalf("supporting admission at epoch %d after the retry; want 3 (the late fact at 2 cleared the pending assignment)", got) + } + if got := adpt.last(); got != 3 { + t.Fatalf("adapter at epoch %d; want 3", got) + } + select { + case m := <-markers: + if m.Epoch != 3 { + t.Fatalf("ready marker for epoch %d; want 3", m.Epoch) + } + case <-time.After(time.Second): + t.Fatal("no ready marker for epoch 3") + } +}