From c9fe8a7123f5e51a30294d920180ee79000a4ee2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 02:42:43 -0800 Subject: [PATCH] authority, master: one decider: a primary change is published only through the promotion gate The promotion gate (one function: the probe round's answers -> the allowed replica and its evidence) now covers every replicated volume, RF2 included: on main RF2 and every observation-fed failover promoted on heartbeat readiness with no evidence of the candidate's data. The gate puts its evidence on the slot it allows; the controller's failover and rebalance carry it and publish nothing without it. The legacy PolicyOwner (no production caller) is deleted. Failback is the operator's planned move through the gate: the target is probed by the round, and the move is allowed only when the target is in every acknowledgement set (sync_all at any replica count, sync_quorum with RF2); RF3 sync_quorum (needs a seal) and best_effort (forced only) are refused with typed errors. About forty tests encoded the evidence-free decision. Their subjects are unchanged; each now gets the candidate's evidence the way the gate gives it (the controller's candidate helper, the convergence snapshots, a stand-in gate sink for the observation-fed routes, a static round answer for the RF2 and failback tests). None is skipped or loosened. New: ready replicas without the gate's evidence promote nothing; RF2 promotes on a ready answer and not without one; the planned-move guard, one row per ack profile and replica count. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/authority/controller.go | 27 +- .../core/authority/controller_test.go | 48 +- .../core/authority/convergence_route_test.go | 18 +- .../core/authority/convergence_test.go | 21 +- .../core/authority/failback_runtime.go | 14 + .../core/authority/failback_runtime_test.go | 43 +- .../core/authority/fake_basis_reader_test.go | 59 + .../core/authority/gate_sink_test.go | 26 + .../core/authority/observation_test.go | 18 +- seaweed-block/core/authority/policy.go | 346 ---- seaweed-block/core/authority/policy_test.go | 1423 ----------------- .../core/authority/restart_route_test.go | 16 +- seaweed-block/core/authority/topology.go | 12 +- .../frontend/nvmerdma/failover_reopen_test.go | 15 + .../core/host/master/failback_runtime_test.go | 14 + .../core/host/master/planned_move.go | 87 + .../core/host/master/planned_move_test.go | 30 + .../core/host/master/product_loop.go | 30 +- .../core/host/master/product_loop_test.go | 11 + .../promotion_frontier_coverage_test.go | 70 +- .../host/master/workspace_restore_test.go | 2 + .../ops/failback_authority_runtime_adapter.go | 7 +- ...failback_authority_runtime_adapter_test.go | 11 +- seaweed-block/docs/design/invariants.md | 6 +- 24 files changed, 501 insertions(+), 1853 deletions(-) create mode 100644 seaweed-block/core/authority/fake_basis_reader_test.go create mode 100644 seaweed-block/core/authority/gate_sink_test.go delete mode 100644 seaweed-block/core/authority/policy_test.go create mode 100644 seaweed-block/core/host/master/planned_move.go create mode 100644 seaweed-block/core/host/master/planned_move_test.go diff --git a/seaweed-block/core/authority/controller.go b/seaweed-block/core/authority/controller.go index a686d0b2bb..1db7cac729 100644 --- a/seaweed-block/core/authority/controller.go +++ b/seaweed-block/core/authority/controller.go @@ -5,6 +5,8 @@ import ( "fmt" "sync" "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" ) // TopologyController is the multi-volume, cluster-scoped directive @@ -493,12 +495,18 @@ func (c *TopologyController) decideVolume( }, "endpoint refresh", true } if target, ok := chooseRebalanceCandidate(vol, current, serverIndex, currentLoad, projectedLoad, c.config.RebalanceSkew); ok { + // A primary change goes out only with the promotion gate's + // evidence for its target (one decider): none, no rebalance. + if target.PromotionEvidence.Kind != adapter.PrimaryKindPromotion { + return AssignmentAsk{}, "", false + } return AssignmentAsk{ VolumeID: vol.VolumeID, ReplicaID: target.ReplicaID, DataAddr: target.DataAddr, CtrlAddr: target.CtrlAddr, Intent: IntentReassign, + Evidence: target.PromotionEvidence, }, "rebalance", true } return AssignmentAsk{}, "", false @@ -523,13 +531,18 @@ func (c *TopologyController) decideVolume( other := acceptableCandidatesExcept(vol, serverIndex, current.ReplicaID) if len(other) > 0 { best := chooseFailoverCandidate(other, projectedLoad) - return AssignmentAsk{ - VolumeID: vol.VolumeID, - ReplicaID: best.ReplicaID, - DataAddr: best.DataAddr, - CtrlAddr: best.CtrlAddr, - Intent: IntentReassign, - }, "failover", true + // A failover goes out only with the promotion gate's evidence for + // its target (one decider): no evidence, no promotion. + if best.PromotionEvidence.Kind == adapter.PrimaryKindPromotion { + return AssignmentAsk{ + VolumeID: vol.VolumeID, + ReplicaID: best.ReplicaID, + DataAddr: best.DataAddr, + CtrlAddr: best.CtrlAddr, + Intent: IntentReassign, + Evidence: best.PromotionEvidence, + }, "failover", true + } } // No promotion-ready peer exists. Keep the current authority endpoint fresh // when the current replica is still reachable/eligible; this preserves diff --git a/seaweed-block/core/authority/controller_test.go b/seaweed-block/core/authority/controller_test.go index 80a1bbaf72..e0280a4d00 100644 --- a/seaweed-block/core/authority/controller_test.go +++ b/seaweed-block/core/authority/controller_test.go @@ -5,6 +5,8 @@ import ( "errors" "testing" "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" ) func clusterVolume(volumeID string, authority AuthorityBasis, slots ...ReplicaCandidate) VolumeTopologySnapshot { @@ -15,16 +17,20 @@ func clusterVolume(volumeID string, authority AuthorityBasis, slots ...ReplicaCa } } +// candidate is a replica as the promotion gate leaves it when it allows it: +// ready, with the gate's probed evidence (a primary change is published only +// with it). func candidate(replicaID, serverID, dataAddr, ctrlAddr string, evidence uint64) ReplicaCandidate { return ReplicaCandidate{ - ReplicaID: replicaID, - ServerID: serverID, - DataAddr: dataAddr, - CtrlAddr: ctrlAddr, - Reachable: true, - ReadyForPrimary: true, - Eligible: true, - EvidenceScore: evidence, + ReplicaID: replicaID, + ServerID: serverID, + DataAddr: dataAddr, + CtrlAddr: ctrlAddr, + Reachable: true, + ReadyForPrimary: true, + Eligible: true, + EvidenceScore: evidence, + PromotionEvidence: adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion, DurableLSN: evidence}, } } @@ -486,3 +492,29 @@ func TestTopologyController_StalePreConfirmSnapshotDoesNotDuplicateQueuedMove(t } expectNoNext(t, ctrl) } + +// One decider: a snapshot whose ready replicas carry no promotion-gate +// evidence (heartbeats alone) makes the controller publish no primary change, +// neither failover nor rebalance. +func TestTopologyController_NoPrimaryChangeWithoutTheGatesEvidence(t *testing.T) { + bare := func(c ReplicaCandidate) ReplicaCandidate { c.PromotionEvidence = adapter.PrimaryEvidence{}; return c } + reader := newFakeBasisReader() + reader.Set("v1", "r1", AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"}) + c := NewTopologyController(TopologyControllerConfig{}, reader) + snap := ClusterSnapshot{ + CollectedRevision: 1, + Volumes: []VolumeTopologySnapshot{clusterVolume("v1", AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"}, + ReplicaCandidate{ReplicaID: "r1", ServerID: "s1", DataAddr: "d1", CtrlAddr: "c1", Reachable: false, Eligible: true}, + bare(candidate("r2", "s2", "d2", "c2", 10)), + bare(candidate("r3", "s3", "d3", "c3", 20)))}, + Servers: []ServerObservation{{ServerID: "s1", Reachable: true, Eligible: true}, {ServerID: "s2", Reachable: true, Eligible: true}, {ServerID: "s3", Reachable: true, Eligible: true}}, + } + if err := c.SubmitClusterSnapshot(snap); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + if ask, err := c.Next(ctx); err == nil && ask.Intent == IntentReassign { + t.Fatalf("a primary change without the gate's evidence: %+v", ask) + } +} diff --git a/seaweed-block/core/authority/convergence_route_test.go b/seaweed-block/core/authority/convergence_route_test.go index 8defba1396..c66f4ee7a5 100644 --- a/seaweed-block/core/authority/convergence_route_test.go +++ b/seaweed-block/core/authority/convergence_route_test.go @@ -55,10 +55,10 @@ import ( type snapshottingReader struct { underlying AuthorityBasisReader - mu sync.Mutex - frozen bool - perVol map[string]AuthorityBasis - perSlot map[string]AuthorityBasis + mu sync.Mutex + frozen bool + perVol map[string]AuthorityBasis + perSlot map[string]AuthorityBasis } func newSnapshottingReader(u AuthorityBasisReader) *snapshottingReader { @@ -211,7 +211,7 @@ func TestConvergenceRoute_ObservationFedFailover_ConfirmsAndClearsDesired(t *tes host := NewObservationHost(ObservationHostConfig{ Freshness: FreshnessConfig{FreshnessWindow: 30 * time.Second, PendingGrace: 10 * time.Millisecond}, Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}}, - Sink: ctrl, + Sink: gatedSink{ctrl}, // the promotion gate decides, as on the master Reader: holder, Now: clk.Now, }) @@ -303,7 +303,7 @@ func TestConvergenceRoute_PublishNotObserved_StuckWithoutChurn(t *testing.T) { host := NewObservationHost(ObservationHostConfig{ Freshness: FreshnessConfig{FreshnessWindow: 30 * time.Second, PendingGrace: 10 * time.Millisecond}, Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}}, - Sink: ctrl, + Sink: gatedSink{ctrl}, // the promotion gate decides, as on the master Reader: hostReader, Now: clk.Now, }) @@ -430,7 +430,7 @@ func TestConvergenceRoute_RefreshEndpoint_ConfirmsAndClearsDesired(t *testing.T) host := NewObservationHost(ObservationHostConfig{ Freshness: FreshnessConfig{FreshnessWindow: 30 * time.Second, PendingGrace: 10 * time.Millisecond}, Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}}, - Sink: ctrl, + Sink: gatedSink{ctrl}, // the promotion gate decides, as on the master Reader: holder, Now: clk.Now, }) @@ -520,7 +520,7 @@ func TestConvergenceRoute_Supersede_PublisherMovedElsewhere_DropsStaleDesired(t host := NewObservationHost(ObservationHostConfig{ Freshness: FreshnessConfig{FreshnessWindow: 30 * time.Second, PendingGrace: 10 * time.Millisecond}, Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}}, - Sink: ctrl, + Sink: gatedSink{ctrl}, // the promotion gate decides, as on the master Reader: hostReader, Now: clk.Now, }) @@ -575,7 +575,7 @@ func TestConvergenceRoute_Supersede_PublisherMovedElsewhere_DropsStaleDesired(t // supersede-relevant shape). if err := pub.apply(AssignmentAsk{ VolumeID: "v1", ReplicaID: "r3", DataAddr: "data-r3", CtrlAddr: "ctrl-r3", - Intent: IntentReassign, + Intent: IntentReassign, Evidence: testPromotion, }); err != nil { t.Fatalf("pub.apply r3 Reassign: %v", err) } diff --git a/seaweed-block/core/authority/convergence_test.go b/seaweed-block/core/authority/convergence_test.go index f051c3082d..7a420bc5c7 100644 --- a/seaweed-block/core/authority/convergence_test.go +++ b/seaweed-block/core/authority/convergence_test.go @@ -4,6 +4,8 @@ import ( "context" "testing" "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" ) // ============================================================ @@ -36,6 +38,9 @@ func convTestCtrl(t *testing.T, retryWindow time.Duration) (*TopologyController, // unreachable (forcing a failover Reassign to r2) and r2/r3 are // healthy. authority is the Authority field on the snapshot // (what the observation reports the system thinks is current). +// gateEvidence is the promotion gate's evidence on a replica it allowed. +var gateEvidence = adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion} + func failoverSnapForV1(authority AuthorityBasis, rev uint64) ClusterSnapshot { return ClusterSnapshot{ CollectedRevision: rev, @@ -50,8 +55,8 @@ func failoverSnapForV1(authority AuthorityBasis, rev uint64) ClusterSnapshot { Authority: authority, Slots: []ReplicaCandidate{ {ReplicaID: "r1", ServerID: "s1", DataAddr: "d1", CtrlAddr: "c1", Reachable: false, ReadyForPrimary: false, Eligible: true}, - {ReplicaID: "r2", ServerID: "s2", DataAddr: "d2", CtrlAddr: "c2", Reachable: true, ReadyForPrimary: true, Eligible: true}, - {ReplicaID: "r3", ServerID: "s3", DataAddr: "d3", CtrlAddr: "c3", Reachable: true, ReadyForPrimary: true, Eligible: true}, + {ReplicaID: "r2", ServerID: "s2", DataAddr: "d2", CtrlAddr: "c2", Reachable: true, ReadyForPrimary: true, Eligible: true, PromotionEvidence: gateEvidence}, + {ReplicaID: "r3", ServerID: "s3", DataAddr: "d3", CtrlAddr: "c3", Reachable: true, ReadyForPrimary: true, Eligible: true, PromotionEvidence: gateEvidence}, }, }}, } @@ -473,8 +478,8 @@ func TestConvergence_OneStuckVolumeDoesNotBlockOthers(t *testing.T) { Authority: v1Stale, Slots: []ReplicaCandidate{ {ReplicaID: "r1", ServerID: "sA", DataAddr: "d1", CtrlAddr: "c1", Reachable: false, ReadyForPrimary: false, Eligible: true}, - {ReplicaID: "r2", ServerID: "sB", DataAddr: "d2", CtrlAddr: "c2", Reachable: true, ReadyForPrimary: true, Eligible: true}, - {ReplicaID: "r3", ServerID: "sC", DataAddr: "d3", CtrlAddr: "c3", Reachable: true, ReadyForPrimary: true, Eligible: true}, + {ReplicaID: "r2", ServerID: "sB", DataAddr: "d2", CtrlAddr: "c2", Reachable: true, ReadyForPrimary: true, Eligible: true, PromotionEvidence: gateEvidence}, + {ReplicaID: "r3", ServerID: "sC", DataAddr: "d3", CtrlAddr: "c3", Reachable: true, ReadyForPrimary: true, Eligible: true, PromotionEvidence: gateEvidence}, }, }, { @@ -482,8 +487,8 @@ func TestConvergence_OneStuckVolumeDoesNotBlockOthers(t *testing.T) { Authority: v2Stale, Slots: []ReplicaCandidate{ {ReplicaID: "s1", ServerID: "sA", DataAddr: "e1", CtrlAddr: "f1", Reachable: false, ReadyForPrimary: false, Eligible: true}, - {ReplicaID: "s2", ServerID: "sB", DataAddr: "e2", CtrlAddr: "f2", Reachable: true, ReadyForPrimary: true, Eligible: true}, - {ReplicaID: "s3", ServerID: "sC", DataAddr: "e3", CtrlAddr: "f3", Reachable: true, ReadyForPrimary: true, Eligible: true}, + {ReplicaID: "s2", ServerID: "sB", DataAddr: "e2", CtrlAddr: "f2", Reachable: true, ReadyForPrimary: true, Eligible: true, PromotionEvidence: gateEvidence}, + {ReplicaID: "s3", ServerID: "sC", DataAddr: "e3", CtrlAddr: "f3", Reachable: true, ReadyForPrimary: true, Eligible: true, PromotionEvidence: gateEvidence}, }, }, }, @@ -565,8 +570,8 @@ func TestConvergence_RetryStateIsPerVolume(t *testing.T) { Authority: v2Stale, Slots: []ReplicaCandidate{ {ReplicaID: "s1", ServerID: "sA", DataAddr: "e1", CtrlAddr: "f1", Reachable: false, ReadyForPrimary: false, Eligible: true}, - {ReplicaID: "s2", ServerID: "sB", DataAddr: "e2", CtrlAddr: "f2", Reachable: true, ReadyForPrimary: true, Eligible: true}, - {ReplicaID: "s3", ServerID: "sC", DataAddr: "e3", CtrlAddr: "f3", Reachable: true, ReadyForPrimary: true, Eligible: true}, + {ReplicaID: "s2", ServerID: "sB", DataAddr: "e2", CtrlAddr: "f2", Reachable: true, ReadyForPrimary: true, Eligible: true, PromotionEvidence: gateEvidence}, + {ReplicaID: "s3", ServerID: "sC", DataAddr: "e3", CtrlAddr: "f3", Reachable: true, ReadyForPrimary: true, Eligible: true, PromotionEvidence: gateEvidence}, }, }}, } diff --git a/seaweed-block/core/authority/failback_runtime.go b/seaweed-block/core/authority/failback_runtime.go index 665994eb24..675ff065ce 100644 --- a/seaweed-block/core/authority/failback_runtime.go +++ b/seaweed-block/core/authority/failback_runtime.go @@ -3,6 +3,8 @@ package authority import ( "context" "fmt" + + "github.com/seaweedfs/seaweed-block/core/adapter" ) // FailbackRuntimeRequest is the narrow authority-owned failback seam. @@ -34,6 +36,10 @@ type FailbackRuntimeResult struct { type FailbackAuthorityRuntime struct { Publisher *Publisher + // Gate is the promotion gate's decision for this planned move: the + // target's probed evidence, or why the move is refused. A failback is a + // primary change: without a gate it publishes nothing. + Gate func(volumeID, targetReplicaID string) (adapter.PrimaryEvidence, error) } func (r FailbackAuthorityRuntime) ExecuteFailback(ctx context.Context, req FailbackRuntimeRequest) (FailbackRuntimeResult, error) { @@ -59,12 +65,20 @@ func (r FailbackAuthorityRuntime) ExecuteFailback(ctx context.Context, req Failb if before.ReplicaID == req.ReplicaID { return FailbackRuntimeResult{}, fmt.Errorf("authority failback runtime: target replica %s is already current", req.ReplicaID) } + if r.Gate == nil { + return FailbackRuntimeResult{}, fmt.Errorf("authority failback runtime: %w (no promotion gate)", ErrReassignWithoutKind) + } + evidence, err := r.Gate(req.VolumeID, req.ReplicaID) + if err != nil { + return FailbackRuntimeResult{}, fmt.Errorf("authority failback runtime: %w", err) + } if err := r.Publisher.apply(AssignmentAsk{ VolumeID: req.VolumeID, ReplicaID: req.ReplicaID, DataAddr: req.TargetDataAddr, CtrlAddr: req.TargetCtrlAddr, Intent: IntentReassign, + Evidence: evidence, }); err != nil { return FailbackRuntimeResult{}, err } diff --git a/seaweed-block/core/authority/failback_runtime_test.go b/seaweed-block/core/authority/failback_runtime_test.go index 41da704e6f..be797beae8 100644 --- a/seaweed-block/core/authority/failback_runtime_test.go +++ b/seaweed-block/core/authority/failback_runtime_test.go @@ -2,8 +2,11 @@ package authority import ( "context" + "errors" "strings" "testing" + + "github.com/seaweedfs/seaweed-block/core/adapter" ) func TestFailbackAuthorityRuntime_ReassignsThroughPublisher(t *testing.T) { @@ -17,7 +20,7 @@ func TestFailbackAuthorityRuntime_ReassignsThroughPublisher(t *testing.T) { }); err != nil { t.Fatalf("bind current: %v", err) } - result, err := (FailbackAuthorityRuntime{Publisher: pub}).ExecuteFailback(context.Background(), validAuthorityFailbackRequest()) + result, err := (FailbackAuthorityRuntime{Publisher: pub, Gate: allowGate}).ExecuteFailback(context.Background(), validAuthorityFailbackRequest()) if err != nil { t.Fatalf("execute failback: %v", err) } @@ -46,7 +49,7 @@ func TestFailbackAuthorityRuntime_RejectsStaleExpectedCurrent(t *testing.T) { } req := validAuthorityFailbackRequest() req.ExpectedCurrentEpoch = 99 - _, err := (FailbackAuthorityRuntime{Publisher: pub}).ExecuteFailback(context.Background(), req) + _, err := (FailbackAuthorityRuntime{Publisher: pub, Gate: allowGate}).ExecuteFailback(context.Background(), req) if err == nil || !strings.Contains(err.Error(), "stale expected current line") { t.Fatalf("err=%v", err) } @@ -60,7 +63,7 @@ func TestFailbackAuthorityRuntime_RequiresTerminalPreconditions(t *testing.T) { pub := NewPublisher(NewStaticDirective(nil)) req := validAuthorityFailbackRequest() req.AckEligible = false - _, err := (FailbackAuthorityRuntime{Publisher: pub}).ExecuteFailback(context.Background(), req) + _, err := (FailbackAuthorityRuntime{Publisher: pub, Gate: allowGate}).ExecuteFailback(context.Background(), req) if err == nil || !strings.Contains(err.Error(), "terminal failback preconditions") { t.Fatalf("err=%v", err) } @@ -84,3 +87,37 @@ func validAuthorityFailbackRequest() FailbackRuntimeRequest { EvidenceRefs: []string{"failback-target"}, } } + +// allowGate stands in for the master's planned-move decision: the target is +// allowed with the probe round's evidence. +func allowGate(volumeID, target string) (adapter.PrimaryEvidence, error) { + return adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion, DurableLSN: 1}, nil +} + +// A failback is a primary change: with no gate, or a gate that refuses (the +// target not in every acknowledgement set, not caught up), nothing is +// published. +func TestFailbackAuthorityRuntime_PublishesNothingWithoutTheGatesEvidence(t *testing.T) { + for name, rt := range map[string]func(*Publisher) FailbackAuthorityRuntime{ + "no gate": func(p *Publisher) FailbackAuthorityRuntime { return FailbackAuthorityRuntime{Publisher: p} }, + "gate refuses": func(p *Publisher) FailbackAuthorityRuntime { + return FailbackAuthorityRuntime{Publisher: p, Gate: func(string, string) (adapter.PrimaryEvidence, error) { + return adapter.PrimaryEvidence{}, errors.New("not caught up") + }} + }, + } { + t.Run(name, func(t *testing.T) { + pub := NewPublisher(NewStaticDirective(nil)) + if err := pub.apply(AssignmentAsk{VolumeID: "v1", ReplicaID: "r2", DataAddr: "data-r2", CtrlAddr: "ctrl-r2", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + before, _ := pub.VolumeAuthorityLine("v1") + if _, err := rt(pub).ExecuteFailback(context.Background(), validAuthorityFailbackRequest()); err == nil { + t.Fatal("a failback without the gate's evidence was executed") + } + if after, _ := pub.VolumeAuthorityLine("v1"); after != before { + t.Fatalf("the line moved without the gate's evidence: %+v -> %+v", before, after) + } + }) + } +} diff --git a/seaweed-block/core/authority/fake_basis_reader_test.go b/seaweed-block/core/authority/fake_basis_reader_test.go new file mode 100644 index 0000000000..271c56790e --- /dev/null +++ b/seaweed-block/core/authority/fake_basis_reader_test.go @@ -0,0 +1,59 @@ +package authority + +import "sync" + +// fakeBasisReader lets unit tests inject an AuthorityBasis result +// without spinning a real Publisher. +type fakeBasisReader struct { + mu sync.Mutex + data map[string]AuthorityBasis +} + +func newFakeBasisReader() *fakeBasisReader { + return &fakeBasisReader{data: make(map[string]AuthorityBasis)} +} + +func (f *fakeBasisReader) LastAuthorityBasis(volumeID, replicaID string) (AuthorityBasis, bool) { + f.mu.Lock() + defer f.mu.Unlock() + b, ok := f.data[volumeID+"/"+replicaID] + return b, ok +} + +// VolumeAuthorityLine satisfies the new AuthorityBasisReader +// method. Iterates stored entries whose key starts with the +// VolumeID prefix and returns the highest-Epoch entry. +func (f *fakeBasisReader) VolumeAuthorityLine(volumeID string) (AuthorityBasis, bool) { + f.mu.Lock() + defer f.mu.Unlock() + prefix := volumeID + "/" + var best AuthorityBasis + any := false + for k, b := range f.data { + if len(k) < len(prefix) || k[:len(prefix)] != prefix { + continue + } + if !any || b.Epoch > best.Epoch { + best = b + any = true + } + } + return best, any +} + +func (f *fakeBasisReader) Set(volumeID, replicaID string, b AuthorityBasis) { + f.mu.Lock() + defer f.mu.Unlock() + f.data[volumeID+"/"+replicaID] = b +} + +func (f *fakeBasisReader) Clear(volumeID, replicaID string) { + f.mu.Lock() + defer f.mu.Unlock() + delete(f.data, volumeID+"/"+replicaID) +} + +// acceptableSlot builds an SlotObservation whose acceptable() +// predicate returns true — all four fields correct and not +// withdrawn. Tests then knock specific fields down to make it +// unacceptable. diff --git a/seaweed-block/core/authority/gate_sink_test.go b/seaweed-block/core/authority/gate_sink_test.go new file mode 100644 index 0000000000..2f3d574fed --- /dev/null +++ b/seaweed-block/core/authority/gate_sink_test.go @@ -0,0 +1,26 @@ +package authority + +import "github.com/seaweedfs/seaweed-block/core/adapter" + +// testPromotion is a reassign's kind in tests of the publisher's epoch +// mechanics: a promotion decided by the gate. +var testPromotion = adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion} + +// gatedSink stands in, in these tests, for the master's promotion gate: it +// gives every slot the gate would allow (ready, reachable, eligible, not +// withdrawn) the gate's evidence before the controller sees the snapshot. A +// primary change is published only with that evidence, so a route fed by +// heartbeats alone (no gate) promotes nothing. +type gatedSink struct{ ctrl ControllerSink } + +func (g gatedSink) SubmitObservedState(snap ClusterSnapshot, report SupportabilityReport) error { + for vi := range snap.Volumes { + for si := range snap.Volumes[vi].Slots { + s := &snap.Volumes[vi].Slots[si] + if s.ReadyForPrimary && s.Reachable && s.Eligible && !s.Withdrawn { + s.PromotionEvidence = adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion, DurableLSN: s.EvidenceScore} + } + } + } + return g.ctrl.SubmitObservedState(snap, report) +} diff --git a/seaweed-block/core/authority/observation_test.go b/seaweed-block/core/authority/observation_test.go index f0b88a4f57..66642e9f72 100644 --- a/seaweed-block/core/authority/observation_test.go +++ b/seaweed-block/core/authority/observation_test.go @@ -12,6 +12,8 @@ import ( "sync" "testing" "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" ) // ============================================================ @@ -48,10 +50,10 @@ type fakeClock struct { t time.Time } -func newFakeClock(t time.Time) *fakeClock { return &fakeClock{t: t} } -func (c *fakeClock) Now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.t } -func (c *fakeClock) Advance(d time.Duration) { c.mu.Lock(); defer c.mu.Unlock(); c.t = c.t.Add(d) } -func (c *fakeClock) Set(t time.Time) { c.mu.Lock(); defer c.mu.Unlock(); c.t = t } +func newFakeClock(t time.Time) *fakeClock { return &fakeClock{t: t} } +func (c *fakeClock) Now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.t } +func (c *fakeClock) Advance(d time.Duration) { c.mu.Lock(); defer c.mu.Unlock(); c.t = c.t.Add(d) } +func (c *fakeClock) Set(t time.Time) { c.mu.Lock(); defer c.mu.Unlock(); c.t = t } // recordingSink captures submitted observed-state calls for // assertions. Implements ControllerSink's SubmitObservedState — @@ -971,9 +973,9 @@ func exprString(e ast.Expr) string { // that need to drive observation-fed snapshots with controlled // per-volume authority basis values. type fakeReaderForHost struct { - mu sync.Mutex - perVol map[string]AuthorityBasis - perSlot map[string]AuthorityBasis + mu sync.Mutex + perVol map[string]AuthorityBasis + perSlot map[string]AuthorityBasis } func newFakeReaderForHost() *fakeReaderForHost { @@ -1275,10 +1277,12 @@ func TestObservationHost_IdenticalSupportedSnapshots_NoDuplicateAsks(t *testing. secondarySlot := ReplicaCandidate{ ReplicaID: "r2", ServerID: "s2", DataAddr: "d2", CtrlAddr: "c2", Reachable: true, ReadyForPrimary: true, Eligible: true, + PromotionEvidence: adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion}, // the gate allowed it } tertiarySlot := ReplicaCandidate{ ReplicaID: "r3", ServerID: "s3", DataAddr: "d3", CtrlAddr: "c3", Reachable: true, ReadyForPrimary: true, Eligible: true, + PromotionEvidence: adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion}, // the gate allowed it } snap := ClusterSnapshot{ CollectedRevision: 1, diff --git a/seaweed-block/core/authority/policy.go b/seaweed-block/core/authority/policy.go index 5d9030050d..12d19a465d 100644 --- a/seaweed-block/core/authority/policy.go +++ b/seaweed-block/core/authority/policy.go @@ -1,9 +1,6 @@ package authority import ( - "context" - "fmt" - "sync" "time" ) @@ -44,42 +41,6 @@ type AuthorityBasis struct { CtrlAddr string } -// SlotObservation is one slot's policy-visible facts in the -// accepted two-slot topology. Every field is a bounded, explicitly -// owned observation supplied by the upstream collector. The policy -// owner NEVER infers these from engine internals. -type SlotObservation struct { - ReplicaID string - ServerID string - DataAddr string - CtrlAddr string - Reachable bool - ReadyForPrimary bool - Eligible bool - Withdrawn bool -} - -// PolicySnapshot is the one complete point-in-time view submitted -// to the policy owner for one volume. Later snapshots supersede -// earlier ones (overwrite-latest semantics). Fields from different -// revisions must never be combined into a synthetic decision basis. -type PolicySnapshot struct { - VolumeID string - CollectedRevision uint64 - CollectedAt time.Time - Authority AuthorityBasis - PrimarySlot SlotObservation // configured-preferred slot - SecondarySlot SlotObservation -} - -// PolicyConfig carries the bounded per-owner configuration. The -// first slice only needs to know which volume this owner serves; -// slot preference is encoded in the snapshot's slot labeling -// (PrimarySlot is the configured-preferred slot by convention). -type PolicyConfig struct { - VolumeID string -} - // AuthorityBasisReader exposes read-only views of the publisher's // current authority state, used by the policy owner for stale- // resistance and out-of-topology-authority checks before emit. @@ -175,171 +136,6 @@ type UnsupportedEvidence struct { Reason string } -// decisionKind is the internal classification of what the decision -// table produced for a given snapshot. -type decisionKind int - -const ( - decisionEmit decisionKind = iota // an ask is ready to emit - decisionNoAsk // current state is correct; wait for next snapshot - decisionUnsupported // authority basis is outside accepted topology set -) - -// PolicyOwner is the first S3 Directive implementation. It consumes -// PolicySnapshot values via SubmitSnapshot and produces -// AssignmentAsk values via Next, following the decision table in -// the sketch and the stale-resistance rule before each emit. -// -// One PolicyOwner serves one volume. Multi-volume support is -// deliberately out of scope for the first slice. -type PolicyOwner struct { - config PolicyConfig - reader AuthorityBasisReader - - // Snapshot ingress: cap-1 overwrite-latest slot + non-blocking - // wake. Matches the authority delivery discipline. - mu sync.Mutex - latest PolicySnapshot - hasLatest bool - wake chan struct{} - - // Unsupported-topology evidence (§8). - lastUnsupported UnsupportedEvidence - hasLastUnsupported bool -} - -// NewPolicyOwner creates a PolicyOwner bound to a single volume. -// reader is usually a *Publisher; tests may inject a fake. -func NewPolicyOwner(config PolicyConfig, reader AuthorityBasisReader) *PolicyOwner { - return &PolicyOwner{ - config: config, - reader: reader, - wake: make(chan struct{}, 1), - } -} - -// SubmitSnapshot hands the policy owner a complete point-in-time -// view. Newer snapshots overwrite unread older ones (§12 coalescing -// rule). Mismatched VolumeID is rejected because the first slice -// binds one owner to one volume. -func (o *PolicyOwner) SubmitSnapshot(snap PolicySnapshot) error { - if snap.VolumeID != o.config.VolumeID { - return fmt.Errorf("policy: snapshot VolumeID=%q, owner bound to %q", - snap.VolumeID, o.config.VolumeID) - } - o.mu.Lock() - o.latest = snap - o.hasLatest = true - o.mu.Unlock() - // Non-blocking wake: if a signal is already pending, the waiter - // will see our new snapshot when it checks the slot. - select { - case o.wake <- struct{}{}: - default: - } - return nil -} - -// LastUnsupported returns the most recent UnsupportedEvidence, if -// any. Tests and observability surfaces use this to verify that a -// no-ask-plus-evidence branch was taken intentionally rather than -// silently idling. -func (o *PolicyOwner) LastUnsupported() (UnsupportedEvidence, bool) { - o.mu.Lock() - defer o.mu.Unlock() - return o.lastUnsupported, o.hasLastUnsupported -} - -// Next satisfies Directive. It blocks until it can emit an ask -// under the decision table with four ordered guards: -// -// 1. topology-honesty on the snapshot itself: the two accepted -// slots must be on distinct non-empty ServerIDs. If they -// share a ServerID, the snapshot violates the accepted -// topology invariant; record unsupported evidence and wait. -// 2. out-of-topology authority: if the publisher's current -// per-volume authority line is on a replica not in the -// snapshot's two slots, the snapshot cannot legitimately -// emit Bind or Reassign on top of it. Record unsupported -// evidence and wait. -// 3. stale-resistance: snap.Authority must match the publisher's -// current per-volume line. If it does not (newer line exists, -// or snap sees no authority while the publisher has one), the -// candidate decision is dropped and the owner waits for a -// newer snapshot. -// 4. decision table: emit the AssignmentAsk if decide() produced -// one; otherwise continue. -// -// Unsupported-topology and no-ask outcomes record evidence and -// loop back to waiting. -func (o *PolicyOwner) Next(ctx context.Context) (AssignmentAsk, error) { - for { - snap, err := o.waitForSnapshot(ctx) - if err != nil { - return AssignmentAsk{}, err - } - - // Guard 1: distinct-servers topology invariant. The - // accepted topology set is "two replica slots on distinct - // servers". Two cases violate the invariant: - // - either ServerID is empty (identity absent, cannot - // prove distinctness), - // - both ServerIDs are non-empty and equal. - // Both are treated as unsupported with evidence. Anything - // softer — for example "empty is permitted" — would let - // the slice claim a topology invariant it cannot check. - if snap.PrimarySlot.ServerID == "" || - snap.SecondarySlot.ServerID == "" || - snap.PrimarySlot.ServerID == snap.SecondarySlot.ServerID { - o.recordUnsupported(snap, snap.Authority, "distinct-servers topology invariant violated (empty or matching ServerID)") - continue - } - - // Guard 2: snapshot-side authority in topology. If the - // snapshot's own Authority field names a replica outside - // the two accepted slots, the snapshot itself is - // unsupported — record evidence and wait. - if snap.Authority.Assigned && !snapshotIncludesReplica(snap, snap.Authority.ReplicaID) { - o.recordUnsupported(snap, snap.Authority, "snapshot authority ReplicaID not in accepted topology: "+snap.Authority.ReplicaID) - continue - } - - // Guard 3: publisher-side out-of-topology authority. Even - // if the snapshot's view is in-topology, the publisher may - // hold authority on some other replica (split collector, - // prior out-of-band Bind). Refuse to emit in that case. - currentLine, hasLine := o.reader.VolumeAuthorityLine(snap.VolumeID) - if hasLine && !snapshotIncludesReplica(snap, currentLine.ReplicaID) { - o.recordUnsupported(snap, currentLine, "publisher authority on replica outside accepted topology: "+currentLine.ReplicaID) - continue - } - - // Guard 4: stale-resistance against the per-volume line. - if !basisMatchesLine(snap.Authority, currentLine, hasLine) { - continue - } - - // Guard 4: decision table. - ask, kind := o.decide(snap) - switch kind { - case decisionUnsupported: - o.recordUnsupported(snap, snap.Authority, "authority ReplicaID not in accepted topology set") - continue - case decisionNoAsk: - continue - case decisionEmit: - return ask, nil - } - } -} - -// snapshotIncludesReplica reports whether replicaID matches either -// of the two slot replicas carried by the snapshot. -func snapshotIncludesReplica(snap PolicySnapshot, replicaID string) bool { - return replicaID != "" && - (replicaID == snap.PrimarySlot.ReplicaID || replicaID == snap.SecondarySlot.ReplicaID) -} - // basisMatchesLine is the per-volume stale-resistance check. // It compares snap.Authority against the publisher's current // per-volume line on VolumeID / ReplicaID / Epoch / EndpointVersion @@ -357,145 +153,3 @@ func basisMatchesLine(snap AuthorityBasis, line AuthorityBasis, hasLine bool) bo // also sees no authority for this volume. return !hasLine } - -// waitForSnapshot drains the overwrite-latest slot. Blocks until -// a snapshot is available or ctx is cancelled. -func (o *PolicyOwner) waitForSnapshot(ctx context.Context) (PolicySnapshot, error) { - for { - o.mu.Lock() - if o.hasLatest { - snap := o.latest - o.hasLatest = false - o.mu.Unlock() - return snap, nil - } - o.mu.Unlock() - select { - case <-o.wake: - // New snapshot may be available; loop to check. - case <-ctx.Done(): - return PolicySnapshot{}, ctx.Err() - } - } -} - -// recordUnsupported stores an evidence entry describing why this -// snapshot did not produce an ask. The offendingBasis argument is -// deliberately separate from snap.Authority: for publisher-side -// out-of-topology findings (guard 3) the real offender is the -// publisher's current per-volume authority line, not the snapshot's -// (often-unassigned) view. Snapshot-side findings pass -// snap.Authority as the offending basis. -func (o *PolicyOwner) recordUnsupported(snap PolicySnapshot, offendingBasis AuthorityBasis, reason string) { - o.mu.Lock() - o.lastUnsupported = UnsupportedEvidence{ - SnapshotRevision: snap.CollectedRevision, - CollectedAt: snap.CollectedAt, - Basis: offendingBasis, - Reason: reason, - } - o.hasLastUnsupported = true - o.mu.Unlock() -} - - -// acceptable is the single predicate shared by the no-authority -// Bind path and the failover Reassign path (sketch §9). Writing it -// once avoids drift where failover becomes stricter or looser than -// initial bind. -func (o *PolicyOwner) acceptable(s SlotObservation) bool { - if s.ReplicaID == "" { - return false - } - return s.Reachable && s.ReadyForPrimary && s.Eligible && !s.Withdrawn -} - -// decide implements the decision table. Returns (ask, decisionKind). -// For non-emit decisions, the returned ask is the zero value and -// must not be sent. -func (o *PolicyOwner) decide(snap PolicySnapshot) (AssignmentAsk, decisionKind) { - // §7.1 — no published authority yet. - if !snap.Authority.Assigned { - primaryOK := o.acceptable(snap.PrimarySlot) - secondaryOK := o.acceptable(snap.SecondarySlot) - switch { - case primaryOK: - // Tie-break: configured-preferred slot. PrimarySlot is - // the preferred slot by the snapshot's labeling - // convention. If both are acceptable we still pick - // primary; if only primary is acceptable we pick it. - return o.bindAskFor(snap.PrimarySlot), decisionEmit - case secondaryOK: - return o.bindAskFor(snap.SecondarySlot), decisionEmit - default: - return AssignmentAsk{}, decisionNoAsk - } - } - - // Published authority exists. Locate the current slot. - var current, other SlotObservation - switch snap.Authority.ReplicaID { - case snap.PrimarySlot.ReplicaID: - current = snap.PrimarySlot - other = snap.SecondarySlot - case snap.SecondarySlot.ReplicaID: - current = snap.SecondarySlot - other = snap.PrimarySlot - default: - // §7.3 — authority points outside the accepted topology set. - return AssignmentAsk{}, decisionUnsupported - } - - // §7.2 — published authority matches one of the two slots. - if o.acceptable(current) { - // Endpoint refresh check: either DataAddr or CtrlAddr - // differs from the published basis. The sketch §13.1 case 5 - // explicitly covers either axis changing. - if current.DataAddr != snap.Authority.DataAddr || - current.CtrlAddr != snap.Authority.CtrlAddr { - return o.refreshAskFor(current), decisionEmit - } - return AssignmentAsk{}, decisionNoAsk - } - - // Current slot is not acceptable. Consider the other slot. - if o.acceptable(other) { - return o.reassignAskFor(other), decisionEmit - } - return AssignmentAsk{}, decisionNoAsk -} - -// bindAskFor / refreshAskFor / reassignAskFor construct the three -// S3-admitted AssignmentAsk shapes. They are the ONLY places in -// this package that construct an AssignmentAsk — the decision -// table branches exclusively through them, which gives a clean -// single-place audit point for later phases. -func (o *PolicyOwner) bindAskFor(s SlotObservation) AssignmentAsk { - return AssignmentAsk{ - VolumeID: o.config.VolumeID, - ReplicaID: s.ReplicaID, - DataAddr: s.DataAddr, - CtrlAddr: s.CtrlAddr, - Intent: IntentBind, - } -} - -func (o *PolicyOwner) refreshAskFor(s SlotObservation) AssignmentAsk { - return AssignmentAsk{ - VolumeID: o.config.VolumeID, - ReplicaID: s.ReplicaID, - DataAddr: s.DataAddr, - CtrlAddr: s.CtrlAddr, - Intent: IntentRefreshEndpoint, - } -} - -func (o *PolicyOwner) reassignAskFor(s SlotObservation) AssignmentAsk { - return AssignmentAsk{ - VolumeID: o.config.VolumeID, - ReplicaID: s.ReplicaID, - DataAddr: s.DataAddr, - CtrlAddr: s.CtrlAddr, - Intent: IntentReassign, - } -} diff --git a/seaweed-block/core/authority/policy_test.go b/seaweed-block/core/authority/policy_test.go deleted file mode 100644 index 29222ef4f5..0000000000 --- a/seaweed-block/core/authority/policy_test.go +++ /dev/null @@ -1,1423 +0,0 @@ -package authority - -// Completion oracle: recover(a,b) band — NOT recover(a) closure. -// See sw-block/design/recover-semantics-adjustment-plan.md §8.1. - -import ( - "context" - "errors" - "strings" - "sync" - "sync/atomic" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/adapter" - "github.com/seaweedfs/seaweed-block/core/engine" -) - -// ============================================================ -// P14 S3 — Policy Owner Test Matrix -// -// Mirrors docs/sw-block/design/v3-phase-14-s3-sketch.md §13. -// Four categories: -// 1. authoring tests (8) -// 2. stale-resistance tests (3) -// 3. boundary tests (4) -// 4. end-to-end closure tests (3) -// ============================================================ - -// fakeBasisReader lets unit tests inject an AuthorityBasis result -// without spinning a real Publisher. -type fakeBasisReader struct { - mu sync.Mutex - data map[string]AuthorityBasis -} - -func newFakeBasisReader() *fakeBasisReader { - return &fakeBasisReader{data: make(map[string]AuthorityBasis)} -} - -func (f *fakeBasisReader) LastAuthorityBasis(volumeID, replicaID string) (AuthorityBasis, bool) { - f.mu.Lock() - defer f.mu.Unlock() - b, ok := f.data[volumeID+"/"+replicaID] - return b, ok -} - -// VolumeAuthorityLine satisfies the new AuthorityBasisReader -// method. Iterates stored entries whose key starts with the -// VolumeID prefix and returns the highest-Epoch entry. -func (f *fakeBasisReader) VolumeAuthorityLine(volumeID string) (AuthorityBasis, bool) { - f.mu.Lock() - defer f.mu.Unlock() - prefix := volumeID + "/" - var best AuthorityBasis - any := false - for k, b := range f.data { - if len(k) < len(prefix) || k[:len(prefix)] != prefix { - continue - } - if !any || b.Epoch > best.Epoch { - best = b - any = true - } - } - return best, any -} - -func (f *fakeBasisReader) Set(volumeID, replicaID string, b AuthorityBasis) { - f.mu.Lock() - defer f.mu.Unlock() - f.data[volumeID+"/"+replicaID] = b -} - -func (f *fakeBasisReader) Clear(volumeID, replicaID string) { - f.mu.Lock() - defer f.mu.Unlock() - delete(f.data, volumeID+"/"+replicaID) -} - -// acceptableSlot builds an SlotObservation whose acceptable() -// predicate returns true — all four fields correct and not -// withdrawn. Tests then knock specific fields down to make it -// unacceptable. -func acceptableSlot(replicaID, server, dataAddr, ctrlAddr string) SlotObservation { - return SlotObservation{ - ReplicaID: replicaID, - ServerID: server, - DataAddr: dataAddr, - CtrlAddr: ctrlAddr, - Reachable: true, - ReadyForPrimary: true, - Eligible: true, - Withdrawn: false, - } -} - -// runNextOnce drives the owner on one submitted snapshot with a -// short deadline. Returns the emitted ask or an error, which for -// the blocking-on-no-ask path is context.DeadlineExceeded. -func runNextOnce(t *testing.T, o *PolicyOwner, snap PolicySnapshot) (AssignmentAsk, error) { - t.Helper() - if err := o.SubmitSnapshot(snap); err != nil { - t.Fatalf("SubmitSnapshot: %v", err) - } - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) - defer cancel() - return o.Next(ctx) -} - -// expectNoEmit asserts that Next blocks (deadline-expires) on the -// given snapshot — i.e. the decision was no-ask or unsupported. -func expectNoEmit(t *testing.T, o *PolicyOwner, snap PolicySnapshot) { - t.Helper() - ask, err := runNextOnce(t, o, snap) - if err == nil { - t.Fatalf("expected no emit, got ask=%+v", ask) - } - if !errors.Is(err, context.DeadlineExceeded) { - t.Fatalf("expected deadline exceeded, got %v", err) - } -} - -// expectEmit asserts Next emits the expected ask (intent + -// replicaID) on the given snapshot. -func expectEmit(t *testing.T, o *PolicyOwner, snap PolicySnapshot, wantIntent AskIntent, wantReplicaID string) AssignmentAsk { - t.Helper() - ask, err := runNextOnce(t, o, snap) - if err != nil { - t.Fatalf("expected emit, got err=%v", err) - } - if ask.Intent != wantIntent { - t.Fatalf("intent: got %s want %s", ask.Intent, wantIntent) - } - if ask.ReplicaID != wantReplicaID { - t.Fatalf("replicaID: got %q want %q", ask.ReplicaID, wantReplicaID) - } - return ask -} - -// ============================================================ -// §13.1 — Policy authoring tests -// ============================================================ - -func TestPolicy_NoAuth_OneAcceptable_EmitsBind(t *testing.T) { - reader := newFakeBasisReader() - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, reader) - snap := PolicySnapshot{ - VolumeID: "v1", - CollectedRevision: 1, - Authority: AuthorityBasis{Assigned: false}, - PrimarySlot: acceptableSlot("r1", "s1", "d1", "c1"), - SecondarySlot: acceptableSlot("r2", "s2", "d2", "c2"), - } - // Make secondary unacceptable so only primary qualifies. - snap.SecondarySlot.Reachable = false - - expectEmit(t, owner, snap, IntentBind, "r1") -} - -func TestPolicy_NoAuth_BothAcceptable_EmitsBindForPreferred(t *testing.T) { - reader := newFakeBasisReader() - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, reader) - snap := PolicySnapshot{ - VolumeID: "v1", - CollectedRevision: 1, - Authority: AuthorityBasis{Assigned: false}, - PrimarySlot: acceptableSlot("r1", "s1", "d1", "c1"), - SecondarySlot: acceptableSlot("r2", "s2", "d2", "c2"), - } - // Both acceptable: tie-break on preferred (PrimarySlot). - expectEmit(t, owner, snap, IntentBind, "r1") -} - -func TestPolicy_NoAuth_NeitherAcceptable_NoAsk(t *testing.T) { - reader := newFakeBasisReader() - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, reader) - primary := acceptableSlot("r1", "s1", "d1", "c1") - primary.Reachable = false - secondary := acceptableSlot("r2", "s2", "d2", "c2") - secondary.Withdrawn = true - snap := PolicySnapshot{ - VolumeID: "v1", - Authority: AuthorityBasis{Assigned: false}, - PrimarySlot: primary, - SecondarySlot: secondary, - } - expectNoEmit(t, owner, snap) -} - -func TestPolicy_CurrentHealthy_Unchanged_NoAsk(t *testing.T) { - reader := newFakeBasisReader() - reader.Set("v1", "r1", AuthorityBasis{ - Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, - DataAddr: "d1", CtrlAddr: "c1", - }) - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, reader) - snap := PolicySnapshot{ - VolumeID: "v1", - Authority: AuthorityBasis{ - Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, - DataAddr: "d1", CtrlAddr: "c1", - }, - PrimarySlot: acceptableSlot("r1", "s1", "d1", "c1"), - SecondarySlot: acceptableSlot("r2", "s2", "d2", "c2"), - } - expectNoEmit(t, owner, snap) -} - -func TestPolicy_CurrentHealthy_DataAddrChanged_EmitsRefresh(t *testing.T) { - reader := newFakeBasisReader() - reader.Set("v1", "r1", AuthorityBasis{ - Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, - DataAddr: "d1", CtrlAddr: "c1", - }) - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, reader) - snap := PolicySnapshot{ - VolumeID: "v1", - Authority: AuthorityBasis{ - Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, - DataAddr: "d1", CtrlAddr: "c1", - }, - // Same identity, new DataAddr. - PrimarySlot: acceptableSlot("r1", "s1", "d1-new", "c1"), - SecondarySlot: acceptableSlot("r2", "s2", "d2", "c2"), - } - ask := expectEmit(t, owner, snap, IntentRefreshEndpoint, "r1") - if ask.DataAddr != "d1-new" { - t.Fatalf("refresh DataAddr: got %q want d1-new", ask.DataAddr) - } -} - -func TestPolicy_CurrentHealthy_CtrlAddrChanged_EmitsRefresh(t *testing.T) { - reader := newFakeBasisReader() - reader.Set("v1", "r1", AuthorityBasis{ - Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, - DataAddr: "d1", CtrlAddr: "c1", - }) - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, reader) - snap := PolicySnapshot{ - VolumeID: "v1", - Authority: AuthorityBasis{ - Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, - DataAddr: "d1", CtrlAddr: "c1", - }, - // Same identity + data addr, new CtrlAddr. - PrimarySlot: acceptableSlot("r1", "s1", "d1", "c1-new"), - SecondarySlot: acceptableSlot("r2", "s2", "d2", "c2"), - } - ask := expectEmit(t, owner, snap, IntentRefreshEndpoint, "r1") - if ask.CtrlAddr != "c1-new" { - t.Fatalf("refresh CtrlAddr: got %q want c1-new", ask.CtrlAddr) - } -} - -func TestPolicy_CurrentUnacceptable_OtherAcceptable_EmitsReassign(t *testing.T) { - reader := newFakeBasisReader() - reader.Set("v1", "r1", AuthorityBasis{ - Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, - DataAddr: "d1", CtrlAddr: "c1", - }) - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, reader) - primary := acceptableSlot("r1", "s1", "d1", "c1") - primary.Reachable = false // current is unacceptable - snap := PolicySnapshot{ - VolumeID: "v1", - Authority: AuthorityBasis{ - Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, - DataAddr: "d1", CtrlAddr: "c1", - }, - PrimarySlot: primary, - SecondarySlot: acceptableSlot("r2", "s2", "d2", "c2"), - } - expectEmit(t, owner, snap, IntentReassign, "r2") -} - -func TestPolicy_CurrentUnacceptable_OtherUnacceptable_NoAsk(t *testing.T) { - reader := newFakeBasisReader() - reader.Set("v1", "r1", AuthorityBasis{ - Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, - DataAddr: "d1", CtrlAddr: "c1", - }) - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, reader) - primary := acceptableSlot("r1", "s1", "d1", "c1") - primary.Reachable = false - secondary := acceptableSlot("r2", "s2", "d2", "c2") - secondary.ReadyForPrimary = false - snap := PolicySnapshot{ - VolumeID: "v1", - Authority: AuthorityBasis{ - Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, - DataAddr: "d1", CtrlAddr: "c1", - }, - PrimarySlot: primary, - SecondarySlot: secondary, - } - expectNoEmit(t, owner, snap) -} - -// TestPolicy_OutOfTopologyPublisherAuthority_NoAskPlusUnsupportedEvidence -// is the regression for finding 1: the publisher already holds -// authority on a replica outside the two accepted slots (e.g. r99 -// from a prior out-of-band Bind), and the snapshot's own -// Authority says Assigned=false. Before this fix, stale- -// resistance only looked at the snapshot's two slot IDs, missed -// the r99 line entirely, and let the policy emit Bind(r1) — which -// Publisher.apply would accept because IntentBind is rejected -// only per (vid, rid), not per volume. Result: two authority -// lines on the same volume. -// -// With per-volume stale-resistance, the r99 line is detected, -// and the snapshot is rejected with explicit unsupported evidence. -func TestPolicy_OutOfTopologyPublisherAuthority_NoAskPlusUnsupportedEvidence(t *testing.T) { - reader := newFakeBasisReader() - // Publisher already holds authority on r99 — outside the - // snapshot's accepted topology (r1, r2). - reader.Set("v1", "r99", AuthorityBasis{ - Assigned: true, ReplicaID: "r99", Epoch: 5, EndpointVersion: 1, - DataAddr: "dx", CtrlAddr: "cx", - }) - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, reader) - - // Snapshot sees no authority in the accepted slots; without - // the per-volume check, policy would emit Bind(r1). - snap := PolicySnapshot{ - VolumeID: "v1", - CollectedRevision: 11, - Authority: AuthorityBasis{Assigned: false}, - PrimarySlot: acceptableSlot("r1", "s1", "d1", "c1"), - SecondarySlot: acceptableSlot("r2", "s2", "d2", "c2"), - } - expectNoEmit(t, owner, snap) - - ev, ok := owner.LastUnsupported() - if !ok { - t.Fatal("expected unsupported evidence for out-of-topology publisher authority") - } - if ev.SnapshotRevision != 11 { - t.Fatalf("evidence revision: got %d want 11", ev.SnapshotRevision) - } - // Structured-artifact assertions (not just the reason string): - // the offending Basis must carry the publisher's current line - // r99@5, NOT the snapshot's unassigned Authority view. - if !ev.Basis.Assigned { - t.Fatal("evidence Basis: must carry the offending publisher line, got unassigned (snapshot's view)") - } - if ev.Basis.ReplicaID != "r99" { - t.Fatalf("evidence Basis.ReplicaID: got %q want r99", ev.Basis.ReplicaID) - } - if ev.Basis.Epoch != 5 { - t.Fatalf("evidence Basis.Epoch: got %d want 5", ev.Basis.Epoch) - } -} - -// TestPolicy_EmptyServerID_NoAskPlusUnsupportedEvidence covers -// the tightened distinct-servers invariant: missing server -// identity on either slot is also unsupported. "Two replica slots -// on distinct servers" cannot be proven if the identities are -// absent; accepting empty ServerID would let the slice claim a -// topology invariant it cannot check. -func TestPolicy_EmptyServerID_NoAskPlusUnsupportedEvidence(t *testing.T) { - reader := newFakeBasisReader() - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, reader) - - // Secondary slot has empty ServerID — invariant violated. - secondary := acceptableSlot("r2", "", "d2", "c2") - snap := PolicySnapshot{ - VolumeID: "v1", - CollectedRevision: 17, - Authority: AuthorityBasis{Assigned: false}, - PrimarySlot: acceptableSlot("r1", "s1", "d1", "c1"), - SecondarySlot: secondary, - } - expectNoEmit(t, owner, snap) - - ev, ok := owner.LastUnsupported() - if !ok { - t.Fatal("empty ServerID must record unsupported evidence") - } - if ev.SnapshotRevision != 17 { - t.Fatalf("evidence revision: got %d want 17", ev.SnapshotRevision) - } - if !strings.Contains(ev.Reason, "ServerID") { - t.Fatalf("expected evidence reason to mention ServerID, got %q", ev.Reason) - } -} - -// TestPolicy_BothSlotsSameServer_NoAskPlusUnsupportedEvidence is -// the regression for finding 3: the accepted topology set -// requires "two replica slots on distinct servers". Two slots -// sharing a ServerID violate that invariant. Policy records -// unsupported evidence and emits no ask, even when the slots are -// otherwise fully acceptable. -func TestPolicy_BothSlotsSameServer_NoAskPlusUnsupportedEvidence(t *testing.T) { - reader := newFakeBasisReader() - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, reader) - - // Both slots on the same ServerID — topology violation. - snap := PolicySnapshot{ - VolumeID: "v1", - CollectedRevision: 13, - Authority: AuthorityBasis{Assigned: false}, - PrimarySlot: acceptableSlot("r1", "sA", "d1", "c1"), - SecondarySlot: acceptableSlot("r2", "sA", "d2", "c2"), - } - expectNoEmit(t, owner, snap) - - ev, ok := owner.LastUnsupported() - if !ok { - t.Fatal("same-server topology violation must record evidence") - } - if ev.SnapshotRevision != 13 { - t.Fatalf("evidence revision: got %d want 13", ev.SnapshotRevision) - } - if !strings.Contains(ev.Reason, "ServerID") { - t.Fatalf("expected evidence reason to mention ServerID, got %q", ev.Reason) - } -} - -func TestPolicy_AuthOutsideTopology_NoAskPlusUnsupportedEvidence(t *testing.T) { - reader := newFakeBasisReader() - // Authority says r99 is published, which is NOT in either of our - // two accepted slots (r1 / r2). - reader.Set("v1", "r99", AuthorityBasis{ - Assigned: true, ReplicaID: "r99", Epoch: 3, EndpointVersion: 1, - DataAddr: "dx", CtrlAddr: "cx", - }) - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, reader) - snap := PolicySnapshot{ - VolumeID: "v1", - CollectedRevision: 42, - Authority: AuthorityBasis{ - Assigned: true, ReplicaID: "r99", Epoch: 3, EndpointVersion: 1, - DataAddr: "dx", CtrlAddr: "cx", - }, - PrimarySlot: acceptableSlot("r1", "s1", "d1", "c1"), - SecondarySlot: acceptableSlot("r2", "s2", "d2", "c2"), - } - expectNoEmit(t, owner, snap) - - // Unsupported evidence must have been recorded — silent idle - // would be a violation of sketch §8. - ev, ok := owner.LastUnsupported() - if !ok { - t.Fatal("expected unsupported evidence, got none") - } - if ev.SnapshotRevision != 42 { - t.Fatalf("evidence revision: got %d want 42", ev.SnapshotRevision) - } - if ev.Basis.ReplicaID != "r99" { - t.Fatalf("evidence basis ReplicaID: got %q want r99", ev.Basis.ReplicaID) - } - if ev.Reason == "" { - t.Fatal("expected non-empty evidence Reason") - } -} - -// ============================================================ -// Reassign semantic regressions (from -// sw-block/design/v3-phase-14-s3-reassign-semantic.md §5) -// -// These tests pin the widened IntentReassign semantic directly -// against the Publisher. They are deliberately placed alongside -// the policy authoring tests because they prove the authority -// contract the policy relies on. -// ============================================================ - -// TestReassign_CrossSlotMintsEpochPlusOne — Publisher.apply with -// IntentReassign targeting a previously-unbound ReplicaID of the -// same VolumeID must mint (targetReplicaID, maxEpoch+1, EV=1). -// This is the first-class cross-slot failover proof. -func TestReassign_CrossSlotMintsEpochPlusOne(t *testing.T) { - pub := NewPublisher(nil) - if err := pub.apply(AssignmentAsk{ - VolumeID: "v1", ReplicaID: "r1", - DataAddr: "d1", CtrlAddr: "c1", - Intent: IntentBind, - }); err != nil { - t.Fatalf("Bind r1: %v", err) - } - // Cross-slot reassign targeting a previously-unbound r2. - if err := pub.apply(AssignmentAsk{ - VolumeID: "v1", ReplicaID: "r2", - DataAddr: "d2", CtrlAddr: "c2", - Intent: IntentReassign, - }); err != nil { - t.Fatalf("cross-slot Reassign r2: %v", err) - } - got, ok := pub.LastPublished("v1", "r2") - if !ok { - t.Fatal("no publication for (v1, r2) after cross-slot Reassign") - } - if got.Epoch != 2 { - t.Fatalf("epoch: got %d want 2 (max across volume + 1)", got.Epoch) - } - if got.EndpointVersion != 1 { - t.Fatalf("EV: got %d want 1 (Reassign resets EV)", got.EndpointVersion) - } - if got.ReplicaID != "r2" { - t.Fatalf("replicaID: got %q want r2", got.ReplicaID) - } -} - -// TestReassign_NoPriorVolumePublish_StillRejects — IntentReassign -// with no prior publication of any kind for this VolumeID must -// still be rejected. First-time establishment stays on -// IntentBind; this prevents confusion about the per-volume -// monotonic line. -func TestReassign_NoPriorVolumePublish_StillRejects(t *testing.T) { - pub := NewPublisher(nil) - err := pub.apply(AssignmentAsk{ - VolumeID: "v1", ReplicaID: "r1", - DataAddr: "d1", CtrlAddr: "c1", - Intent: IntentReassign, - }) - if !errors.Is(err, ErrReassignNotBound) { - t.Fatalf("want ErrReassignNotBound, got %v", err) - } -} - -// TestReassign_PerSlotOpsOnOldSlotDoNotAdvanceVolumeLine — after -// a cross-slot Reassign moves per-volume authority from r1@1 to -// r2@2, the old slot state for (v1, r1) is intentionally -// preserved so per-slot operations (like RefreshEndpoint on r1) -// still work locally. The tightened claim this test proves is: -// -// A RefreshEndpoint on the OLD slot bumps only its own EV; -// it does NOT retroactively advance the Epoch of the old slot -// above its frozen value, and it does NOT change the current -// per-volume line (still r2@2). -// -// This test does NOT claim that the old slot is invisible to any -// subscriber that might still be listening on it. Subscribers to -// (v1, r1) see per-slot updates for r1 as usual — that is a -// property of the per-subscription fan-out model from S2 and is -// out of scope for this per-volume-line regression. -func TestReassign_PerSlotOpsOnOldSlotDoNotAdvanceVolumeLine(t *testing.T) { - pub := NewPublisher(nil) - if err := pub.apply(AssignmentAsk{ - VolumeID: "v1", ReplicaID: "r1", - DataAddr: "d1", CtrlAddr: "c1", - Intent: IntentBind, - }); err != nil { - t.Fatalf("Bind r1: %v", err) - } - if err := pub.apply(AssignmentAsk{ - VolumeID: "v1", ReplicaID: "r2", - DataAddr: "d2", CtrlAddr: "c2", - Intent: IntentReassign, - }); err != nil { - t.Fatalf("cross-slot Reassign r2: %v", err) - } - - // Old slot state: last published (v1, r1, epoch=1, ev=1) — - // frozen by design so per-slot Refresh on r1 still works. - oldBasis, ok := pub.LastAuthorityBasis("v1", "r1") - if !ok { - t.Fatal("(v1, r1) state unexpectedly missing after cross-slot Reassign") - } - if oldBasis.Epoch != 1 { - t.Fatalf("old slot Epoch: got %d want 1 (frozen)", oldBasis.Epoch) - } - - // Per-slot Refresh on r1. This is intentionally still allowed. - // The tight claim: it bumps r1's own EV but does not touch r1's - // Epoch and does not change the current per-volume line. - if err := pub.apply(AssignmentAsk{ - VolumeID: "v1", ReplicaID: "r1", - DataAddr: "d1-changed", CtrlAddr: "c1", - Intent: IntentRefreshEndpoint, - }); err != nil { - t.Fatalf("RefreshEndpoint on old slot: %v", err) - } - r1After, _ := pub.LastAuthorityBasis("v1", "r1") - if r1After.Epoch != 1 { - t.Fatalf("old-slot Refresh must not retroactively advance its Epoch, got %d", - r1After.Epoch) - } - if r1After.EndpointVersion != 2 { - t.Fatalf("old-slot Refresh must advance its own EV: got %d want 2", - r1After.EndpointVersion) - } - - // The per-volume current line remains r2@2. - r2, ok := pub.LastAuthorityBasis("v1", "r2") - if !ok { - t.Fatal("(v1, r2) state missing after cross-slot Reassign") - } - if r2.Epoch != 2 { - t.Fatalf("new slot Epoch: got %d want 2", r2.Epoch) - } -} - -// TestReassign_PerSlotEndpointVersionMonotonicityPreserved — after -// a cross-slot Reassign puts the new slot at EV=1, a subsequent -// RefreshEndpoint on that slot advances its EV from 1 to 2, not -// from the OLD slot's EV or from some synthetic starting point. -func TestReassign_PerSlotEndpointVersionMonotonicityPreserved(t *testing.T) { - pub := NewPublisher(nil) - if err := pub.apply(AssignmentAsk{ - VolumeID: "v1", ReplicaID: "r1", - DataAddr: "d1", CtrlAddr: "c1", - Intent: IntentBind, - }); err != nil { - t.Fatalf("Bind r1: %v", err) - } - // Inflate r1's EV so we can tell the two slots apart if they - // were accidentally merged. - if err := pub.apply(AssignmentAsk{ - VolumeID: "v1", ReplicaID: "r1", - DataAddr: "d1-v2", CtrlAddr: "c1", - Intent: IntentRefreshEndpoint, - }); err != nil { - t.Fatalf("Refresh r1: %v", err) - } - // Cross-slot reassign: r2 must land at EV=1, not EV=3 or any - // value derived from r1's history. - if err := pub.apply(AssignmentAsk{ - VolumeID: "v1", ReplicaID: "r2", - DataAddr: "d2", CtrlAddr: "c2", - Intent: IntentReassign, - }); err != nil { - t.Fatalf("cross-slot Reassign r2: %v", err) - } - first, _ := pub.LastAuthorityBasis("v1", "r2") - if first.EndpointVersion != 1 { - t.Fatalf("post-Reassign r2 EV: got %d want 1", first.EndpointVersion) - } - // A Refresh on r2 advances ITS own EV from 1 → 2. - if err := pub.apply(AssignmentAsk{ - VolumeID: "v1", ReplicaID: "r2", - DataAddr: "d2-v2", CtrlAddr: "c2", - Intent: IntentRefreshEndpoint, - }); err != nil { - t.Fatalf("Refresh r2: %v", err) - } - second, _ := pub.LastAuthorityBasis("v1", "r2") - if second.EndpointVersion != 2 { - t.Fatalf("post-Refresh r2 EV: got %d want 2 (per-slot monotonic from 1)", second.EndpointVersion) - } - if second.Epoch != 2 { - t.Fatalf("post-Refresh r2 Epoch: got %d want 2 (unchanged by Refresh)", second.Epoch) - } -} - -// ============================================================ -// §13.2 — Stale-resistance tests -// ============================================================ - -func TestPolicy_StaleDecision_DroppedWhenAuthorityAdvances(t *testing.T) { - reader := newFakeBasisReader() - // Snapshot basis: epoch=1. Reader reports epoch=2 already — - // the candidate decision is stale. - reader.Set("v1", "r1", AuthorityBasis{ - Assigned: true, ReplicaID: "r1", Epoch: 2, EndpointVersion: 1, - DataAddr: "d1", CtrlAddr: "c1", - }) - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, reader) - primary := acceptableSlot("r1", "s1", "d1", "c1") - primary.Reachable = false // would normally trigger Reassign - staleSnap := PolicySnapshot{ - VolumeID: "v1", - Authority: AuthorityBasis{ - Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, - DataAddr: "d1", CtrlAddr: "c1", - }, - PrimarySlot: primary, - SecondarySlot: acceptableSlot("r2", "s2", "d2", "c2"), - } - expectNoEmit(t, owner, staleSnap) -} - -func TestPolicy_StaleRefresh_DroppedWhenNewerEndpointVersion(t *testing.T) { - reader := newFakeBasisReader() - // Snapshot basis: EV=1. Reader reports EV=2 already. - reader.Set("v1", "r1", AuthorityBasis{ - Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 2, - DataAddr: "d1-newer", CtrlAddr: "c1", - }) - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, reader) - staleSnap := PolicySnapshot{ - VolumeID: "v1", - Authority: AuthorityBasis{ - Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, - DataAddr: "d1", CtrlAddr: "c1", - }, - PrimarySlot: acceptableSlot("r1", "s1", "d1-new", "c1"), - SecondarySlot: acceptableSlot("r2", "s2", "d2", "c2"), - } - expectNoEmit(t, owner, staleSnap) -} - -// TestPolicy_StaleSnapshotAfterCrossSlotFailover_Dropped is the -// regression for the architect finding that the earlier per-slot -// stale check was wrong under the widened S3 IntentReassign -// semantic. After cross-slot failover (r1@1 -> r2@2), the -// preserved (v1, r1)=epoch=1 state made a stale pre-failover -// snapshot still look "current" to the per-slot compare, so the -// policy would emit another Reassign producing r2@3 spuriously. -// -// With per-volume-line stale-resistance, the snapshot is compared -// against the highest-epoch basis across both slots (= r2@2) and -// dropped cleanly. -func TestPolicy_StaleSnapshotAfterCrossSlotFailover_Dropped(t *testing.T) { - reader := newFakeBasisReader() - // Post-failover state: (v1, r1) preserved at epoch=1, current - // per-volume line at r2@2. This is exactly what Publisher.apply - // produces after IntentBind(r1) + IntentReassign(r2). - reader.Set("v1", "r1", AuthorityBasis{ - Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, - DataAddr: "d1", CtrlAddr: "c1", - }) - reader.Set("v1", "r2", AuthorityBasis{ - Assigned: true, ReplicaID: "r2", Epoch: 2, EndpointVersion: 1, - DataAddr: "d2", CtrlAddr: "c2", - }) - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, reader) - - // Stale snapshot: still thinks r1@1 is the current authority - // AND observes r1 as unreachable, which (without the fix) - // would drive another Reassign to r2 — spuriously producing - // r2@3 on top of the already-moved authority line. - staleSnap := PolicySnapshot{ - VolumeID: "v1", - Authority: AuthorityBasis{ - Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, - DataAddr: "d1", CtrlAddr: "c1", - }, - PrimarySlot: func() SlotObservation { - s := acceptableSlot("r1", "s1", "d1", "c1") - s.Reachable = false - return s - }(), - SecondarySlot: acceptableSlot("r2", "s2", "d2", "c2"), - } - expectNoEmit(t, owner, staleSnap) -} - -func TestPolicy_NewerSnapshotOverwritesOlder_OnlyLatestValidEmits(t *testing.T) { - reader := newFakeBasisReader() - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, reader) - - // Submit three snapshots WITHOUT calling Next in between; the - // overwrite-latest slot discards older unread snapshots. - olderBoth := PolicySnapshot{ - VolumeID: "v1", - CollectedRevision: 1, - Authority: AuthorityBasis{Assigned: false}, - PrimarySlot: acceptableSlot("r1", "s1", "d1-OLD", "c1-OLD"), - SecondarySlot: acceptableSlot("r2", "s2", "d2", "c2"), - } - intermediate := olderBoth - intermediate.CollectedRevision = 2 - intermediate.PrimarySlot.DataAddr = "d1-MID" - newest := olderBoth - newest.CollectedRevision = 3 - newest.PrimarySlot.DataAddr = "d1-NEW" - newest.PrimarySlot.CtrlAddr = "c1-NEW" - - if err := owner.SubmitSnapshot(olderBoth); err != nil { - t.Fatalf("submit 1: %v", err) - } - if err := owner.SubmitSnapshot(intermediate); err != nil { - t.Fatalf("submit 2: %v", err) - } - if err := owner.SubmitSnapshot(newest); err != nil { - t.Fatalf("submit 3: %v", err) - } - - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) - defer cancel() - ask, err := owner.Next(ctx) - if err != nil { - t.Fatalf("Next: %v", err) - } - if ask.Intent != IntentBind { - t.Fatalf("intent: got %s want Bind", ask.Intent) - } - if ask.DataAddr != "d1-NEW" || ask.CtrlAddr != "c1-NEW" { - t.Fatalf("expected latest snapshot addrs, got data=%q ctrl=%q", - ask.DataAddr, ask.CtrlAddr) - } -} - -// ============================================================ -// §13.3 — Boundary tests -// ============================================================ - -// The non-forgeability test already walks the repo and enforces -// "policy code cannot construct AssignmentInfo directly" — policy.go -// lives in core/authority/, so it is allowed to reference types -// from adapter for consumption, but the test flags any -// AssignmentInfo construction. This test file proves NO construction -// happens in the policy implementation by grepping at the source -// level the decision paths must only produce AssignmentAsk values. -func TestPolicy_NoDirectAssignmentInfoConstruction(t *testing.T) { - // The real proof lives in - // TestNonForgeability_NoAssignmentInfoMintingOutsideAuthority — - // which audits the whole repo, including core/authority/. That - // test would fail if policy.go minted AssignmentInfo. This - // stub asserts the audit runs cleanly on the current tree. - if _, err := auditNonForgeability("policy.go"); err != nil { - t.Fatalf("audit: %v", err) - } - // Deeper coverage is the whole-repo audit: - t.Run("delegates to repo-wide audit", TestNonForgeability_NoAssignmentInfoMintingOutsideAuthority) -} - -// TestPolicy_DoesNotAddAdapterIngress — the only verb the policy -// exposes to callers is Next (Directive) + SubmitSnapshot + -// LastUnsupported. None of them writes to the adapter directly. -// We assert the Directive interface is satisfied (so Publisher can -// consume it) and that PolicyOwner has no OnAssignment-style -// method accidentally added. -func TestPolicy_DoesNotAddAdapterIngress(t *testing.T) { - var _ Directive = (*PolicyOwner)(nil) // compile-time check - - // Reflectively guard against an accidentally-added - // OnAssignment method on PolicyOwner. This catches a refactor - // that routes decisions through a direct adapter call. - // Using a type assertion against a narrow interface is - // simplest. - type hiddenAdapterIngress interface { - OnAssignment(info adapter.AssignmentInfo) adapter.ApplyLog - } - var po any = (*PolicyOwner)(nil) - if _, ok := po.(hiddenAdapterIngress); ok { - t.Fatal("PolicyOwner must not expose OnAssignment — adapter ingress stays on VolumeReplicaAdapter only") - } -} - -func TestPolicy_OnlyThreeIntentsProduced(t *testing.T) { - // Run the decision table over a spread of inputs. Every ask - // produced must be one of Bind / RefreshEndpoint / Reassign — - // Remove / retirement intents do not appear in this slice. - reader := newFakeBasisReader() - reader.Set("v1", "r1", AuthorityBasis{ - Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, - DataAddr: "d1", CtrlAddr: "c1", - }) - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, reader) - - cases := []struct { - name string - snap PolicySnapshot - }{ - {"bind-only-primary", PolicySnapshot{VolumeID: "v1", - PrimarySlot: acceptableSlot("r1", "s1", "d1", "c1"), - }}, - {"refresh-data", PolicySnapshot{VolumeID: "v1", - Authority: AuthorityBasis{ - Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, - DataAddr: "d1", CtrlAddr: "c1", - }, - PrimarySlot: acceptableSlot("r1", "s1", "d1-new", "c1"), - SecondarySlot: acceptableSlot("r2", "s2", "d2", "c2"), - }}, - {"reassign", PolicySnapshot{VolumeID: "v1", - Authority: AuthorityBasis{ - Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, - DataAddr: "d1", CtrlAddr: "c1", - }, - PrimarySlot: func() SlotObservation { - s := acceptableSlot("r1", "s1", "d1", "c1") - s.Reachable = false - return s - }(), - SecondarySlot: acceptableSlot("r2", "s2", "d2", "c2"), - }}, - } - for _, c := range cases { - ask, kind := owner.decide(c.snap) - if kind != decisionEmit { - continue - } - switch ask.Intent { - case IntentBind, IntentRefreshEndpoint, IntentReassign: - // ok - default: - t.Fatalf("%s: illegal intent produced: %s", c.name, ask.Intent) - } - } -} - -func TestPolicy_UnsupportedTopology_AlwaysEmitsEvidence(t *testing.T) { - reader := newFakeBasisReader() - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, reader) - // Authority points to a replica not in either slot. - snap := PolicySnapshot{ - VolumeID: "v1", - CollectedRevision: 7, - Authority: AuthorityBasis{ - Assigned: true, ReplicaID: "r-unknown", Epoch: 1, EndpointVersion: 1, - }, - PrimarySlot: acceptableSlot("r1", "s1", "d1", "c1"), - SecondarySlot: acceptableSlot("r2", "s2", "d2", "c2"), - } - expectNoEmit(t, owner, snap) - - ev, ok := owner.LastUnsupported() - if !ok { - t.Fatal("unsupported topology must not be silent idle — evidence required") - } - if ev.SnapshotRevision != 7 { - t.Fatalf("evidence revision: got %d want 7", ev.SnapshotRevision) - } -} - -// ============================================================ -// §13.4 — End-to-end closure tests -// ============================================================ - -// policyClosureExecutor is a minimal CommandExecutor that drives -// the adapter to Healthy on a caught-up replica. -// -// Fence behavior is configurable: -// - default: fires onFenceComplete inline (deterministic for -// tests that do not need to observe the ack-gated window). -// - after ArmHoldNextFence: the NEXT Fence call stashes its -// result in heldResult instead of firing. Tests release it -// via ReleaseHeldFence() once they have observed the -// transitional state (adapter at new Epoch but not yet -// Healthy). One-shot per arm. -type policyClosureExecutor struct { - mu sync.Mutex - onFenceComplete adapter.OnFenceComplete - nextSession atomic.Uint64 - - holdNext bool - heldResult *adapter.FenceResult -} - -func newPolicyClosureExecutor() *policyClosureExecutor { - pe := &policyClosureExecutor{} - pe.nextSession.Store(2000) - return pe -} - -func (e *policyClosureExecutor) SetOnSessionStart(fn adapter.OnSessionStart) {} -func (e *policyClosureExecutor) SetOnSessionClose(fn adapter.OnSessionClose) {} -func (e *policyClosureExecutor) SetOnFenceComplete(fn adapter.OnFenceComplete) { - e.mu.Lock() - e.onFenceComplete = fn - e.mu.Unlock() -} - -func (e *policyClosureExecutor) Probe(replicaID, dataAddr, ctrlAddr string, sessionID, epoch, endpointVersion uint64) adapter.ProbeResult { - return adapter.ProbeResult{ - ReplicaID: replicaID, Success: true, - EndpointVersion: endpointVersion, TransportEpoch: epoch, - ReplicaFlushedLSN: 100, PrimaryTailLSN: 10, PrimaryHeadLSN: 100, - } -} - -func (e *policyClosureExecutor) StartCatchUp(replicaID string, sessionID, epoch, endpointVersion, fromLSN, targetLSN uint64) error { - return nil -} -func (e *policyClosureExecutor) StartRebuild(replicaID string, sessionID, epoch, endpointVersion, targetLSN uint64) error { - return nil -} -func (e *policyClosureExecutor) StartRecoverySession(replicaID string, sessionID, epoch, endpointVersion, targetLSN uint64, contentKind engine.RecoveryContentKind, policy engine.RecoveryRuntimePolicy) error { - return nil -} -func (e *policyClosureExecutor) InvalidateSession(replicaID string, sessionID uint64, reason string) {} -func (e *policyClosureExecutor) PublishHealthy(replicaID string) {} -func (e *policyClosureExecutor) PublishDegraded(replicaID string, reason string) {} - -func (e *policyClosureExecutor) Fence(replicaID string, sessionID, epoch, endpointVersion uint64) error { - result := adapter.FenceResult{ - ReplicaID: replicaID, SessionID: sessionID, - Epoch: epoch, EndpointVersion: endpointVersion, - Success: true, - } - e.mu.Lock() - if e.holdNext { - e.heldResult = &result - e.holdNext = false - e.mu.Unlock() - return nil - } - cb := e.onFenceComplete - e.mu.Unlock() - if cb != nil { - cb(result) - } - return nil -} - -// ArmHoldNextFence causes the next Fence() call to stash its -// FenceResult instead of firing onFenceComplete. Used by the -// publication-honesty-during-transition test to observe the -// ack-gated window deterministically. -func (e *policyClosureExecutor) ArmHoldNextFence() { - e.mu.Lock() - e.holdNext = true - e.mu.Unlock() -} - -// HasHeldFence reports whether a held FenceResult is waiting to -// be released. -func (e *policyClosureExecutor) HasHeldFence() bool { - e.mu.Lock() - defer e.mu.Unlock() - return e.heldResult != nil -} - -// ReleaseHeldFence fires the previously-held FenceResult (if any) -// to onFenceComplete. Returns true if a release happened. -func (e *policyClosureExecutor) ReleaseHeldFence() bool { - e.mu.Lock() - held := e.heldResult - e.heldResult = nil - cb := e.onFenceComplete - e.mu.Unlock() - if held == nil || cb == nil { - return false - } - cb(*held) - return true -} - -func waitHealthy(t *testing.T, a *adapter.VolumeReplicaAdapter, deadline time.Duration) { - t.Helper() - end := time.Now().Add(deadline) - for time.Now().Before(end) { - if a.Projection().Mode == engine.ModeHealthy { - return - } - time.Sleep(10 * time.Millisecond) - } - t.Fatalf("adapter did not reach Healthy; mode=%s", a.Projection().Mode) -} - -// waitHealthyAtEpoch waits for the adapter to report Healthy AT or -// above the given epoch. Distinct from waitHealthy because an -// adapter that was already Healthy from a prior bind satisfies -// waitHealthy trivially — failover/refresh tests need to confirm -// the identity actually advanced to the expected epoch. -func waitHealthyAtEpoch(t *testing.T, a *adapter.VolumeReplicaAdapter, minEpoch uint64, deadline time.Duration) { - t.Helper() - end := time.Now().Add(deadline) - for time.Now().Before(end) { - p := a.Projection() - if p.Mode == engine.ModeHealthy && p.Epoch >= minEpoch { - return - } - time.Sleep(10 * time.Millisecond) - } - p := a.Projection() - t.Fatalf("adapter did not reach Healthy at epoch>=%d; mode=%s epoch=%d", - minEpoch, p.Mode, p.Epoch) -} - -// TestPolicyToAdapter_E2E_Bind proves the full S3→S2 route for a -// first-time bind: -// policy snapshot -> PolicyOwner.Next -> Publisher -> Bridge -> -// adapter.OnAssignment -> engine Healthy. -func TestPolicyToAdapter_E2E_Bind(t *testing.T) { - exec := newPolicyClosureExecutor() - a := adapter.NewVolumeReplicaAdapter(exec) - - pub := NewPublisher(nil) // Directive wired below - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, pub) - pub.dir = owner // the publisher drives the policy owner as its directive - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - go pub.Run(ctx) - go Bridge(ctx, pub, a, "v1", "r1") - - if err := owner.SubmitSnapshot(PolicySnapshot{ - VolumeID: "v1", - Authority: AuthorityBasis{Assigned: false}, - PrimarySlot: acceptableSlot("r1", "s1", "10.0.0.2:9333", "10.0.0.2:9334"), - SecondarySlot: acceptableSlot("r2", "s2", "10.0.0.3:9333", "10.0.0.3:9334"), - }); err != nil { - t.Fatalf("submit: %v", err) - } - - waitHealthy(t, a, 2*time.Second) -} - -// TestPolicyToAdapter_E2E_Failover — initial Bind on primary, then -// primary becomes unreachable, policy emits Reassign, adapter -// re-anchors and reaches Healthy on the new epoch. -// -// This test uses ONE VolumeBridge for the accepted two-slot -// topology, started at the top and never torn down. The adapter -// retarget from r1 to r2 happens through the authority route — -// no test-side bridge teardown-and-retarget choreography. That is -// the honest closure claim of "failover is system-driven". -func TestPolicyToAdapter_E2E_Failover(t *testing.T) { - exec := newPolicyClosureExecutor() - a := adapter.NewVolumeReplicaAdapter(exec) - - pub := NewPublisher(nil) - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, pub) - pub.dir = owner - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - go pub.Run(ctx) - - // One VolumeBridge covers both accepted slots. It spawns - // internal per-slot Bridges and forwards each delivery to the - // same adapter. The adapter's monotonic applyAssignment - // handles the r1→r2 identity advance on cross-slot Reassign. - go VolumeBridge(ctx, pub, a, "v1", "r1", "r2") - - // Initial bind. - if err := owner.SubmitSnapshot(PolicySnapshot{ - VolumeID: "v1", - Authority: AuthorityBasis{Assigned: false}, - PrimarySlot: acceptableSlot("r1", "s1", "10.0.0.2:9333", "10.0.0.2:9334"), - SecondarySlot: acceptableSlot("r2", "s2", "10.0.0.3:9333", "10.0.0.3:9334"), - }); err != nil { - t.Fatalf("submit 1: %v", err) - } - waitHealthy(t, a, 2*time.Second) - - // Failover snapshot: primary unreachable, secondary healthy. - base, _ := pub.LastAuthorityBasis("v1", "r1") - primary := acceptableSlot("r1", "s1", "10.0.0.2:9333", "10.0.0.2:9334") - primary.Reachable = false - if err := owner.SubmitSnapshot(PolicySnapshot{ - VolumeID: "v1", - Authority: base, - PrimarySlot: primary, - SecondarySlot: acceptableSlot("r2", "s2", "10.0.0.3:9333", "10.0.0.3:9334"), - }); err != nil { - t.Fatalf("submit 2: %v", err) - } - // Wait for the adapter to move to the new epoch via the same - // VolumeBridge — no test-side retargeting. - waitHealthyAtEpoch(t, a, 2, 2*time.Second) - - // Verify the epoch bumped (Reassign bumps epoch, resets EV=1) - // and the new replica is r2 — cross-slot failover worked. - final, ok := pub.LastAuthorityBasis("v1", "r2") - if !ok { - t.Fatal("post-failover: no basis published for r2") - } - if final.Epoch != 2 { - t.Fatalf("post-failover epoch: got %d want 2", final.Epoch) - } - if final.EndpointVersion != 1 { - t.Fatalf("post-failover EV: got %d want 1 (Reassign resets EV)", final.EndpointVersion) - } -} - -// TestVolumeBridge_FollowsFailoverWithoutTestChoreography is the -// direct closure regression for finding 2: the S3 failover path -// must be system-owned. One VolumeBridge is started at the top of -// the test; no bridge cancel/restart happens during the test. -// After cross-slot failover, the adapter reports Healthy at the -// new epoch without any test orchestration. -func TestVolumeBridge_FollowsFailoverWithoutTestChoreography(t *testing.T) { - exec := newPolicyClosureExecutor() - a := adapter.NewVolumeReplicaAdapter(exec) - - pub := NewPublisher(nil) - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, pub) - pub.dir = owner - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - // ONE VolumeBridge for the accepted two-slot topology; no - // per-slot Bridge calls in this test. - go pub.Run(ctx) - go VolumeBridge(ctx, pub, a, "v1", "r1", "r2") - - // Initial bind. - if err := owner.SubmitSnapshot(PolicySnapshot{ - VolumeID: "v1", - Authority: AuthorityBasis{Assigned: false}, - PrimarySlot: acceptableSlot("r1", "s1", "10.0.0.2:9333", "10.0.0.2:9334"), - SecondarySlot: acceptableSlot("r2", "s2", "10.0.0.3:9333", "10.0.0.3:9334"), - }); err != nil { - t.Fatalf("submit 1: %v", err) - } - waitHealthyAtEpoch(t, a, 1, 2*time.Second) - - // Cross-slot failover: primary unreachable. - base, _ := pub.LastAuthorityBasis("v1", "r1") - primary := acceptableSlot("r1", "s1", "10.0.0.2:9333", "10.0.0.2:9334") - primary.Reachable = false - if err := owner.SubmitSnapshot(PolicySnapshot{ - VolumeID: "v1", - Authority: base, - PrimarySlot: primary, - SecondarySlot: acceptableSlot("r2", "s2", "10.0.0.3:9333", "10.0.0.3:9334"), - }); err != nil { - t.Fatalf("submit 2: %v", err) - } - - // Without any test-side retarget, the adapter must reach - // Healthy at epoch=2 on the new replica. - waitHealthyAtEpoch(t, a, 2, 2*time.Second) -} - -// TestPolicyToAdapter_E2E_EndpointRefresh — initial bind, then the -// primary's data address changes, policy emits RefreshEndpoint, -// publisher bumps EndpointVersion, adapter re-anchors on same -// epoch with new EV. -func TestPolicyToAdapter_E2E_EndpointRefresh(t *testing.T) { - exec := newPolicyClosureExecutor() - a := adapter.NewVolumeReplicaAdapter(exec) - - pub := NewPublisher(nil) - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, pub) - pub.dir = owner - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - go pub.Run(ctx) - go Bridge(ctx, pub, a, "v1", "r1") - - if err := owner.SubmitSnapshot(PolicySnapshot{ - VolumeID: "v1", - Authority: AuthorityBasis{Assigned: false}, - PrimarySlot: acceptableSlot("r1", "s1", "10.0.0.2:9333", "10.0.0.2:9334"), - SecondarySlot: acceptableSlot("r2", "s2", "10.0.0.3:9333", "10.0.0.3:9334"), - }); err != nil { - t.Fatalf("submit 1: %v", err) - } - waitHealthy(t, a, 2*time.Second) - - // DataAddr changes on the primary. - base, _ := pub.LastAuthorityBasis("v1", "r1") - if err := owner.SubmitSnapshot(PolicySnapshot{ - VolumeID: "v1", - Authority: base, - PrimarySlot: acceptableSlot("r1", "s1", "10.0.0.2:9335", "10.0.0.2:9334"), - SecondarySlot: acceptableSlot("r2", "s2", "10.0.0.3:9333", "10.0.0.3:9334"), - }); err != nil { - t.Fatalf("submit 2: %v", err) - } - - // Wait for EV to advance on r1. - deadline := time.Now().Add(2 * time.Second) - for time.Now().Before(deadline) { - if b, ok := pub.LastAuthorityBasis("v1", "r1"); ok && b.EndpointVersion == 2 { - return - } - time.Sleep(10 * time.Millisecond) - } - b, _ := pub.LastAuthorityBasis("v1", "r1") - t.Fatalf("EndpointVersion did not advance to 2; basis=%+v", b) -} - -// TestVolumeBridge_PostFailoverOldSlotRefreshRejectedByAdapter -// closes the 14A gap "preserved old-slot state must not perturb -// the new authoritative state". After cross-slot failover moves -// authority from r1@1 to r2@2 and the adapter is Healthy at -// epoch=2, an out-of-band RefreshEndpoint on the OLD slot r1 -// (which bumps publisher state to r1@epoch=1,EV=2) is delivered -// through VolumeBridge. The adapter must reject it on the -// engine-side monotonic-epoch guard (e.Epoch=1 < current=2) and -// remain Healthy at epoch=2, unperturbed. -// -// The test uses pub.apply() directly to inject the old-slot -// refresh because the policy decision table would never emit such -// a refresh once authority has moved. The point here is adapter- -// level rejection of stale-identity input delivered through the -// real VolumeBridge route. -func TestVolumeBridge_PostFailoverOldSlotRefreshRejectedByAdapter(t *testing.T) { - exec := newPolicyClosureExecutor() - a := adapter.NewVolumeReplicaAdapter(exec) - - pub := NewPublisher(nil) - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, pub) - pub.dir = owner - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - go pub.Run(ctx) - go VolumeBridge(ctx, pub, a, "v1", "r1", "r2") - - // Step 1: Bind on r1 + wait for epoch=1 Healthy. - if err := owner.SubmitSnapshot(PolicySnapshot{ - VolumeID: "v1", - Authority: AuthorityBasis{Assigned: false}, - PrimarySlot: acceptableSlot("r1", "s1", "10.0.0.2:9333", "10.0.0.2:9334"), - SecondarySlot: acceptableSlot("r2", "s2", "10.0.0.3:9333", "10.0.0.3:9334"), - }); err != nil { - t.Fatalf("submit bind: %v", err) - } - waitHealthyAtEpoch(t, a, 1, 2*time.Second) - - // Step 2: cross-slot failover to r2 + wait for epoch=2 Healthy. - base, _ := pub.LastAuthorityBasis("v1", "r1") - primary := acceptableSlot("r1", "s1", "10.0.0.2:9333", "10.0.0.2:9334") - primary.Reachable = false - if err := owner.SubmitSnapshot(PolicySnapshot{ - VolumeID: "v1", - Authority: base, - PrimarySlot: primary, - SecondarySlot: acceptableSlot("r2", "s2", "10.0.0.3:9333", "10.0.0.3:9334"), - }); err != nil { - t.Fatalf("submit failover: %v", err) - } - waitHealthyAtEpoch(t, a, 2, 2*time.Second) - preEpoch := a.Projection().Epoch - preMode := a.Projection().Mode - - // Step 3: inject an out-of-band RefreshEndpoint on the old slot - // r1. This bumps publisher state to (r1, epoch=1, EV=2) and - // the VolumeBridge-internal Bridge for r1 delivers it to the - // adapter. The adapter's engine is at (r2, epoch=2); the new - // assignment's Epoch=1 is strictly less, so the engine drops - // it as stale. - if err := pub.apply(AssignmentAsk{ - VolumeID: "v1", ReplicaID: "r1", - DataAddr: "10.0.0.2:CHANGED", CtrlAddr: "10.0.0.2:9334", - Intent: IntentRefreshEndpoint, - }); err != nil { - t.Fatalf("out-of-band Refresh on r1: %v", err) - } - - // Give the bridge time to forward and the engine time to reject. - time.Sleep(150 * time.Millisecond) - - post := a.Projection() - if post.Mode != preMode { - t.Fatalf("adapter Mode perturbed by old-slot refresh: pre=%s post=%s", - preMode, post.Mode) - } - if post.Epoch != preEpoch { - t.Fatalf("adapter Epoch perturbed by old-slot refresh: pre=%d post=%d", - preEpoch, post.Epoch) - } - if post.Epoch != 2 { - t.Fatalf("adapter Epoch: got %d want 2 (unperturbed)", post.Epoch) - } - if post.Mode != engine.ModeHealthy { - t.Fatalf("adapter Mode: got %s want Healthy (unperturbed)", post.Mode) - } -} - -// TestPolicyToAdapter_E2E_Failover_PublicationHonestyDuringTransition -// closes the 14A "publication honesty during authority transition" -// proof gap. When policy moves authority r1@1 -> r2@2, the adapter -// MUST NOT remain Healthy throughout the transition: after the new -// assignment lands, Publication must be held non-Healthy until the -// fence ack gates it (P14 S1's ack-gated Healthy contract). Only -// after FenceCompleted does Mode flip back to Healthy at the new -// epoch. -// -// The test uses the fence-hold hook on the executor to observe the -// transitional state deterministically rather than racing the -// inline fence callback. -func TestPolicyToAdapter_E2E_Failover_PublicationHonestyDuringTransition(t *testing.T) { - exec := newPolicyClosureExecutor() - a := adapter.NewVolumeReplicaAdapter(exec) - - pub := NewPublisher(nil) - owner := NewPolicyOwner(PolicyConfig{VolumeID: "v1"}, pub) - pub.dir = owner - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - go pub.Run(ctx) - go VolumeBridge(ctx, pub, a, "v1", "r1", "r2") - - // Initial Bind at epoch=1 with inline fence (default). - if err := owner.SubmitSnapshot(PolicySnapshot{ - VolumeID: "v1", - Authority: AuthorityBasis{Assigned: false}, - PrimarySlot: acceptableSlot("r1", "s1", "10.0.0.2:9333", "10.0.0.2:9334"), - SecondarySlot: acceptableSlot("r2", "s2", "10.0.0.3:9333", "10.0.0.3:9334"), - }); err != nil { - t.Fatalf("submit bind: %v", err) - } - waitHealthyAtEpoch(t, a, 1, 2*time.Second) - - // Hold the NEXT fence — this will be the fence for the r2@2 - // assignment that the failover Reassign will produce. - exec.ArmHoldNextFence() - - // Failover. - base, _ := pub.LastAuthorityBasis("v1", "r1") - primary := acceptableSlot("r1", "s1", "10.0.0.2:9333", "10.0.0.2:9334") - primary.Reachable = false - if err := owner.SubmitSnapshot(PolicySnapshot{ - VolumeID: "v1", - Authority: base, - PrimarySlot: primary, - SecondarySlot: acceptableSlot("r2", "s2", "10.0.0.3:9333", "10.0.0.3:9334"), - }); err != nil { - t.Fatalf("submit failover: %v", err) - } - - // Wait until the adapter has taken on the new identity (epoch=2) - // AND the fence is in flight (held). During this window the - // engine's ack-gated Publication must hold Mode non-Healthy. - deadline := time.Now().Add(2 * time.Second) - for time.Now().Before(deadline) { - if a.Projection().Epoch == 2 && exec.HasHeldFence() { - break - } - time.Sleep(5 * time.Millisecond) - } - proj := a.Projection() - if proj.Epoch != 2 { - t.Fatalf("transition window: adapter did not advance to Epoch=2 (got %d)", proj.Epoch) - } - if !exec.HasHeldFence() { - t.Fatal("transition window: fence was not held as expected") - } - - // Publication honesty: the adapter MUST NOT claim Healthy - // while the fence is still in flight under the new epoch. - if proj.Mode == engine.ModeHealthy { - t.Fatalf("publication honesty violated: adapter Healthy at Epoch=2 before fence ack") - } - - // Release the held fence; adapter should flip to Healthy@2. - if !exec.ReleaseHeldFence() { - t.Fatal("ReleaseHeldFence returned false") - } - waitHealthyAtEpoch(t, a, 2, 2*time.Second) -} diff --git a/seaweed-block/core/authority/restart_route_test.go b/seaweed-block/core/authority/restart_route_test.go index 5bc187e23e..a8359404fd 100644 --- a/seaweed-block/core/authority/restart_route_test.go +++ b/seaweed-block/core/authority/restart_route_test.go @@ -49,9 +49,9 @@ import ( type restartExecutor struct { mu sync.Mutex - onStart adapter.OnSessionStart - onClose adapter.OnSessionClose - onFence adapter.OnFenceComplete + onStart adapter.OnSessionStart + onClose adapter.OnSessionClose + onFence adapter.OnFenceComplete // fenceMode drives what Fence() does with incoming calls. // "autoSuccess" (default): fire OnFenceComplete{Success:true} inline @@ -223,7 +223,7 @@ func newRestartRoute(t *testing.T, dir string, clk *fakeClock, cfg restartRouteC host := NewObservationHost(ObservationHostConfig{ Freshness: FreshnessConfig{FreshnessWindow: 30 * time.Second, PendingGrace: 10 * time.Millisecond}, Topology: cfg.Topology, - Sink: ctrl, + Sink: gatedSink{ctrl}, // the promotion gate decides, as on the master Reader: hostRdr, Now: now, }) @@ -483,8 +483,8 @@ func TestS7_Restart_StaleObservationCannotMoveBackward(t *testing.T) { // assertions simple. All four expect: no ask reaches the // adapter beyond the single reloaded line. sub := []struct { - name string - freeze AuthorityBasis // fake stale line to feed through the host reader + name string + freeze AuthorityBasis // fake stale line to feed through the host reader }{ {"stale-epoch", AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 0, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"}}, {"stale-replica", AuthorityBasis{Assigned: true, ReplicaID: "r-old", Epoch: 1, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"}}, @@ -583,7 +583,7 @@ func TestS7_Restart_OldSlotNotRevivedFromDurable(t *testing.T) { Topology: threeSlotTopology("vr"), Directive: NewStaticDirective([]AssignmentAsk{ {VolumeID: "vr", ReplicaID: "r1", DataAddr: "d1", CtrlAddr: "c1", Intent: IntentBind}, - {VolumeID: "vr", ReplicaID: "r2", DataAddr: "d2", CtrlAddr: "c2", Intent: IntentReassign}, + {VolumeID: "vr", ReplicaID: "r2", DataAddr: "d2", CtrlAddr: "c2", Intent: IntentReassign, Evidence: testPromotion}, }), }) // Wait until publisher line advances to r2@2. @@ -661,7 +661,7 @@ func TestS7_LiveRoute_OldSlotDeliveryRejectedByAdapter(t *testing.T) { // state that legitimately holds both per-replica keys. dir := NewStaticDirective([]AssignmentAsk{ {VolumeID: "vr", ReplicaID: "r1", DataAddr: "d1", CtrlAddr: "c1", Intent: IntentBind}, - {VolumeID: "vr", ReplicaID: "r2", DataAddr: "d2", CtrlAddr: "c2", Intent: IntentReassign}, + {VolumeID: "vr", ReplicaID: "r2", DataAddr: "d2", CtrlAddr: "c2", Intent: IntentReassign, Evidence: testPromotion}, }) pub := NewPublisher(dir) ctx, cancel := context.WithCancel(context.Background()) diff --git a/seaweed-block/core/authority/topology.go b/seaweed-block/core/authority/topology.go index 712accf052..ad563e25ef 100644 --- a/seaweed-block/core/authority/topology.go +++ b/seaweed-block/core/authority/topology.go @@ -4,6 +4,8 @@ import ( "fmt" "sort" "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" ) // ServerObservation is one server's cluster-visible readiness for @@ -26,9 +28,13 @@ type ReplicaCandidate struct { CtrlAddr string Reachable bool ReadyForPrimary bool - Eligible bool - Withdrawn bool - EvidenceScore uint64 + // PromotionEvidence is what the promotion gate probed on this replica + // when it allowed it (kind PROMOTION); a reassign to it carries this to + // the target. A replica without it is never promoted. + PromotionEvidence adapter.PrimaryEvidence + Eligible bool + Withdrawn bool + EvidenceScore uint64 // Incarnation identifies the reporting volume process; it changes // on every process start. Empty from older volume binaries. Incarnation string diff --git a/seaweed-block/core/frontend/nvmerdma/failover_reopen_test.go b/seaweed-block/core/frontend/nvmerdma/failover_reopen_test.go index 1f9583335b..901eddbffe 100644 --- a/seaweed-block/core/frontend/nvmerdma/failover_reopen_test.go +++ b/seaweed-block/core/frontend/nvmerdma/failover_reopen_test.go @@ -16,6 +16,17 @@ import ( "github.com/seaweedfs/seaweed-block/core/lifecycle" ) +// readyGate is a promotion gate whose candidates all answered ready. +type readyGate struct{} + +func (readyGate) ProbePromotionCandidates(_ string, _ authority.AuthorityBasis, cs []authority.ReplicaCandidate) (master.PromotionProbeResult, error) { + res := master.PromotionProbeResult{AckProfile: "sync_all", SyncAckKnown: true} + for _, c := range cs { + res.Candidates = append(res.Candidates, master.PromotionCandidateEvidence{ReplicaID: c.ReplicaID, Ready: true, DurableLSN: 1}) + } + return res, nil +} + func reopenWait(t *testing.T, what string, fn func() bool) { t.Helper() end := time.Now().Add(5 * time.Second) @@ -37,6 +48,10 @@ func TestProviderBackendReopensAfterRealMasterFailover(t *testing.T) { if err != nil { t.Fatal(err) } + // The promotion gate: every candidate the controller asks about answers a + // probe round ready (this test is about the frontend reopening, not the + // gate). + m.SetPromotionEvidenceProvider(readyGate{}) m.Start() t.Cleanup(func() { ctx, c := context.WithTimeout(context.Background(), 3*time.Second) diff --git a/seaweed-block/core/host/master/failback_runtime_test.go b/seaweed-block/core/host/master/failback_runtime_test.go index 8b2f06d7a2..6197c4f3c6 100644 --- a/seaweed-block/core/host/master/failback_runtime_test.go +++ b/seaweed-block/core/host/master/failback_runtime_test.go @@ -18,6 +18,7 @@ import ( func TestHostFailbackAuthorityRuntimeUsesLivePublisher(t *testing.T) { h := newTestMaster(t, t.TempDir()) defer closeTestMaster(t, h) + installPlannedMoveGate(h) // the operator's planned move decides on the promotion gate seedVerifiedExistingReplicaPlacement(t, h) if _, err := h.RunLifecycleProductTick(); err != nil { @@ -66,6 +67,7 @@ func TestHostFailbackAuthorityRuntimeUsesLivePublisher(t *testing.T) { func TestHostFrontendPublicationRuntimeHTTPConfirmsPostFailbackAuthorityLine(t *testing.T) { h := newTestMasterWithFrontendPublicationRuntimeHTTP(t) defer closeTestMaster(t, h) + installPlannedMoveGate(h) // the operator's planned move decides on the promotion gate seedVerifiedExistingReplicaPlacement(t, h) if _, err := h.RunLifecycleProductTick(); err != nil { t.Fatalf("product tick: %v", err) @@ -196,6 +198,7 @@ func TestFailbackServiceDefaultDisabled(t *testing.T) { func TestFailbackServiceEnabledUsesHostRuntime(t *testing.T) { h := newTestMasterWithFailbackRuntimeRPC(t) defer closeTestMaster(t, h) + installPlannedMoveGate(h) // the operator's planned move decides on the promotion gate seedVerifiedExistingReplicaPlacement(t, h) if _, err := h.RunLifecycleProductTick(); err != nil { t.Fatalf("product tick: %v", err) @@ -238,6 +241,7 @@ func TestFailbackServiceEnabledUsesHostRuntime(t *testing.T) { func TestFailbackExecutorGRPCRuntimeUsesRealMasterService(t *testing.T) { h := newTestMasterWithFailbackRuntimeRPC(t) defer closeTestMaster(t, h) + installPlannedMoveGate(h) // the operator's planned move decides on the promotion gate seedVerifiedExistingReplicaPlacement(t, h) if _, err := h.RunLifecycleProductTick(); err != nil { t.Fatalf("product tick: %v", err) @@ -367,3 +371,13 @@ func (c *failbackExecutorMasterServiceClient) WriteReplicaFailbackStatus(_ conte c.writes = append(c.writes, failbackExecutorMasterServiceWrite{ref: ref, status: status}) return nil } + +// installPlannedMoveGate gives the master a promotion gate under which a +// planned move to r1 is allowed: sync_all (the target is in every +// acknowledgement set) and r1 answers the probe round ready. +func installPlannedMoveGate(h *Host) { + h.SetPromotionEvidenceProvider(staticPromotionProbe{result: PromotionProbeResult{ + AckProfile: "sync_all", + Candidates: []PromotionCandidateEvidence{{ReplicaID: "r1", Ready: true, DurableLSN: 1}}, + }}) +} diff --git a/seaweed-block/core/host/master/planned_move.go b/seaweed-block/core/host/master/planned_move.go new file mode 100644 index 0000000000..90dd8e4000 --- /dev/null +++ b/seaweed-block/core/host/master/planned_move.go @@ -0,0 +1,87 @@ +package master + +import ( + "errors" + "fmt" + "strings" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/authority" +) + +// ErrPlannedMoveNeedsSeal: under this ack profile and replica count a write +// can be acknowledged without the target holding it (RF3 sync_quorum: the +// other replica acks alone), so a planned move is safe only after the old +// primary stops acknowledging (a seal), which v1 does not have. +var ErrPlannedMoveNeedsSeal = errors.New("planned move: the target is not in every acknowledgement set; it needs the old primary sealed first (not available), or use a forced move with its lost range") + +// ErrPlannedMoveBestEffort: best_effort acknowledges a write without any +// replica, so a planned move can drop acknowledged writes by definition. +var ErrPlannedMoveBestEffort = errors.New("planned move: best_effort acknowledges writes without a replica; only a forced move (its lost range reported) can change the primary") + +// plannedMoveAllowed is the guard of a planned move (an operator moving the +// primary to a live, caught-up replica without a seal): the target must be +// in every acknowledgement set, so every write acknowledged before it adopts +// is already durable on it (and after it adopts, its epoch floor refuses the +// old primary's frames). That holds for sync_all at any replica count, and +// for sync_quorum when the target is the only replica (RF2). replicas counts +// every slot of the volume, the primary included. +func plannedMoveAllowed(ackProfile string, replicas int) error { + switch strings.ToLower(strings.ReplaceAll(ackProfile, "-", "_")) { + case "sync_all": + return nil + case "sync_quorum": + if replicas <= 2 { + return nil + } + return ErrPlannedMoveNeedsSeal + case "best_effort": + return ErrPlannedMoveBestEffort + } + return fmt.Errorf("planned move: unknown ack profile %q", ackProfile) +} + +// ackProfiled is a promotion evidence provider that knows the ack profile. +type ackProfiled interface{ AckProfile() string } + +func (p *roundEvidenceProvider) AckProfile() string { return p.ackProfile } + +// plannedMoveEvidence is the promotion gate's decision for an operator's +// planned move to target: the guard, then a probe round of the target, which +// must answer ready; its evidence goes on the line (kind PROMOTION). +func (h *Host) plannedMoveEvidence(volumeID, target string) (adapter.PrimaryEvidence, error) { + h.promotionMu.RLock() + prober := h.promotionProber + h.promotionMu.RUnlock() + if prober == nil { + return adapter.PrimaryEvidence{}, fmt.Errorf("planned move: no promotion gate is configured") + } + profile := "" + if ap, ok := prober.(ackProfiled); ok { + profile = ap.AckProfile() + } + // The volume's replicas and the target's node, from its placement. + placement, ok := h.lifecycle.Placements.GetPlacement(volumeID) + if !ok || len(placement.Slots) == 0 { + return adapter.PrimaryEvidence{}, fmt.Errorf("planned move: volume %s has no placement", volumeID) + } + targetServer := "" + for _, s := range placement.Slots { + if s.ReplicaID == target { + targetServer = s.ServerID + } + } + if err := plannedMoveAllowed(profile, len(placement.Slots)); err != nil { + return adapter.PrimaryEvidence{}, err + } + 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) + } + for _, c := range result.Candidates { + if c.ReplicaID == target && c.Ready { + return promotionEvidenceFor(result, target), nil + } + } + return adapter.PrimaryEvidence{}, fmt.Errorf("planned move: replica %s did not answer the probe round ready (caught up, epoch table valid)", target) +} diff --git a/seaweed-block/core/host/master/planned_move_test.go b/seaweed-block/core/host/master/planned_move_test.go new file mode 100644 index 0000000000..805a392b52 --- /dev/null +++ b/seaweed-block/core/host/master/planned_move_test.go @@ -0,0 +1,30 @@ +package master + +import ( + "errors" + "testing" +) + +// A planned move without a seal is safe exactly when the target is in every +// acknowledgement set: one row per ack profile and replica count. +func TestPlannedMoveAllowedByAckProfileAndReplicas(t *testing.T) { + for _, c := range []struct { + profile string + replicas int + want error + }{ + {"sync_all", 2, nil}, + {"sync_all", 3, nil}, + {"sync-quorum", 2, nil}, + {"sync_quorum", 3, ErrPlannedMoveNeedsSeal}, + {"best_effort", 2, ErrPlannedMoveBestEffort}, + {"best_effort", 3, ErrPlannedMoveBestEffort}, + } { + if err := plannedMoveAllowed(c.profile, c.replicas); !errors.Is(err, c.want) && !(c.want == nil && err == nil) { + t.Errorf("%s RF%d: %v; want %v", c.profile, c.replicas, err, c.want) + } + } + if err := plannedMoveAllowed("unknown", 2); err == nil { + t.Error("an unknown ack profile was allowed") + } +} diff --git a/seaweed-block/core/host/master/product_loop.go b/seaweed-block/core/host/master/product_loop.go index 6ce027a580..88a588832a 100644 --- a/seaweed-block/core/host/master/product_loop.go +++ b/seaweed-block/core/host/master/product_loop.go @@ -5,6 +5,7 @@ import ( "reflect" "strings" + "github.com/seaweedfs/seaweed-block/core/adapter" "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/lifecycle" "github.com/seaweedfs/seaweed-block/core/ops" @@ -26,6 +27,14 @@ type PromotionCandidateEvidence struct { Ready bool DurableLSN uint64 ProbeAddr string + // LastDataEpoch and LastDataFirstLSN are the candidate's epoch-table row + // at DurableLSN (zero: no table, or no row): the promotion line carries + // them, and the target adopts only if its own row at that LSN is the same. + LastDataEpoch uint64 + LastDataFirstLSN uint64 + // TableInvalid: a recovery left the candidate's table without a known + // history; such a candidate is never Ready (never a promotion survivor). + TableInvalid bool } type PromotionProbeResult struct { @@ -204,7 +213,9 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int, } for vi := range snap.Volumes { vol := &snap.Volumes[vi] - if len(vol.Slots) < 3 || !vol.Authority.Assigned { + h.noteSlotServers(vol.VolumeID, vol.Slots) + // Every replicated volume (RF2 and RF3) decides a promotion here. + if len(vol.Slots) < 2 || !vol.Authority.Assigned { continue } currentIdx := replicaIndex(vol.Slots, vol.Authority.ReplicaID) @@ -244,9 +255,11 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int, } if allowed[slot.ReplicaID] { slot.ReadyForPrimary = true + slot.PromotionEvidence = promotionEvidenceFor(result, slot.ReplicaID) enabledCandidate = true } else { slot.ReadyForPrimary = false + slot.PromotionEvidence = adapter.PrimaryEvidence{} } } // After the (blocking) probe, judge the current primary from its @@ -266,6 +279,7 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int, DataAddr: target.DataAddr, CtrlAddr: target.CtrlAddr, Intent: authority.IntentReassign, + Evidence: promotionEvidenceFor(result, target.ReplicaID), }) } } @@ -297,7 +311,7 @@ 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) - if len(placement.Slots) < 3 || !placementIsConcreteExistingReplica(placement) || !unsupportedReasonsAllowPromotionProbe(evidence.Reasons) { + if len(placement.Slots) < 2 || !placementIsConcreteExistingReplica(placement) || !unsupportedReasonsAllowPromotionProbe(evidence.Reasons) { continue } current, ok := h.Publisher().VolumeAuthorityLine(placement.VolumeID) @@ -361,6 +375,7 @@ func (h *Host) applyUnsupportedPromotionEvidenceGate(placements []lifecycle.Plac DataAddr: target.DataAddr, CtrlAddr: target.CtrlAddr, Intent: authority.IntentReassign, + Evidence: promotionEvidenceFor(result, target.ReplicaID), }) } continue @@ -668,6 +683,17 @@ func promotionAllowedReplicas(result PromotionProbeResult, ok bool, peerCount in return allowed } +// promotionEvidenceFor is the line's evidence for promoting replicaID: what +// this tick's probe saw on it (its durable LSN and its epoch-table row there). +func promotionEvidenceFor(result PromotionProbeResult, replicaID string) adapter.PrimaryEvidence { + for _, c := range result.Candidates { + if c.ReplicaID == replicaID { + return adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion, DurableLSN: c.DurableLSN, DataEpoch: c.LastDataEpoch, DataFirstLSN: c.LastDataFirstLSN} + } + } + return adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion} +} + func chooseAllowedPromotionTarget(vol authority.VolumeTopologySnapshot, result PromotionProbeResult, allowed map[string]bool) (authority.ReplicaCandidate, bool) { durable := map[string]uint64{} for _, candidate := range result.Candidates { diff --git a/seaweed-block/core/host/master/product_loop_test.go b/seaweed-block/core/host/master/product_loop_test.go index c52a824938..9bdb14ae5f 100644 --- a/seaweed-block/core/host/master/product_loop_test.go +++ b/seaweed-block/core/host/master/product_loop_test.go @@ -102,6 +102,14 @@ func TestMountedFailover_ProductLoopRF2UsesAuthorityControllerForFailover(t *tes ExpectedSlotsPerVolume: 2, }) defer closeTestMaster(t, h) + // The candidate's answer to the promotion probe round: RF2 decides a + // failover on it like RF3 (a primary change goes out only with evidence). + h.SetPromotionEvidenceProvider(staticPromotionProbe{result: PromotionProbeResult{ + AckProfile: "sync-quorum", + CurrentKnown: true, + Current: PromotionCandidateEvidence{ReplicaID: "r1"}, + Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 1}}, + }}) seedRF2Placement(t, h) ingestRF2Observation(t, h, true, true) @@ -982,6 +990,9 @@ func (s staticPromotionProbe) ProbePromotionCandidates(string, authority.Authori return s.result, s.err } +// AckProfile reports the probe's ack profile (as the round provider does). +func (s staticPromotionProbe) AckProfile() string { return s.result.AckProfile } + func recvAssignmentInfo(t *testing.T, ch <-chan adapter.AssignmentInfo) adapter.AssignmentInfo { t.Helper() select { diff --git a/seaweed-block/core/host/master/promotion_frontier_coverage_test.go b/seaweed-block/core/host/master/promotion_frontier_coverage_test.go index 41bf39f282..c2acaa4341 100644 --- a/seaweed-block/core/host/master/promotion_frontier_coverage_test.go +++ b/seaweed-block/core/host/master/promotion_frontier_coverage_test.go @@ -6,6 +6,7 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/adapter" "github.com/seaweedfs/seaweed-block/core/authority" ) @@ -241,27 +242,52 @@ func TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused(t *te // RF2 never consults the RF3 promotion gate: a probe that would refuse every // candidate (unknown frontier, no survivors) does not stop RF2 failover. -func TestMountedFailover_ProductLoopRF2IgnoresRF3FrontierGate(t *testing.T) { - h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 2}) - defer closeTestMaster(t, h) - h.SetPromotionEvidenceProvider(staticPromotionProbe{result: PromotionProbeResult{AckProfile: "sync-quorum"}}) - seedRF2Placement(t, h) - ingestRF2Observation(t, h, true, true) - if _, err := h.RunLifecycleProductTick(); err != nil { - t.Fatalf("initial product tick: %v", err) - } - if initial := waitAuthorityLine(t, h.Publisher(), "vol-rf2"); initial.ReplicaID != "r1" { - t.Fatalf("initial line=%+v want r1", initial) - } - ingestRF2Observation(t, h, false, true) - result, err := h.RunLifecycleProductTick() - if err != nil { - t.Fatalf("failover product tick: %v", err) - } - if result.PromotionProbes != 0 { - t.Fatalf("result=%+v want no RF3 promotion probe for RF2", result) - } - if failover := waitAuthorityReplica(t, h.Publisher(), "vol-rf2", "r2"); failover.Epoch != 2 { - t.Fatalf("failover line=%+v want r2@2", failover) +// RF2 decides a promotion on the promotion gate too (one replica besides the +// primary): with the candidate's answer ready the failover goes to it with +// the gate's evidence on the line; without a ready answer nothing is +// promoted, whatever the heartbeats say. +func TestMountedFailover_ProductLoopRF2DecidesOnThePromotionGate(t *testing.T) { + for _, ready := range []bool{true, false} { + t.Run(map[bool]string{true: "candidate ready", false: "no ready answer"}[ready], func(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 2}) + defer closeTestMaster(t, h) + h.SetPromotionEvidenceProvider(staticPromotionProbe{result: PromotionProbeResult{ + AckProfile: "sync-quorum", + CurrentKnown: true, + Current: PromotionCandidateEvidence{ReplicaID: "r1"}, + Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: ready, DurableLSN: 1}}, + }}) + seedRF2Placement(t, h) + ingestRF2Observation(t, h, true, true) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("initial product tick: %v", err) + } + if initial := waitAuthorityLine(t, h.Publisher(), "vol-rf2"); initial.ReplicaID != "r1" { + t.Fatalf("initial line=%+v want r1", initial) + } + ingestRF2Observation(t, h, false, true) + result, err := h.RunLifecycleProductTick() + if err != nil { + t.Fatalf("failover product tick: %v", err) + } + if result.PromotionProbes == 0 { + t.Fatalf("result=%+v: RF2 was not decided on the promotion gate", result) + } + if !ready { + time.Sleep(200 * time.Millisecond) + if line, _ := h.Publisher().VolumeAuthorityLine("vol-rf2"); line.ReplicaID != "r1" || line.Epoch != 1 { + t.Fatalf("promoted without a ready answer: line %+v", line) + } + return + } + failover := waitAuthorityReplica(t, h.Publisher(), "vol-rf2", "r2") + if failover.Epoch != 2 { + t.Fatalf("failover line=%+v want r2@2", failover) + } + info, _ := h.Publisher().LastPublished("vol-rf2", "r2") + if info.Primary.Kind != adapter.PrimaryKindPromotion || info.Primary.DurableLSN != 1 { + t.Fatalf("failover line evidence %+v; want the gate's PROMOTION at durable LSN 1", info.Primary) + } + }) } } diff --git a/seaweed-block/core/host/master/workspace_restore_test.go b/seaweed-block/core/host/master/workspace_restore_test.go index 95282bf1c2..27359cf045 100644 --- a/seaweed-block/core/host/master/workspace_restore_test.go +++ b/seaweed-block/core/host/master/workspace_restore_test.go @@ -91,6 +91,8 @@ func TestWorkspaceMoveRestoresLazilyAndFencesOldHost(t *testing.T) { // The authority runtime, not either provider, allocates the next epoch. // Admission evidence is supplied by this fixture, as in the runtime's // existing tests; this is not a VM-stop or physical fencing qualification. + // The planned move decides on the promotion gate (its fixture, too). + installPlannedMoveGate(m) if _, err := m.FailbackAuthorityRuntime().ExecuteFailback(ctx, authority.FailbackRuntimeRequest{ VolumeID: "vol-a", ReplicaID: "r1", TargetDataAddr: "127.0.0.1:9201", TargetCtrlAddr: "127.0.0.1:9101", ExpectedCurrentReplicaID: oldLine.ReplicaID, ExpectedCurrentEpoch: oldLine.Epoch, diff --git a/seaweed-block/core/ops/failback_authority_runtime_adapter.go b/seaweed-block/core/ops/failback_authority_runtime_adapter.go index 5a1acc3abd..aaabfb83ba 100644 --- a/seaweed-block/core/ops/failback_authority_runtime_adapter.go +++ b/seaweed-block/core/ops/failback_authority_runtime_adapter.go @@ -3,6 +3,7 @@ package ops import ( "context" + "github.com/seaweedfs/seaweed-block/core/adapter" "github.com/seaweedfs/seaweed-block/core/authority" ) @@ -13,9 +14,11 @@ type AuthorityFailbackRuntime struct { Runtime authority.FailbackAuthorityRuntime } -func NewAuthorityFailbackRuntime(publisher *authority.Publisher) *AuthorityFailbackRuntime { +// NewAuthorityFailbackRuntime adapts the authority failback runtime; gate is +// the promotion gate's planned-move decision (nil: every failback refuses). +func NewAuthorityFailbackRuntime(publisher *authority.Publisher, gate func(volumeID, targetReplicaID string) (adapter.PrimaryEvidence, error)) *AuthorityFailbackRuntime { return &AuthorityFailbackRuntime{ - Runtime: authority.FailbackAuthorityRuntime{Publisher: publisher}, + Runtime: authority.FailbackAuthorityRuntime{Publisher: publisher, Gate: gate}, } } diff --git a/seaweed-block/core/ops/failback_authority_runtime_adapter_test.go b/seaweed-block/core/ops/failback_authority_runtime_adapter_test.go index 8f0c997b7f..109dc3259b 100644 --- a/seaweed-block/core/ops/failback_authority_runtime_adapter_test.go +++ b/seaweed-block/core/ops/failback_authority_runtime_adapter_test.go @@ -6,6 +6,7 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweed-block/core/adapter" "github.com/seaweedfs/seaweed-block/core/authority" ) @@ -19,7 +20,7 @@ func TestFailbackExecutorUsesAuthorityRuntimeAdapter(t *testing.T) { result, err := (FailbackExecutorReconciler{ Namespace: "kube-system", Client: client, - Runtime: NewAuthorityFailbackRuntime(publisher), + Runtime: NewAuthorityFailbackRuntime(publisher, opsAllowGate), ExecutionRequested: true, ExecutionPolicyEnabled: true, Now: func() time.Time { return time.Date(2026, 6, 26, 15, 0, 0, 0, time.UTC) }, @@ -69,7 +70,7 @@ func TestFailbackAuthorityRuntimeAdapterRejectsStaleExpectedCurrent(t *testing.T result, err := (FailbackExecutorReconciler{ Namespace: "kube-system", Client: client, - Runtime: NewAuthorityFailbackRuntime(publisher), + Runtime: NewAuthorityFailbackRuntime(publisher, opsAllowGate), ExecutionRequested: true, ExecutionPolicyEnabled: true, }).Reconcile(context.Background()) @@ -113,6 +114,7 @@ func seededFailbackPublisher(t *testing.T) *authority.Publisher { DataAddr: "data-r2", CtrlAddr: "ctrl-r2", Intent: authority.IntentReassign, + Evidence: adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion}, }, }) publisher := authority.NewPublisher(directive) @@ -143,3 +145,8 @@ func seededFailbackPublisher(t *testing.T) *authority.Publisher { } } } + +// opsAllowGate stands in for the master's planned-move decision (allowed). +func opsAllowGate(string, string) (adapter.PrimaryEvidence, error) { + return adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion, DurableLSN: 1}, nil +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index f1c837e451..2b344f72b1 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -228,7 +228,7 @@ RF2 qualification limitation until ordered-live certification is wired (#297). S | Excluded | Excluded (no change) | an older recorded foreign fact cannot replace the newer epoch/endpoint-version fence; a stale replay cannot re-enable the frontend | `core/host/volume/host.go` `recordOtherLine`, `IsSuperseded` | `INV-AUTH-HOLDER-IDENTITY-001` | | 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=3 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` | +| 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` | **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. @@ -1030,7 +1030,7 @@ Notes: | `INV-AUTH-ONE-PRIMARY-001` | A volume's authority line names one replica at its highest epoch, a reassignment supersedes the previous primary, and observed dual primaries make the volume `invalid`. A genesis `Bind` is refused once any slot of the volume holds a line. | M2 Unbound → Bound, Bound → Reassigned; K8s readiness | `core/authority/authority.go` `applyWithWorkspaceMove` (`IntentBind`, `boundReplicaForVolume`); `core/authority/policy.go` `VolumeAuthorityLine`; `core/authority/controller.go` `decideVolume`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestPublisher_RunRejectsSecondSlotGenesisBind` (`core/authority/bind_volume_regression_test.go`); `TestPublisher_BindSecondSlotOfBoundVolumeRejected`, `TestPublisher_BindOtherVolumeUnaffected`, `TestPublisher_ReassignToOtherSlotStillAllowedThenBindRejected`, `TestPublisher_BindAfterRestartRejectedForAnySlot` (`core/authority/bind_volume_genesis_test.go`); `TestManagedVolumeProjection_InvalidDualPrimaryBeatsReady` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | | `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/promotion_probe.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 volume with three or more slots, the gate allows no candidate unless this tick's promotion probe succeeded with a known ack profile. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas` | `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe` (`core/host/master/product_loop_test.go`); `TestMountedFailover_ProductLoopRF2IgnoresRF3FrontierGate` (`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-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 | @@ -1054,7 +1054,7 @@ Notes: - `INV-AUTH-ONE-PRIMARY-001`: Narrowed. The lab evidence field `post_failure_primary_count=1` is not read by any Go test. `IntentBind` is checked per volume: the Publisher refuses a genesis `Bind` (`ErrBindAlreadyBound`) once any slot of the volume holds a present line, also after a restart, when only the current slot is reloaded; `decideVolume` also binds only when the volume has no line ([#183](https://github.com/seaweedfs/seaweed-block/issues/183)). - `INV-FENCE-STALE-PRIMARY-001`: Narrowed. A primary cut off from blockmaster that has not seen the newer line keeps admitting I/O, and under `best_effort` its local `fsync` still acknowledges (no primary lease on the Kubernetes path; see the Kubernetes known gaps). The lab counter `old_primary_stale_io_success_count=0` is lab evidence only. - `INV-PROMOTE-FRONTIER-001`: Fixed for [#181](https://github.com/seaweedfs/seaweed-block/issues/181). `cmd/blockmaster` does not set `RequiredLSNByVolume`, so in a deployment the frontier is unknown and the survivor rule applies (an RF=3 `sync_quorum` volume with one peer unseen is not promoted automatically). Limits: blockmaster has no source for the required frontier ([#192](https://github.com/seaweedfs/seaweed-block/issues/192)); the rule covers only the acknowledgements represented by the frontiers sampled in one tick, because those probes are snapshots, not a fence, and a deposed primary can still acknowledge after a sample (no primary lease, [#195](https://github.com/seaweedfs/seaweed-block/issues/195)). See [Kubernetes design §6 and §12](kubernetes-block-design.md). RF=2 relies on `INV-REPL-PROMOTION-READY-001`. -- `INV-PROMOTE-FRONTIER-PROBE-001`, `INV-PROMOTE-FRONTIER-UNKNOWN-001`, `INV-PROMOTE-FRONTIER-BEST-EFFORT-001`: new rows split from `INV-PROMOTE-FRONTIER-001`, kept beside it. N_peers is the number of replicas other than the current primary; for RF=3 (two peers) both must be seen under `sync_quorum`, one under `sync_all`. An unknown frontier is never read as zero. Heartbeat freshness is the observation store's rule (`FreshSlotCandidate`). The gate runs for a volume with three or more slots; "RF=3" names today's topologies. +- `INV-PROMOTE-FRONTIER-PROBE-001`, `INV-PROMOTE-FRONTIER-UNKNOWN-001`, `INV-PROMOTE-FRONTIER-BEST-EFFORT-001`: new rows split from `INV-PROMOTE-FRONTIER-001`, kept beside it. N_peers is the number of replicas other than the current primary; for RF=3 (two peers) both must be seen under `sync_quorum`, one under `sync_all`. An unknown frontier is never read as zero. Heartbeat freshness is the observation store's rule (`FreshSlotCandidate`). The gate runs for every volume with two or more slots (RF=2 included); a primary change is published only with its evidence. - `INV-K8S-NONLOOPBACK-001`: Rejection is opt-in: the chart default for `network.rejectLoopbackPublishTargets` is false; the generator sets it for multi-node values. - `INV-OBS-PRODUCT-EVENTS-001`: Each event type has a unit test; all four together in one node-loss run is lab evidence only. - `INV-HOSTPATH-TRANSPARENT-001`: Narrowed to the classifier. It does not compare the host path target with the promoted target, and only the missing-multipath case has a negative test. The mounted-failover run is lab evidence.