From f9ce00ce6bb5202f58ce4e31957547670d9afd3b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 03:55:13 -0800 Subject: [PATCH] transport, volume: a fencing round's answer is the replica's durable promise On a probe round with a fence epoch naming its store, the replica raises its epoch floor in memory (new frames below it are refused at once), waits for every mutation admitted before to finish, persists the floor, and only then reads its evidence and answers with the durable floor. A failed fence is not answered; a round naming another store raises nothing; a plain round reports the floor. The floor never goes down, and the line re-issued to the same primary at the fenced epoch is admitted as before. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/volume/probe_round.go | 57 +++++++- .../host/volume/probe_round_fence_test.go | 122 +++++++++++++++++ .../core/transport/fence_floor_test.go | 127 ++++++++++++++++++ seaweed-block/core/transport/replica.go | 38 +++++- 4 files changed, 341 insertions(+), 3 deletions(-) create mode 100644 seaweed-block/core/host/volume/probe_round_fence_test.go create mode 100644 seaweed-block/core/transport/fence_floor_test.go diff --git a/seaweed-block/core/host/volume/probe_round.go b/seaweed-block/core/host/volume/probe_round.go index 8e71d6d084..9c3163830c 100644 --- a/seaweed-block/core/host/volume/probe_round.go +++ b/seaweed-block/core/host/volume/probe_round.go @@ -1,6 +1,7 @@ package volume import ( + "bytes" "context" "io" "sync/atomic" @@ -14,6 +15,13 @@ import ( // master's rounds for its node and answers each one for this replica from // the store as it is now (durable end, epoch-table row there, validity) and // its role. It keeps no state and reports nothing unasked. +// +// A fencing round (fence_epoch > 0) is answered only after its promise: when +// the round names this replica's store, the listener's floor is raised to +// fence_epoch, every mutation admitted before has drained and the floor is +// durable; only then is the evidence read, so the end it reports is final +// for every epoch below. A round naming another store raises nothing; a +// fence that fails is not answered. // probeRoleSource is this replica's role as the promotion probe reads it // (StatusServer.ProbeRoles): ready to be promoted, or a primary that serves. @@ -61,7 +69,10 @@ func (h *Host) probeStreamOnce(ctx context.Context) error { if round.GetVolumeId() != h.cfg.VolumeID || round.GetReplicaId() != h.cfg.ReplicaID { continue // another replica on this node answers its own rounds } - answer := h.probeAnswer(round.GetRoundId()) + answer, ok := h.roundAnswer(round) + if !ok { + continue + } rpcCtx, cancel := context.WithTimeout(ctx, 2*time.Second) _, err = h.obsCli.AnswerProbe(rpcCtx, answer) cancel() @@ -71,6 +82,50 @@ func (h *Host) probeStreamOnce(ctx context.Context) error { } } +// floorFencer is the replication listener's fencing-round side +// (transport.ReplicaListener). +type floorFencer interface { + FenceFloor(epoch uint64) error + DurableFloor() uint64 +} + +func (h *Host) floorFencer() (floorFencer, bool) { + h.selfFenceMu.Lock() + defer h.selfFenceMu.Unlock() + f, ok := h.selfFence.(floorFencer) + return f, ok && f != nil +} + +// roundAnswer is the answer to round, or false when none may be sent: a +// fencing round for this store whose fence did not complete. +func (h *Host) roundAnswer(round *control.ProbeRound) (*control.ProbeAnswer, bool) { + fencer, hasFloor := h.floorFencer() + if fe := round.GetFenceEpoch(); fe > 0 && hasFloor && h.roundNamesThisStore(round) { + if err := fencer.FenceFloor(fe); err != nil { + h.log.Printf("blockvolume: fencing round=%d at epoch %d not answered: %v", round.GetRoundId(), fe, err) + return nil, false + } + } else if fe > 0 { + h.log.Printf("blockvolume: fencing round=%d at epoch %d names another store; floor unchanged", round.GetRoundId(), fe) + } + a := h.probeAnswer(round.GetRoundId()) + if hasFloor { + a.Floor = fencer.DurableFloor() + } + return a, true +} + +// roundNamesThisStore reports whether the round's expected store is this +// replica's store (a store without an id never matches). +func (h *Host) roundNamesThisStore(round *control.ProbeRound) bool { + sid, ok := h.getReplication().(interface{ LocalStoreID() storage.StoreID }) + if !ok || sid == nil { + return false + } + id := sid.LocalStoreID() + return !id.IsZero() && bytes.Equal(round.GetExpectedStoreId(), id[:]) +} + // probeAnswer is this replica's evidence now, for round. func (h *Host) probeAnswer(round uint64) *control.ProbeAnswer { a := &control.ProbeAnswer{ServerId: h.cfg.ServerID, VolumeId: h.cfg.VolumeID, ReplicaId: h.cfg.ReplicaID, RoundId: round} diff --git a/seaweed-block/core/host/volume/probe_round_fence_test.go b/seaweed-block/core/host/volume/probe_round_fence_test.go new file mode 100644 index 0000000000..3fde3ed37b --- /dev/null +++ b/seaweed-block/core/host/volume/probe_round_fence_test.go @@ -0,0 +1,122 @@ +package volume + +import ( + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/replication" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// fenceListener is the replica listener as a fencing round sees it: its +// durable floor, raised by FenceFloor (or failing). +type fenceListener struct { + floor uint64 + fences []uint64 + failErr error +} + +func (f *fenceListener) FenceAsPrimary(uint64) error { return nil } +func (f *fenceListener) AdmitAsReplica(uint64) error { return nil } +func (f *fenceListener) FenceFloor(e uint64) error { + f.fences = append(f.fences, e) + if f.failErr != nil { + return f.failErr + } + if e > f.floor { + f.floor = e + } + return nil +} +func (f *fenceListener) DurableFloor() uint64 { return f.floor } + +// fenceEvidence is the replication slot: its store and its evidence, which +// records the floor it was read under (the read must follow the fence). +type fenceEvidence struct { + id storage.StoreID + ln *fenceListener + end uint64 + readsAt []uint64 // the listener's floor at each evidence read +} + +func (e *fenceEvidence) UpdateReplicaSet(uint64, []replication.ReplicaTarget) error { return nil } +func (e *fenceEvidence) LocalStoreID() storage.StoreID { return e.id } +func (e *fenceEvidence) LocalPrimaryEvidence() (replication.EpochTableStatus, uint64, error) { + e.readsAt = append(e.readsAt, e.ln.floor) + return replication.EpochTableStatus{}, e.end, nil +} + +func fenceHost(t *testing.T) (*Host, *fenceListener, *fenceEvidence) { + t.Helper() + h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "s2", VolumeID: "v1", ReplicaID: "r2", DataAddr: "127.0.0.1:19303", CtrlAddr: "127.0.0.1:19304", EnableT1Readiness: true}) + if err != nil { + t.Fatal(err) + } + ln := &fenceListener{floor: 3} + if err := h.SetSelfFence(ln); err != nil { + t.Fatal(err) + } + ev := &fenceEvidence{id: storage.StoreID{7, 7, 7}, ln: ln, end: 42} + h.replicationMu.Lock() + h.replication = ev + h.replicationMu.Unlock() + return h, ln, ev +} + +// A fencing round naming this store: the floor is raised and durable +// BEFORE the evidence is read, and the answer carries that floor and the end +// read under it (the model's fence-before shape; reading first is the +// violating fence-after shape). +func TestFencingRoundRaisesTheFloorBeforeTheEvidence(t *testing.T) { + h, ln, ev := fenceHost(t) + a, ok := h.roundAnswer(&control.ProbeRound{VolumeId: "v1", ReplicaId: "r2", RoundId: 9, FenceEpoch: 4, ExpectedStoreId: ev.id[:]}) + if !ok { + t.Fatal("a completed fence was not answered") + } + if len(ln.fences) != 1 || ln.fences[0] != 4 { + t.Fatalf("fences %v, want one at 4", ln.fences) + } + if len(ev.readsAt) != 1 || ev.readsAt[0] != 4 { + t.Fatalf("evidence read under floor %v; want read once, after the floor reached 4", ev.readsAt) + } + if a.GetFloor() != 4 || a.GetRoundId() != 9 || a.GetDurableEnd() != 42 || string(a.GetStoreId()) != string(ev.id[:]) { + t.Fatalf("answer %+v; want round 9, floor 4, end 42, this store", a) + } +} + +// A fencing round naming another store raises nothing; its answer carries +// the unchanged floor, which the master does not count. +func TestFencingRoundForAnotherStoreRaisesNothing(t *testing.T) { + h, ln, _ := fenceHost(t) + other := storage.StoreID{9} + a, ok := h.roundAnswer(&control.ProbeRound{VolumeId: "v1", ReplicaId: "r2", RoundId: 10, FenceEpoch: 4, ExpectedStoreId: other[:]}) + if !ok || len(ln.fences) != 0 || a.GetFloor() != 3 { + t.Fatalf("answered=%t fences=%v floor=%d; want an answer at the unchanged floor 3 and no fence", ok, ln.fences, a.GetFloor()) + } + if _, ok := h.roundAnswer(&control.ProbeRound{VolumeId: "v1", ReplicaId: "r2", RoundId: 11, FenceEpoch: 4}); !ok || len(ln.fences) != 0 { + t.Fatalf("a fencing round without an expected store fenced: %v", ln.fences) + } +} + +// A fence that fails (drain timeout, floor not durable) is not answered: no +// promise was made, so none may be counted. +func TestFailedFenceIsNotAnswered(t *testing.T) { + h, ln, ev := fenceHost(t) + ln.failErr = errors.New("floor record not written") + if a, ok := h.roundAnswer(&control.ProbeRound{VolumeId: "v1", ReplicaId: "r2", RoundId: 12, FenceEpoch: 4, ExpectedStoreId: ev.id[:]}); ok { + t.Fatalf("a failed fence was answered: %+v", a) + } + if len(ev.readsAt) != 0 { + t.Fatal("the evidence was read for a round whose fence failed") + } +} + +// A plain round (fence_epoch 0) raises nothing and reports the floor. +func TestPlainRoundRaisesNothing(t *testing.T) { + h, ln, ev := fenceHost(t) + a, ok := h.roundAnswer(&control.ProbeRound{VolumeId: "v1", ReplicaId: "r2", RoundId: 13, ExpectedStoreId: ev.id[:]}) + if !ok || len(ln.fences) != 0 || a.GetFloor() != 3 || a.GetDurableEnd() != 42 { + t.Fatalf("plain round: answered=%t fences=%v answer=%+v", ok, ln.fences, a) + } +} diff --git a/seaweed-block/core/transport/fence_floor_test.go b/seaweed-block/core/transport/fence_floor_test.go new file mode 100644 index 0000000000..88b1d27a8c --- /dev/null +++ b/seaweed-block/core/transport/fence_floor_test.go @@ -0,0 +1,127 @@ +package transport + +import ( + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// The replica's half of a fencing round: FenceFloor(e+1) is a durable +// promise. From its return nothing below e+1 is applied or ACKed, across a +// restart; a failed round heals by the same primary's line re-issued at e+1. +func TestFenceFloor_PromiseRefusesBelowAndSurvivesRestart(t *testing.T) { + store := storage.NewBlockStore(16, 4096) + floor := g1Fresh(t) + ln := g1Listener(t, store, floor) + if err := ln.AdmitAsReplica(3); err != nil { + t.Fatal(err) + } + if !g1Ship(t, ln, store, g1Lineage(1, 3), 1, 'a') || !g1Barrier(t, ln, g1Lineage(1, 3)) { + t.Fatal("fixture: the epoch-3 primary's ship and barrier were refused before the fence") + } + if err := ln.FenceFloor(4); err != nil { + t.Fatal(err) + } + if got := ln.DurableFloor(); got != 4 || g1Persisted(t, floor) != 4 { + t.Fatalf("after the fence: durable floor %d, record %d; want 4", got, g1Persisted(t, floor)) + } + // the model's violating row: the old primary acknowledged after the promise + if g1Barrier(t, ln, g1Lineage(2, 3)) { + t.Fatal("an epoch-3 barrier was ACKed after the replica promised floor 4") + } + if g1Ship(t, ln, store, g1Lineage(3, 3), 2, 'b') || g1Rebuild(t, ln, store, g1Lineage(4, 3), 'r') { + t.Fatal("an epoch-3 mutation was applied after the replica promised floor 4") + } + ln.StopHard() + + restarted := g1Listener(t, store, floor) + if err := restarted.AdmitAsReplica(3); err != nil { // the stale line, again + t.Fatal(err) + } + if g1Barrier(t, restarted, g1Lineage(5, 3)) || g1Ship(t, restarted, store, g1Lineage(6, 3), 3, 'c') { + t.Fatal("after a restart the replica took the epoch-3 primary below its promised floor 4") + } + // closure: the round failed, the master re-issues the same primary at 4 + if err := restarted.AdmitAsReplica(4); err != nil { + t.Fatal(err) + } + if !g1Ship(t, restarted, store, g1Lineage(7, 4), 4, 'd') || !g1Barrier(t, restarted, g1Lineage(7, 4)) { + t.Fatal("the line re-issued at the fenced epoch 4 was refused: a failed round would degrade the volume for ever") + } +} + +// A ship admitted before the fence is still applying when FenceFloor is +// called: the promise is not made until it has applied, so it can never +// apply (or ACK) after the replica answered. +func TestFenceFloor_WaitsForAMutationAlreadyPastTheGate(t *testing.T) { + listener, store := g2PausedShip(t) + type result struct { + at time.Time + err error + } + fenced := make(chan result, 1) + go func() { + err := listener.FenceFloor(2) + fenced <- result{time.Now(), err} + }() + select { + case r := <-fenced: + close(store.release) + t.Fatalf("FenceFloor returned (err=%v) while an admitted epoch-1 ship was still applying", r.err) + case <-time.After(300 * time.Millisecond): + } + // a new epoch-1 frame is refused at once, while the fence drains + old := RecoveryLineage{SessionID: 5, Epoch: 1, EndpointVersion: 1, TargetLSN: 1} + if !g2Refused(t, listener.Addr(), MsgShipEntry, g2ShipPayload(old, 2)) { + close(store.release) + t.Fatal("a new epoch-1 ship was admitted while the floor-2 fence was draining") + } + close(store.release) + appliedAt := <-store.applied + select { + case r := <-fenced: + if r.err != nil { + t.Fatalf("fence: %v", r.err) + } + if r.at.Before(appliedAt) { + t.Fatalf("FenceFloor returned %v before the in-flight apply finished", appliedAt.Sub(r.at)) + } + case <-time.After(5 * time.Second): + t.Fatal("FenceFloor never returned after the in-flight apply finished") + } +} + +// A fence whose floor cannot be made durable is an error: no promise, the +// record keeps the old floor (a restart is not bound), while this process +// keeps refusing below the fence epoch. A fence never lowers the floor. +func TestFenceFloor_PersistFailureMakesNoPromise(t *testing.T) { + other := g1Listener(t, storage.NewBlockStore(16, 4096), g1Fresh(t)) + if err := other.AdmitAsReplica(5); err != nil { + t.Fatal(err) + } + if err := other.FenceFloor(4); err != nil { + t.Fatal(err) + } + if got := other.DurableFloor(); got != 5 { + t.Fatalf("a fence at 4 over floor 5: durable floor %d, want 5 (never lowered)", got) + } + + store := storage.NewBlockStore(16, 4096) + floor := g1Fresh(t) + ln := g1Listener(t, store, floor) + if err := ln.AdmitAsReplica(3); err != nil { + t.Fatal(err) + } + failAt(t, ln, "write") + if err := ln.FenceFloor(4); err == nil { + t.Fatal("FenceFloor returned nil though the floor record could not be written") + } + if got := ln.DurableFloor(); got != 3 || g1Persisted(t, floor) != 3 { + t.Fatalf("after a failed fence: durable floor %d, record %d; want 3", got, g1Persisted(t, floor)) + } + if g1Barrier(t, ln, g1Lineage(1, 3)) { + t.Fatal("after a failed fence the epoch-3 barrier was ACKed") + } + +} diff --git a/seaweed-block/core/transport/replica.go b/seaweed-block/core/transport/replica.go index f0b9090abb..4243a4a5bd 100644 --- a/seaweed-block/core/transport/replica.go +++ b/seaweed-block/core/transport/replica.go @@ -786,9 +786,43 @@ func (r *ReplicaListener) FenceAsPrimary(epoch uint64) error { } func (r *ReplicaListener) fenceAndDrain(epoch uint64) error { + return r.floorAndDrain(epoch, true) +} + +// FenceFloor is this replica's half of a fencing round (the ack fence): its +// promise that nothing below epoch is applied or acknowledged any more, +// durable before it returns. Order: the floor in memory first (every new +// frame below epoch is refused at once), then the drain of every mutation +// admitted before it (none of them applies or ACKs after the promise), then +// the floor persisted. A drain timeout or a persist error is returned and the +// caller must not answer the round (no promise was made); frames below epoch +// stay refused. The role is unchanged: a line re-issued at epoch to the same +// primary (a failed round's heal) is admitted by AdmitAsReplica as usual. +func (r *ReplicaListener) FenceFloor(epoch uint64) error { + if err := r.floorAndDrain(epoch, false); err != nil { + return err + } + return r.raiseFloor(epoch) +} + +// DurableFloor is the floor persisted in the volume's floor record (in +// memory for a listener without one): the epoch below which this replica +// has promised to apply and acknowledge nothing. +func (r *ReplicaListener) DurableFloor() uint64 { + r.floorMu.Lock() + defer r.floorMu.Unlock() + return r.persisted +} + +// floorAndDrain raises the in-memory floor to epoch (and, for a primary +// fence, refuses every mutation), then waits until no mutation admitted +// before it is still in flight. +func (r *ReplicaListener) floorAndDrain(epoch uint64, primary bool) error { r.mu.Lock() defer r.mu.Unlock() - r.primary = true + if primary { + r.primary = true + } if epoch > r.epochFloor { r.epochFloor = epoch } @@ -812,7 +846,7 @@ func (r *ReplicaListener) fenceAndDrain(epoch uint64) error { drained.Wait() } if r.inFlight > 0 { - return fmt.Errorf("replica listener: %d replication mutation(s) still in flight %v after fencing as primary at epoch %d", r.inFlight, timeout, epoch) + return fmt.Errorf("replica listener: %d replication mutation(s) still in flight %v after fencing at epoch %d", r.inFlight, timeout, epoch) } return nil }