mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 19:17:28 +01:00
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 <noreply@anthropic.com>
This commit is contained in:
1 parent
26ffb11403
commit
c9fe8a7123
24 files changed
+501
-1853
No files matched your search
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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},
|
||||
},
|
||||
}},
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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())
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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}},
|
||||
}})
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
Reference in new issue
Block a user