diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index c37a7da141..8aa2d12663 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.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/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..2f9a20e04a 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,27 @@ 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 + // 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, 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 @@ -472,6 +494,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 +505,109 @@ 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. +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 + // 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) + 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, 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.pendingSupport = nil + h.completeSupportingIfCurrentLocked(p.info, p.primary) + } + h.selfFenceMu.Unlock() + delay = roleRetryMin + continue + } + h.selfFenceMu.Unlock() + if delay *= 2; delay > roleRetryMax { + delay = roleRetryMax + } + } +} + +// 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 +// 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) + 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. @@ -617,10 +743,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 } @@ -901,6 +1028,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 @@ -923,20 +1056,29 @@ 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) + h.selfFenceMu.Lock() + // 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.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.selfFenceMu.Lock() + 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 } // The new authoritative set excludes us: close assignment-gated 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_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 467b525e17..85a293042f 100644 --- a/seaweed-block/core/host/volume/peer_adapter_registry.go +++ b/seaweed-block/core/host/volume/peer_adapter_registry.go @@ -38,7 +38,19 @@ 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 + // 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 + + // 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 @@ -58,12 +70,22 @@ func NewPeerAdapterRegistry(volumeID, selfReplicaID string) *PeerAdapterRegistry volumeID: volumeID, selfReplicaID: selfReplicaID, adapters: make(map[string]*adapter.VolumeReplicaAdapter), + pending: make(map[string]adapter.AssignmentInfo), + peers: make(map[string]*replication.ReplicaPeer), } } // 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 +135,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,9 +143,10 @@ func (r *PeerAdapterRegistry) OnPeerAdded(peer *replication.ReplicaPeer) { DataAddr: target.DataAddr, CtrlAddr: target.ControlAddr, PrimaryStartLSN: start, - }) + } 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) } @@ -141,9 +164,104 @@ func (r *PeerAdapterRegistry) OnPeerRemoved(replicaID string) { return } delete(r.adapters, replicaID) + delete(r.pending, replicaID) + delete(r.peers, 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. +// +// 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 +// 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] + 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 +} + // AdapterFor returns the per-peer adapter for replicaID, or nil if // no adapter is registered. Safe to call from any goroutine. // @@ -182,4 +300,6 @@ 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_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_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 new file mode 100644 index 0000000000..f28ca77823 --- /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.AdapterForPeer, reg.PrimePendingFor), 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..0fe58fab41 100644 --- a/seaweed-block/core/host/volume/probe_loop_wiring.go +++ b/seaweed-block/core/host/volume/probe_loop_wiring.go @@ -76,6 +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 { + 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. +// +// 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 @@ -125,10 +150,13 @@ func ProductionProbeFn(router AdapterRouter) replication.ProbeFn { // 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(peer) { + return nil + } result := exec.Probe(t.ReplicaID, t.DataAddr, t.ControlAddr, sessionID, t.Epoch, t.EndpointVersion) 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..c79eb44d4c --- /dev/null +++ b/seaweed-block/core/host/volume/role_retry_order_test.go @@ -0,0 +1,245 @@ +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) + } + } + }) + } +} + +// 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) + } + } + }) + } +} 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..18b9c07132 --- /dev/null +++ b/seaweed-block/core/host/volume/role_retry_support_test.go @@ -0,0 +1,145 @@ +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) + } + }) + } +} + +// 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") + } +} 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()) + } + }) + } +} 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..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 @@ -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.AdapterForPeer, registry.PrimePendingFor), 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 {