From 5fb4fccd858188d0cb4546e0c418e644ff92fa1a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 02:42:49 -0800 Subject: [PATCH] authority, volume: the line carries its primary kind and evidence; the target checks its own store before it adopts A line names how it made its primary the primary: BOOTSTRAP (the volume's first primary), PROMOTION (with the gate's evidence: the target's durable LSN and its epoch-table row there) or FORCED. The one mint refuses a reassign without a kind, the kind and evidence are kept on the durable authority record so a replayed line carries them, and AssignmentFact carries them to the target. The target adopts the primary role of a replicated volume only if its own store still shows what was probed: a replay of an epoch it adopted needs a valid epoch table; BOOTSTRAP needs no data; PROMOTION needs a valid table, a durable end at or above the probed LSN and the probed row at that LSN (a tail beyond it is its own log); FORCED adopts. A line without a kind to a node holding data is refused, except a store from before the epoch table replaying the line of its own durable floor (the upgrade). A refusal latches the role admission failure (the slot becomes ineligible), and the next round shows the store's real end and row. A single-replica workspace move keeps its own start check. Red: the promotion adoption trace (a store replaced between the line and its adoption, an acknowledged block lost) fails on main and passes; one row per guard of the adoption check; the mint refuses a kind-less reassign. Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/replication_ingress.go | 9 + seaweed-block/cmd/sparrow/main.go | 6 +- seaweed-block/core/adapter/normalize.go | 23 +++ seaweed-block/core/authority/authority.go | 16 ++ .../core/authority/authority_restart_test.go | 12 +- .../core/authority/authority_store.go | 6 + .../core/authority/authority_test.go | 12 +- .../authority/bind_volume_genesis_test.go | 22 +++ seaweed-block/core/authority/directive.go | 18 +- .../authority/g8_0_authority_failover_test.go | 2 +- seaweed-block/core/authority/queue_test.go | 2 +- seaweed-block/core/authority/workspace.go | 8 +- .../core/authority/workspace_test.go | 2 +- .../core/frontend/t1_route_helpers_test.go | 27 +-- .../promotion_adoption_regression_test.go | 174 ++++++++++++++++++ seaweed-block/core/host/master/services.go | 18 +- seaweed-block/core/host/volume/host.go | 26 ++- .../core/host/volume/primary_evidence.go | 106 +++++++++++ .../core/host/volume/primary_evidence_test.go | 55 ++++++ seaweed-block/core/transport/floor.go | 3 + 20 files changed, 504 insertions(+), 43 deletions(-) create mode 100644 seaweed-block/core/host/master/promotion_adoption_regression_test.go create mode 100644 seaweed-block/core/host/volume/primary_evidence.go create mode 100644 seaweed-block/core/host/volume/primary_evidence_test.go diff --git a/seaweed-block/cmd/blockvolume/replication_ingress.go b/seaweed-block/cmd/blockvolume/replication_ingress.go index 5c7a4a4604..8b0cd5eb75 100644 --- a/seaweed-block/cmd/blockvolume/replication_ingress.go +++ b/seaweed-block/cmd/blockvolume/replication_ingress.go @@ -48,6 +48,15 @@ func newReplicationIngress(f flags, store storage.LogicalStorage) *replicationIn return r } +// EpochFloor is the volume's durable epoch floor (the highest epoch it took a +// role at), read from the floor record. +func (r *replicationIngress) EpochFloor() (uint64, error) { + if r.floorPath == "" { + return 0, fmt.Errorf("volume %s keeps no floor record", r.volumeID) + } + return transport.LoadFloorRecord(r.floorPath, r.volumeID) +} + // EpochTable is the volume's epoch table (nil when it failed to load). func (r *replicationIngress) EpochTable() *transport.EpochTable { return r.epochs } diff --git a/seaweed-block/cmd/sparrow/main.go b/seaweed-block/cmd/sparrow/main.go index bdcad2a099..da2b628f0d 100644 --- a/seaweed-block/cmd/sparrow/main.go +++ b/seaweed-block/cmd/sparrow/main.go @@ -257,7 +257,8 @@ func runValidationPass(state *ops.State, volumeID string, pubOpts ...authority.P dir.Append(authority.AssignmentAsk{ VolumeID: volumeID, ReplicaID: "r1", DataAddr: replicaAddr, CtrlAddr: replicaAddr, - Intent: authority.IntentReassign, + Intent: authority.IntentReassign, + Evidence: adapter.PrimaryEvidence{Kind: adapter.PrimaryKindForced}, // a demo: a forced move }) results = append(results, buildResult("catch_up", waitForMode(adpt2, engine.ModeHealthy, 5*time.Second))) bridge2Cancel() @@ -281,7 +282,8 @@ func runValidationPass(state *ops.State, volumeID string, pubOpts ...authority.P dir.Append(authority.AssignmentAsk{ VolumeID: volumeID, ReplicaID: "r1", DataAddr: replicaAddr2, CtrlAddr: replicaAddr2, - Intent: authority.IntentReassign, + Intent: authority.IntentReassign, + Evidence: adapter.PrimaryEvidence{Kind: adapter.PrimaryKindForced}, // a demo: a forced move }) results = append(results, buildResult("rebuild", waitForMode(adpt3, engine.ModeHealthy, 5*time.Second))) diff --git a/seaweed-block/core/adapter/normalize.go b/seaweed-block/core/adapter/normalize.go index 3247b733c4..1de5df6c71 100644 --- a/seaweed-block/core/adapter/normalize.go +++ b/seaweed-block/core/adapter/normalize.go @@ -34,6 +34,29 @@ type AssignmentInfo struct { DataAddr string CtrlAddr string PrimaryStartLSN uint64 // see engine.AssignmentObserved.PrimaryStartLSN; 0 = not known + // Primary is how this line made its primary the primary, with the + // evidence the master probed on the target; the target checks it before + // adopting the role. The zero value is a line without a kind. + Primary PrimaryEvidence +} + +// PrimaryKind is how a line made its primary the primary. +type PrimaryKind uint8 + +const ( + PrimaryKindUnspecified PrimaryKind = iota // a line without a kind (a pre-release master) + PrimaryKindBootstrap // the volume's first primary: the target holds no data + PrimaryKindPromotion // promoted on the master's probed evidence + PrimaryKindForced // the operator's forced promotion: no evidence +) + +// PrimaryEvidence is a line's kind and, for a promotion, what the master +// probed on the target: its durable LSN and its epoch-table row at that LSN. +type PrimaryEvidence struct { + Kind PrimaryKind + DurableLSN uint64 + DataEpoch uint64 // the target's epoch-table row at DurableLSN + DataFirstLSN uint64 } // ProbeResult is the outcome of a transport probe. diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index fce81f1169..46a1d50b94 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -286,6 +286,9 @@ func (p *Publisher) reloadFromStore() { }, present: true, } + if rec.Primary != nil { + loaded.info.Primary = *rec.Primary + } p.captureAssignmentOwner(&loaded.info, rec.Workspace) p.state[key] = loaded if rec.WriteSeq > p.writeSeqByVolume[rec.VolumeID] { @@ -526,6 +529,7 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr EndpointVersion: 1, DataAddr: ask.DataAddr, CtrlAddr: ask.CtrlAddr, + Primary: adapter.PrimaryEvidence{Kind: adapter.PrimaryKindBootstrap}, } case IntentRefreshEndpoint: @@ -545,6 +549,13 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr next.CtrlAddr = ask.CtrlAddr case IntentReassign: + // A primary change carries how it was decided (a kind, and for a + // promotion the gate's evidence): the mint never issues a line its + // target could not check. + if ask.Evidence.Kind == adapter.PrimaryKindUnspecified { + p.mu.Unlock() + return fmt.Errorf("%w: volume %s replica %s", ErrReassignWithoutKind, ask.VolumeID, ask.ReplicaID) + } // Per the P14 S3 "reassign semantic" boundary note // (sw-block/design/v3-phase-14-s3-reassign-semantic.md): // IntentReassign is a PER-VOLUME authority advance, not a @@ -572,6 +583,7 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr EndpointVersion: 1, DataAddr: ask.DataAddr, CtrlAddr: ask.CtrlAddr, + Primary: ask.Evidence, } if reservedEpoch != 0 { next.Epoch = reservedEpoch @@ -605,6 +617,10 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr WriteSeq: nextSeq, Workspace: cloneWorkspace(p.workspace[ask.VolumeID]), } + if next.Primary != (adapter.PrimaryEvidence{}) { + pe := next.Primary + record.Primary = &pe + } if issuedWorkspace != nil { record.Workspace = cloneWorkspace(issuedWorkspace) } diff --git a/seaweed-block/core/authority/authority_restart_test.go b/seaweed-block/core/authority/authority_restart_test.go index 8a152c4e24..d7d47e7b0b 100644 --- a/seaweed-block/core/authority/authority_restart_test.go +++ b/seaweed-block/core/authority/authority_restart_test.go @@ -44,7 +44,7 @@ func TestDurableAuthority_ReloadReproducesCurrentLine(t *testing.T) { if err := pubA.apply(AssignmentAsk{ VolumeID: "v1", ReplicaID: "r2", DataAddr: "d2", CtrlAddr: "c2", - Intent: IntentReassign, + Intent: IntentReassign, Evidence: testPromotion, }); err != nil { t.Fatalf("apply Reassign: %v", err) } @@ -96,7 +96,7 @@ func TestDurableAuthority_StalePreFailoverRecordRejectedOnReload(t *testing.T) { _ = pubA.apply(AssignmentAsk{ VolumeID: "v1", ReplicaID: "r2", DataAddr: "d2", CtrlAddr: "c2", - Intent: IntentReassign, + Intent: IntentReassign, Evidence: testPromotion, }) _ = storeA.Close() @@ -129,8 +129,8 @@ func TestDurableAuthority_PublisherAdvancesFromReloaded(t *testing.T) { storeA, _ := NewFileAuthorityStore(dir) pubA := NewPublisher(NewStaticDirective(nil), WithStore(storeA)) _ = pubA.apply(AssignmentAsk{VolumeID: "v1", ReplicaID: "r1", DataAddr: "d1", CtrlAddr: "c1", Intent: IntentBind}) - _ = pubA.apply(AssignmentAsk{VolumeID: "v1", ReplicaID: "r2", DataAddr: "d2", CtrlAddr: "c2", Intent: IntentReassign}) - _ = pubA.apply(AssignmentAsk{VolumeID: "v1", ReplicaID: "r3", DataAddr: "d3", CtrlAddr: "c3", Intent: IntentReassign}) + _ = pubA.apply(AssignmentAsk{VolumeID: "v1", ReplicaID: "r2", DataAddr: "d2", CtrlAddr: "c2", Intent: IntentReassign, Evidence: testPromotion}) + _ = pubA.apply(AssignmentAsk{VolumeID: "v1", ReplicaID: "r3", DataAddr: "d3", CtrlAddr: "c3", Intent: IntentReassign, Evidence: testPromotion}) _ = storeA.Close() // Phase 2: restart. Continue advancing. The next Reassign @@ -141,7 +141,7 @@ func TestDurableAuthority_PublisherAdvancesFromReloaded(t *testing.T) { if err := pubB.apply(AssignmentAsk{ VolumeID: "v1", ReplicaID: "r1", DataAddr: "d1-new", CtrlAddr: "c1-new", - Intent: IntentReassign, + Intent: IntentReassign, Evidence: testPromotion, }); err != nil { t.Fatalf("post-restart Reassign: %v", err) } @@ -170,7 +170,7 @@ func TestDurableAuthority_ControllerSeesReloadedLineAtBoot(t *testing.T) { _ = pubA.apply(AssignmentAsk{ VolumeID: "v1", ReplicaID: "r2", DataAddr: "d2", CtrlAddr: "c2", - Intent: IntentReassign, + Intent: IntentReassign, Evidence: testPromotion, }) _ = storeA.Close() diff --git a/seaweed-block/core/authority/authority_store.go b/seaweed-block/core/authority/authority_store.go index 8a3864ac62..12843a3bc0 100644 --- a/seaweed-block/core/authority/authority_store.go +++ b/seaweed-block/core/authority/authority_store.go @@ -6,6 +6,8 @@ import ( "encoding/json" "errors" "fmt" + + "github.com/seaweedfs/seaweed-block/core/adapter" ) // ============================================================ @@ -48,6 +50,10 @@ type DurableRecord struct { // checksum of pre-workspace records. Authority itself remains non-expiring; // the lease gates serving, never authorizes an epoch by itself. Workspace *WorkspaceState `json:",omitempty"` + // Primary is the line's kind and promotion evidence, so a replayed line + // carries what the first publication carried. Omitting nil preserves the + // checksum of records written before it. + Primary *adapter.PrimaryEvidence `json:",omitempty"` } // AuthorityStore is the narrow durable-authority interface. The diff --git a/seaweed-block/core/authority/authority_test.go b/seaweed-block/core/authority/authority_test.go index d645a976d4..633a36b7dc 100644 --- a/seaweed-block/core/authority/authority_test.go +++ b/seaweed-block/core/authority/authority_test.go @@ -188,7 +188,7 @@ func TestPublisher_Reassign_BumpsEpochAndResetsEndpointVersion(t *testing.T) { if err := pub.apply(AssignmentAsk{ VolumeID: "v1", ReplicaID: "r1", DataAddr: "d2", CtrlAddr: "c2", - Intent: IntentReassign, + Intent: IntentReassign, Evidence: testPromotion, }); err != nil { t.Fatalf("Reassign: %v", err) } @@ -206,7 +206,7 @@ func TestPublisher_Reassign_RejectsUnboundKey(t *testing.T) { err := pub.apply(AssignmentAsk{ VolumeID: "v1", ReplicaID: "r1", DataAddr: "d", CtrlAddr: "c", - Intent: IntentReassign, + Intent: IntentReassign, Evidence: testPromotion, }) if !errors.Is(err, ErrReassignNotBound) { t.Fatalf("want ErrReassignNotBound, got %v", err) @@ -409,7 +409,7 @@ func TestPublisher_DeliveryConvergesToLatestOnSlowConsumer(t *testing.T) { if err := pub.apply(AssignmentAsk{ VolumeID: "v1", ReplicaID: "r1", DataAddr: "d3", CtrlAddr: "c3", - Intent: IntentReassign, + Intent: IntentReassign, Evidence: testPromotion, }); err != nil { t.Fatalf("Reassign: %v", err) } @@ -523,7 +523,7 @@ func TestPublisher_LateSubscriberReceivesLatestUnderConcurrentPublish(t *testing _ = pub.apply(AssignmentAsk{ VolumeID: "v1", ReplicaID: "r1", DataAddr: "d", CtrlAddr: "c", - Intent: IntentReassign, + Intent: IntentReassign, Evidence: testPromotion, }) }() @@ -620,8 +620,8 @@ func TestPublisher_Run_LogsAndContinuesOnRejectedAsk(t *testing.T) { // ask must still be processed. This is the "continue on reject" // Run semantic. dir := NewStaticDirective([]AssignmentAsk{ - {VolumeID: "v1", ReplicaID: "r1", DataAddr: "d", CtrlAddr: "c", Intent: IntentReassign}, // rejected - {VolumeID: "v1", ReplicaID: "r1", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}, // accepted + {VolumeID: "v1", ReplicaID: "r1", DataAddr: "d", CtrlAddr: "c", Intent: IntentReassign, Evidence: testPromotion}, // rejected + {VolumeID: "v1", ReplicaID: "r1", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}, // accepted }) pub := NewPublisher(dir) ch, cancelSub := pub.Subscribe("v1", "r1") diff --git a/seaweed-block/core/authority/bind_volume_genesis_test.go b/seaweed-block/core/authority/bind_volume_genesis_test.go index 0e80e42f6e..22df2459b4 100644 --- a/seaweed-block/core/authority/bind_volume_genesis_test.go +++ b/seaweed-block/core/authority/bind_volume_genesis_test.go @@ -16,6 +16,7 @@ func bindAsk(volumeID, replicaID string) AssignmentAsk { func reassignAsk(volumeID, replicaID string) AssignmentAsk { ask := bindAsk(volumeID, replicaID) ask.Intent = IntentReassign + ask.Evidence = testPromotion return ask } @@ -102,3 +103,24 @@ func TestPublisher_BindAfterRestartRejectedForAnySlot(t *testing.T) { t.Fatalf("reloaded line=%+v ok=%t want r2 epoch 2", got, ok) } } + +// The one mint never issues a primary change its target could not check: a +// reassign without a kind is refused and the line stays. +func TestPublisher_ReassignWithoutAKindIsRefused(t *testing.T) { + pub := NewPublisher(NewStaticDirective(nil)) + if err := pub.apply(bindAsk("v1", "r1")); err != nil { + t.Fatal(err) + } + ask := bindAsk("v1", "r2") + ask.Intent = IntentReassign + if err := pub.apply(ask); !errors.Is(err, ErrReassignWithoutKind) { + t.Fatalf("a reassign without a kind: %v; want ErrReassignWithoutKind", err) + } + if line, _ := pub.VolumeAuthorityLine("v1"); line.ReplicaID != "r1" || line.Epoch != 1 { + t.Fatalf("the line moved: %+v", line) + } + ask.Evidence = testPromotion + if err := pub.apply(ask); err != nil { + t.Fatalf("a reassign with a kind: %v", err) + } +} diff --git a/seaweed-block/core/authority/directive.go b/seaweed-block/core/authority/directive.go index f65349d76b..3c688fbf9c 100644 --- a/seaweed-block/core/authority/directive.go +++ b/seaweed-block/core/authority/directive.go @@ -5,10 +5,10 @@ // (VolumeID, ReplicaID). // // Three boundaries hold: -// 1. The authority package owns publication of assignment truth. -// 2. The authority package does NOT own failover policy. -// 3. Engine and adapter remain consumers, not producers, of -// assignment truth. +// 1. The authority package owns publication of assignment truth. +// 2. The authority package does NOT own failover policy. +// 3. Engine and adapter remain consumers, not producers, of +// assignment truth. package authority import ( @@ -16,6 +16,8 @@ import ( "errors" "sync" "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" ) // AskIntent is the only control knob a Directive has. The publisher @@ -67,8 +69,16 @@ type AssignmentAsk struct { DataAddr string CtrlAddr string Intent AskIntent + // Evidence is the kind and probed evidence a reassign carries to its + // target (a bind is always a bootstrap); see adapter.PrimaryEvidence. It + // is a probe fact about the target, never an authority fact. + Evidence adapter.PrimaryEvidence } +// ErrReassignWithoutKind: a primary change was asked without a kind (no +// promotion-gate evidence, not a forced move); the publisher mints no line. +var ErrReassignWithoutKind = errors.New("authority: a reassign needs a primary kind (promotion evidence or a forced move)") + // Directive is the input side of the authority route. A Directive // emits one AssignmentAsk at a time. The publisher's Run loop calls // Next repeatedly until ctx cancellation. diff --git a/seaweed-block/core/authority/g8_0_authority_failover_test.go b/seaweed-block/core/authority/g8_0_authority_failover_test.go index 421cd8e66c..b24244d982 100644 --- a/seaweed-block/core/authority/g8_0_authority_failover_test.go +++ b/seaweed-block/core/authority/g8_0_authority_failover_test.go @@ -91,7 +91,7 @@ func TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots(t *test t.Fatalf("bind r1: %v", err) } if err := pub.apply(AssignmentAsk{ - VolumeID: "v1", ReplicaID: "r2", DataAddr: "d2", CtrlAddr: "c2", Intent: IntentReassign, + VolumeID: "v1", ReplicaID: "r2", DataAddr: "d2", CtrlAddr: "c2", Intent: IntentReassign, Evidence: testPromotion, }); err != nil { t.Fatalf("reassign r2: %v", err) } diff --git a/seaweed-block/core/authority/queue_test.go b/seaweed-block/core/authority/queue_test.go index 40adf17c85..f19ab49378 100644 --- a/seaweed-block/core/authority/queue_test.go +++ b/seaweed-block/core/authority/queue_test.go @@ -13,7 +13,7 @@ func TestAssignmentQueue_ReplacesLatestPerVolume(t *testing.T) { VolumeID: "v1", ReplicaID: "r1", DataAddr: "d1", CtrlAddr: "c1", Intent: IntentBind, }) q.enqueue(AssignmentAsk{ - VolumeID: "v1", ReplicaID: "r2", DataAddr: "d2", CtrlAddr: "c2", Intent: IntentReassign, + VolumeID: "v1", ReplicaID: "r2", DataAddr: "d2", CtrlAddr: "c2", Intent: IntentReassign, Evidence: testPromotion, }) ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index b66e6f8c22..bf9e395028 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -5,6 +5,8 @@ import ( "errors" "fmt" "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" ) // WorkspaceHead is read from the configured HEAD source, never supplied as @@ -270,7 +272,11 @@ func (p *Publisher) MoveWorkspace(ctx context.Context, req WorkspaceMoveRequest, if replay { return r, nil } - err = p.applyWithWorkspaceMove(AssignmentAsk{VolumeID: req.VolumeID, ReplicaID: req.TargetReplicaID, DataAddr: req.TargetDataAddr, CtrlAddr: req.TargetCtrlAddr, Intent: IntentReassign}, &workspaceGrant{req, head}) + kind := adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion} // a clean move: the source detached at its sealed image + if req.Kind == "forced" { + kind = adapter.PrimaryEvidence{Kind: adapter.PrimaryKindForced} + } + err = p.applyWithWorkspaceMove(AssignmentAsk{VolumeID: req.VolumeID, ReplicaID: req.TargetReplicaID, DataAddr: req.TargetDataAddr, CtrlAddr: req.TargetCtrlAddr, Intent: IntentReassign, Evidence: kind}, &workspaceGrant{req, head}) if err != nil { return WorkspaceMoveRecord{}, err } diff --git a/seaweed-block/core/authority/workspace_test.go b/seaweed-block/core/authority/workspace_test.go index 546ca03ae0..cda50e45d1 100644 --- a/seaweed-block/core/authority/workspace_test.go +++ b/seaweed-block/core/authority/workspace_test.go @@ -181,7 +181,7 @@ func TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry(t *testing.T) { t.Fatal("implicit forced move") } req.Force = true - if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "new", DataAddr: "nd", CtrlAddr: "nc", Intent: IntentReassign}); err == nil { + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "new", DataAddr: "nd", CtrlAddr: "nc", Intent: IntentReassign, Evidence: testPromotion}); err == nil { t.Fatal("ordinary failover bypassed move") } // Reload uses a full-TTL conservative barrier before admitting forced moves. diff --git a/seaweed-block/core/frontend/t1_route_helpers_test.go b/seaweed-block/core/frontend/t1_route_helpers_test.go index 7abc7349fe..92aab6dfea 100644 --- a/seaweed-block/core/frontend/t1_route_helpers_test.go +++ b/seaweed-block/core/frontend/t1_route_helpers_test.go @@ -3,12 +3,13 @@ // route builder used by t1_route_test.go. // // Route wired here: -// StaticDirective -> -// authority.Publisher -> -// authority.Bridge (per-replica subscription) -> -// adapter.VolumeReplicaAdapter (real, with HealthyPathExecutor) -> -// volume.AdapterProjectionView -> -// frontend.Provider. +// +// StaticDirective -> +// authority.Publisher -> +// authority.Bridge (per-replica subscription) -> +// adapter.VolumeReplicaAdapter (real, with HealthyPathExecutor) -> +// volume.AdapterProjectionView -> +// frontend.Provider. // // Readiness source: volume.AdapterProjectionView reads // (*VolumeReplicaAdapter).Projection() -> engine.ReplicaProjection @@ -40,12 +41,12 @@ type t1Route struct { pub *authority.Publisher dir *authority.StaticDirective - mu sync.Mutex - slots map[string]*replicaSlot // replicaID -> slot - current string // current primary replicaID - cancel context.CancelFunc - runDone chan struct{} - volCtx context.Context + mu sync.Mutex + slots map[string]*replicaSlot // replicaID -> slot + current string // current primary replicaID + cancel context.CancelFunc + runDone chan struct{} + volCtx context.Context } // replicaSlot holds one replica's real adapter + AdapterProjectionView. @@ -148,6 +149,8 @@ func (r *t1Route) reassignReplica(replicaID, dataAddr, ctrlAddr string) { DataAddr: dataAddr, CtrlAddr: ctrlAddr, Intent: authority.IntentReassign, + // The test is the decider here: a primary change carries its kind. + Evidence: adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion}, }) } diff --git a/seaweed-block/core/host/master/promotion_adoption_regression_test.go b/seaweed-block/core/host/master/promotion_adoption_regression_test.go new file mode 100644 index 0000000000..38301466c2 --- /dev/null +++ b/seaweed-block/core/host/master/promotion_adoption_regression_test.go @@ -0,0 +1,174 @@ +package master + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + "github.com/seaweedfs/seaweed-block/core/replication" + "github.com/seaweedfs/seaweed-block/core/replication/component" + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +// The decision and adoption are separate events. A successful fresh probe +// cannot authorize an empty replacement store opened after the line was issued. +func TestPromotionRefusesReplicaMissingAcknowledgedWrite(t *testing.T) { + for _, replace := range []bool{false, true} { + name := "retained_store" + if replace { + name = "recreated_after_decision" + } + t.Run(name, func(t *testing.T) { + h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3}) + t.Cleanup(func() { closeTestMaster(t, h) }) + cluster := component.NewCluster(t, component.Walstore).WithReplicas(2).WithLiveShip().Start() + cluster.Primary().RepVol.SetDurabilityMode(replication.DurabilitySyncAll) + acknowledged := bytes.Repeat([]byte{0xa7}, 4096) + cluster.PrimaryWriteViaBackend(7, acknowledged) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := cluster.Primary().Backend.Sync(ctx); err != nil { + t.Fatalf("guest sync ACK: %v", err) + } + // Shipping to both peers is a legal extension of the one-peer ACK trace. + // The product still uses its UNKNOWN-frontier survivor rule, not a test LSN. + cluster.Primary().RepVol.SetDurabilityMode(replication.DurabilitySyncQuorum) + for i := 0; i < 2; i++ { + got, err := cluster.Replica(i).Store.Read(7) + if err != nil || !bytes.Equal(got, acknowledged) { + t.Fatalf("ACK fixture replica %d missing data: %v", i, err) + } + } + seedRF3Placement(t, h) + ingestRF3Observation(t, h, true, true, true) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + if initial.ReplicaID != "r1" { + t.Fatalf("initial line=%+v", initial) + } + if err := cluster.Primary().RepVol.Close(); err != nil { + t.Fatal(err) + } + servers := make([]*httptest.Server, 2) + plans := []lifecycle.BlockVolumeWorkloadPlan{{VolumeID: "vol-rf3", Protocol: "iscsi"}} + routes := map[string]string{} + for i, id := range []string{"r2", "r3"} { + store := cluster.Replica(i).Store + servers[i] = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/status": + _ = json.NewEncoder(w).Encode(volume.StatusProjection{Projection: frontend.Projection{VolumeID: "vol-rf3", ReplicaID: id}, ReplicationRole: "replica_ready"}) + case "/status/durable": + // As the volume's /status/durable reports it: DurableLSN is + // R, the store's synced LSN (storage_adapter.go Boundaries). + r, _, _ := store.Boundaries() + _ = json.NewEncoder(w).Encode(struct{ Volumes []durable.VolumeStatus }{[]durable.VolumeStatus{{VolumeID: "vol-rf3", ReplicaID: id, FrontierKnown: true, DurableLSN: r}}}) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(servers[i].Close) + port := 3260 + i + plans[0].Replicas = append(plans[0].Replicas, lifecycle.BlockVolumeReplicaWorkload{ReplicaID: id, ISCSIListenPort: port}) + host := "127.0.0.1:23260" + if i == 1 { + host = "127.0.0.1:23261" + } + routes[host] = servers[i].URL + } + h.SetPromotionEvidenceProvider(NewWorkloadPlanPromotionEvidenceProvider(plans, WorkloadPlanPromotionProbeConfig{AckProfile: "sync-quorum", HTTPClient: &http.Client{Transport: promotionTraceRoutes(routes), Timeout: time.Second}})) + ingestRF3ObservationForServersWithReady(t, h, "vol-rf3", "node-a", "node-b", "node-c", false, false, true, true, true, true) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + issued := initial + publishDeadline := time.Now().Add(5 * time.Second) + for issued.Epoch <= initial.Epoch && time.Now().Before(publishDeadline) { + issued, _ = h.Publisher().VolumeAuthorityLine("vol-rf3") + if issued.Epoch <= initial.Epoch { + time.Sleep(10 * time.Millisecond) + } + } + if issued.Epoch <= initial.Epoch || (issued.ReplicaID != "r2" && issued.ReplicaID != "r3") { + t.Fatalf("promotion did not publish a surviving replica: %+v", issued) + } + selected, serverID := 0, "node-b" + if issued.ReplicaID == "r3" { + selected, serverID = 1, "node-c" + } + targetStore := cluster.Replica(selected).Store + // No target subscription exists yet: replacement occurs after publication, + // before the actual blockvolume receives and adopts the published line. + cluster.Replica(selected).Listener.StopHard() + if replace { + s, err := storage.CreateWALStore(filepath.Join(t.TempDir(), "replacement.wal"), 64, 4096) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + targetStore = s + } + rv := replication.NewReplicationVolume("vol-rf3", targetStore) + t.Cleanup(func() { _ = rv.Close() }) + listener, err := transport.NewReplicaListener("127.0.0.1:0", targetStore) + if err != nil { + t.Fatal(err) + } + listener.Serve() + t.Cleanup(listener.StopHard) + target, err := volume.New(volume.Config{MasterAddr: h.Addr(), ServerID: serverID, VolumeID: "vol-rf3", ReplicaID: issued.ReplicaID, DataAddr: issued.DataAddr, CtrlAddr: issued.CtrlAddr, HeartbeatInterval: time.Second, EnableT1Readiness: true, ReplicationVolume: rv}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = target.Close() }) + if err := target.SetSelfFence(listener); err != nil { + t.Fatal(err) + } + target.Start() + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + if refused, reason := target.RoleAdmissionFailure(); refused { + if !replace { + t.Fatalf("retained-store control refused: %s", reason) + } + t.Logf("replacement refused: %s", reason) + return + } + if p := target.Adapter().Projection(); p.Epoch >= issued.Epoch { + got, err := targetStore.Read(7) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, acknowledged) { + t.Fatalf("NoAckedLoss: issued epoch %d adopted after store replacement, acknowledged block missing", issued.Epoch) + } + return + } + time.Sleep(10 * time.Millisecond) + } + t.Fatal("neither adoption nor explicit refusal: timeout is not safety evidence") + }) + } +} + +type promotionTraceRoutes map[string]string + +func (routes promotionTraceRoutes) RoundTrip(r *http.Request) (*http.Response, error) { + if base, ok := routes[r.URL.Host]; ok { + return (rewriteRoundTripper{base: base, host: r.URL.Host}).RoundTrip(r) + } + return http.DefaultTransport.RoundTrip(r) +} diff --git a/seaweed-block/core/host/master/services.go b/seaweed-block/core/host/master/services.go index 45a3df563b..6610a2e388 100644 --- a/seaweed-block/core/host/master/services.go +++ b/seaweed-block/core/host/master/services.go @@ -995,13 +995,17 @@ func (h *Host) ingestHeartbeatRecordingHealth(msg authority.HeartbeatMessage) er // assignmentFact encodes one captured publication at the stream boundary. func (s *services) assignmentFact(info adapter.AssignmentInfo) *control.AssignmentFact { fact := &control.AssignmentFact{ - VolumeId: info.VolumeID, - ReplicaId: info.ReplicaID, - ServerId: s.host.workspaceLineOwner(authority.PublishedLine{ReplicaID: info.ReplicaID, Epoch: info.Epoch, IssuedHost: info.ServerID, OwnerFromMove: info.OwnerFromMove}, info.VolumeID, info.ReplicaID, info.Epoch), - Epoch: info.Epoch, - EndpointVersion: info.EndpointVersion, - DataAddr: info.DataAddr, - CtrlAddr: info.CtrlAddr, + VolumeId: info.VolumeID, + ReplicaId: info.ReplicaID, + ServerId: s.host.workspaceLineOwner(authority.PublishedLine{ReplicaID: info.ReplicaID, Epoch: info.Epoch, IssuedHost: info.ServerID, OwnerFromMove: info.OwnerFromMove}, info.VolumeID, info.ReplicaID, info.Epoch), + Epoch: info.Epoch, + EndpointVersion: info.EndpointVersion, + DataAddr: info.DataAddr, + CtrlAddr: info.CtrlAddr, + PrimaryKind: control.PrimaryKind(info.Primary.Kind), + EvidenceDurableLsn: info.Primary.DurableLSN, + EvidenceEpoch: info.Primary.DataEpoch, + EvidenceFirstLsn: info.Primary.DataFirstLSN, } // Populate the peer set from publisher LastPublished // queries for every non-self replica slot in this volume's diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 0c3e2e202d..ab4b9bb854 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -171,6 +171,8 @@ type Host struct { conn *grpc.ClientConn obsCli control.ObservationServiceClient + // probeRoles answers the promotion probe round's role fields (probe_round.go). + probeRoles probeRoles asnCli control.AssignmentServiceClient cancel context.CancelFunc @@ -596,9 +598,10 @@ func (h *Host) Start() context.Context { ctx, cancel := context.WithCancel(context.Background()) h.cancel = cancel - h.wg.Add(2) + h.wg.Add(3) go h.runHeartbeat(ctx) go h.runSubscribe(ctx) + go h.runProbeRounds(ctx) return ctx } @@ -905,11 +908,30 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { } } + // The target's own store must still show what the master probed before + // it adopts the role (nothing is installed yet, so a refusal has no + // effect to undo). + rv := h.getReplication() + if src, ok := rv.(primaryEvidenceSource); ok && rv != nil { + st, end, err := src.LocalPrimaryEvidence() + if err != nil { + h.refusePrimary(fmt.Sprintf("epoch %d: the local store's evidence is unreadable: %v", fact.Epoch, err)) + return + } + floor, floorErr := uint64(0), error(nil) + if fr, ok := h.selfFenceFloor(); ok { + floor, floorErr = fr.EpochFloor() + } + if reason := checkPrimaryEvidence(fact, st, end, floor, floorErr == nil && floor > 0); reason != "" { + h.refusePrimary(reason) + return + } + } + // Step (2a): install replication peer set first. Decoded via // the separate host-only decodeReplicaTargets path (not through // AssignmentInfo), so the TestNoOtherAssignmentInfoConstruction // AST fence stays green. - rv := h.getReplication() if rv != nil { targets, gen := decodeReplicaTargets(fact) if err := rv.UpdateReplicaSet(gen, targets); err != nil { diff --git a/seaweed-block/core/host/volume/primary_evidence.go b/seaweed-block/core/host/volume/primary_evidence.go new file mode 100644 index 0000000000..9ebd6e61e3 --- /dev/null +++ b/seaweed-block/core/host/volume/primary_evidence.go @@ -0,0 +1,106 @@ +package volume + +import ( + "fmt" + + "github.com/seaweedfs/seaweed-block/core/replication" + "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +// primaryEvidenceSource is the local store's epoch table and durable end, as +// a primary line's target checks them before adopting the role +// (replication.ReplicationVolume). +type primaryEvidenceSource interface { + LocalPrimaryEvidence() (replication.EpochTableStatus, uint64, error) +} + +// checkPrimaryEvidence decides whether this node may adopt the primary role a +// line names. "" = adopt; otherwise why it refuses. The target's own store is +// the proof: the master's decision was taken from a probe, and the store may +// have changed since (re-created, restarted lower, a recovery in progress). +// - a replay of a line this node already adopted (its table has a row for +// the line's epoch): the table must be valid; +// - BOOTSTRAP: the node holds no data; +// - PROMOTION: the table is valid, the durable end is at least the probed +// durable LSN, and the row at that LSN is the probed (epoch, first LSN); +// a tail beyond it is this node's own log and becomes the new history; +// - FORCED: adopted without evidence (the operator's lost range); +// - a line without a kind to a node holding data: refused. +// +// The rule is for a replicated volume's lines (a non-empty peer set). A +// single-replica workspace move starts from the published image and is +// governed by the layout's own start check and claim id instead. A store +// without an epoch table has no rows: a probed row cannot match it. +func checkPrimaryEvidence(fact *control.AssignmentFact, st replication.EpochTableStatus, end uint64, floor uint64, floorKnown bool) string { + if len(fact.Peers) == 0 { + return "" + } + for _, r := range st.Rows { + if r.Epoch == fact.Epoch { + if st.Invalid { + return fmt.Sprintf("epoch %d replayed over an epoch table a recovery left invalid", fact.Epoch) + } + return "" + } + } + switch fact.PrimaryKind { + case control.PrimaryKind_PRIMARY_KIND_BOOTSTRAP: + if end != 0 || len(st.Rows) != 0 || st.Invalid { + return fmt.Sprintf("a bootstrap line at epoch %d to a node that holds data (durable end %d)", fact.Epoch, end) + } + return "" + case control.PrimaryKind_PRIMARY_KIND_PROMOTION: + if st.Invalid { + return fmt.Sprintf("promoted at epoch %d over an epoch table a recovery left invalid", fact.Epoch) + } + if end < fact.EvidenceDurableLsn { + return fmt.Sprintf("promoted at epoch %d on a probed durable LSN %d, the store's durable end is %d", fact.Epoch, fact.EvidenceDurableLsn, end) + } + var row struct{ epoch, first uint64 } + for _, r := range st.Rows { + if r.FirstLSN <= fact.EvidenceDurableLsn { + row.epoch, row.first = r.Epoch, r.FirstLSN + } + } + if row.epoch != fact.EvidenceEpoch || row.first != fact.EvidenceFirstLsn { + return fmt.Sprintf("promoted at epoch %d on the probed row (epoch %d from %d) at LSN %d, the store's row there is (epoch %d from %d)", + fact.Epoch, fact.EvidenceEpoch, fact.EvidenceFirstLsn, fact.EvidenceDurableLsn, row.epoch, row.first) + } + return "" + case control.PrimaryKind_PRIMARY_KIND_FORCED: + return "" + } + // Upgrade: a store from before the epoch table (no rows, not invalid) + // replays the line it held before the upgrade (its durable floor is the + // line's epoch: a line at one epoch names one primary). Its adoption then + // notes the row. The master never mints a line without a kind. + if len(st.Rows) == 0 && !st.Invalid && floorKnown && floor == fact.Epoch { + return "" + } + if end != 0 || len(st.Rows) != 0 { + return fmt.Sprintf("a line without a primary kind at epoch %d to a node that holds data (durable end %d)", fact.Epoch, end) + } + return "" +} + +// epochFloorReader is the self fence's durable epoch floor (the replication +// ingress in production). +type epochFloorReader interface { + EpochFloor() (uint64, error) +} + +func (h *Host) selfFenceFloor() (epochFloorReader, bool) { + h.selfFenceMu.Lock() + f := h.selfFence + h.selfFenceMu.Unlock() + fr, ok := f.(epochFloorReader) + return fr, ok && f != nil +} + +// refusePrimary latches a refused primary role: RoleAdmissionFailure reports +// it (the heartbeat makes the slot ineligible), and the master's next probe +// sees the store's real end and row and decides again at a new epoch. +func (h *Host) refusePrimary(reason string) { + h.roleAdmissionFailed.Store(reason) + h.log.Printf("blockvolume: volume %s refuses the primary role: %s — NOT applying to adapter (fail-closed)", h.cfg.VolumeID, reason) +} diff --git a/seaweed-block/core/host/volume/primary_evidence_test.go b/seaweed-block/core/host/volume/primary_evidence_test.go new file mode 100644 index 0000000000..e93985df42 --- /dev/null +++ b/seaweed-block/core/host/volume/primary_evidence_test.go @@ -0,0 +1,55 @@ +package volume + +import ( + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/replication" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +// One row per guard of the target's adoption check. +func TestCheckPrimaryEvidence(t *testing.T) { + peers := []*control.ReplicaDescriptor{{ReplicaId: "r2"}} + rows := func(r ...transport.EpochRow) replication.EpochTableStatus { + return replication.EpochTableStatus{Rows: r, Present: true} + } + promo := func(lsn, ep, first uint64) *control.AssignmentFact { + return &control.AssignmentFact{Epoch: 3, Peers: peers, PrimaryKind: control.PrimaryKind_PRIMARY_KIND_PROMOTION, EvidenceDurableLsn: lsn, EvidenceEpoch: ep, EvidenceFirstLsn: first} + } + for _, c := range []struct { + name string + fact *control.AssignmentFact + st replication.EpochTableStatus + end uint64 + floor uint64 + refused string // "" = adopted; else a word of the reason + }{ + {"replay of an adopted epoch", &control.AssignmentFact{Epoch: 3, Peers: peers}, rows(transport.EpochRow{Epoch: 3, FirstLSN: 10}), 12, 3, ""}, + {"replay over an invalid table", &control.AssignmentFact{Epoch: 3, Peers: peers}, replication.EpochTableStatus{Rows: []transport.EpochRow{{Epoch: 3, FirstLSN: 10}}, Present: true, Invalid: true}, 12, 3, "invalid"}, + {"bootstrap on an empty node", &control.AssignmentFact{Epoch: 1, Peers: peers, PrimaryKind: control.PrimaryKind_PRIMARY_KIND_BOOTSTRAP}, rows(), 0, 0, ""}, + {"bootstrap on a node with data", &control.AssignmentFact{Epoch: 1, Peers: peers, PrimaryKind: control.PrimaryKind_PRIMARY_KIND_BOOTSTRAP}, rows(), 5, 0, "bootstrap"}, + {"promotion as probed", promo(8, 2, 5), rows(transport.EpochRow{Epoch: 1, FirstLSN: 1}, transport.EpochRow{Epoch: 2, FirstLSN: 5}), 8, 2, ""}, + {"promotion, end grown since the probe", promo(8, 2, 5), rows(transport.EpochRow{Epoch: 1, FirstLSN: 1}, transport.EpochRow{Epoch: 2, FirstLSN: 5}), 11, 2, ""}, + {"promotion, store lower than probed", promo(8, 2, 5), rows(transport.EpochRow{Epoch: 1, FirstLSN: 1}, transport.EpochRow{Epoch: 2, FirstLSN: 5}), 6, 2, "durable end"}, + {"promotion, another row at the probed LSN", promo(8, 2, 5), rows(transport.EpochRow{Epoch: 1, FirstLSN: 1}, transport.EpochRow{Epoch: 2, FirstLSN: 7}), 8, 2, "row"}, + {"promotion over an invalid table", promo(8, 2, 5), replication.EpochTableStatus{Present: true, Invalid: true}, 8, 2, "invalid"}, + {"promotion to a store replaced empty", promo(8, 2, 5), rows(), 0, 0, "durable end"}, + {"forced", &control.AssignmentFact{Epoch: 3, Peers: peers, PrimaryKind: control.PrimaryKind_PRIMARY_KIND_FORCED}, rows(transport.EpochRow{Epoch: 1, FirstLSN: 1}), 5, 2, ""}, + {"no kind to a node with data", &control.AssignmentFact{Epoch: 3, Peers: peers}, rows(transport.EpochRow{Epoch: 1, FirstLSN: 1}), 5, 2, "without a primary kind"}, + {"upgrade: a pre-table store replays its own line", &control.AssignmentFact{Epoch: 3, Peers: peers}, rows(), 5, 3, ""}, + {"upgrade: a pre-table store, another epoch", &control.AssignmentFact{Epoch: 4, Peers: peers}, rows(), 5, 3, "without a primary kind"}, + {"a single-replica line (no peers)", &control.AssignmentFact{Epoch: 3}, rows(), 5, 0, ""}, + } { + t.Run(c.name, func(t *testing.T) { + got := checkPrimaryEvidence(c.fact, c.st, c.end, c.floor, c.floor > 0) + switch { + case c.refused == "" && got != "": + t.Fatalf("refused: %s", got) + case c.refused != "" && !strings.Contains(got, c.refused): + t.Fatalf("got %q; want a refusal naming %q", got, c.refused) + } + }) + } +} diff --git a/seaweed-block/core/transport/floor.go b/seaweed-block/core/transport/floor.go index 30d1528ea0..64bf2763a6 100644 --- a/seaweed-block/core/transport/floor.go +++ b/seaweed-block/core/transport/floor.go @@ -152,6 +152,9 @@ func rejectDuplicateKeys(raw []byte) error { return nil } +// LoadFloorRecord reads the replica epoch floor record at path (see loadFloor). +func LoadFloorRecord(path, volumeID string) (uint64, error) { return loadFloor(path, volumeID) } + // loadFloor reads the floor record at path. A missing record is // ErrFloorRecordMissing; any other read or parse problem is an error. func loadFloor(path, volumeID string) (uint64, error) {