From 9fccb4024725d1791e89fe846b2d051bc68b8580 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 17:04:18 -0800 Subject: [PATCH 01/12] test(master): RF3 sync_quorum manual failover decides on the fencing round (red) Co-Authored-By: Claude Opus 5.5 --- .../host/master/manual_failover_fence_test.go | 168 ++++++++++++++++++ 1 file changed, 168 insertions(+) create mode 100644 seaweed-block/core/host/master/manual_failover_fence_test.go diff --git a/seaweed-block/core/host/master/manual_failover_fence_test.go b/seaweed-block/core/host/master/manual_failover_fence_test.go new file mode 100644 index 0000000000..4e26bd8129 --- /dev/null +++ b/seaweed-block/core/host/master/manual_failover_fence_test.go @@ -0,0 +1,168 @@ +package master + +import ( + "context" + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/authority" +) + +// ackedFenceProbe is a fenceProbe that reports its ack profile, as the +// round provider does (plannedMoveEvidence reads it). +type ackedFenceProbe struct{ *fenceProbe } + +func (p ackedFenceProbe) AckProfile() string { return p.plain.AckProfile } + +// rf3LineOnR1 is a master whose RF3 volume's line is on r1, bound by a +// product tick. +func rf3LineOnR1(t *testing.T) (*Host, authority.AuthorityBasis) { + t.Helper() + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3}) + h.SetPromotionEvidenceProvider(staticPromotionProbe{result: PromotionProbeResult{ + AckProfile: "sync_quorum", + Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 1}, {ReplicaID: "r3", Ready: true, DurableLSN: 1}}, + }}) + seedRF3PlacementForServersWithAddrs(t, h, "vol-rf3", "node-a", "node-b", "node-c") + ingestRF3Observation(t, h, true, true, true) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("initial product tick: %v", err) + } + line := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + if line.ReplicaID != "r1" { + t.Fatalf("initial line=%+v want r1", line) + } + return h, line +} + +func failoverTo(h *Host, current authority.AuthorityBasis, target string) error { + addr := map[string][2]string{"r2": {"127.0.0.1:19201", "127.0.0.1:19202"}, "r3": {"127.0.0.1:19301", "127.0.0.1:19302"}}[target] + _, err := h.FailbackAuthorityRuntime().ExecuteFailback(context.Background(), authority.FailbackRuntimeRequest{ + VolumeID: "vol-rf3", ReplicaID: target, TargetDataAddr: addr[0], TargetCtrlAddr: addr[1], + ExpectedCurrentReplicaID: current.ReplicaID, ExpectedCurrentEpoch: current.Epoch, + AckEligible: true, FrontendFencedBeforeFailback: true, DurableFrontierCovered: true, NoCrossVolumeIdentityChange: true, + }) + return err +} + +// The operator's failover of an RF3 sync_quorum volume (its primary +// powered off: no answer) needs no seal: it runs the fencing round, and the +// decision is the round's (Fence model Open/Answer/Decide). Survivors answer +// at floor e+1, both of them (N-K+1 = 2), so the old primary can no longer +// collect an acknowledgement; the target must hold the highest fenced end and +// be ready; the published line carries basis Fenced at e+1. Anything less +// publishes nothing and leaves the fence pending, so a returning primary is +// healed at e+1 (the product loop's heal). +func TestManualFailoverRF3SyncQuorumDecidesOnTheFencingRound(t *testing.T) { + plain := PromotionProbeResult{AckProfile: "sync_quorum", SyncAckKnown: true, Candidates: []PromotionCandidateEvidence{ + {ReplicaID: "r2", Ready: true, DurableLSN: 10}, + {ReplicaID: "r3", Ready: true, DurableLSN: 9}, + }} + at := func(r string, lsn uint64, floorAbove uint64, ready bool) PromotionCandidateEvidence { + return PromotionCandidateEvidence{ReplicaID: r, Ready: ready, DurableLSN: lsn, Floor: floorAbove, TableValid: true} + } + for _, c := range []struct { + name string + target string + fenced func(e uint64) func(authority.AuthorityBasis, []PromotionCandidateEvidence) (PromotionProbeResult, error) + want uint64 // the promoted line's evidence LSN; 0 = refused + }{ + {"both fenced; the target holds the highest fenced end", "r3", + func(e uint64) func(authority.AuthorityBasis, []PromotionCandidateEvidence) (PromotionProbeResult, error) { + return fencedAs(at("r2", 10, e+1, true), at("r3", 12, e+1, true)) + }, 12}, + {"the target is below the other survivor's fenced end", "r2", + func(e uint64) func(authority.AuthorityBasis, []PromotionCandidateEvidence) (PromotionProbeResult, error) { + return fencedAs(at("r2", 10, e+1, true), at("r3", 12, e+1, true)) + }, 0}, + {"one survivor silent: too few fenced answers", "r2", + func(e uint64) func(authority.AuthorityBasis, []PromotionCandidateEvidence) (PromotionProbeResult, error) { + return fencedAs(at("r2", 10, e+1, true)) + }, 0}, + {"one answered at a higher floor (superseded): not counted", "r2", + func(e uint64) func(authority.AuthorityBasis, []PromotionCandidateEvidence) (PromotionProbeResult, error) { + return fencedAs(at("r2", 10, e+1, true), at("r3", 9, e+2, true)) + }, 0}, + {"the target holds the highest end but is not ready", "r3", + func(e uint64) func(authority.AuthorityBasis, []PromotionCandidateEvidence) (PromotionProbeResult, error) { + return fencedAs(at("r2", 10, e+1, true), at("r3", 12, e+1, false)) + }, 0}, + {"the fencing round failed", "r2", + func(uint64) func(authority.AuthorityBasis, []PromotionCandidateEvidence) (PromotionProbeResult, error) { + return func(authority.AuthorityBasis, []PromotionCandidateEvidence) (PromotionProbeResult, error) { + return PromotionProbeResult{}, errors.New("no stream") + } + }, 0}, + } { + t.Run(c.name, func(t *testing.T) { + h, line := rf3LineOnR1(t) + defer closeTestMaster(t, h) + p := &fenceProbe{plain: plain, fenced: c.fenced(line.Epoch)} + h.SetPromotionEvidenceProvider(ackedFenceProbe{p}) + + err := failoverTo(h, line, c.target) + if len(p.survivors) != 2 { + t.Fatalf("fenced %v; want both survivors r2, r3 fenced before any decision", p.survivors) + } + after, _ := h.Publisher().VolumeAuthorityLine("vol-rf3") + if c.want == 0 { + if err == nil || after != line { + t.Fatalf("err=%v line=%+v; want refused, line %+v unchanged", err, after, line) + } + if !h.pendingFence("vol-rf3", line.Epoch) { + t.Fatal("a refused fenced failover left no pending fence: a returning primary would not be healed at e+1") + } + return + } + if err != nil { + t.Fatalf("failover to %s: %v", c.target, err) + } + if after.ReplicaID != c.target || after.Epoch != line.Epoch+1 { + t.Fatalf("line=%+v; want %s at %d", after, c.target, line.Epoch+1) + } + }) + } +} + +// The evidence the fenced failover hands the publisher: kind PROMOTION, +// basis Fenced, the round's epoch (e+1), the target's fenced end. +func TestManualFailoverRF3EvidenceIsTheFencingRounds(t *testing.T) { + h, line := rf3LineOnR1(t) + defer closeTestMaster(t, h) + p := &fenceProbe{ + plain: PromotionProbeResult{AckProfile: "sync_quorum", SyncAckKnown: true, Candidates: []PromotionCandidateEvidence{ + {ReplicaID: "r2", Ready: true, DurableLSN: 10}, {ReplicaID: "r3", Ready: true, DurableLSN: 12}}}, + fenced: fencedAs( + PromotionCandidateEvidence{ReplicaID: "r2", Ready: true, DurableLSN: 10, Floor: line.Epoch + 1, TableValid: true}, + PromotionCandidateEvidence{ReplicaID: "r3", Ready: true, DurableLSN: 12, Floor: line.Epoch + 1, TableValid: true}), + } + h.SetPromotionEvidenceProvider(ackedFenceProbe{p}) + ev, err := h.plannedMoveEvidence("vol-rf3", "r3") + if err != nil { + t.Fatal(err) + } + if ev.Kind != adapter.PrimaryKindPromotion || ev.Basis != adapter.BasisFenced || ev.FencedEpoch != line.Epoch+1 || ev.DurableLSN != 12 { + t.Fatalf("evidence %+v; want PROMOTION, basis fenced at %d, end 12", ev, line.Epoch+1) + } +} + +// An RF2 sync_quorum failover stays a planned move (its target is in every +// acknowledgement set): no fencing round, basis Planned. +func TestManualFailoverRF2SyncQuorumStaysPlanned(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 2}) + defer closeTestMaster(t, h) + seedRF2Placement(t, h) + p := &fenceProbe{ + plain: PromotionProbeResult{AckProfile: "sync_quorum", SyncAckKnown: true, Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 5}}}, + fenced: fencedAs(), + } + h.SetPromotionEvidenceProvider(ackedFenceProbe{p}) + ev, err := h.plannedMoveEvidence("vol-rf2", "r2") + if err != nil { + t.Fatal(err) + } + if ev.Basis != adapter.BasisPlanned || ev.FencedEpoch != 0 || len(p.survivors) != 0 { + t.Fatalf("evidence %+v fenced=%v; want a planned move with no fencing round", ev, p.survivors) + } +} From 8058cad9e5c02049d4e60f7607b6749ad740afcc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 17:05:26 -0800 Subject: [PATCH 02/12] fix(master): RF3 sync_quorum manual failover runs the fencing round A planned move of an RF3 sync_quorum volume needs a seal (its target is not in every acknowledgement set), so the operator's failover was refused and a volume whose primary host is lost could not be moved at all. The fencing round is that seal: the failover now fences every other replica at the line's next epoch and publishes only on the round's decision (enough fenced survivors; the target holds the highest fenced end and is ready), with basis Fenced. A refused round leaves the fence pending so a returning primary is continued at e+1. RF2 and sync_all stay planned moves. Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/planned_move.go | 48 +++++++++++++++++++ .../host/master/planned_move_paths_test.go | 14 ++++-- seaweed-block/deploy/k8s/alpha/README.md | 2 +- seaweed-block/docs/design/invariants.md | 2 +- 4 files changed, 61 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/host/master/planned_move.go b/seaweed-block/core/host/master/planned_move.go index f80f9a47d0..6a270f6604 100644 --- a/seaweed-block/core/host/master/planned_move.go +++ b/seaweed-block/core/host/master/planned_move.go @@ -3,10 +3,12 @@ package master import ( "errors" "fmt" + "sort" "strings" "github.com/seaweedfs/seaweed-block/core/adapter" "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/lifecycle" ) // ErrPlannedMoveNeedsSeal: under this ack profile and replica count a write @@ -72,6 +74,9 @@ func (h *Host) plannedMoveEvidence(volumeID, target string) (adapter.PrimaryEvid } } if err := plannedMoveAllowed(profile, len(placement.Slots)); err != nil { + if errors.Is(err, ErrPlannedMoveNeedsSeal) { + return h.fencedMoveEvidence(volumeID, target, profile, placement.Slots) + } return adapter.PrimaryEvidence{}, err } result, err := prober.ProbePromotionCandidates(volumeID, authority.AuthorityBasis{}, []authority.ReplicaCandidate{{ReplicaID: target, ServerID: targetServer}}) @@ -87,3 +92,46 @@ func (h *Host) plannedMoveEvidence(volumeID, target string) (adapter.PrimaryEvid } return adapter.PrimaryEvidence{}, fmt.Errorf("planned move: replica %s did not answer the probe round ready (caught up, epoch table valid)", target) } + +// fencedMoveEvidence is the operator's move where a planned move needs a seal +// (the target is not in every acknowledgement set: RF3 sync_quorum). The +// fencing round is that seal: every other replica is fenced at the line's +// next epoch, so the old primary, dead or alive, can no longer collect an +// acknowledgement, and the decision is read from the round alone +// (fencedDecision: enough counted answers, the target holds the highest +// fenced end and is ready). A round that does not allow the target publishes +// nothing and leaves the fence pending, so a primary that answers again is +// continued at e+1 (healAfterFailedFence) by the product loop. +func (h *Host) fencedMoveEvidence(volumeID, target, profile string, slots []lifecycle.PlacementSlotIntent) (adapter.PrimaryEvidence, error) { + current, ok := h.Publisher().VolumeAuthorityLine(volumeID) + if !ok { + return adapter.PrimaryEvidence{}, fmt.Errorf("fenced move: volume %s has no authority line", volumeID) + } + h.promotionMu.RLock() + prober := h.promotionProber + h.promotionMu.RUnlock() + var candidates []authority.ReplicaCandidate + for _, s := range slots { + if s.ReplicaID != current.ReplicaID { + candidates = append(candidates, authority.ReplicaCandidate{ReplicaID: s.ReplicaID, ServerID: s.ServerID}) + } + } + plain, err := prober.ProbePromotionCandidates(volumeID, current, candidates) + if err != nil { + return adapter.PrimaryEvidence{}, fmt.Errorf("fenced move: probe round: %w", err) + } + if plain.AckProfile == "" { + plain.AckProfile = profile + } + fenced, allowed := h.fencedDecision(volumeID, current, plain, len(candidates)) + if allowed[target] { + return promotionEvidenceFor(fenced, target), nil + } + h.noteFencePending(volumeID, current.Epoch+1) + others := make([]string, 0, len(allowed)) + for r := range allowed { + others = append(others, r) + } + sort.Strings(others) + return adapter.PrimaryEvidence{}, fmt.Errorf("fenced move: the fencing round at epoch %d does not allow %s (allowed: %v): it must hold the highest fenced end and be ready, with enough fenced survivors", current.Epoch+1, target, others) +} diff --git a/seaweed-block/core/host/master/planned_move_paths_test.go b/seaweed-block/core/host/master/planned_move_paths_test.go index 86bc59771a..830fd67add 100644 --- a/seaweed-block/core/host/master/planned_move_paths_test.go +++ b/seaweed-block/core/host/master/planned_move_paths_test.go @@ -1,6 +1,7 @@ package master import ( + "errors" "fmt" "testing" @@ -11,7 +12,8 @@ import ( // passes one guard: a failback (plannedMoveEvidence) and a rebalance (the // gate's PlannedMoveAllowed on the slot, which the controller requires) are // allowed exactly when plannedMoveAllowed holds for the volume's ack profile -// and replica count. One row per profile x RF; each row checks both paths. +// and replica count; where it refuses for want of a seal, the failback +// takes the fencing round instead. One row per profile x RF; each row checks both paths. func TestPlannedMoveOneGuardForFailbackAndRebalance(t *testing.T) { for _, profile := range []string{"sync_all", "sync_quorum", "best_effort"} { for _, rf := range []int{2, 3} { @@ -39,9 +41,15 @@ func TestPlannedMoveOneGuardForFailbackAndRebalance(t *testing.T) { Candidates: candidates, }}) - // Failback. + // Failback. Where a planned move needs a seal (RF3 + // sync_quorum), the failback runs the fencing round instead + // (manual_failover_fence_test.go); the rebalance stays refused. _, err := h.plannedMoveEvidence(vol, "r2") - if (err == nil) != want { + if errors.Is(plannedMoveAllowed(profile, rf), ErrPlannedMoveNeedsSeal) { + if errors.Is(err, ErrPlannedMoveNeedsSeal) { + t.Fatalf("failback to r2 refused for want of a seal; want the fencing round: %v", err) + } + } else if (err == nil) != want { t.Fatalf("failback to r2: err=%v; want allowed=%t", err, want) } diff --git a/seaweed-block/deploy/k8s/alpha/README.md b/seaweed-block/deploy/k8s/alpha/README.md index b63fe8efd8..cbc6344153 100644 --- a/seaweed-block/deploy/k8s/alpha/README.md +++ b/seaweed-block/deploy/k8s/alpha/README.md @@ -210,7 +210,7 @@ This alpha MVP does not yet claim: - production-ready durability - multi-node Kubernetes operation - failover while a pod remains mounted -- automatic failover when the primary node or pod is lost: blockmaster does not reassign on a primary it cannot read; failover is a manual admin action (a `SwBlockReplicaFailback` with the expected current line, applied for the failback executor, which calls blockmaster's admin `ExecuteFailback`) +- automatic failover when the primary node or pod is lost: blockmaster does not reassign on a primary it cannot read; failover is a manual admin action (a `SwBlockReplicaFailback` with the expected current line, applied for the failback executor, which calls blockmaster's admin `ExecuteFailback`); for an RF3 `sync_quorum` volume that failover runs the fencing round first and moves only to a ready replica holding the highest fenced end - real operator reconciliation - backend data shredding on delete - snapshots, clone, resize, block mode, topology spread, or NVMe-oF diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 6cab6100a2..c04a95be00 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -946,7 +946,7 @@ Notes: | `INV-FENCE-STALE-PRIMARY-001` | Once a primary has observed a newer line for another replica, its backend refuses `Read`, `Write` and `Sync`, and replicas refuse its frames below their epoch floor. | M3 Primary → Supporting \| Excluded | `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/frontend/durable/storage_adapter.go` `lineageCheck`; `core/transport/replica.go` `admitMutation` | `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | `ReplicationFailover` `NoStaleAck` | ACTIVE | | `INV-PROMOTE-FRONTIER-001` | With a known required acknowledgement frontier under `sync_quorum` or `sync_all`, the RF=3 promotion gate allows only probed-ready candidates whose durable LSN is at least the required LSN. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `applyPromotionEvidenceGate`; `core/host/master/probe_round.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe` (`core/host/master/product_loop_test.go`); `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | | `INV-PROMOTE-FRONTIER-PROBE-001` | For a replicated volume (two or more slots), the gate allows no candidate unless this tick's promotion probe succeeded with a known ack profile. | M3 Supporting → promotion candidate (the gate, RF=2 and up) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas` | `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe` (`core/host/master/product_loop_test.go`); `TestMountedFailover_ProductLoopRF2DecidesOnThePromotionGate` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | -| `INV-PROMOTE-UNKNOWN-CURRENT-001` | A current primary whose status cannot be read (probe refused, timed out, pod gone) is unknown, never failed: no promotion path reassigns on it; a direct reassign needs the primary's own not-ready report. | M3 Primary → promotion candidate (both promotion paths) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate` (supported path), `applyUnsupportedPromotionEvidenceGate` (unsupported path) | `TestUnsupportedPathNeverReassignsOnAnUnansweredPrimary` (`core/host/master/primary_boot_grace_gate_test.go`); `TestMountedFailover_ProductLoopRF3DoesNotReassignWhenCurrentSlotMissing` (`core/host/master/product_loop_test.go`). Limits: Kubernetes alpha failover on node or pod loss is a manual admin action in this release | — | ACTIVE | +| `INV-PROMOTE-UNKNOWN-CURRENT-001` | A current primary whose status cannot be read (probe refused, timed out, pod gone) is unknown, never failed: no promotion path reassigns on it; a direct reassign needs the primary's own not-ready report. | M3 Primary → promotion candidate (both promotion paths) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate` (supported path), `applyUnsupportedPromotionEvidenceGate` (unsupported path) | `TestUnsupportedPathNeverReassignsOnAnUnansweredPrimary` (`core/host/master/primary_boot_grace_gate_test.go`); `TestMountedFailover_ProductLoopRF3DoesNotReassignWhenCurrentSlotMissing` (`core/host/master/product_loop_test.go`). Limits: Kubernetes alpha failover on node or pod loss is a manual admin action in this release; the admin's failover of an RF3 `sync_quorum` volume (a planned move there needs a seal) runs the fencing round and publishes only on its decision (`core/host/master/planned_move.go` `fencedMoveEvidence`, basis Fenced; `TestManualFailoverRF3SyncQuorumDecidesOnTheFencingRound`) | — | ACTIVE | | `INV-PROMOTE-FRONTIER-UNKNOWN-001` | With an unknown frontier under `sync_quorum` or `sync_all`, the gate allows the highest-durable ready candidate only if at least N_peers-K+1 of the N_peers peers are probed ready this tick and have a fresh heartbeat (K as in `waitForSyncAcks`); else none. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/replication/async_ack.go` `waitForSyncAcks` | `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | | `INV-PROMOTE-FRONTIER-BEST-EFFORT-001` | Under `best_effort`, the gate allows no candidate when a nonzero required frontier is given, and otherwise allows the highest-durable ready candidate. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas` | `TestMountedFailover_ProductLoopRF3BestEffortUnknownRequiredLSNCanSelectHighestDurableLSN`, `TestMountedFailover_ProductLoopRF3RejectsBestEffortProbeForHA` (`core/host/master/product_loop_test.go`); `TestPromotionAllowedReplicas_RequiredFrontierCoverage` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | | `INV-CSI-CONSUMES-AUTHORITY-001` | CSI never imports authority code or builds assignment facts; it takes the publish target from blockmaster and refreshes it before a stage, and blockmaster mints the IDs of the events CSI reports. | M2 (read side) | `core/csi/master_backend.go` `LookupPublishTarget`; `core/csi/node.go` `refreshPublishContext`; `core/host/master/observation_service.go` `ReportClusterEvent` | `TestG15a_CSI_DoesNotImportAuthorityOrConstructAssignmentFacts` (`core/csi/boundary_guard_test.go`); `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestObservationService_ReportClusterEventAppearsInVolumeTimeline` (`core/host/master/observation_service_test.go`) | — | ACTIVE | From 6db8fbd8cf2f29307c07f30fcc9129d08c93a78a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 17:12:07 -0800 Subject: [PATCH 03/12] test(master): RF2 manual failover of an unreachable primary decides on the fencing round (red) Co-Authored-By: Claude Opus 5.5 --- .../host/master/manual_failover_fence_test.go | 123 +++++++++++++++++- 1 file changed, 118 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/host/master/manual_failover_fence_test.go b/seaweed-block/core/host/master/manual_failover_fence_test.go index 4e26bd8129..65f7822222 100644 --- a/seaweed-block/core/host/master/manual_failover_fence_test.go +++ b/seaweed-block/core/host/master/manual_failover_fence_test.go @@ -37,9 +37,13 @@ func rf3LineOnR1(t *testing.T) (*Host, authority.AuthorityBasis) { } func failoverTo(h *Host, current authority.AuthorityBasis, target string) error { + return failoverVolumeTo(h, "vol-rf3", current, target) +} + +func failoverVolumeTo(h *Host, volumeID string, current authority.AuthorityBasis, target string) error { addr := map[string][2]string{"r2": {"127.0.0.1:19201", "127.0.0.1:19202"}, "r3": {"127.0.0.1:19301", "127.0.0.1:19302"}}[target] _, err := h.FailbackAuthorityRuntime().ExecuteFailback(context.Background(), authority.FailbackRuntimeRequest{ - VolumeID: "vol-rf3", ReplicaID: target, TargetDataAddr: addr[0], TargetCtrlAddr: addr[1], + VolumeID: volumeID, ReplicaID: target, TargetDataAddr: addr[0], TargetCtrlAddr: addr[1], ExpectedCurrentReplicaID: current.ReplicaID, ExpectedCurrentEpoch: current.Epoch, AckEligible: true, FrontendFencedBeforeFailback: true, DurableFrontierCovered: true, NoCrossVolumeIdentityChange: true, }) @@ -147,12 +151,121 @@ func TestManualFailoverRF3EvidenceIsTheFencingRounds(t *testing.T) { } } -// An RF2 sync_quorum failover stays a planned move (its target is in every -// acknowledgement set): no fencing round, basis Planned. -func TestManualFailoverRF2SyncQuorumStaysPlanned(t *testing.T) { +// rf2LineOnR1 is a master whose RF2 volume's line is on r1, bound by a +// product tick under the given ack profile. +func rf2LineOnR1(t *testing.T, profile string) (*Host, authority.AuthorityBasis) { + t.Helper() h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 2}) - defer closeTestMaster(t, h) + h.SetPromotionEvidenceProvider(staticPromotionProbe{result: PromotionProbeResult{ + AckProfile: profile, + Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 1}}, + }}) seedRF2Placement(t, h) + ingestRF2Observation(t, h, true, true) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("initial product tick: %v", err) + } + line := waitAuthorityLine(t, h.Publisher(), "vol-rf2") + if line.ReplicaID != "r1" { + t.Fatalf("initial line=%+v want r1", line) + } + return h, line +} + +// The operator's failover of an RF2 volume whose primary is unreachable (its +// host powered off: no fresh heartbeat) is decided on the fencing round too, +// one path with RF3 (Fence model Open/Answer/Decide; the count is a +// parameter: RF2 needs the one survivor's answer). The survivor must answer +// at floor e+1, on a valid table, ready; the line carries basis Fenced at +// e+1. Anything less publishes nothing and leaves the fence pending. +func TestManualFailoverRF2UnreachablePrimaryDecidesOnTheFencingRound(t *testing.T) { + for _, profile := range []string{"sync_quorum", "sync_all"} { + for _, c := range []struct { + name string + survivor func(e uint64) PromotionCandidateEvidence + fail bool + promoted bool + }{ + {"the survivor fenced at e+1, ready", func(e uint64) PromotionCandidateEvidence { + return PromotionCandidateEvidence{ReplicaID: "r2", Ready: true, DurableLSN: 5, Floor: e + 1, TableValid: true} + }, false, true}, + {"the survivor answered at a higher floor (superseded)", func(e uint64) PromotionCandidateEvidence { + return PromotionCandidateEvidence{ReplicaID: "r2", Ready: true, DurableLSN: 5, Floor: e + 2, TableValid: true} + }, false, false}, + {"the survivor is not ready", func(e uint64) PromotionCandidateEvidence { + return PromotionCandidateEvidence{ReplicaID: "r2", DurableLSN: 5, Floor: e + 1, TableValid: true} + }, false, false}, + {"the survivor's table is invalid", func(e uint64) PromotionCandidateEvidence { + return PromotionCandidateEvidence{ReplicaID: "r2", Ready: true, DurableLSN: 5, Floor: e + 1, TableInvalid: true} + }, false, false}, + {"the fencing round failed", nil, true, false}, + } { + t.Run(profile+"/"+c.name, func(t *testing.T) { + h, line := rf2LineOnR1(t, profile) + defer closeTestMaster(t, h) + ingestRF2Observation(t, h, false, true) // r1's host is gone + p := &fenceProbe{plain: PromotionProbeResult{AckProfile: profile, SyncAckKnown: true, Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 5}}}} + if c.fail { + p.fenced = func(authority.AuthorityBasis, []PromotionCandidateEvidence) (PromotionProbeResult, error) { + return PromotionProbeResult{}, errors.New("no stream") + } + } else { + p.fenced = fencedAs(c.survivor(line.Epoch)) + } + h.SetPromotionEvidenceProvider(ackedFenceProbe{p}) + + if c.promoted { + ev, err := h.plannedMoveEvidence("vol-rf2", "r2") + if err != nil || ev.Basis != adapter.BasisFenced || ev.FencedEpoch != line.Epoch+1 || ev.DurableLSN != 5 { + t.Fatalf("evidence %+v err=%v; want basis fenced at %d, end 5", ev, err, line.Epoch+1) + } + } + err := failoverVolumeTo(h, "vol-rf2", line, "r2") + if len(p.survivors) == 0 || p.survivors[len(p.survivors)-1] != "r2" { + t.Fatalf("fenced %v; want the survivor r2 fenced before any decision", p.survivors) + } + after, _ := h.Publisher().VolumeAuthorityLine("vol-rf2") + if !c.promoted { + if err == nil || after != line { + t.Fatalf("err=%v line=%+v; want refused, line %+v unchanged", err, after, line) + } + if !h.pendingFence("vol-rf2", line.Epoch) { + t.Fatal("a refused fenced failover left no pending fence") + } + return + } + if err != nil || after.ReplicaID != "r2" || after.Epoch != line.Epoch+1 { + t.Fatalf("err=%v line=%+v; want r2 at %d", err, after, line.Epoch+1) + } + }) + } + } +} + +// best_effort acknowledges a write without any replica, so no round can +// prove the survivor holds every acknowledged write: the operator's failover +// of an unreachable best_effort primary is refused (never basis Fenced), +// and no fencing round runs. +func TestManualFailoverRF2BestEffortIsNeverFenced(t *testing.T) { + h, line := rf2LineOnR1(t, "best_effort") + defer closeTestMaster(t, h) + ingestRF2Observation(t, h, false, true) + p := &fenceProbe{ + plain: PromotionProbeResult{AckProfile: "best_effort", Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 5}}}, + fenced: fencedAs(PromotionCandidateEvidence{ReplicaID: "r2", Ready: true, DurableLSN: 5, Floor: line.Epoch + 1, TableValid: true}), + } + h.SetPromotionEvidenceProvider(ackedFenceProbe{p}) + if _, err := h.plannedMoveEvidence("vol-rf2", "r2"); !errors.Is(err, ErrPlannedMoveBestEffort) || len(p.survivors) != 0 { + t.Fatalf("err=%v fenced=%v; want ErrPlannedMoveBestEffort and no fencing round", err, p.survivors) + } +} + +// An RF2 sync_quorum failover from a reachable primary stays a planned move +// (its target is in every acknowledgement set): no fencing round, basis +// Planned. +func TestManualFailoverRF2ReachablePrimaryStaysPlanned(t *testing.T) { + h, _ := rf2LineOnR1(t, "sync_quorum") + defer closeTestMaster(t, h) p := &fenceProbe{ plain: PromotionProbeResult{AckProfile: "sync_quorum", SyncAckKnown: true, Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 5}}}, fenced: fencedAs(), From 43ccf9456e4e27d74d97d9b2342f98790c03bdae Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 17:12:18 -0800 Subject: [PATCH 04/12] fix(master): manual failover of an unreachable primary runs the fencing round at every replica count An operator failover whose primary has no fresh, reachable heartbeat (a lost host) is no planned move from a live primary: it is now decided on the fencing round for RF2 as for RF3 (one path, basis Fenced). A failover from a reachable RF2 primary stays planned; best_effort stays refused. Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/planned_move.go | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/host/master/planned_move.go b/seaweed-block/core/host/master/planned_move.go index 6a270f6604..647ce0739a 100644 --- a/seaweed-block/core/host/master/planned_move.go +++ b/seaweed-block/core/host/master/planned_move.go @@ -79,6 +79,12 @@ func (h *Host) plannedMoveEvidence(volumeID, target string) (adapter.PrimaryEvid } return adapter.PrimaryEvidence{}, err } + // The primary is unreachable (a lost host stops heartbeating): the move + // is the operator's failover, not a planned move from a live primary, and + // it is decided on the fencing round at every replica count. + if h.primaryUnreachable(volumeID) { + return h.fencedMoveEvidence(volumeID, target, profile, placement.Slots) + } result, err := prober.ProbePromotionCandidates(volumeID, authority.AuthorityBasis{}, []authority.ReplicaCandidate{{ReplicaID: target, ServerID: targetServer}}) if err != nil { return adapter.PrimaryEvidence{}, fmt.Errorf("planned move: probe round: %w", err) @@ -93,8 +99,20 @@ func (h *Host) plannedMoveEvidence(volumeID, target string) (adapter.PrimaryEvid return adapter.PrimaryEvidence{}, fmt.Errorf("planned move: replica %s did not answer the probe round ready (caught up, epoch table valid)", target) } +// primaryUnreachable: the line's primary has no fresh, reachable heartbeat +// slot. A volume without a line has no primary to lose. +func (h *Host) primaryUnreachable(volumeID string) bool { + current, ok := h.Publisher().VolumeAuthorityLine(volumeID) + if !ok { + return false + } + slot, fresh := h.freshCurrentSlot(volumeID, current.ReplicaID) + return !fresh || !slot.Reachable +} + // fencedMoveEvidence is the operator's move where a planned move needs a seal -// (the target is not in every acknowledgement set: RF3 sync_quorum). The +// (the target is not in every acknowledgement set: RF3 sync_quorum), or +// whose primary is unreachable (the operator's failover, any count). The // fencing round is that seal: every other replica is fenced at the line's // next epoch, so the old primary, dead or alive, can no longer collect an // acknowledgement, and the decision is read from the round alone From 2a146a90cd1cc02f6a27e0f4e75d1cb154f3979c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 17:17:14 -0800 Subject: [PATCH 05/12] docs: the manual failover's fencing round in INV-PROMOTE-UNKNOWN-CURRENT-001 and the alpha README Co-Authored-By: Claude Opus 5.5 --- seaweed-block/deploy/k8s/alpha/README.md | 2 +- seaweed-block/docs/design/invariants.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/deploy/k8s/alpha/README.md b/seaweed-block/deploy/k8s/alpha/README.md index cbc6344153..9fc2631fb7 100644 --- a/seaweed-block/deploy/k8s/alpha/README.md +++ b/seaweed-block/deploy/k8s/alpha/README.md @@ -210,7 +210,7 @@ This alpha MVP does not yet claim: - production-ready durability - multi-node Kubernetes operation - failover while a pod remains mounted -- automatic failover when the primary node or pod is lost: blockmaster does not reassign on a primary it cannot read; failover is a manual admin action (a `SwBlockReplicaFailback` with the expected current line, applied for the failback executor, which calls blockmaster's admin `ExecuteFailback`); for an RF3 `sync_quorum` volume that failover runs the fencing round first and moves only to a ready replica holding the highest fenced end +- automatic failover when the primary node or pod is lost: blockmaster does not reassign on a primary it cannot read; failover is a manual admin action (a `SwBlockReplicaFailback` with the expected current line, applied for the failback executor, which calls blockmaster's admin `ExecuteFailback`); when the primary is unreachable, and for any RF3 `sync_quorum` move, that failover runs the fencing round first and moves only to a ready replica holding the highest fenced end (a `best_effort` volume is refused) - real operator reconciliation - backend data shredding on delete - snapshots, clone, resize, block mode, topology spread, or NVMe-oF diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index c04a95be00..d52e921ba1 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -946,7 +946,7 @@ Notes: | `INV-FENCE-STALE-PRIMARY-001` | Once a primary has observed a newer line for another replica, its backend refuses `Read`, `Write` and `Sync`, and replicas refuse its frames below their epoch floor. | M3 Primary → Supporting \| Excluded | `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/frontend/durable/storage_adapter.go` `lineageCheck`; `core/transport/replica.go` `admitMutation` | `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | `ReplicationFailover` `NoStaleAck` | ACTIVE | | `INV-PROMOTE-FRONTIER-001` | With a known required acknowledgement frontier under `sync_quorum` or `sync_all`, the RF=3 promotion gate allows only probed-ready candidates whose durable LSN is at least the required LSN. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `applyPromotionEvidenceGate`; `core/host/master/probe_round.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe` (`core/host/master/product_loop_test.go`); `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | | `INV-PROMOTE-FRONTIER-PROBE-001` | For a replicated volume (two or more slots), the gate allows no candidate unless this tick's promotion probe succeeded with a known ack profile. | M3 Supporting → promotion candidate (the gate, RF=2 and up) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas` | `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe` (`core/host/master/product_loop_test.go`); `TestMountedFailover_ProductLoopRF2DecidesOnThePromotionGate` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | -| `INV-PROMOTE-UNKNOWN-CURRENT-001` | A current primary whose status cannot be read (probe refused, timed out, pod gone) is unknown, never failed: no promotion path reassigns on it; a direct reassign needs the primary's own not-ready report. | M3 Primary → promotion candidate (both promotion paths) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate` (supported path), `applyUnsupportedPromotionEvidenceGate` (unsupported path) | `TestUnsupportedPathNeverReassignsOnAnUnansweredPrimary` (`core/host/master/primary_boot_grace_gate_test.go`); `TestMountedFailover_ProductLoopRF3DoesNotReassignWhenCurrentSlotMissing` (`core/host/master/product_loop_test.go`). Limits: Kubernetes alpha failover on node or pod loss is a manual admin action in this release; the admin's failover of an RF3 `sync_quorum` volume (a planned move there needs a seal) runs the fencing round and publishes only on its decision (`core/host/master/planned_move.go` `fencedMoveEvidence`, basis Fenced; `TestManualFailoverRF3SyncQuorumDecidesOnTheFencingRound`) | — | ACTIVE | +| `INV-PROMOTE-UNKNOWN-CURRENT-001` | A current primary whose status cannot be read (probe refused, timed out, pod gone) is unknown, never failed: no promotion path reassigns on it; a direct reassign needs the primary's own not-ready report. | M3 Primary → promotion candidate (both promotion paths) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate` (supported path), `applyUnsupportedPromotionEvidenceGate` (unsupported path) | `TestUnsupportedPathNeverReassignsOnAnUnansweredPrimary` (`core/host/master/primary_boot_grace_gate_test.go`); `TestMountedFailover_ProductLoopRF3DoesNotReassignWhenCurrentSlotMissing` (`core/host/master/product_loop_test.go`). Limits: Kubernetes alpha failover on node or pod loss is a manual admin action in this release; the admin's failover runs the fencing round and publishes only on its decision (basis Fenced) when the primary is unreachable (any replica count) or a planned move needs a seal (RF3 `sync_quorum`); `best_effort` stays refused (`core/host/master/planned_move.go` `fencedMoveEvidence`; `TestManualFailoverRF3SyncQuorumDecidesOnTheFencingRound`, `TestManualFailoverRF2UnreachablePrimaryDecidesOnTheFencingRound`, `TestManualFailoverRF2BestEffortIsNeverFenced`) | — | ACTIVE | | `INV-PROMOTE-FRONTIER-UNKNOWN-001` | With an unknown frontier under `sync_quorum` or `sync_all`, the gate allows the highest-durable ready candidate only if at least N_peers-K+1 of the N_peers peers are probed ready this tick and have a fresh heartbeat (K as in `waitForSyncAcks`); else none. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/replication/async_ack.go` `waitForSyncAcks` | `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | | `INV-PROMOTE-FRONTIER-BEST-EFFORT-001` | Under `best_effort`, the gate allows no candidate when a nonzero required frontier is given, and otherwise allows the highest-durable ready candidate. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas` | `TestMountedFailover_ProductLoopRF3BestEffortUnknownRequiredLSNCanSelectHighestDurableLSN`, `TestMountedFailover_ProductLoopRF3RejectsBestEffortProbeForHA` (`core/host/master/product_loop_test.go`); `TestPromotionAllowedReplicas_RequiredFrontierCoverage` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | | `INV-CSI-CONSUMES-AUTHORITY-001` | CSI never imports authority code or builds assignment facts; it takes the publish target from blockmaster and refreshes it before a stage, and blockmaster mints the IDs of the events CSI reports. | M2 (read side) | `core/csi/master_backend.go` `LookupPublishTarget`; `core/csi/node.go` `refreshPublishContext`; `core/host/master/observation_service.go` `ReportClusterEvent` | `TestG15a_CSI_DoesNotImportAuthorityOrConstructAssignmentFacts` (`core/csi/boundary_guard_test.go`); `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestObservationService_ReportClusterEventAppearsInVolumeTimeline` (`core/host/master/observation_service_test.go`) | — | ACTIVE | From 45550928542c79923f79673aa2034da6721cc4ec Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 17:22:09 -0800 Subject: [PATCH 06/12] fix(master): fence only the failover of an unreachable primary; test the race with the promotion loop A reachable RF3 sync_quorum primary's move is a planned move again and stays refused for want of a seal; only the operator's failover of an unreachable primary is decided on the fencing round. Adds the test where the operator's failover and the master's promotion loop decide the same volume at once: both fence at the same next epoch, one line is published. Co-Authored-By: Claude Opus 5.5 --- .../host/master/manual_failover_fence_test.go | 104 +++++++++++++++++- .../core/host/master/planned_move.go | 22 ++-- .../host/master/planned_move_paths_test.go | 14 +-- seaweed-block/deploy/k8s/alpha/README.md | 2 +- seaweed-block/docs/design/invariants.md | 2 +- 5 files changed, 117 insertions(+), 27 deletions(-) diff --git a/seaweed-block/core/host/master/manual_failover_fence_test.go b/seaweed-block/core/host/master/manual_failover_fence_test.go index 65f7822222..e6ba2f9844 100644 --- a/seaweed-block/core/host/master/manual_failover_fence_test.go +++ b/seaweed-block/core/host/master/manual_failover_fence_test.go @@ -3,7 +3,9 @@ package master import ( "context" "errors" + "sync" "testing" + "time" "github.com/seaweedfs/seaweed-block/core/adapter" "github.com/seaweedfs/seaweed-block/core/authority" @@ -50,8 +52,9 @@ func failoverVolumeTo(h *Host, volumeID string, current authority.AuthorityBasis return err } -// The operator's failover of an RF3 sync_quorum volume (its primary -// powered off: no answer) needs no seal: it runs the fencing round, and the +// The operator's failover of an RF3 sync_quorum volume whose primary is +// unreachable (its host powered off: no fresh heartbeat) runs the fencing +// round, which is the seal a planned move there lacks, and the // decision is the round's (Fence model Open/Answer/Decide). Survivors answer // at floor e+1, both of them (N-K+1 = 2), so the old primary can no longer // collect an acknowledgement; the target must hold the highest fenced end and @@ -102,6 +105,7 @@ func TestManualFailoverRF3SyncQuorumDecidesOnTheFencingRound(t *testing.T) { t.Run(c.name, func(t *testing.T) { h, line := rf3LineOnR1(t) defer closeTestMaster(t, h) + ingestRF3Observation(t, h, false, true, true) // r1's host is gone p := &fenceProbe{plain: plain, fenced: c.fenced(line.Epoch)} h.SetPromotionEvidenceProvider(ackedFenceProbe{p}) @@ -134,6 +138,7 @@ func TestManualFailoverRF3SyncQuorumDecidesOnTheFencingRound(t *testing.T) { func TestManualFailoverRF3EvidenceIsTheFencingRounds(t *testing.T) { h, line := rf3LineOnR1(t) defer closeTestMaster(t, h) + ingestRF3Observation(t, h, false, true, true) p := &fenceProbe{ plain: PromotionProbeResult{AckProfile: "sync_quorum", SyncAckKnown: true, Candidates: []PromotionCandidateEvidence{ {ReplicaID: "r2", Ready: true, DurableLSN: 10}, {ReplicaID: "r3", Ready: true, DurableLSN: 12}}}, @@ -279,3 +284,98 @@ func TestManualFailoverRF2ReachablePrimaryStaysPlanned(t *testing.T) { t.Fatalf("evidence %+v fenced=%v; want a planned move with no fencing round", ev, p.survivors) } } + +// A reachable RF3 sync_quorum primary's move is a planned move, and a planned +// move there needs a seal v1 does not have: refused, with no fencing round. +// Only the failover of an unreachable primary is fenced. +func TestManualFailoverRF3ReachablePrimaryIsRefused(t *testing.T) { + h, line := rf3LineOnR1(t) + defer closeTestMaster(t, h) + p := &fenceProbe{ + plain: PromotionProbeResult{AckProfile: "sync_quorum", SyncAckKnown: true, Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 10}, {ReplicaID: "r3", Ready: true, DurableLSN: 12}}}, + fenced: fencedAs(), + } + h.SetPromotionEvidenceProvider(ackedFenceProbe{p}) + err := failoverTo(h, line, "r3") + if !errors.Is(err, ErrPlannedMoveNeedsSeal) || len(p.survivors) != 0 { + t.Fatalf("err=%v fenced=%v; want ErrPlannedMoveNeedsSeal and no fencing round", err, p.survivors) + } + if after, _ := h.Publisher().VolumeAuthorityLine("vol-rf3"); after != line { + t.Fatalf("line=%+v; want %+v unchanged", after, line) + } +} + +// meetingFenceProbe holds each fencing round until two have arrived (or a +// bound passes), so two callers decide the same volume at the same time. +type meetingFenceProbe struct { + *fenceProbe + mu sync.Mutex + arrived int + both chan struct{} +} + +func (p *meetingFenceProbe) FencePromotionCandidates(v string, current authority.AuthorityBasis, survivors []PromotionCandidateEvidence) (PromotionProbeResult, error) { + p.mu.Lock() + p.arrived++ + if p.arrived == 2 { + close(p.both) + } + p.mu.Unlock() + select { + case <-p.both: + case <-time.After(2 * time.Second): + } + p.mu.Lock() + defer p.mu.Unlock() + return p.fenceProbe.FencePromotionCandidates(v, current, survivors) +} + +func (p *meetingFenceProbe) AckProfile() string { return p.plain.AckProfile } + +// The operator's failover and the master's own promotion loop decide the +// same volume at once: both fence at the same next epoch and both allow the +// target, but exactly one line is published (the line's conditional update +// refuses the second), so the epoch moves once. +func TestManualFailoverAndThePromotionLoopPublishOneLine(t *testing.T) { + h, line := rf3LineOnR1(t) + defer closeTestMaster(t, h) + ingestRF3Observation(t, h, false, true, true) + e := line.Epoch + p := &meetingFenceProbe{both: make(chan struct{}), fenceProbe: &fenceProbe{ + // The primary answered not ready: the loop's own promotion applies. + plain: PromotionProbeResult{AckProfile: "sync_quorum", SyncAckKnown: true, CurrentKnown: true, + Current: PromotionCandidateEvidence{ReplicaID: "r1"}, + Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 10}, {ReplicaID: "r3", Ready: true, DurableLSN: 12}}}, + fenced: fencedAs( + PromotionCandidateEvidence{ReplicaID: "r2", Ready: true, DurableLSN: 10, Floor: e + 1, TableValid: true}, + PromotionCandidateEvidence{ReplicaID: "r3", Ready: true, DurableLSN: 12, Floor: e + 1, TableValid: true}), + }} + h.SetPromotionEvidenceProvider(p) + + var wg sync.WaitGroup + var opErr, loopErr error + wg.Add(2) + go func() { defer wg.Done(); opErr = failoverTo(h, line, "r3") }() + go func() { defer wg.Done(); _, loopErr = h.RunLifecycleProductTick() }() + wg.Wait() + if loopErr != nil { + t.Fatalf("product tick: %v", loopErr) + } + p.mu.Lock() + met := p.arrived + p.mu.Unlock() + if met < 2 { + t.Fatalf("%d fencing rounds; want both callers deciding at once", met) + } + after := waitAuthorityReplica(t, h.Publisher(), "vol-rf3", "r3") + deadline := time.Now().Add(500 * time.Millisecond) + for time.Now().Before(deadline) { + if cur, _ := h.Publisher().VolumeAuthorityLine("vol-rf3"); cur.Epoch != e+1 || cur.ReplicaID != "r3" { + t.Fatalf("line=%+v; want exactly one publication: r3 at %d (operator err=%v)", cur, e+1, opErr) + } + time.Sleep(20 * time.Millisecond) + } + if after.Epoch != e+1 { + t.Fatalf("line=%+v; want r3 at %d", after, e+1) + } +} diff --git a/seaweed-block/core/host/master/planned_move.go b/seaweed-block/core/host/master/planned_move.go index 647ce0739a..b764c1e990 100644 --- a/seaweed-block/core/host/master/planned_move.go +++ b/seaweed-block/core/host/master/planned_move.go @@ -73,17 +73,17 @@ func (h *Host) plannedMoveEvidence(volumeID, target string) (adapter.PrimaryEvid targetServer = s.ServerID } } - if err := plannedMoveAllowed(profile, len(placement.Slots)); err != nil { - if errors.Is(err, ErrPlannedMoveNeedsSeal) { - return h.fencedMoveEvidence(volumeID, target, profile, placement.Slots) - } - return adapter.PrimaryEvidence{}, err - } // The primary is unreachable (a lost host stops heartbeating): the move // is the operator's failover, not a planned move from a live primary, and - // it is decided on the fencing round at every replica count. - if h.primaryUnreachable(volumeID) { + // it is decided on the fencing round at every replica count, where the + // planned guard refuses only for want of a seal. A reachable primary's + // move stays a planned move under its guard. + if err := plannedMoveAllowed(profile, len(placement.Slots)); err != nil && !errors.Is(err, ErrPlannedMoveNeedsSeal) { + return adapter.PrimaryEvidence{}, err + } else if h.primaryUnreachable(volumeID) { return h.fencedMoveEvidence(volumeID, target, profile, placement.Slots) + } else if err != nil { + return adapter.PrimaryEvidence{}, err } result, err := prober.ProbePromotionCandidates(volumeID, authority.AuthorityBasis{}, []authority.ReplicaCandidate{{ReplicaID: target, ServerID: targetServer}}) if err != nil { @@ -110,10 +110,8 @@ func (h *Host) primaryUnreachable(volumeID string) bool { return !fresh || !slot.Reachable } -// fencedMoveEvidence is the operator's move where a planned move needs a seal -// (the target is not in every acknowledgement set: RF3 sync_quorum), or -// whose primary is unreachable (the operator's failover, any count). The -// fencing round is that seal: every other replica is fenced at the line's +// fencedMoveEvidence is the operator's failover of an unreachable primary, +// at any replica count. The fencing round seals the old primary: every other replica is fenced at the line's // next epoch, so the old primary, dead or alive, can no longer collect an // acknowledgement, and the decision is read from the round alone // (fencedDecision: enough counted answers, the target holds the highest diff --git a/seaweed-block/core/host/master/planned_move_paths_test.go b/seaweed-block/core/host/master/planned_move_paths_test.go index 830fd67add..86bc59771a 100644 --- a/seaweed-block/core/host/master/planned_move_paths_test.go +++ b/seaweed-block/core/host/master/planned_move_paths_test.go @@ -1,7 +1,6 @@ package master import ( - "errors" "fmt" "testing" @@ -12,8 +11,7 @@ import ( // passes one guard: a failback (plannedMoveEvidence) and a rebalance (the // gate's PlannedMoveAllowed on the slot, which the controller requires) are // allowed exactly when plannedMoveAllowed holds for the volume's ack profile -// and replica count; where it refuses for want of a seal, the failback -// takes the fencing round instead. One row per profile x RF; each row checks both paths. +// and replica count. One row per profile x RF; each row checks both paths. func TestPlannedMoveOneGuardForFailbackAndRebalance(t *testing.T) { for _, profile := range []string{"sync_all", "sync_quorum", "best_effort"} { for _, rf := range []int{2, 3} { @@ -41,15 +39,9 @@ func TestPlannedMoveOneGuardForFailbackAndRebalance(t *testing.T) { Candidates: candidates, }}) - // Failback. Where a planned move needs a seal (RF3 - // sync_quorum), the failback runs the fencing round instead - // (manual_failover_fence_test.go); the rebalance stays refused. + // Failback. _, err := h.plannedMoveEvidence(vol, "r2") - if errors.Is(plannedMoveAllowed(profile, rf), ErrPlannedMoveNeedsSeal) { - if errors.Is(err, ErrPlannedMoveNeedsSeal) { - t.Fatalf("failback to r2 refused for want of a seal; want the fencing round: %v", err) - } - } else if (err == nil) != want { + if (err == nil) != want { t.Fatalf("failback to r2: err=%v; want allowed=%t", err, want) } diff --git a/seaweed-block/deploy/k8s/alpha/README.md b/seaweed-block/deploy/k8s/alpha/README.md index 9fc2631fb7..8c4cb69c86 100644 --- a/seaweed-block/deploy/k8s/alpha/README.md +++ b/seaweed-block/deploy/k8s/alpha/README.md @@ -210,7 +210,7 @@ This alpha MVP does not yet claim: - production-ready durability - multi-node Kubernetes operation - failover while a pod remains mounted -- automatic failover when the primary node or pod is lost: blockmaster does not reassign on a primary it cannot read; failover is a manual admin action (a `SwBlockReplicaFailback` with the expected current line, applied for the failback executor, which calls blockmaster's admin `ExecuteFailback`); when the primary is unreachable, and for any RF3 `sync_quorum` move, that failover runs the fencing round first and moves only to a ready replica holding the highest fenced end (a `best_effort` volume is refused) +- automatic failover when the primary node or pod is lost: blockmaster does not reassign on a primary it cannot read; failover is a manual admin action (a `SwBlockReplicaFailback` with the expected current line, applied for the failback executor, which calls blockmaster's admin `ExecuteFailback`); when the primary is unreachable that failover runs the fencing round first and moves only to a ready replica holding the highest fenced end (a `best_effort` volume, and a reachable RF3 `sync_quorum` primary, are refused; the round stops the old primary's writes, not its reads, so confirm the old node is off or cut from its clients first) - real operator reconciliation - backend data shredding on delete - snapshots, clone, resize, block mode, topology spread, or NVMe-oF diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d52e921ba1..7a6eb833d1 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -946,7 +946,7 @@ Notes: | `INV-FENCE-STALE-PRIMARY-001` | Once a primary has observed a newer line for another replica, its backend refuses `Read`, `Write` and `Sync`, and replicas refuse its frames below their epoch floor. | M3 Primary → Supporting \| Excluded | `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/frontend/durable/storage_adapter.go` `lineageCheck`; `core/transport/replica.go` `admitMutation` | `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | `ReplicationFailover` `NoStaleAck` | ACTIVE | | `INV-PROMOTE-FRONTIER-001` | With a known required acknowledgement frontier under `sync_quorum` or `sync_all`, the RF=3 promotion gate allows only probed-ready candidates whose durable LSN is at least the required LSN. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `applyPromotionEvidenceGate`; `core/host/master/probe_round.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe` (`core/host/master/product_loop_test.go`); `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | | `INV-PROMOTE-FRONTIER-PROBE-001` | For a replicated volume (two or more slots), the gate allows no candidate unless this tick's promotion probe succeeded with a known ack profile. | M3 Supporting → promotion candidate (the gate, RF=2 and up) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas` | `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe` (`core/host/master/product_loop_test.go`); `TestMountedFailover_ProductLoopRF2DecidesOnThePromotionGate` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | -| `INV-PROMOTE-UNKNOWN-CURRENT-001` | A current primary whose status cannot be read (probe refused, timed out, pod gone) is unknown, never failed: no promotion path reassigns on it; a direct reassign needs the primary's own not-ready report. | M3 Primary → promotion candidate (both promotion paths) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate` (supported path), `applyUnsupportedPromotionEvidenceGate` (unsupported path) | `TestUnsupportedPathNeverReassignsOnAnUnansweredPrimary` (`core/host/master/primary_boot_grace_gate_test.go`); `TestMountedFailover_ProductLoopRF3DoesNotReassignWhenCurrentSlotMissing` (`core/host/master/product_loop_test.go`). Limits: Kubernetes alpha failover on node or pod loss is a manual admin action in this release; the admin's failover runs the fencing round and publishes only on its decision (basis Fenced) when the primary is unreachable (any replica count) or a planned move needs a seal (RF3 `sync_quorum`); `best_effort` stays refused (`core/host/master/planned_move.go` `fencedMoveEvidence`; `TestManualFailoverRF3SyncQuorumDecidesOnTheFencingRound`, `TestManualFailoverRF2UnreachablePrimaryDecidesOnTheFencingRound`, `TestManualFailoverRF2BestEffortIsNeverFenced`) | — | ACTIVE | +| `INV-PROMOTE-UNKNOWN-CURRENT-001` | A current primary whose status cannot be read (probe refused, timed out, pod gone) is unknown, never failed: no promotion path reassigns on it; a direct reassign needs the primary's own not-ready report. | M3 Primary → promotion candidate (both promotion paths) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate` (supported path), `applyUnsupportedPromotionEvidenceGate` (unsupported path) | `TestUnsupportedPathNeverReassignsOnAnUnansweredPrimary` (`core/host/master/primary_boot_grace_gate_test.go`); `TestMountedFailover_ProductLoopRF3DoesNotReassignWhenCurrentSlotMissing` (`core/host/master/product_loop_test.go`). Limits: Kubernetes alpha failover on node or pod loss is a manual admin action in this release; the admin's failover runs the fencing round and publishes only on its decision (basis Fenced) when the primary is unreachable (no fresh, reachable heartbeat; any replica count); a reachable RF3 `sync_quorum` primary's move stays refused (it needs a seal) and `best_effort` stays refused (`core/host/master/planned_move.go` `fencedMoveEvidence`; `TestManualFailoverRF3SyncQuorumDecidesOnTheFencingRound`, `TestManualFailoverRF2UnreachablePrimaryDecidesOnTheFencingRound`, `TestManualFailoverRF2BestEffortIsNeverFenced`, `TestManualFailoverRF3ReachablePrimaryIsRefused`, `TestManualFailoverAndThePromotionLoopPublishOneLine`) | — | ACTIVE | | `INV-PROMOTE-FRONTIER-UNKNOWN-001` | With an unknown frontier under `sync_quorum` or `sync_all`, the gate allows the highest-durable ready candidate only if at least N_peers-K+1 of the N_peers peers are probed ready this tick and have a fresh heartbeat (K as in `waitForSyncAcks`); else none. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/replication/async_ack.go` `waitForSyncAcks` | `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | | `INV-PROMOTE-FRONTIER-BEST-EFFORT-001` | Under `best_effort`, the gate allows no candidate when a nonzero required frontier is given, and otherwise allows the highest-durable ready candidate. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas` | `TestMountedFailover_ProductLoopRF3BestEffortUnknownRequiredLSNCanSelectHighestDurableLSN`, `TestMountedFailover_ProductLoopRF3RejectsBestEffortProbeForHA` (`core/host/master/product_loop_test.go`); `TestPromotionAllowedReplicas_RequiredFrontierCoverage` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | | `INV-CSI-CONSUMES-AUTHORITY-001` | CSI never imports authority code or builds assignment facts; it takes the publish target from blockmaster and refreshes it before a stage, and blockmaster mints the IDs of the events CSI reports. | M2 (read side) | `core/csi/master_backend.go` `LookupPublishTarget`; `core/csi/node.go` `refreshPublishContext`; `core/host/master/observation_service.go` `ReportClusterEvent` | `TestG15a_CSI_DoesNotImportAuthorityOrConstructAssignmentFacts` (`core/csi/boundary_guard_test.go`); `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestObservationService_ReportClusterEventAppearsInVolumeTimeline` (`core/host/master/observation_service_test.go`) | — | ACTIVE | From 7903ffaeb1aa0d78bdc8593844b79e740afb13c7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 17:28:26 -0800 Subject: [PATCH 07/12] test(master): a fenced failover's recovery: unpublished allowed round, unsupported-path heal (red) Co-Authored-By: Claude Opus 5.5 --- .../host/master/manual_failover_fence_test.go | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/seaweed-block/core/host/master/manual_failover_fence_test.go b/seaweed-block/core/host/master/manual_failover_fence_test.go index e6ba2f9844..6e135974ac 100644 --- a/seaweed-block/core/host/master/manual_failover_fence_test.go +++ b/seaweed-block/core/host/master/manual_failover_fence_test.go @@ -9,6 +9,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/adapter" "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/storage" ) // ackedFenceProbe is a fenceProbe that reports its ack profile, as the @@ -379,3 +380,76 @@ func TestManualFailoverAndThePromotionLoopPublishOneLine(t *testing.T) { t.Fatalf("line=%+v; want r3 at %d", after, e+1) } } + +// healedR1 is the line's own primary answering a heal round ready. +var healedR1 = PromotionProbeResult{CurrentKnown: true, Current: PromotionCandidateEvidence{ReplicaID: "r1", Ready: true, DurableLSN: 11, + LastDataEpoch: 1, LastDataFirstLSN: 1, StoreID: storage.StoreID{7}, TableValid: true}} + +// A fencing round the operator's failover allowed, whose publication then +// failed (here: the evidence is decided and never applied), has fenced the +// survivors above the line all the same. The fence is pending from the +// moment the round is attempted, so when the primary comes back the next +// tick continues it at e+1, without a ready survivor (they refuse it now). +func TestManualFailoverAllowedButUnpublishedFenceIsHealed(t *testing.T) { + h, line := rf3LineOnR1(t) + defer closeTestMaster(t, h) + ingestRF3Observation(t, h, false, true, true) + e := line.Epoch + p := &fenceProbe{ + plain: PromotionProbeResult{AckProfile: "sync_quorum", SyncAckKnown: true, Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 10}, {ReplicaID: "r3", Ready: true, DurableLSN: 12}}}, + fenced: fencedAs( + PromotionCandidateEvidence{ReplicaID: "r2", Ready: true, DurableLSN: 10, Floor: e + 1, TableValid: true}, + PromotionCandidateEvidence{ReplicaID: "r3", Ready: true, DurableLSN: 12, Floor: e + 1, TableValid: true}), + } + h.SetPromotionEvidenceProvider(ackedFenceProbe{p}) + if _, err := h.plannedMoveEvidence("vol-rf3", "r3"); err != nil { + t.Fatalf("the fenced failover was not allowed: %v", err) + } + // The publication failed: the line is still r1 at e. + if !h.pendingFence("vol-rf3", e) { + t.Fatal("an allowed fencing round left no pending fence") + } + p.heal = healedR1 + snap := rf3DeadPrimary() + snap.Volumes[0].Authority.Epoch = e + s := snap.Volumes[0].Slots + s[0].Reachable, s[0].ReadyForPrimary = true, true + s[1].ReadyForPrimary, s[2].ReadyForPrimary = false, false // fenced: they refuse r1 at e + _, _, asks := h.applyPromotionEvidenceGate(&snap) + if len(asks) != 1 || asks[0].ReplicaID != "r1" || asks[0].Evidence.Basis != adapter.BasisHeal || asks[0].Evidence.FencedEpoch != e+1 { + t.Fatalf("asks %+v; want r1 healed at %d", asks, e+1) + } +} + +// A refused operator failover leaves the fence pending; the primary then +// returns ready while another slot is still stale, so the volume is +// unsupported (partial inventory). The unsupported gate heals the line's own +// primary at e+1 before any candidate check, as the supported gate does. +func TestManualFailoverRefusedFenceIsHealedOnTheUnsupportedPath(t *testing.T) { + h, line := rf3LineOnR1(t) + defer closeTestMaster(t, h) + ingestRF3Observation(t, h, false, true, true) + e := line.Epoch + p := &fenceProbe{ + plain: PromotionProbeResult{AckProfile: "sync_quorum", SyncAckKnown: true, Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 10}, {ReplicaID: "r3", Ready: true, DurableLSN: 12}}}, + fenced: fencedAs( + PromotionCandidateEvidence{ReplicaID: "r2", Ready: true, DurableLSN: 10, Floor: e + 1, TableValid: true}, + PromotionCandidateEvidence{ReplicaID: "r3", Ready: true, DurableLSN: 12, Floor: e + 1, TableValid: true}), + } + h.SetPromotionEvidenceProvider(ackedFenceProbe{p}) + if err := failoverTo(h, line, "r2"); err == nil { + t.Fatal("a failover to the survivor below the highest fenced end was allowed") + } + // r1 is back and ready; r3's slot is stale. + ingestRF3ObservationForServersWithReady(t, h, "vol-rf3", "node-a", "node-b", "node-c", true, true, true, true, false, false) + p.plain = PromotionProbeResult{AckProfile: "sync_quorum", SyncAckKnown: true, CurrentKnown: true, Current: PromotionCandidateEvidence{ReplicaID: "r1", Ready: true}, + Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", DurableLSN: 10}}} + p.heal = healedR1 + report := authority.SupportabilityReport{Unsupported: map[string]authority.VolumeUnsupportedEvidence{ + "vol-rf3": {VolumeID: "vol-rf3", Reasons: []string{authority.ReasonPartialInventory}}, + }} + _, _, asks := h.applyUnsupportedPromotionEvidenceGate(h.Lifecycle().Placements.ListPlacements(), report, nil) + if len(asks) != 1 || asks[0].ReplicaID != "r1" || asks[0].Evidence.Basis != adapter.BasisHeal || asks[0].Evidence.FencedEpoch != e+1 { + t.Fatalf("asks %+v; want r1 healed at %d on the unsupported path", asks, e+1) + } +} From 17004151bf55a939db86407d55aecb33e126bada Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 17:28:56 -0800 Subject: [PATCH 08/12] fix(master): a fenced failover's fence is pending from the attempt; the unsupported gate heals it The operator's fencing round may fence survivors above the line whatever it decides, and an allowed decision may still fail to publish: the fence is now pending from the attempt until a line reaches its epoch. The unsupported gate continues the line's own primary at e+1 on a pending fence before any candidate check, as the supported gate does. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/master/planned_move.go | 5 ++++- seaweed-block/core/host/master/product_loop.go | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/host/master/planned_move.go b/seaweed-block/core/host/master/planned_move.go index b764c1e990..88469beda2 100644 --- a/seaweed-block/core/host/master/planned_move.go +++ b/seaweed-block/core/host/master/planned_move.go @@ -139,11 +139,14 @@ func (h *Host) fencedMoveEvidence(volumeID, target, profile string, slots []life if plain.AckProfile == "" { plain.AckProfile = profile } + // Pending from the attempt on: the round may fence survivors above the + // line whatever it decides, and an allowed decision may still fail to + // publish. It is forgotten once a line reaches that epoch. + h.noteFencePending(volumeID, current.Epoch+1) fenced, allowed := h.fencedDecision(volumeID, current, plain, len(candidates)) if allowed[target] { return promotionEvidenceFor(fenced, target), nil } - h.noteFencePending(volumeID, current.Epoch+1) others := make([]string, 0, len(allowed)) for r := range allowed { others = append(others, r) diff --git a/seaweed-block/core/host/master/product_loop.go b/seaweed-block/core/host/master/product_loop.go index 6b8a53ecdb..c5802f5d0d 100644 --- a/seaweed-block/core/host/master/product_loop.go +++ b/seaweed-block/core/host/master/product_loop.go @@ -525,6 +525,17 @@ func (h *Host) applyUnsupportedPromotionEvidenceGate(placements []lifecycle.Plac // and every start counts toward flap history (#128). The // promotion rules below are unchanged. h.recordCurrentBootFact(placement.VolumeID) + // A fencing round fenced survivors above this line and nothing was + // published (e.g. the operator's refused failover): continue the + // line's own primary at e+1 when it is back and answers ready, + // before any candidate check, as the supported gate does. + if line, ok := h.Publisher().VolumeAuthorityLine(placement.VolumeID); ok && line.Assigned && + h.pendingFence(placement.VolumeID, line.Epoch) && h.freshPrimaryAcceptable(placement.VolumeID, line.ReplicaID) { + if heal, healed := h.healAfterFailedFence(placement.VolumeID, line); healed { + directAsks = append(directAsks, heal) + continue + } + } if len(placement.Slots) < 2 || !placementIsConcreteExistingReplica(placement) || !unsupportedReasonsAllowPromotionProbe(evidence.Reasons) { continue } @@ -1066,6 +1077,13 @@ func (h *Host) recordCurrentBootFact(volumeID string) { // freshCurrentSlot returns the replica's own fresh heartbeat slot from // the observation store (server facts folded in). +// freshPrimaryAcceptable: the replica has a fresh heartbeat slot that is +// reachable, eligible and not withdrawn. +func (h *Host) freshPrimaryAcceptable(volumeID, replicaID string) bool { + s, ok := h.freshCurrentSlot(volumeID, replicaID) + return ok && s.Reachable && s.Eligible && !s.Withdrawn +} + func (h *Host) freshCurrentSlot(volumeID, replicaID string) (authority.ReplicaCandidate, bool) { if h.obs == nil { return authority.ReplicaCandidate{}, false From d4416a1e96e6e3f94de0f44f271c106da5e21130 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 17:34:46 -0800 Subject: [PATCH 09/12] docs: the operator's fenced failover in M3 (Part A) and the promotion diagram Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 1 + seaweed-block/docs/design/kubernetes-block-design.md | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7a6eb833d1..4d3c3aa67a 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -230,6 +230,7 @@ RF2 qualification limitation until ordered-live certification is wired (#297). S | any | role admission failed | the listener cannot be fenced or its floor cannot be persisted; the role is not adopted and the projection is not healthy | `core/host/volume/host.go` `latchRoleAdmission` | `INV-FENCE-FLOOR-DURABLE-001` | | (every inbound frame) | — | a mutating frame is refused on a primary, below the floor, or before a role is known; the rebuild port applies the same rules; a failed apply closes the connection | `core/transport/replica.go` `acceptMutationLineage`, `admitMutation`, `EnterDualLane`, `handleConn` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001`, `INV-REPL-REBUILD-PORT-FENCE-001`, `INV-REPL-APPLY-FAIL-001` | | Supporting | promotion candidate | no active recovery session; member, reachable, caught up, fenced at the current epoch, post-rebuild durable acknowledgement delivered; for RF=2 and up also a fresh probe and coverage of the required frontier: known, or proven by at least N_peers-K+1 fresh ready peers when it is unknown | `core/engine/promotion_ready.go` `BuildPromotionReadyFact`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-REPL-PROMOTION-READY-001`, `INV-PROMOTE-FRONTIER-001`, `INV-PROMOTE-FRONTIER-PROBE-001`, `INV-PROMOTE-FRONTIER-UNKNOWN-001` | +| Primary (unreachable) | another replica Primary at e+1 | the operator's failover (`ExecuteFailback`) of a line whose primary has no fresh, reachable heartbeat slot: the fence is pending from the attempt; the fencing round fences every other replica at e+1; only `fencedDecision`'s allowed target is published, basis Fenced at e+1, through the line's conditional update (a concurrent promotion-loop decision at the same epoch is refused); a refused or unpublished round is healed by either gate (the line's own primary continued at e+1); `best_effort` is refused, and a reachable RF3 `sync_quorum` primary's move stays refused (needs a seal) | `core/host/master/planned_move.go` `plannedMoveEvidence`, `primaryUnreachable`, `fencedMoveEvidence`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `applyUnsupportedPromotionEvidenceGate` | `INV-PROMOTE-UNKNOWN-CURRENT-001` | **Recovery observation and apply ordering.** A probe publishes its fresh boundaries before reachability, and each emitted recovery is prepared under the adapter mutex before the next event. Same-identity delayed probes retain completed durable R; missing probe boundaries remain unknown until a valid observation arrives. Every lane and session shares one replica-wide per-LBA applied-LSN map under the apply mutex; session close releases coverage only. Recovery skips stale data while advancing its own coverage; stale live data fails without advancing recovery coverage. diff --git a/seaweed-block/docs/design/kubernetes-block-design.md b/seaweed-block/docs/design/kubernetes-block-design.md index 4dfeeb2619..ab710d8a3b 100644 --- a/seaweed-block/docs/design/kubernetes-block-design.md +++ b/seaweed-block/docs/design/kubernetes-block-design.md @@ -210,7 +210,7 @@ The volume computes whether it may become primary; blockmaster decides; only the **RF=3 gate** (`core/host/master/promotion_probe.go`, `promotionAllowedReplicas`, `chooseAllowedPromotionTarget`): no promotion when the probe failed or is not installed, or the ack profile is unknown; a candidate is skipped when it is not `replica_ready` with a known frontier, or its durable LSN is below the required frontier. The decision is recorded as an ops event (`candidate_covers_required_frontier`, `candidate_frontier_behind`, `no_promotion_ready_candidate`). The required frontier per volume (`RequiredLSNByVolume`) is not set by `cmd/blockmaster` today, so the frontier is unknown and coverage is proven from the survivors instead: with `sync_quorum` or `sync_all`, the ready candidate with the highest durable LSN is promoted only when at least P-K+1 of the P peers are probed ready (known durable LSN) and have a fresh heartbeat, where K is the number of peer acks a write needs (`waitForSyncAcks`: P for `sync_all`, (P+1)/2 for `sync_quorum`). Any P-K+1 peers include one that holds every acknowledged write that their sampled frontiers represent. The probes of one tick are snapshots, not a fence: a primary that is still running can acknowledge after a sample was taken (for example, r3 reports 70 in a held probe response, the old primary then acknowledges 71, and r2 at 70 is still selected). That is the missing primary lease below (§12, #195). For RF=3 that is both peers under `sync_quorum` and one under `sync_all`; with fewer, nothing is promoted. An unknown frontier is never read as zero. `best_effort` is unchanged (§12). -**A current primary that does not answer is unknown, not failed.** When its status cannot be read (a pod gone, a partition), blockmaster does not reassign on either path, however ready the survivors: on a partition the primary may still be serving. Only the primary's own not-ready report moves the line automatically; otherwise failover is a manual admin action in this release. +**A current primary that does not answer is unknown, not failed.** When its status cannot be read (a pod gone, a partition), blockmaster does not reassign on either path, however ready the survivors: on a partition the primary may still be serving. Only the primary's own not-ready report moves the line automatically; otherwise failover is a manual admin action in this release. The admin's failover of an unreachable primary (no fresh, reachable heartbeat) is decided on the fencing round, at any replica count: every other replica is fenced at N+1, the target must hold the highest fenced end and be ready, and the line carries basis Fenced; a round that publishes nothing leaves the fence pending, and the line's own primary is continued at N+1 when it answers ready again. The round stops the old primary's writes, not its reads: confirm the old node is off or cut from its clients first. **What blocks a promotion:** any engine reason above; a current primary whose status cannot be read; `unhealthy_reason` set or withdrawn; an unreachable or ineligible server; boot grace still holding; a current primary whose probe is ready; a snapshot rejected for slot count; slots that changed while the probe ran. @@ -222,6 +222,8 @@ stateDiagram-v2 Suspect --> Blocked: no promotion-ready candidate Blocked --> Suspect: next product tick Suspect --> Reassigned: candidate chosen, IntentReassign + Suspect --> Reassigned: admin failover of an unreachable primary, fencing round allows the target (basis Fenced) + Suspect --> Serving: fencing round refused or unpublished, own primary answers ready (heal at N+1) Reassigned --> Serving: publisher persists epoch N+1, new primary fences and serves ``` From 0f2182b18997379d66da91d6eb90ddd0d0a37bba Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 17:43:19 -0800 Subject: [PATCH 10/12] test(master): the failover race barrier fails on timeout; recovery proven end to end through a store fault and a normal tick Co-Authored-By: Claude Opus 5.5 --- .../host/master/manual_failover_fence_test.go | 172 ++++++++++++++---- 1 file changed, 133 insertions(+), 39 deletions(-) diff --git a/seaweed-block/core/host/master/manual_failover_fence_test.go b/seaweed-block/core/host/master/manual_failover_fence_test.go index 6e135974ac..b7872db085 100644 --- a/seaweed-block/core/host/master/manual_failover_fence_test.go +++ b/seaweed-block/core/host/master/manual_failover_fence_test.go @@ -3,6 +3,9 @@ package master import ( "context" "errors" + "os" + "path/filepath" + "strings" "sync" "testing" "time" @@ -306,12 +309,16 @@ func TestManualFailoverRF3ReachablePrimaryIsRefused(t *testing.T) { } } -// meetingFenceProbe holds each fencing round until two have arrived (or a -// bound passes), so two callers decide the same volume at the same time. +// meetingFenceProbe holds each fencing round until two have arrived, so two +// callers decide the same volume at the same time. A caller that waits past +// the bound gets an error (no decision) and marks the probe late: the test +// then fails, it never proceeds with one caller alone. type meetingFenceProbe struct { *fenceProbe mu sync.Mutex arrived int + late bool + bound time.Duration both chan struct{} } @@ -324,7 +331,11 @@ func (p *meetingFenceProbe) FencePromotionCandidates(v string, current authority p.mu.Unlock() select { case <-p.both: - case <-time.After(2 * time.Second): + case <-time.After(p.bound): + p.mu.Lock() + p.late = true + p.mu.Unlock() + return PromotionProbeResult{}, errors.New("meetingFenceProbe: the other caller did not arrive") } p.mu.Lock() defer p.mu.Unlock() @@ -342,7 +353,7 @@ func TestManualFailoverAndThePromotionLoopPublishOneLine(t *testing.T) { defer closeTestMaster(t, h) ingestRF3Observation(t, h, false, true, true) e := line.Epoch - p := &meetingFenceProbe{both: make(chan struct{}), fenceProbe: &fenceProbe{ + p := &meetingFenceProbe{both: make(chan struct{}), bound: 5 * time.Second, fenceProbe: &fenceProbe{ // The primary answered not ready: the loop's own promotion applies. plain: PromotionProbeResult{AckProfile: "sync_quorum", SyncAckKnown: true, CurrentKnown: true, Current: PromotionCandidateEvidence{ReplicaID: "r1"}, @@ -363,10 +374,10 @@ func TestManualFailoverAndThePromotionLoopPublishOneLine(t *testing.T) { t.Fatalf("product tick: %v", loopErr) } p.mu.Lock() - met := p.arrived + met, late := p.arrived, p.late p.mu.Unlock() - if met < 2 { - t.Fatalf("%d fencing rounds; want both callers deciding at once", met) + if met != 2 || late { + t.Fatalf("%d fencing rounds, late=%t; want both callers held together before either decided", met, late) } after := waitAuthorityReplica(t, h.Publisher(), "vol-rf3", "r3") deadline := time.Now().Add(500 * time.Millisecond) @@ -381,16 +392,92 @@ func TestManualFailoverAndThePromotionLoopPublishOneLine(t *testing.T) { } } +// The barrier's negative control: with one caller only, the round is refused +// at the bound and the probe is marked late, so a test that relies on two +// callers held together cannot pass with one. +func TestMeetingFenceProbeFailsWhenTheOtherCallerIsLate(t *testing.T) { + p := &meetingFenceProbe{both: make(chan struct{}), bound: 50 * time.Millisecond, fenceProbe: &fenceProbe{fenced: fencedAs()}} + if _, err := p.FencePromotionCandidates("v", authority.AuthorityBasis{Epoch: 1}, nil); err == nil || !p.late { + t.Fatalf("err=%v late=%t; want a refusal and late", err, p.late) + } +} + +// storeFault makes every authority record write of one volume fail (a +// directory where the store writes the record's temp file; open fails +// before any rename, as a full or failing disk would) until cleared. +func storeFault(t *testing.T, h *Host, volumeID string) (arm, clear func()) { + t.Helper() + var record string + matches, _ := filepath.Glob(filepath.Join(h.cfg.AuthorityStoreDir, volumeID+".*")) + for _, m := range matches { + if !strings.HasSuffix(m, ".tmp") { + record = m + } + } + if record == "" { + t.Fatalf("no authority record for %s in %s (%v)", volumeID, h.cfg.AuthorityStoreDir, matches) + } + tmp := record + ".tmp" + arm = func() { + if err := os.Mkdir(tmp, 0o700); err != nil { + t.Fatal(err) + } + } + clear = func() { _ = os.Remove(tmp) } + t.Cleanup(clear) + return arm, clear +} + +// waitLine polls until the volume's line is replica at epoch, else fails. +func waitLine(t *testing.T, h *Host, volumeID, replica string, epoch uint64) { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for { + cur, _ := h.Publisher().VolumeAuthorityLine(volumeID) + if cur.ReplicaID == replica && cur.Epoch == epoch { + return + } + if time.Now().After(deadline) { + t.Fatalf("line=%+v; want %s at %d", cur, replica, epoch) + } + time.Sleep(20 * time.Millisecond) + } +} + // healedR1 is the line's own primary answering a heal round ready. var healedR1 = PromotionProbeResult{CurrentKnown: true, Current: PromotionCandidateEvidence{ReplicaID: "r1", Ready: true, DurableLSN: 11, LastDataEpoch: 1, LastDataFirstLSN: 1, StoreID: storage.StoreID{7}, TableValid: true}} -// A fencing round the operator's failover allowed, whose publication then -// failed (here: the evidence is decided and never applied), has fenced the -// survivors above the line all the same. The fence is pending from the -// moment the round is attempted, so when the primary comes back the next -// tick continues it at e+1, without a ready survivor (they refuse it now). -func TestManualFailoverAllowedButUnpublishedFenceIsHealed(t *testing.T) { +// back puts r1 back ready and the fenced survivors not ready for primary +// (they refuse r1 at e); with r3Missing its server reports no slot for the +// volume (a partial inventory: the volume is unsupported). +func back(t *testing.T, h *Host, r3Missing bool) { + t.Helper() + now := time.Now().UTC() + slot := func(r, d, c string, ready bool) []authority.SlotFact { + return []authority.SlotFact{{VolumeID: "vol-rf3", ReplicaID: r, DataAddr: d, CtrlAddr: c, Reachable: true, ReadyForPrimary: ready, Eligible: true, EvidenceScore: 10}} + } + r3 := slot("r3", "127.0.0.1:19301", "127.0.0.1:19302", false) + if r3Missing { + r3 = nil + } + for _, obs := range []authority.Observation{ + {ServerID: "node-a", ObservedAt: now, Server: authority.ServerFact{Reachable: true, Eligible: true}, Slots: slot("r1", "127.0.0.1:19101", "127.0.0.1:19102", true)}, + {ServerID: "node-b", ObservedAt: now, Server: authority.ServerFact{Reachable: true, Eligible: true}, Slots: slot("r2", "127.0.0.1:19201", "127.0.0.1:19202", false)}, + {ServerID: "node-c", ObservedAt: now, Server: authority.ServerFact{Reachable: true, Eligible: true}, Slots: r3}, + } { + if err := h.ObservationHost().Ingest(obs); err != nil { + t.Fatal(err) + } + } +} + +// End to end: the operator's failover is allowed by its fencing round, and +// the publication fails (the authority store refuses the write). The line is +// still r1 at e, but its survivors are fenced at e+1. When r1 is back, a +// normal product tick publishes r1 at e+1 (the heal, through the same +// dispatch as every tick), and a further tick adds no epoch. +func TestManualFailoverPublicationFailureIsHealedByTheNextTick(t *testing.T) { h, line := rf3LineOnR1(t) defer closeTestMaster(t, h) ingestRF3Observation(t, h, false, true, true) @@ -402,30 +489,35 @@ func TestManualFailoverAllowedButUnpublishedFenceIsHealed(t *testing.T) { PromotionCandidateEvidence{ReplicaID: "r3", Ready: true, DurableLSN: 12, Floor: e + 1, TableValid: true}), } h.SetPromotionEvidenceProvider(ackedFenceProbe{p}) - if _, err := h.plannedMoveEvidence("vol-rf3", "r3"); err != nil { - t.Fatalf("the fenced failover was not allowed: %v", err) + arm, clear := storeFault(t, h, "vol-rf3") + arm() + if err := failoverTo(h, line, "r3"); err == nil { + t.Fatal("the failover published through a failing authority store") } - // The publication failed: the line is still r1 at e. - if !h.pendingFence("vol-rf3", e) { - t.Fatal("an allowed fencing round left no pending fence") + clear() + if cur, _ := h.Publisher().VolumeAuthorityLine("vol-rf3"); cur != line || len(p.survivors) != 2 { + t.Fatalf("after the fault line=%+v fenced=%v; want %+v unchanged and both survivors fenced", cur, p.survivors, line) } + + back(t, h, false) p.heal = healedR1 - snap := rf3DeadPrimary() - snap.Volumes[0].Authority.Epoch = e - s := snap.Volumes[0].Slots - s[0].Reachable, s[0].ReadyForPrimary = true, true - s[1].ReadyForPrimary, s[2].ReadyForPrimary = false, false // fenced: they refuse r1 at e - _, _, asks := h.applyPromotionEvidenceGate(&snap) - if len(asks) != 1 || asks[0].ReplicaID != "r1" || asks[0].Evidence.Basis != adapter.BasisHeal || asks[0].Evidence.FencedEpoch != e+1 { - t.Fatalf("asks %+v; want r1 healed at %d", asks, e+1) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) } + waitLine(t, h, "vol-rf3", "r1", e+1) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } + time.Sleep(200 * time.Millisecond) + waitLine(t, h, "vol-rf3", "r1", e+1) } -// A refused operator failover leaves the fence pending; the primary then -// returns ready while another slot is still stale, so the volume is -// unsupported (partial inventory). The unsupported gate heals the line's own -// primary at e+1 before any candidate check, as the supported gate does. -func TestManualFailoverRefusedFenceIsHealedOnTheUnsupportedPath(t *testing.T) { +// End to end on the unsupported path: the operator's failover is refused (the +// target is below the highest fenced end), so its survivors are fenced at e+1 +// and nothing is published. r1 is back while r3's server reports no slot (a +// partial inventory: unsupported). A normal product tick publishes r1 at +// e+1, and a further tick adds no epoch. +func TestManualFailoverRefusedFenceIsHealedByTheNextTickOnTheUnsupportedPath(t *testing.T) { h, line := rf3LineOnR1(t) defer closeTestMaster(t, h) ingestRF3Observation(t, h, false, true, true) @@ -440,16 +532,18 @@ func TestManualFailoverRefusedFenceIsHealedOnTheUnsupportedPath(t *testing.T) { if err := failoverTo(h, line, "r2"); err == nil { t.Fatal("a failover to the survivor below the highest fenced end was allowed") } - // r1 is back and ready; r3's slot is stale. - ingestRF3ObservationForServersWithReady(t, h, "vol-rf3", "node-a", "node-b", "node-c", true, true, true, true, false, false) + + back(t, h, true) p.plain = PromotionProbeResult{AckProfile: "sync_quorum", SyncAckKnown: true, CurrentKnown: true, Current: PromotionCandidateEvidence{ReplicaID: "r1", Ready: true}, Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", DurableLSN: 10}}} p.heal = healedR1 - report := authority.SupportabilityReport{Unsupported: map[string]authority.VolumeUnsupportedEvidence{ - "vol-rf3": {VolumeID: "vol-rf3", Reasons: []string{authority.ReasonPartialInventory}}, - }} - _, _, asks := h.applyUnsupportedPromotionEvidenceGate(h.Lifecycle().Placements.ListPlacements(), report, nil) - if len(asks) != 1 || asks[0].ReplicaID != "r1" || asks[0].Evidence.Basis != adapter.BasisHeal || asks[0].Evidence.FencedEpoch != e+1 { - t.Fatalf("asks %+v; want r1 healed at %d on the unsupported path", asks, e+1) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) } + waitLine(t, h, "vol-rf3", "r1", e+1) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } + time.Sleep(200 * time.Millisecond) + waitLine(t, h, "vol-rf3", "r1", e+1) } From 76e5b02d3baa131b487f5c1e9760f1db0a4dd04b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 17:45:06 -0800 Subject: [PATCH 11/12] test(master): the unsupported-path recovery test runs past the pending grace and asserts the volume is unsupported Co-Authored-By: Claude Opus 5.5 --- .../host/master/manual_failover_fence_test.go | 28 +++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/host/master/manual_failover_fence_test.go b/seaweed-block/core/host/master/manual_failover_fence_test.go index b7872db085..460c418f3b 100644 --- a/seaweed-block/core/host/master/manual_failover_fence_test.go +++ b/seaweed-block/core/host/master/manual_failover_fence_test.go @@ -25,7 +25,26 @@ func (p ackedFenceProbe) AckProfile() string { return p.plain.AckProfile } // product tick. func rf3LineOnR1(t *testing.T) (*Host, authority.AuthorityBasis) { t.Helper() - h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3}) + return rf3LineOnR1With(t, newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3})) +} + +// rf3MasterShortGrace is a master whose observation store reports a partial +// inventory at once (no startup pending grace), so a fresh server that omits +// a slot makes the volume unsupported. +func rf3MasterShortGrace(t *testing.T) *Host { + t.Helper() + h, err := New(Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", + ControllerConfig: authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3}, + Freshness: authority.FreshnessConfig{PendingGrace: time.Millisecond}}) + if err != nil { + t.Fatalf("master.New: %v", err) + } + h.Start() + return h +} + +func rf3LineOnR1With(t *testing.T, h *Host) (*Host, authority.AuthorityBasis) { + t.Helper() h.SetPromotionEvidenceProvider(staticPromotionProbe{result: PromotionProbeResult{ AckProfile: "sync_quorum", Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 1}, {ReplicaID: "r3", Ready: true, DurableLSN: 1}}, @@ -518,7 +537,7 @@ func TestManualFailoverPublicationFailureIsHealedByTheNextTick(t *testing.T) { // partial inventory: unsupported). A normal product tick publishes r1 at // e+1, and a further tick adds no epoch. func TestManualFailoverRefusedFenceIsHealedByTheNextTickOnTheUnsupportedPath(t *testing.T) { - h, line := rf3LineOnR1(t) + h, line := rf3LineOnR1With(t, rf3MasterShortGrace(t)) defer closeTestMaster(t, h) ingestRF3Observation(t, h, false, true, true) e := line.Epoch @@ -534,6 +553,11 @@ func TestManualFailoverRefusedFenceIsHealedByTheNextTickOnTheUnsupportedPath(t * } back(t, h, true) + time.Sleep(5 * time.Millisecond) // past the pending grace + topo, _ := acceptedTopologyFromPlacementIntents(h.Lifecycle().Placements.ListPlacements()) + if b := authority.BuildSnapshot(h.obs.Store().Snapshot(), topo, h.Publisher()); len(b.Report.Unsupported["vol-rf3"].Reasons) == 0 { + t.Fatalf("vol-rf3 is not unsupported (report %+v): the test would not reach the unsupported gate", b.Report.Unsupported) + } p.plain = PromotionProbeResult{AckProfile: "sync_quorum", SyncAckKnown: true, CurrentKnown: true, Current: PromotionCandidateEvidence{ReplicaID: "r1", Ready: true}, Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", DurableLSN: 10}}} p.heal = healedR1 From d759eeefa11ab8e0ebcb3548800943363af5ad02 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 17:45:43 -0800 Subject: [PATCH 12/12] test(master): the unsupported-path heal is dispatched and published, and asks nothing once the line reaches the fenced epoch Co-Authored-By: Claude Opus 5.5 --- .../host/master/manual_failover_fence_test.go | 54 ++++++++----------- 1 file changed, 22 insertions(+), 32 deletions(-) diff --git a/seaweed-block/core/host/master/manual_failover_fence_test.go b/seaweed-block/core/host/master/manual_failover_fence_test.go index 460c418f3b..fe68846297 100644 --- a/seaweed-block/core/host/master/manual_failover_fence_test.go +++ b/seaweed-block/core/host/master/manual_failover_fence_test.go @@ -28,21 +28,6 @@ func rf3LineOnR1(t *testing.T) (*Host, authority.AuthorityBasis) { return rf3LineOnR1With(t, newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3})) } -// rf3MasterShortGrace is a master whose observation store reports a partial -// inventory at once (no startup pending grace), so a fresh server that omits -// a slot makes the volume unsupported. -func rf3MasterShortGrace(t *testing.T) *Host { - t.Helper() - h, err := New(Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", - ControllerConfig: authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3}, - Freshness: authority.FreshnessConfig{PendingGrace: time.Millisecond}}) - if err != nil { - t.Fatalf("master.New: %v", err) - } - h.Start() - return h -} - func rf3LineOnR1With(t *testing.T, h *Host) (*Host, authority.AuthorityBasis) { t.Helper() h.SetPromotionEvidenceProvider(staticPromotionProbe{result: PromotionProbeResult{ @@ -531,13 +516,15 @@ func TestManualFailoverPublicationFailureIsHealedByTheNextTick(t *testing.T) { waitLine(t, h, "vol-rf3", "r1", e+1) } -// End to end on the unsupported path: the operator's failover is refused (the -// target is below the highest fenced end), so its survivors are fenced at e+1 -// and nothing is published. r1 is back while r3's server reports no slot (a -// partial inventory: unsupported). A normal product tick publishes r1 at -// e+1, and a further tick adds no epoch. -func TestManualFailoverRefusedFenceIsHealedByTheNextTickOnTheUnsupportedPath(t *testing.T) { - h, line := rf3LineOnR1With(t, rf3MasterShortGrace(t)) +// The unsupported path: the operator's failover is refused (the target is +// below the highest fenced end), so its survivors are fenced at e+1 and +// nothing is published. r1 is back while the volume is unsupported (a +// partial inventory: the report is built as the other unsupported-gate tests +// build it). The gate's heal ask goes through the tick's own dispatch +// (SubmitAssignmentAsk) and r1 is published at e+1; a further gate pass +// asks nothing (the pending fence is cleared by that line). +func TestManualFailoverRefusedFenceIsHealedAndPublishedOnTheUnsupportedPath(t *testing.T) { + h, line := rf3LineOnR1(t) defer closeTestMaster(t, h) ingestRF3Observation(t, h, false, true, true) e := line.Epoch @@ -553,21 +540,24 @@ func TestManualFailoverRefusedFenceIsHealedByTheNextTickOnTheUnsupportedPath(t * } back(t, h, true) - time.Sleep(5 * time.Millisecond) // past the pending grace - topo, _ := acceptedTopologyFromPlacementIntents(h.Lifecycle().Placements.ListPlacements()) - if b := authority.BuildSnapshot(h.obs.Store().Snapshot(), topo, h.Publisher()); len(b.Report.Unsupported["vol-rf3"].Reasons) == 0 { - t.Fatalf("vol-rf3 is not unsupported (report %+v): the test would not reach the unsupported gate", b.Report.Unsupported) - } p.plain = PromotionProbeResult{AckProfile: "sync_quorum", SyncAckKnown: true, CurrentKnown: true, Current: PromotionCandidateEvidence{ReplicaID: "r1", Ready: true}, Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", DurableLSN: 10}}} p.heal = healedR1 - if _, err := h.RunLifecycleProductTick(); err != nil { - t.Fatalf("product tick: %v", err) + report := authority.SupportabilityReport{Unsupported: map[string]authority.VolumeUnsupportedEvidence{ + "vol-rf3": {VolumeID: "vol-rf3", Reasons: []string{authority.ReasonPartialInventory}}, + }} + _, _, asks := h.applyUnsupportedPromotionEvidenceGate(h.Lifecycle().Placements.ListPlacements(), report, nil) + if len(asks) != 1 { + t.Fatalf("asks %+v; want the heal of r1", asks) + } + for _, a := range asks { + if err := h.ctrl.SubmitAssignmentAsk(a); err != nil { + t.Fatalf("dispatch %+v: %v", a, err) + } } waitLine(t, h, "vol-rf3", "r1", e+1) - if _, err := h.RunLifecycleProductTick(); err != nil { - t.Fatalf("product tick: %v", err) + if _, _, again := h.applyUnsupportedPromotionEvidenceGate(h.Lifecycle().Placements.ListPlacements(), report, nil); len(again) != 0 { + t.Fatalf("a second pass asks %+v; want none (the line reached the fenced epoch)", again) } - time.Sleep(200 * time.Millisecond) waitLine(t, h, "vol-rf3", "r1", e+1) }