Merge pull request #584 from seaweedfs/fix/promotion-g1-line-evidence

master, authority, volume: one promotion decider; the line carries its evidence and the target checks it
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-25 08:09:23 -08:00
commit a9f3ed741e
89 files changed
+6451 -2814

No files matched your search

+3 -6
View File
@@ -259,6 +259,9 @@ func run(f flags) int {
fmt.Fprintln(os.Stderr, "blockmaster:", err)
return 1
}
// Every promotion decides on the probe round's answers: each candidate
// answers a fresh round over its authenticated node stream.
h.SetPromotionEvidenceProvider(h.NewRoundPromotionEvidenceProvider(f.launcherReplicationAck, nil))
if len(clusterImport.Volumes) > 0 {
if err := importLifecycleVolumes(h, clusterImport.Volumes); err != nil {
fmt.Fprintln(os.Stderr, "blockmaster:", err)
@@ -455,12 +458,6 @@ func runLifecycleLauncherTick(h *master.Host, f flags) error {
if err != nil {
return err
}
if f.launcherStatus {
h.SetPromotionEvidenceProvider(master.NewWorkloadPlanPromotionEvidenceProvider(result.Plans, master.WorkloadPlanPromotionProbeConfig{
AckProfile: f.launcherReplicationAck,
ExternalStatus: f.launcherExternalStatus,
}))
}
if f.launcherManifestDir == "" && !f.launcherKubernetesApply {
return nil
}
@@ -0,0 +1,226 @@
//go:build subprocess && chunkstore_integration
package main_test
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"syscall"
"testing"
"time"
)
// TestFencingRoundHealContinuesThePrimary runs the heal of a failed fencing
// round through the production binaries: an RF3 sync-quorum volume whose
// primary r1 stops long enough to be judged lost. The fencing round reaches
// r2, but r3 cannot make its floor durable (a regular file stands where its
// durable root was, so the floor record write fails with ENOTDIR, root too),
// so it does not answer: one fenced survivor, two needed, nothing is
// published, and r1 does not answer the heal. When r1 resumes, the master
// continues it at epoch 2 on its own evidence; a write after that reads back
// with the one before it.
func TestFencingRoundHealContinuesThePrimary(t *testing.T) { fencingRoundHeal(t, false) }
// TestFencingRoundSurvivorRejoins is the same scenario carried one step
// further: once r3 can persist again, both replicas serve r1 at epoch 2
// (healthy peers of the primary).
func TestFencingRoundSurvivorRejoins(t *testing.T) { fencingRoundHeal(t, true) }
func fencingRoundHeal(t *testing.T, rejoin bool) {
if isWindows() {
t.Skip("SIGSTOP: Linux only")
}
bins := buildG54Binaries(t)
h := &plannedHandoffHarness{dir: t.TempDir(), t: t}
h.masterAddr = handoffAddress(t)
type host struct {
id, data, ctrl, status, nvme, root string
d *daemon
args []string
}
hosts := make([]*host, 3)
var nodes, placements strings.Builder
for i := range hosts {
id := fmt.Sprintf("s%d", i+1)
hosts[i] = &host{id: id, data: handoffAddress(t), ctrl: handoffAddress(t), status: handoffAddress(t), nvme: handoffAddress(t), root: filepath.Join(h.dir, "vol-"+id)}
fmt.Fprintf(&nodes, " - server_id: %s\n data_addr: %s\n ctrl_addr: %s\n", id, hosts[i].data, hosts[i].ctrl)
fmt.Fprintf(&placements, " - server_id: %s\n replica_id: r%d\n", id, i+1)
}
spec := filepath.Join(h.dir, "cluster-spec.yaml")
if err := os.WriteFile(spec, []byte("nodes:\n"+nodes.String()+"volumes:\n - id: v1\n size_bytes: 268435456\n replication_factor: 3\n placements:\n"+placements.String()), 0o644); err != nil {
t.Fatal(err)
}
master := h.start(t, "blockmaster", bins.master,
"--authority-store", filepath.Join(h.dir, "master", "authority"), "--lifecycle-store", filepath.Join(h.dir, "master", "lifecycle"),
"--cluster-spec", spec, "--expected-slots-per-volume", "3", "--lifecycle-product-loop-interval", "200ms",
"--freshness-window", "2s", "--launcher-replication-ack", "sync-quorum", "--listen", h.masterAddr)
master.waitLog(t, 30*time.Second, "blockmaster: lock acquired")
for i, b := range hosts {
lockDir := b.root + ".locks"
if err := os.MkdirAll(lockDir, 0o700); err != nil {
t.Fatal(err)
}
b.args = []string{"--volume-lock-dir-test-only", lockDir, "--master", h.masterAddr, "--server-id", b.id, "--volume-id", "v1",
"--replica-id", fmt.Sprintf("r%d", i+1), "--data-addr", b.data, "--ctrl-addr", b.ctrl, "--status-addr", b.status,
"--durable-root", b.root, "--durable-impl", "walstore", "--durable-blocks", "65536", "--durable-blocksize", "4096",
"--heartbeat-interval", "200ms", "--t1-readiness", "--replication-ack", "sync-quorum",
"--nvme-listen", b.nvme, "--nvme-subsysnqn", plannedHandoffNQN}
b.d = h.start(t, "blockvolume-"+b.id, bins.volume, b.args...)
// Registered after the daemon's own cleanup, so it runs first: a
// stopped child is resumed before it is cancelled.
d := b.d
t.Cleanup(func() { _ = d.proc.Signal(syscall.SIGCONT) })
}
r1, r2, r3 := hosts[0], hosts[1], hosts[2]
// r3's floor fault: its durable root moved aside and a regular file put
// at its path, so a new file under it fails with ENOTDIR (for root as
// well); the files r3 already holds open keep working.
aside := r3.root + ".aside"
breakFloor := func() {
if err := os.Rename(r3.root, aside); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(r3.root, nil, 0o644); err != nil {
t.Fatal(err)
}
}
healFloor := func() {
if err := os.Remove(r3.root); err != nil {
t.Fatal(err)
}
if err := os.Rename(aside, r3.root); err != nil {
t.Fatal(err)
}
}
t.Cleanup(func() {
if st, err := os.Stat(aside); err == nil && st.IsDir() {
_ = os.Remove(r3.root)
_ = os.Rename(aside, r3.root)
}
})
// 1. r1 serves at epoch 1 with both replicas healthy behind it.
h.waitPrimaryAt(t, r1.status, 1)
waitPeersHealthy(t, r1.status, 1)
a := bytes.Repeat([]byte{0xa1}, 4096)
c := dialNVMe(t, r1.nvme, plannedHandoffNQN)
c.write(t, 0, a)
c.flush(t)
if got := c.read(t, 0, 4096); !bytes.Equal(got, a) {
t.Fatal("block A did not read back at epoch 1")
}
c.close()
// The gate has seen both replicas ready on the stores r1 attested (its
// probe of a ready primary logs each candidate's readiness).
poll(t, 30*time.Second, "the gate never saw r2 and r3 ready on attested stores", func() bool {
data, _ := os.ReadFile(master.log)
for _, l := range strings.Split(string(data), string(rune(10))) {
if strings.Contains(l, "promotion gate volume=v1 current=r1") && strings.Contains(l, "{r2 true") && strings.Contains(l, "{r3 true") {
return true
}
}
return false
})
// 2. r3 can no longer persist a floor; r1 stops: a fencing round at 2
// gets only r2, publishes nothing, and r1 cannot answer the heal.
breakFloor()
if err := r1.d.proc.Signal(syscall.SIGSTOP); err != nil {
t.Fatal(err)
}
master.waitLog(t, 60*time.Second, "fencing round at 2: 1 fenced survivors, need 2")
master.waitLog(t, 30*time.Second, "heal: primary r1 did not answer ready")
r3.d.waitLog(t, 30*time.Second, "fencing round=")
if master.has("heal: continuing") || master.has("direct_reassign") {
t.Fatal("a line was published while the fencing round had too few survivors")
}
for _, b := range []*host{r2, r3} {
if e := statusEpoch(t, b.status); e != 1 {
t.Fatalf("%s is at epoch %d while nothing may be published; want 1", b.id, e)
}
}
// 3. r1 resumes: the remembered round heals it at epoch 2.
if err := r1.d.proc.Signal(syscall.SIGCONT); err != nil {
t.Fatal(err)
}
master.waitLog(t, 60*time.Second, "heal: continuing r1 at epoch 2")
h.waitPrimaryAt(t, r1.status, 2)
if master.has("direct_reassign=r2") || master.has("direct_reassign=r3") {
t.Fatal("a survivor was promoted instead of the heal")
}
// 4. A write at epoch 2 reads back with the one before it.
b := bytes.Repeat([]byte{0xb2}, 4096)
c = dialNVMe(t, r1.nvme, plannedHandoffNQN)
c.write(t, 1, b)
c.flush(t)
if got := c.read(t, 0, 8192); !bytes.Equal(got, append(append([]byte(nil), a...), b...)) {
t.Fatal("blocks A and B did not read back at epoch 2")
}
c.close()
if !rejoin {
return
}
// 5. r3 can persist again: both replicas rejoin r1 at epoch 2.
healFloor()
waitPeersHealthy(t, r1.status, 2)
}
// statusEpoch is the epoch a host's /status reports.
func statusEpoch(t *testing.T, statusAddr string) uint64 {
t.Helper()
resp, err := (&http.Client{Timeout: 5 * time.Second}).Get("http://" + statusAddr + "/status?volume=v1")
if err != nil {
t.Fatalf("status %s: %v", statusAddr, err)
}
defer resp.Body.Close()
var st struct{ Epoch uint64 }
if err := json.NewDecoder(resp.Body).Decode(&st); err != nil {
t.Fatalf("status %s: %v", statusAddr, err)
}
return st.Epoch
}
// waitPeersHealthy waits until the primary's /status/peers lists r2 and r3
// healthy at epoch: the primary ships to both and counts them again.
func waitPeersHealthy(t *testing.T, statusAddr string, epoch uint64) {
t.Helper()
c := &http.Client{Timeout: 5 * time.Second}
var last string
end := time.Now().Add(90 * time.Second)
for time.Now().Before(end) {
if resp, err := c.Get("http://" + statusAddr + "/status/peers?volume=v1"); err == nil {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
resp.Body.Close()
last = string(body)
var st struct {
Peers []struct {
ReplicaID string
State string
Epoch uint64
}
}
if json.Unmarshal(body, &st) == nil {
healthy := map[string]bool{}
for _, p := range st.Peers {
if p.State == "healthy" && p.Epoch == epoch {
healthy[p.ReplicaID] = true
}
}
if healthy["r2"] && healthy["r3"] {
return
}
}
}
time.Sleep(200 * time.Millisecond)
}
t.Fatalf("the primary's peers never were r2 and r3 healthy at epoch %d; last: %s", epoch, last)
}
+1
View File
@@ -903,6 +903,7 @@ func runVolume(f flags, exits *processExit) int {
replVolume = replication.NewReplicationVolume(f.volumeID, store)
if status != nil {
status.SetPeerStatusSource(replVolume)
h.SetProbeRoleSource(status.ProbeRoles)
status.SetRuntimeRecoverySource(replVolume)
}
repMode, writeAck, err := parseReplicationAckProfile(f.replicationAck)
@@ -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 }
@@ -132,6 +141,29 @@ func (r *replicationIngress) AdmitAsReplica(epoch uint64) error {
}
return r.roleLocked(epoch, false)
}
// FenceFloor is a fencing round's promise on this replica: the listener
// makes epoch its durable floor (refusing every frame and ACK below it)
// before the round is answered. Without a listener (no replica role yet)
// there is nothing to fence and no promise to give.
func (r *replicationIngress) FenceFloor(epoch uint64) error {
r.mu.Lock()
defer r.mu.Unlock()
if r.closed || r.listener == nil {
return fmt.Errorf("volume %s has no replica listener to fence at epoch %d", r.volumeID, epoch)
}
return r.listener.FenceFloor(epoch)
}
// DurableFloor is the listener's durable floor (0 without a listener).
func (r *replicationIngress) DurableFloor() uint64 {
r.mu.Lock()
defer r.mu.Unlock()
if r.listener == nil {
return 0
}
return r.listener.DurableFloor()
}
func (r *replicationIngress) roleLocked(epoch uint64, primary bool) error {
listener := r.listener
fresh := listener == nil
+4 -2
View File
@@ -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)))
+48
View File
@@ -34,8 +34,56 @@ 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
StoreID [16]byte // the probed store's id (its superblock UUID)
// FencedEpoch: the survivors made this epoch their durable floor before
// answering (a fencing round); the line is minted only at this epoch.
// 0: no fencing round (a planned move).
FencedEpoch uint64
// Basis is why a promotion may be minted; a promotion without one is
// refused.
Basis PromotionBasis
}
// PromotionBasis is the one reason a promotion is minted.
type PromotionBasis uint8
const (
BasisNone PromotionBasis = iota
// BasisFenced: decided on a fencing round's answers; FencedEpoch is the
// epoch minted.
BasisFenced
// BasisPlanned: a planned move after its guard (the target in every
// acknowledgement set while the current primary is alive); no fencing
// round, FencedEpoch 0.
BasisPlanned
// BasisHeal: the line's own primary continued at FencedEpoch after a
// fencing round that published nothing.
BasisHeal
)
// ProbeResult is the outcome of a transport probe.
type ProbeResult struct {
ReplicaID string
+32
View File
@@ -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,10 +583,27 @@ 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
}
// A decision made on a fencing round holds only for the epoch its
// survivors were fenced at: the line must still be at the epoch
// below it.
if ask.Evidence.FencedEpoch != 0 && next.Epoch != ask.Evidence.FencedEpoch {
p.mu.Unlock()
return fmt.Errorf("%w: volume %s fenced at %d, the next epoch is %d", ErrFenceSuperseded, ask.VolumeID, ask.Evidence.FencedEpoch, next.Epoch)
}
// A promotion states its basis, exactly one: fenced (at this epoch),
// planned (after the planned-move guard, no fence), or heal (the
// line's own primary, at this epoch). No path mints one without.
if ask.Evidence.Kind == adapter.PrimaryKindPromotion {
if err := promotionBasisHolds(ask, next.Epoch, p.state, maxEpoch); err != nil {
p.mu.Unlock()
return fmt.Errorf("%w: volume %s replica %s: %v", ErrPromotionUnfenced, ask.VolumeID, ask.ReplicaID, err)
}
}
default:
p.mu.Unlock()
@@ -605,6 +633,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)
}
@@ -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()
@@ -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
@@ -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")
@@ -3,6 +3,8 @@ package authority
import (
"errors"
"testing"
"github.com/seaweedfs/seaweed-block/core/adapter"
)
// #183: Bind is genesis for the volume. These cover the branches around
@@ -16,6 +18,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 +105,78 @@ 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)
}
}
// A decision made on a fencing round at e+1 is minted only while the line
// is still at e: once the line moved, it is refused and nothing changes.
func TestPublisher_AFencedDecisionIsMintedOnlyAtItsFencedEpoch(t *testing.T) {
pub := NewPublisher(NewStaticDirective(nil))
if err := pub.apply(bindAsk("v1", "r1")); err != nil {
t.Fatal(err)
}
ask := reassignAsk("v1", "r2")
ask.Evidence.Basis = adapter.BasisFenced
ask.Evidence.FencedEpoch = 3 // fenced for a line at 2; the line is at 1
if err := pub.apply(ask); !errors.Is(err, ErrFenceSuperseded) {
t.Fatalf("a decision fenced at 3 on a line at 1: %v; want ErrFenceSuperseded", err)
}
if line, _ := pub.VolumeAuthorityLine("v1"); line.ReplicaID != "r1" || line.Epoch != 1 {
t.Fatalf("the line moved: %+v", line)
}
ask.Evidence.FencedEpoch = 2
if err := pub.apply(ask); err != nil {
t.Fatalf("a decision fenced at the next epoch: %v", err)
}
}
// A promotion is minted only on a fencing round's decision or as a guarded
// planned move: one with neither (a decision read from a plain round) is
// refused, so no path can skip the fence.
func TestPublisher_AnUnfencedPromotionIsRefused(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
ask.Evidence = adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion, DurableLSN: 9}
if err := pub.apply(ask); !errors.Is(err, ErrPromotionUnfenced) {
t.Fatalf("an unfenced, unplanned promotion: %v; want ErrPromotionUnfenced", err)
}
if line, _ := pub.VolumeAuthorityLine("v1"); line.ReplicaID != "r1" || line.Epoch != 1 {
t.Fatalf("the line moved: %+v", line)
}
ask.Evidence.Basis = adapter.BasisFenced // but fenced at another epoch
ask.Evidence.FencedEpoch = 3
if err := pub.apply(ask); err == nil {
t.Fatal("a fenced basis at another epoch was minted")
}
ask.Evidence.Basis, ask.Evidence.FencedEpoch = adapter.BasisHeal, 2 // r2 is not the line's primary
if err := pub.apply(ask); !errors.Is(err, ErrPromotionUnfenced) {
t.Fatalf("a heal of another replica: %v; want ErrPromotionUnfenced", err)
}
ask.Evidence.Basis, ask.Evidence.FencedEpoch = adapter.BasisPlanned, 0
if err := pub.apply(ask); err != nil {
t.Fatalf("a guarded planned move: %v", err)
}
}
+29 -7
View File
@@ -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,20 @@ 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. The
// current primary is alive, so it is a planned move: the same
// guard as a failback (the target in every acknowledgement set).
if target.PromotionEvidence.Kind != adapter.PrimaryKindPromotion || !target.PlannedMoveAllowed {
return AssignmentAsk{}, "", false
}
return AssignmentAsk{
VolumeID: vol.VolumeID,
ReplicaID: target.ReplicaID,
DataAddr: target.DataAddr,
CtrlAddr: target.CtrlAddr,
Intent: IntentReassign,
Evidence: plannedEvidence(target.PromotionEvidence),
}, "rebalance", true
}
return AssignmentAsk{}, "", false
@@ -523,13 +533,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
@@ -729,3 +744,10 @@ func sameAsk(a, b AssignmentAsk) bool {
a.CtrlAddr == b.CtrlAddr &&
a.Intent == b.Intent
}
// plannedEvidence is a rebalance's evidence: the gate's probe of the target,
// a planned move after the planned-move guard (PlannedMoveAllowed).
func plannedEvidence(ev adapter.PrimaryEvidence) adapter.PrimaryEvidence {
ev.FencedEpoch, ev.Basis = 0, adapter.BasisPlanned
return ev
}
@@ -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,23 @@ 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, Basis: adapter.BasisPlanned},
// The gate's planned-move guard held (the profile puts the target in
// every acknowledgement set).
PlannedMoveAllowed: true,
}
}
@@ -486,3 +495,67 @@ 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)
}
}
// A rebalance moves the primary while it is alive: a planned move. With the
// gate's evidence but not its planned-move guard (RF3 sync_quorum, or
// best_effort), the controller publishes no rebalance.
func TestTopologyController_RebalanceNeedsThePlannedMoveGuard(t *testing.T) {
for _, guard := range []bool{true, false} {
t.Run(map[bool]string{true: "guard held", false: "guard refused"}[guard], func(t *testing.T) {
planned := func(c ReplicaCandidate) ReplicaCandidate { c.PlannedMoveAllowed = guard; return c }
reader := newFakeBasisReader()
reader.Set("v1", "v1r1", AuthorityBasis{Assigned: true, ReplicaID: "v1r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d11", CtrlAddr: "c11"})
reader.Set("v2", "v2r1", AuthorityBasis{Assigned: true, ReplicaID: "v2r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d21", CtrlAddr: "c21"})
reader.Set("v3", "v3r2", AuthorityBasis{Assigned: true, ReplicaID: "v3r2", Epoch: 1, EndpointVersion: 1, DataAddr: "d32", CtrlAddr: "c32"})
ctrl := NewTopologyController(TopologyControllerConfig{RebalanceSkew: 1}, reader)
snap := ClusterSnapshot{
CollectedRevision: 3,
Servers: []ServerObservation{{ServerID: "s1", Reachable: true, Eligible: true}, {ServerID: "s2", Reachable: true, Eligible: true}, {ServerID: "s3", Reachable: true, Eligible: true}},
Volumes: []VolumeTopologySnapshot{
clusterVolume("v1", AuthorityBasis{Assigned: true, ReplicaID: "v1r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d11", CtrlAddr: "c11"},
candidate("v1r1", "s1", "d11", "c11", 10), planned(candidate("v1r2", "s2", "d12", "c12", 10)), planned(candidate("v1r3", "s3", "d13", "c13", 30))),
clusterVolume("v2", AuthorityBasis{Assigned: true, ReplicaID: "v2r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d21", CtrlAddr: "c21"},
candidate("v2r1", "s1", "d21", "c21", 10), planned(candidate("v2r2", "s2", "d22", "c22", 10)), planned(candidate("v2r3", "s3", "d23", "c23", 10))),
clusterVolume("v3", AuthorityBasis{Assigned: true, ReplicaID: "v3r2", Epoch: 1, EndpointVersion: 1, DataAddr: "d32", CtrlAddr: "c32"},
planned(candidate("v3r1", "s1", "d31", "c31", 10)), candidate("v3r2", "s2", "d32", "c32", 10), planned(candidate("v3r3", "s3", "d33", "c33", 10))),
},
}
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
ask, err := ctrl.Next(ctx)
moved := err == nil && ask.Intent == IntentReassign
if moved != guard {
t.Fatalf("guard=%t: ask=%+v err=%v", guard, ask, err)
}
})
}
}
@@ -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,10 @@ 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.
// gateEvidence stands in for the gate's decision (a test basis: planned).
var gateEvidence = adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion, Basis: adapter.BasisPlanned}
func failoverSnapForV1(authority AuthorityBasis, rev uint64) ClusterSnapshot {
return ClusterSnapshot{
CollectedRevision: rev,
@@ -50,8 +56,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 +479,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 +488,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 +571,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},
},
}},
}
+49 -4
View File
@@ -5,17 +5,20 @@
// (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 (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
)
// AskIntent is the only control knob a Directive has. The publisher
@@ -67,6 +70,48 @@ 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)")
// ErrFenceSuperseded: a primary change decided on a fencing round at epoch
// e+1 arrived after the volume's line left e; the publisher mints nothing.
var ErrFenceSuperseded = errors.New("authority: the fencing round's epoch is no longer the next epoch of the line")
// ErrPromotionUnfenced: a promotion carried neither a fencing round's epoch
// nor the planned-move mark; the publisher mints nothing.
var ErrPromotionUnfenced = errors.New("authority: a promotion needs a fencing round's decision or a guarded planned move")
// promotionBasisHolds checks a promotion's basis against the epoch it is
// minted at; for a heal, the target must be the replica the line names now.
func promotionBasisHolds(ask AssignmentAsk, epoch uint64, state map[subKey]assignmentState, lineEpoch uint64) error {
ev := ask.Evidence
switch ev.Basis {
case adapter.BasisFenced:
if ev.FencedEpoch != epoch {
return fmt.Errorf("fenced at %d, minted at %d", ev.FencedEpoch, epoch)
}
case adapter.BasisPlanned:
if ev.FencedEpoch != 0 {
return fmt.Errorf("a planned move carries no fenced epoch (%d)", ev.FencedEpoch)
}
case adapter.BasisHeal:
if ev.FencedEpoch != epoch {
return fmt.Errorf("heal fenced at %d, minted at %d", ev.FencedEpoch, epoch)
}
if cur, ok := state[subKey{volumeID: ask.VolumeID, replicaID: ask.ReplicaID}]; !ok || !cur.present || cur.info.Epoch != lineEpoch {
return fmt.Errorf("a heal continues the line's own primary; %s is not it", ask.ReplicaID)
}
default:
return fmt.Errorf("no basis")
}
return nil
}
// Directive is the input side of the authority route. A Directive
@@ -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, Basis: adapter.BasisPlanned}, 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.
@@ -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)
}
@@ -0,0 +1,27 @@
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.
// testPromotion: the tests here stand in for the master as a planned move.
var testPromotion = adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion, Basis: adapter.BasisPlanned}
// 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, Basis: adapter.BasisPlanned}
}
}
}
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, Basis: adapter.BasisPlanned}, // 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, Basis: adapter.BasisPlanned}, // the gate allowed it
}
snap := ClusterSnapshot{
CollectedRevision: 1,
-346
View File
@@ -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
@@ -0,0 +1,92 @@
package authority
import (
"go/ast"
"go/parser"
"go/token"
"io/fs"
"path/filepath"
"sort"
"strings"
"testing"
)
// The guard census of promotion bases: every place in the product code that
// sets a PrimaryEvidence basis, with the basis it sets. The publisher mints a
// promotion only with a basis, so this list is every way a primary can be
// promoted; a new one fails this test until it is reviewed and added.
//
// - fenced: the gate's decision on a fencing round (promotionEvidenceFor
// with the round's fenced epoch);
// - heal: the line's own primary continued after a fencing round that
// published nothing;
// - planned: a planned move after its guard (failback, rebalance), and the
// single-replica workspace clean move.
func TestPromotionBasisCensus(t *testing.T) {
want := []string{
"core/authority/controller.go plannedEvidence BasisPlanned",
"core/authority/workspace.go MoveWorkspace BasisPlanned",
"core/host/master/planned_move.go plannedMoveEvidence BasisPlanned",
"core/host/master/product_loop.go healAfterFailedFence BasisHeal",
"core/host/master/product_loop.go promotionEvidenceFor BasisFenced",
}
root := filepath.Join("..", "..")
var got []string
for _, dir := range []string{"core", "cmd"} {
err := filepath.WalkDir(filepath.Join(root, dir), func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
return err
}
f, err := parser.ParseFile(token.NewFileSet(), path, nil, 0)
if err != nil {
return err
}
rel, _ := filepath.Rel(root, path)
rel = filepath.ToSlash(rel)
for _, decl := range f.Decls {
fn, ok := decl.(*ast.FuncDecl)
if !ok || fn.Body == nil {
continue
}
ast.Inspect(fn.Body, func(n ast.Node) bool {
switch n := n.(type) {
case *ast.KeyValueExpr: // Basis: adapter.BasisX
if k, ok := n.Key.(*ast.Ident); ok && k.Name == "Basis" && isPromotionBasis(n.Value) {
got = append(got, rel+" "+fn.Name.Name+" "+basisName(n.Value))
}
case *ast.AssignStmt: // ev.Basis = adapter.BasisX (also in a tuple)
for i, lhs := range n.Lhs {
if sel, ok := lhs.(*ast.SelectorExpr); ok && sel.Sel.Name == "Basis" && i < len(n.Rhs) && isPromotionBasis(n.Rhs[i]) {
got = append(got, rel+" "+fn.Name.Name+" "+basisName(n.Rhs[i]))
}
}
}
return true
})
}
return nil
})
if err != nil {
t.Fatal(err)
}
}
sort.Strings(got)
if strings.Join(got, "\n") != strings.Join(want, "\n") {
t.Fatalf("promotion basis setters changed; review each, then update the census.\ngot:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
}
}
// isPromotionBasis: the value is one of the PromotionBasis constants
// (adapter.BasisX). Known limit: a basis copied from a variable is not seen;
// the bases are only ever set from the constants.
func isPromotionBasis(e ast.Expr) bool {
sel, ok := e.(*ast.SelectorExpr)
return ok && strings.HasPrefix(sel.Sel.Name, "Basis")
}
func basisName(e ast.Expr) string {
if sel, ok := e.(*ast.SelectorExpr); ok {
return sel.Sel.Name
}
return "?"
}
+1 -1
View File
@@ -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)
@@ -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())
+13 -3
View File
@@ -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,17 @@ 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
// PlannedMoveAllowed: the gate also allows a move to this replica while
// the current primary is alive (the planned-move guard of the volume's
// ack profile and replica count held). A rebalance needs it.
PlannedMoveAllowed bool
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
+7 -1
View File
@@ -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, Basis: adapter.BasisPlanned} // 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
}
@@ -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.
@@ -32,6 +32,10 @@ func (f *fakeObservationClient) ReportHeartbeat(context.Context, *control.Heartb
return &control.HeartbeatAck{}, nil
}
func (f *fakeObservationClient) AnswerProbe(context.Context, *control.ProbeAnswer, ...grpc.CallOption) (*control.ProbeAck, error) {
return &control.ProbeAck{}, nil
}
func (f *fakeObservationClient) ReportClusterEvent(_ context.Context, event *control.ClusterEvent, _ ...grpc.CallOption) (*control.ClusterEventAck, error) {
f.event = event
if f.err != nil {
@@ -348,6 +348,7 @@ type VolumeStatus struct {
Path string // its store path under --durable-root
Impl string // the durable implementation (walstore, smartwal, walstore-chunk, ...)
ReplicaID string // the replica this store holds
StoreID string `json:",omitempty"` // the store's superblock UUID (hex); empty when it carries none
Epoch uint64 // the epoch the store is latched to; 0 before an assignment
EndpointVersion uint64 // the endpoint version it is latched to
Latched bool // an assignment latched the store (epoch and endpoint version set)
@@ -39,6 +39,7 @@ package durable
import (
"context"
"encoding/hex"
"errors"
"fmt"
"log"
@@ -356,7 +357,12 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus
writeProfile.DirtyMapUpdateOps = storageProfile.DirtyMapUpdateOps
writeProfile.DirtyMapUpdateDurationNanos = storageProfile.DirtyMapUpdateDurationNanos
}
var storeID string
if id := storage.StoreIDOf(b.storage); !id.IsZero() {
storeID = hex.EncodeToString(id[:])
}
return VolumeStatus{
StoreID: storeID,
Warnings: warnings,
HolesSuspected: holes,
VolumeID: volumeID,
@@ -16,6 +16,28 @@ 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
}
// FencePromotionCandidates: every survivor obeys the fence.
func (readyGate) FencePromotionCandidates(_ string, current authority.AuthorityBasis, survivors []master.PromotionCandidateEvidence) (master.PromotionProbeResult, error) {
res := master.PromotionProbeResult{FencedEpoch: current.Epoch + 1}
for _, s := range survivors {
s.Floor = current.Epoch + 1
s.TableValid = true // a replica that obeys reads its evidence
res.Candidates = append(res.Candidates, s)
}
return res, nil
}
func reopenWait(t *testing.T, what string, fn func() bool) {
t.Helper()
end := time.Now().Add(5 * time.Second)
@@ -37,6 +59,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)
@@ -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, Basis: adapter.BasisPlanned},
})
}
+2
View File
@@ -20,6 +20,8 @@ var masterRules = map[string]auth.Rule{
control.ObservationService_ReportClusterEvent_FullMethodName: {Min: auth.RoleOperator},
control.AssignmentService_SubscribeAssignments_FullMethodName: {Node: true},
control.AssignmentService_SubscribeProbeRounds_FullMethodName: {Node: true},
control.ObservationService_AnswerProbe_FullMethodName: {Node: true},
control.EvidenceService_QueryVolumeStatus_FullMethodName: {Min: auth.RoleViewer, Node: true},
+4 -2
View File
@@ -40,8 +40,10 @@ func TestMasterAuthorizationTableCoversEveryMethod(t *testing.T) {
if len(missing) > 0 || len(stale) > 0 {
t.Fatalf("authorization table out of date: methods without a rule %v; rules without a method %v", missing, stale)
}
if len(registered) != 24 {
t.Fatalf("%d registered methods; the table was written for 24: review the new ones", len(registered))
// 26: SubscribeProbeRounds and AnswerProbe (the promotion probe round)
// are node-only, each for the caller's own server id.
if len(registered) != 26 {
t.Fatalf("%d registered methods; the table was written for 26: review the new ones", len(registered))
}
}
@@ -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,46 @@
package master
import "github.com/seaweedfs/seaweed-block/core/authority"
// fenceObeyed is a fencing round in which every survivor obeys the fence: it
// makes the line's next epoch its durable floor and answers as it did in the
// plain round.
func fenceObeyed(current authority.AuthorityBasis, survivors []PromotionCandidateEvidence) (PromotionProbeResult, error) {
out := make([]PromotionCandidateEvidence, len(survivors))
for i, s := range survivors {
s.Floor = current.Epoch + 1
s.TableValid = true // a replica that obeys reads its evidence
out[i] = s
}
return PromotionProbeResult{FencedEpoch: current.Epoch + 1, Candidates: out}, nil
}
func (s staticPromotionProbe) FencePromotionCandidates(_ string, current authority.AuthorityBasis, survivors []PromotionCandidateEvidence) (PromotionProbeResult, error) {
if s.err != nil {
return PromotionProbeResult{}, s.err
}
return fenceObeyed(current, survivors)
}
func (p *switchProbe) FencePromotionCandidates(_ string, current authority.AuthorityBasis, survivors []PromotionCandidateEvidence) (PromotionProbeResult, error) {
p.mu.Lock()
silent := p.fenceSilent
p.fenceCalls++
p.mu.Unlock()
if silent {
return PromotionProbeResult{FencedEpoch: current.Epoch + 1}, nil
}
return fenceObeyed(current, survivors)
}
func (p *swapPromotionProbe) FencePromotionCandidates(_ string, current authority.AuthorityBasis, survivors []PromotionCandidateEvidence) (PromotionProbeResult, error) {
return fenceObeyed(current, survivors)
}
func (p reviewHeldPromotion) FencePromotionCandidates(_ string, current authority.AuthorityBasis, survivors []PromotionCandidateEvidence) (PromotionProbeResult, error) {
return fenceObeyed(current, survivors)
}
func (p *workloadPlanPromotionEvidenceProvider) FencePromotionCandidates(_ string, current authority.AuthorityBasis, survivors []PromotionCandidateEvidence) (PromotionProbeResult, error) {
return fenceObeyed(current, survivors)
}
@@ -0,0 +1,305 @@
package master
import (
"errors"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// fenceProbe answers the plain round with plain, the fencing round with
// fenced (given the survivors), and a heal round (no candidates) with heal.
type fenceProbe struct {
plain PromotionProbeResult
fenced func(current authority.AuthorityBasis, survivors []PromotionCandidateEvidence) (PromotionProbeResult, error)
heal PromotionProbeResult
survivors []string
}
func (p *fenceProbe) ProbePromotionCandidates(_ string, _ authority.AuthorityBasis, candidates []authority.ReplicaCandidate) (PromotionProbeResult, error) {
if candidates == nil {
return p.heal, nil
}
return p.plain, nil
}
func (p *fenceProbe) FencePromotionCandidates(_ string, current authority.AuthorityBasis, survivors []PromotionCandidateEvidence) (PromotionProbeResult, error) {
for _, s := range survivors {
p.survivors = append(p.survivors, s.ReplicaID)
}
return p.fenced(current, survivors)
}
// fencedAs answers the fencing round with these candidates (their floors as
// given).
func fencedAs(cs ...PromotionCandidateEvidence) func(authority.AuthorityBasis, []PromotionCandidateEvidence) (PromotionProbeResult, error) {
return func(current authority.AuthorityBasis, _ []PromotionCandidateEvidence) (PromotionProbeResult, error) {
return PromotionProbeResult{FencedEpoch: current.Epoch + 1, Candidates: cs}, nil
}
}
// rf3DeadPrimary is an RF3 snapshot whose primary r1 (line at epoch 1) is
// not acceptable: the gate is to replace it.
func rf3DeadPrimary() authority.ClusterSnapshot {
slot := func(r, s string, up bool) authority.ReplicaCandidate {
return authority.ReplicaCandidate{ReplicaID: r, ServerID: s, DataAddr: "d-" + r, CtrlAddr: "c-" + r, Reachable: up, ReadyForPrimary: up, Eligible: true}
}
return authority.ClusterSnapshot{
Servers: []authority.ServerObservation{{ServerID: "s1", Reachable: true, Eligible: true}, {ServerID: "s2", Reachable: true, Eligible: true}, {ServerID: "s3", Reachable: true, Eligible: true}},
Volumes: []authority.VolumeTopologySnapshot{{
VolumeID: "vol-rf3",
Authority: authority.AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d-r1", CtrlAddr: "c-r1"},
Slots: []authority.ReplicaCandidate{slot("r1", "s1", false), slot("r2", "s2", true), slot("r3", "s3", true)},
}},
}
}
func allowedSlots(snap authority.ClusterSnapshot) map[string]adapter.PrimaryEvidence {
out := map[string]adapter.PrimaryEvidence{}
for _, s := range snap.Volumes[0].Slots[1:] {
if s.ReadyForPrimary {
out[s.ReplicaID] = s.PromotionEvidence
}
}
return out
}
// The decision to replace a primary is read from the fencing round: the
// survivors must answer at floor e+1 (N-K+1 of them under sync_quorum RF3),
// the target is the highest FENCED end, and its evidence names the fenced
// epoch. Anything less publishes nothing.
func TestPromotionGate_DecidesOnTheFencingRound(t *testing.T) {
plain := PromotionProbeResult{AckProfile: "sync_quorum", SyncAckKnown: true, Candidates: []PromotionCandidateEvidence{
{ReplicaID: "r2", Ready: true, DurableLSN: 10},
{ReplicaID: "r3", Ready: true, DurableLSN: 9},
}}
for _, c := range []struct {
name string
fenced func(authority.AuthorityBasis, []PromotionCandidateEvidence) (PromotionProbeResult, error)
want map[string]uint64 // allowed replica -> its evidence LSN
}{
{"both fenced: the highest fenced end, not the plain one",
fencedAs(PromotionCandidateEvidence{ReplicaID: "r2", Ready: true, DurableLSN: 10, Floor: 2, TableValid: true}, PromotionCandidateEvidence{ReplicaID: "r3", Ready: true, DurableLSN: 12, Floor: 2, TableValid: true}),
map[string]uint64{"r3": 12}},
{"one fenced, one silent: too few",
fencedAs(PromotionCandidateEvidence{ReplicaID: "r2", Ready: true, DurableLSN: 10, Floor: 2, TableValid: true}),
map[string]uint64{}},
{"one answered at a higher floor (superseded): not counted",
fencedAs(PromotionCandidateEvidence{ReplicaID: "r2", Ready: true, DurableLSN: 10, Floor: 2, TableValid: true}, PromotionCandidateEvidence{ReplicaID: "r3", Ready: true, DurableLSN: 12, Floor: 3, TableValid: true}),
map[string]uint64{}},
{"one answered without the fence (another store: its floor did not move)",
fencedAs(PromotionCandidateEvidence{ReplicaID: "r2", Ready: true, DurableLSN: 10, Floor: 2, TableValid: true}, PromotionCandidateEvidence{ReplicaID: "r3", Ready: true, DurableLSN: 12, Floor: 1, TableValid: true}),
map[string]uint64{}},
{"r3 lagging (not ready) with a lower fenced end: counted, r2 is the target",
fencedAs(PromotionCandidateEvidence{ReplicaID: "r2", Ready: true, DurableLSN: 10, Floor: 2, TableValid: true}, PromotionCandidateEvidence{ReplicaID: "r3", DurableLSN: 8, Floor: 2, TableValid: true}),
map[string]uint64{"r2": 10}},
{"r3 lagging (not ready) holds the highest fenced end: wait",
fencedAs(PromotionCandidateEvidence{ReplicaID: "r2", Ready: true, DurableLSN: 10, Floor: 2, TableValid: true}, PromotionCandidateEvidence{ReplicaID: "r3", DurableLSN: 12, Floor: 2, TableValid: true}),
map[string]uint64{}},
{"r3 on an invalid table: not counted",
fencedAs(PromotionCandidateEvidence{ReplicaID: "r2", Ready: true, DurableLSN: 10, Floor: 2, TableValid: true}, PromotionCandidateEvidence{ReplicaID: "r3", DurableLSN: 8, Floor: 2, TableInvalid: true}),
map[string]uint64{}},
{"r3 fenced but its evidence unreadable (table absent): not counted",
fencedAs(PromotionCandidateEvidence{ReplicaID: "r2", Ready: true, DurableLSN: 10, Floor: 2, TableValid: true}, PromotionCandidateEvidence{ReplicaID: "r3", Floor: 2}),
map[string]uint64{}},
{"the fencing round failed",
func(authority.AuthorityBasis, []PromotionCandidateEvidence) (PromotionProbeResult, error) {
return PromotionProbeResult{}, errors.New("no stream")
},
map[string]uint64{}},
} {
t.Run(c.name, func(t *testing.T) {
h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3})
defer closeTestMaster(t, h)
p := &fenceProbe{plain: plain, fenced: c.fenced}
h.SetPromotionEvidenceProvider(p)
snap := rf3DeadPrimary()
h.applyPromotionEvidenceGate(&snap)
if len(p.survivors) != 2 {
t.Fatalf("fenced %v; want every replica that answered the plain round: r2, r3", p.survivors)
}
got := allowedSlots(snap)
if len(got) != len(c.want) {
t.Fatalf("allowed %v; want %v", got, c.want)
}
for r, lsn := range c.want {
ev, ok := got[r]
if !ok || ev.DurableLSN != lsn || ev.FencedEpoch != 2 || ev.Kind != adapter.PrimaryKindPromotion {
t.Fatalf("%s evidence %+v; want PROMOTION at %d fenced at 2", r, ev, lsn)
}
}
})
}
}
// An empty replicated volume whose primary was lost: every fenced end is 0,
// so nothing was acknowledged, and a ready survivor takes the line. With one
// survivor silent the same volume waits (two are needed to prove it).
func TestPromotionGate_EmptyVolumePrimaryLost(t *testing.T) {
plain := PromotionProbeResult{AckProfile: "sync_quorum", Candidates: []PromotionCandidateEvidence{
{ReplicaID: "r2", Ready: true}, {ReplicaID: "r3", Ready: true},
}}
for name, c := range map[string]struct {
fenced func(authority.AuthorityBasis, []PromotionCandidateEvidence) (PromotionProbeResult, error)
want int
}{
"both fenced at end 0": {fencedAs(PromotionCandidateEvidence{ReplicaID: "r2", Ready: true, Floor: 2, TableValid: true}, PromotionCandidateEvidence{ReplicaID: "r3", Ready: true, Floor: 2, TableValid: true}), 2},
"one fenced": {fencedAs(PromotionCandidateEvidence{ReplicaID: "r2", Ready: true, Floor: 2, TableValid: true}), 0},
// Empty means evidence read on a present, valid table at end 0: an
// answer whose read failed (no table reported) proves nothing.
"both at end 0, one read failed": {fencedAs(PromotionCandidateEvidence{ReplicaID: "r2", Ready: true, Floor: 2, TableValid: true}, PromotionCandidateEvidence{ReplicaID: "r3", Ready: true, Floor: 2}), 0},
} {
t.Run(name, func(t *testing.T) {
h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3})
defer closeTestMaster(t, h)
h.SetPromotionEvidenceProvider(&fenceProbe{plain: plain, fenced: c.fenced})
snap := rf3DeadPrimary()
h.applyPromotionEvidenceGate(&snap)
got := allowedSlots(snap)
if len(got) != c.want {
t.Fatalf("allowed %v; want %d", got, c.want)
}
for r, ev := range got {
if ev.FencedEpoch != 2 || ev.DurableLSN != 0 {
t.Fatalf("%s evidence %+v; want end 0 fenced at 2", r, ev)
}
}
})
}
}
// A fencing round that publishes nothing leaves survivors refusing the
// primary at e: the gate continues the line's own primary at e+1 when it
// answers ready (a PROMOTION with its own evidence), else the volume waits
// with a visible reason.
func TestPromotionGate_HealsAFailedFencingRoundOnTheCurrentPrimary(t *testing.T) {
store := storage.StoreID{7}
for _, ready := range []bool{true, false} {
t.Run(map[bool]string{true: "primary answers ready", false: "primary not ready: wait"}[ready], func(t *testing.T) {
h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3})
defer closeTestMaster(t, h)
p := &fenceProbe{
plain: PromotionProbeResult{AckProfile: "sync_quorum", SyncAckKnown: true, CurrentKnown: true, Current: PromotionCandidateEvidence{ReplicaID: "r1"},
Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 10}, {ReplicaID: "r3", Ready: true, DurableLSN: 10}}},
fenced: fencedAs(PromotionCandidateEvidence{ReplicaID: "r2", Ready: true, DurableLSN: 10, Floor: 2, TableValid: true}), // r3 silent
heal: PromotionProbeResult{CurrentKnown: true, Current: PromotionCandidateEvidence{ReplicaID: "r1", Ready: ready, DurableLSN: 11,
LastDataEpoch: 1, LastDataFirstLSN: 1, StoreID: store, TableValid: true}},
}
h.SetPromotionEvidenceProvider(p)
snap := rf3DeadPrimary()
snap.Volumes[0].Slots[0].Reachable, snap.Volumes[0].Slots[0].ReadyForPrimary = true, true
_, _, asks := h.applyPromotionEvidenceGate(&snap)
if got := allowedSlots(snap); len(got) != 0 {
t.Fatalf("a survivor was allowed after a failed fencing round: %v", got)
}
if !ready {
if len(asks) != 0 {
t.Fatalf("asks %+v; want none (the volume waits)", asks)
}
return
}
if len(asks) != 1 {
t.Fatalf("asks %+v; want the heal", asks)
}
a := asks[0]
if a.ReplicaID != "r1" || a.Intent != authority.IntentReassign || a.Evidence.Kind != adapter.PrimaryKindPromotion ||
a.Evidence.DurableLSN != 11 || a.Evidence.StoreID != store || a.Evidence.FencedEpoch != 2 {
t.Fatalf("heal ask %+v; want r1 continued at 2 on its own evidence", a)
}
})
}
}
// The heal outlives the tick of the failed fencing round: the primary did not
// answer then, and on a later tick (now acceptable, its survivors no longer
// looking ready) it is continued at e+1. Without a remembered round, a
// survivor answering above the line triggers the same heal.
func TestPromotionGate_HealsOnALaterTick(t *testing.T) {
store := storage.StoreID{7}
healed := PromotionProbeResult{CurrentKnown: true, Current: PromotionCandidateEvidence{ReplicaID: "r1", Ready: true, DurableLSN: 11, StoreID: store, TableValid: true}}
t.Run("remembered failed round", func(t *testing.T) {
h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3})
defer closeTestMaster(t, h)
p := &fenceProbe{
plain: PromotionProbeResult{AckProfile: "sync_quorum", SyncAckKnown: true, Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 10}, {ReplicaID: "r3", Ready: true, DurableLSN: 10}}},
fenced: fencedAs(PromotionCandidateEvidence{ReplicaID: "r2", Ready: true, DurableLSN: 10, Floor: 2, TableValid: true}),
}
h.SetPromotionEvidenceProvider(p)
snap := rf3DeadPrimary()
if _, _, asks := h.applyPromotionEvidenceGate(&snap); len(asks) != 0 {
t.Fatalf("tick 1 asks %+v; want none (primary silent)", asks)
}
p.heal = healed
snap = rf3DeadPrimary()
s := snap.Volumes[0].Slots
s[0].Reachable, s[0].ReadyForPrimary = true, true
s[1].ReadyForPrimary, s[2].ReadyForPrimary = false, false // fenced: they refuse the primary
_, _, asks := h.applyPromotionEvidenceGate(&snap)
if len(asks) != 1 || asks[0].ReplicaID != "r1" || asks[0].Evidence.FencedEpoch != 2 {
t.Fatalf("tick 2 asks %+v; want r1 continued at 2", asks)
}
})
t.Run("a survivor answers above the line", func(t *testing.T) {
h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3})
defer closeTestMaster(t, h)
h.SetPromotionEvidenceProvider(&fenceProbe{
plain: PromotionProbeResult{AckProfile: "sync_quorum", SyncAckKnown: true, CurrentKnown: true, Current: PromotionCandidateEvidence{ReplicaID: "r1", Ready: true},
Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 10, Floor: 2, TableValid: true}, {ReplicaID: "r3", Ready: true, DurableLSN: 10, Floor: 1, TableValid: true}}},
heal: healed,
})
snap := rf3DeadPrimary()
snap.Volumes[0].Slots[0].Reachable, snap.Volumes[0].Slots[0].ReadyForPrimary = true, true
_, _, asks := h.applyPromotionEvidenceGate(&snap)
if len(asks) != 1 || asks[0].ReplicaID != "r1" || asks[0].Evidence.FencedEpoch != 2 {
t.Fatalf("asks %+v; want r1 continued at 2", asks)
}
})
}
// The round sends a fencing ask with the fenced epoch and the reference store
// (the last attested), and reads each answer's floor; an answer from another
// store carries no floor.
func TestProbeRound_FencingAskCarriesTheEpochAndStore(t *testing.T) {
hub := newProbeHub()
p := &roundEvidenceProvider{hub: hub, serverOf: func(_, r string) string { return "s2" }, wait: 300 * time.Millisecond, attested: attestedAs}
var asked *control.ProbeRound
roundNode(t, hub, "s2", func(r *control.ProbeRound) *control.ProbeAnswer {
asked = r
a := readyAnswer("s2")(r)
a.Floor = r.FenceEpoch
return a
})
res, err := p.FencePromotionCandidates("v1", authority.AuthorityBasis{ReplicaID: "r1", Epoch: 4}, []PromotionCandidateEvidence{{ReplicaID: "r2", StoreID: storeOf("r2")}})
if err != nil {
t.Fatal(err)
}
want := storeOf("r2")
if asked == nil || asked.FenceEpoch != 5 || string(asked.ExpectedStoreId) != string(want[:]) {
t.Fatalf("fencing ask %+v; want fence epoch 5 on r2's store", asked)
}
if res.FencedEpoch != 5 || len(res.Candidates) != 1 || res.Candidates[0].Floor != 5 || !res.Candidates[0].Ready {
t.Fatalf("fencing result %+v", res)
}
}
func TestProbeRound_FencingAnswerFromAnotherStoreIsNotCounted(t *testing.T) {
hub := newProbeHub()
p := &roundEvidenceProvider{hub: hub, serverOf: func(_, r string) string { return "s2" }, wait: 300 * time.Millisecond, attested: attestedAs}
roundNode(t, hub, "s2", func(r *control.ProbeRound) *control.ProbeAnswer {
a := readyAnswer("s2")(r)
a.StoreId = []byte("another-store-16")
a.Floor = r.FenceEpoch
return a
})
res, err := p.FencePromotionCandidates("v1", authority.AuthorityBasis{ReplicaID: "r1", Epoch: 4}, []PromotionCandidateEvidence{{ReplicaID: "r2"}})
if err != nil {
t.Fatal(err)
}
if len(res.Candidates) != 1 || res.Candidates[0].Floor != 0 {
t.Fatalf("an answer from another store kept its floor: %+v", res.Candidates)
}
}
+18 -7
View File
@@ -122,7 +122,10 @@ type LifecycleStores struct {
// Host is the composed master-side block product daemon. Lifecycle
// is: New -> Start -> (serve requests) -> Close.
type Host struct {
probeHub *probeHub // the promotion probe round (probe_round.go)
probeSlots slotServers // replica -> server, for the round
cfg Config
attest *storeAttestations // primaries' attested write-ACK stores
healthMu sync.Mutex // orders replica health events with their accepted heartbeats (#128 rule 6)
log *log.Logger
boot *bootstrap.DurableAuthorityBootstrap
@@ -143,6 +146,10 @@ type Host struct {
events *eventRing
promotionMu sync.RWMutex
promotionProber PromotionEvidenceProvider
// fencePending: volume -> the epoch a fencing round fenced survivors at
// without a line being published there. Until the line reaches it, those
// survivors refuse the primary, so the gate keeps trying to heal it.
fencePending map[string]uint64
cancel context.CancelFunc
wg sync.WaitGroup
@@ -235,12 +242,13 @@ func New(cfg Config) (*Host, error) {
ctrl := authority.NewTopologyController(ctrlCfg, holder)
h := &Host{
cfg: cfg,
log: lg,
ctrl: ctrl,
topo: cfg.Topology,
events: newEventRing(1024),
journal: newJournalIsolation(storeident.Identity{}), // sampled once the store exists
probeHub: newProbeHub(),
cfg: cfg,
log: lg,
ctrl: ctrl,
topo: cfg.Topology,
events: newEventRing(1024),
journal: newJournalIsolation(storeident.Identity{}), // sampled once the store exists
}
boot, err := bootstrap.BootstrapWithOptions(cfg.AuthorityStoreDir, ctrl, bootstrap.Options{
@@ -256,6 +264,9 @@ func New(cfg Config) (*Host, error) {
// now, or a first start would compare against an unknown device forever.
// An unknown identity (stat error, unsupported platform) never matches.
h.journal.setSelf(storeident.Of(cfg.AuthorityStoreDir))
if h.attest, err = loadStoreAttestations(cfg.AuthorityStoreDir); err != nil {
return nil, fmt.Errorf("master.New: %w", err)
}
var sink authority.ControllerSink = ctrl
if len(cfg.Topology.Volumes) == 0 {
@@ -424,7 +435,7 @@ func (h *Host) Publisher() *authority.Publisher {
// the live Publisher. Callers still need an explicit policy gate before using
// it; constructing the runtime does not execute failback.
func (h *Host) FailbackAuthorityRuntime() authority.FailbackAuthorityRuntime {
return authority.FailbackAuthorityRuntime{Publisher: h.Publisher()}
return authority.FailbackAuthorityRuntime{Publisher: h.Publisher(), Gate: h.plannedMoveEvidence}
}
// Controller exposes the controller for tests.
@@ -0,0 +1,89 @@
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 {
ev := promotionEvidenceFor(result, target)
ev.FencedEpoch, ev.Basis = 0, adapter.BasisPlanned
return ev, 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,76 @@
package master
import (
"fmt"
"testing"
"github.com/seaweedfs/seaweed-block/core/authority"
)
// Every primary change with a live current primary is a planned move and
// passes one guard: a failback (plannedMoveEvidence) and a rebalance (the
// gate's PlannedMoveAllowed on the slot, which the controller requires) are
// allowed exactly when plannedMoveAllowed holds for the volume's ack profile
// and replica count. One row per profile x RF; each row checks both paths.
func TestPlannedMoveOneGuardForFailbackAndRebalance(t *testing.T) {
for _, profile := range []string{"sync_all", "sync_quorum", "best_effort"} {
for _, rf := range []int{2, 3} {
t.Run(fmt.Sprintf("%s/RF%d", profile, rf), func(t *testing.T) {
want := plannedMoveAllowed(profile, rf) == nil
h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: rf})
defer closeTestMaster(t, h)
vol := "vol-rf2"
if rf == 3 {
vol = "vol-rf3"
seedRF3Placement(t, h)
} else {
seedRF2Placement(t, h)
}
candidates := []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 1}}
if rf == 3 {
candidates = append(candidates, PromotionCandidateEvidence{ReplicaID: "r3", Ready: true, DurableLSN: 1})
}
// The current primary is alive and ready: a move now is planned.
h.SetPromotionEvidenceProvider(staticPromotionProbe{result: PromotionProbeResult{
AckProfile: profile,
SyncAckKnown: true,
CurrentKnown: true,
Current: PromotionCandidateEvidence{ReplicaID: "r1", Ready: true, DurableLSN: 1},
Candidates: candidates,
}})
// Failback.
_, err := h.plannedMoveEvidence(vol, "r2")
if (err == nil) != want {
t.Fatalf("failback to r2: err=%v; want allowed=%t", err, want)
}
// Rebalance: the gate's annotation of the snapshot the
// controller reads.
slot := func(r, s string) authority.ReplicaCandidate {
return authority.ReplicaCandidate{ReplicaID: r, ServerID: s, DataAddr: "d-" + r, CtrlAddr: "c-" + r, Reachable: true, ReadyForPrimary: true, Eligible: true}
}
snap := authority.ClusterSnapshot{
Servers: []authority.ServerObservation{{ServerID: "s1", Reachable: true, Eligible: true}, {ServerID: "s2", Reachable: true, Eligible: true}, {ServerID: "s3", Reachable: true, Eligible: true}},
Volumes: []authority.VolumeTopologySnapshot{{
VolumeID: vol,
Authority: authority.AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d-r1", CtrlAddr: "c-r1"},
Slots: []authority.ReplicaCandidate{slot("r1", "s1"), slot("r2", "s2")},
}},
}
if rf == 3 {
snap.Volumes[0].Slots = append(snap.Volumes[0].Slots, slot("r3", "s3"))
}
h.applyPromotionEvidenceGate(&snap)
for _, s := range snap.Volumes[0].Slots[1:] {
if !s.ReadyForPrimary {
t.Fatalf("%s: the gate did not allow a ready candidate: %+v", s.ReplicaID, s)
}
if s.PlannedMoveAllowed != want {
t.Fatalf("rebalance to %s: PlannedMoveAllowed=%t; want %t", s.ReplicaID, s.PlannedMoveAllowed, want)
}
}
})
}
}
}
@@ -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")
}
}
@@ -59,10 +59,14 @@ func ingestRF3Incarnations(t *testing.T, h *Host, r1, r2, r3 rf3Slot) {
}
}
// switchProbe is the promotion probe: r2 is always a ready survivor;
// switchProbe is the promotion probe: r2 is always a ready survivor, r3
// answers as a lagging replica (not ready; its end is r3End, 60 when unset);
// the current primary r1 is ready only while currentReady is set.
type switchProbe struct {
mu sync.Mutex
r3End uint64
fenceSilent bool // no survivor answers the fencing round
fenceCalls int
currentReady bool
// currentUnknown: the current primary did not answer (status GET
// refused or timed out), so CurrentKnown is false.
@@ -99,15 +103,22 @@ func (p *switchProbe) ProbePromotionCandidates(volumeID string, current authorit
defer p.mu.Unlock()
return PromotionProbeResult{
AckProfile: "sync-quorum",
// Only r2 is seen, so its promotion needs a known frontier
// it covers (#181); r3 is silent in these tests.
// Only r2 is ready, so its promotion needs a known frontier it
// covers (#181); r3 answers but lags. A fencing round counts both.
SyncAckLSN: 70,
CurrentKnown: !p.currentUnknown,
Current: PromotionCandidateEvidence{ReplicaID: "r1", Ready: p.currentReady, DurableLSN: 70},
Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 70}},
Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 70}, {ReplicaID: "r3", DurableLSN: p.lagEnd()}},
}, nil
}
func (p *switchProbe) lagEnd() uint64 {
if p.r3End == 0 {
return 60
}
return p.r3End
}
func probeOf(t *testing.T, h *Host) *switchProbe {
t.Helper()
h.promotionMu.RLock()
@@ -234,6 +245,60 @@ func TestUnsupportedPathNeverReassignsOnAnUnansweredPrimary(t *testing.T) {
expectLineStaysR1(t, h, "still unanswered on the next tick")
}
// The unsupported path decides a failover on a fencing round too: with the
// round unanswered nothing is published, however ready the survivor looked
// in the plain round; answered, the line carries the fenced epoch.
func TestUnsupportedPathFailsOverOnlyOnAFencingRound(t *testing.T) {
ineligible := restarting
ineligible.eligible = false
t.Run("fencing round unanswered", func(t *testing.T) {
h := newBootGraceMaster(t, Config{})
defer closeTestMaster(t, h)
p := probeOf(t, h)
p.mu.Lock()
p.fenceSilent = true
p.mu.Unlock()
unsupportedTick(t, h, ineligible)
expectLineStaysR1(t, h, "the survivors did not answer the fencing round")
})
t.Run("fencing round answered", func(t *testing.T) {
h := newBootGraceMaster(t, Config{})
defer closeTestMaster(t, h)
unsupportedTick(t, h, ineligible)
expectFailoverToR2(t, h, "fenced survivors")
if info, _ := h.Publisher().LastPublished("vol-rf3", "r2"); info.Primary.FencedEpoch != 2 {
t.Fatalf("failover line evidence %+v; want fenced at 2", info.Primary)
}
})
}
// A primary restarting inside its boot grace is not replaced, so no fencing
// round cuts its replicas off from it; past the grace it is fenced.
func TestBootGrace_NoFencingRoundInsideTheGrace(t *testing.T) {
h := newBootGraceMaster(t, Config{ControllerConfig: authority.TopologyControllerConfig{PrimaryBootGrace: 600 * time.Millisecond}})
defer closeTestMaster(t, h)
p := probeOf(t, h)
calls := func() int { p.mu.Lock(); defer p.mu.Unlock(); return p.fenceCalls }
ingestRF3Incarnations(t, h, restarting, readySlot("r2-a"), readySlot("r3-a"))
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
if n := calls(); n != 0 {
t.Fatalf("%d fencing rounds against a primary inside its boot grace", n)
}
expectLineStaysR1(t, h, "restarted primary inside its boot grace")
time.Sleep(600 * time.Millisecond)
ingestRF3Incarnations(t, h, restarting, readySlot("r2-a"), readySlot("r3-a"))
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
if calls() == 0 {
t.Fatal("no fencing round once the grace has passed")
}
}
// An explicit unhealthy current primary gets no grace on this path.
func TestBootGrace_UnsupportedPathUnhealthyCurrentFailsOverAtOnce(t *testing.T) {
h := newBootGraceMaster(t, Config{})
@@ -54,7 +54,7 @@ func (f *fakeStatus) serve(t *testing.T) int {
_ = json.NewEncoder(w).Encode(body)
case "/status/durable":
_ = json.NewEncoder(w).Encode(map[string]any{"Volumes": []map[string]any{{
"VolumeID": "vol-rf3", "ReplicaID": f.replicaID, "FrontierKnown": true, "DurableLSN": 70,
"VolumeID": "vol-rf3", "ReplicaID": f.replicaID, "StoreID": testStoreHex, "FrontierKnown": true, "DurableLSN": 70,
}}})
default:
http.NotFound(w, r)
@@ -97,6 +97,7 @@ func useProductionProbe(t *testing.T, h *Host) (r1, r2 *fakeStatus) {
// it covers (#181): r2 reports durable 70.
h.SetPromotionEvidenceProvider(NewWorkloadPlanPromotionEvidenceProvider(plans, WorkloadPlanPromotionProbeConfig{
AckProfile: "sync-quorum",
Attested: attestEvery(testStoreID),
RequiredLSNByVolume: map[string]uint64{"vol-rf3": 70},
}))
return r1, r2
@@ -0,0 +1,269 @@
package master
import (
"crypto/rand"
"encoding/binary"
"sync"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// The promotion probe round. When the master decides a promotion it mints a
// fresh round id, sends a ProbeRound to the node of each replica it asks
// (the current primary and every candidate) over that node's authenticated
// round stream, and counts only the answers that carry this round id, from
// the node it asked, for the replica it asked. Nothing else a replica says
// is promotion evidence: a report, an old answer, an answer for another
// replica or from another node are never counted.
// probeHub routes rounds to subscribed nodes and answers to open rounds.
type probeHub struct {
mu sync.Mutex
subs map[string]map[chan *control.ProbeRound]struct{} // server id -> its streams
rounds map[uint64]*openRound
}
type openRound struct {
volumeID string
asked map[string]string // replica id -> the server id it was asked on
answers chan *control.ProbeAnswer
}
func newProbeHub() *probeHub {
return &probeHub{subs: map[string]map[chan *control.ProbeRound]struct{}{}, rounds: map[uint64]*openRound{}}
}
// subscribe opens a node's round stream; the returned cancel closes it.
func (h *probeHub) subscribe(serverID string) (<-chan *control.ProbeRound, func()) {
ch := make(chan *control.ProbeRound, 16)
h.mu.Lock()
if h.subs[serverID] == nil {
h.subs[serverID] = map[chan *control.ProbeRound]struct{}{}
}
h.subs[serverID][ch] = struct{}{}
h.mu.Unlock()
return ch, func() {
h.mu.Lock()
delete(h.subs[serverID], ch)
if len(h.subs[serverID]) == 0 {
delete(h.subs, serverID)
}
h.mu.Unlock()
}
}
// open registers a round; close removes it (late answers are then dropped).
func (h *probeHub) open(roundID uint64, volumeID string) *openRound {
r := &openRound{volumeID: volumeID, asked: map[string]string{}, answers: make(chan *control.ProbeAnswer, 16)}
h.mu.Lock()
h.rounds[roundID] = r
h.mu.Unlock()
return r
}
func (h *probeHub) close(roundID uint64) {
h.mu.Lock()
delete(h.rounds, roundID)
h.mu.Unlock()
}
// ask sends the round for replicaID to its node; false when the node has no
// open round stream (it cannot answer: the replica is not ready).
func (h *probeHub) ask(roundID uint64, r *openRound, serverID, replicaID string) bool {
return h.send(r, serverID, replicaID, &control.ProbeRound{VolumeId: r.volumeID, ReplicaId: replicaID, RoundId: roundID})
}
// askFence asks a replica in a fencing round: it makes fenceEpoch its durable
// floor first (when its store is store), then answers.
func (h *probeHub) askFence(roundID uint64, r *openRound, serverID, replicaID string, fenceEpoch uint64, store storage.StoreID) bool {
return h.send(r, serverID, replicaID, &control.ProbeRound{VolumeId: r.volumeID, ReplicaId: replicaID, RoundId: roundID, FenceEpoch: fenceEpoch, ExpectedStoreId: append([]byte(nil), store[:]...)})
}
func (h *probeHub) send(r *openRound, serverID, replicaID string, msg *control.ProbeRound) bool {
h.mu.Lock()
defer h.mu.Unlock()
r.asked[replicaID] = serverID
sent := false
for ch := range h.subs[serverID] {
select {
case ch <- msg:
sent = true
default: // a full stream is a slow node: its answer will be late
}
}
return sent
}
// deliver hands an answer to its open round if it is the answer that round
// asked for: this round id, this volume, a replica the round asked, from the
// node it was asked on. Anything else is dropped (false).
func (h *probeHub) deliver(a *control.ProbeAnswer) bool {
h.mu.Lock()
r := h.rounds[a.GetRoundId()]
ok := r != nil && a.GetVolumeId() == r.volumeID && r.asked[a.GetReplicaId()] != "" && r.asked[a.GetReplicaId()] == a.GetServerId()
h.mu.Unlock()
if !ok {
return false
}
select {
case r.answers <- a:
return true
default:
return false
}
}
// roundEvidenceProvider is the PromotionEvidenceProvider of the probe round.
type roundEvidenceProvider struct {
hub *probeHub
serverOf func(volumeID, replicaID string) string
ackProfile string
required map[string]uint64
wait time.Duration
// attested is the store the volume's primary last attested for a
// replica (Host.AttestedStore); a candidate answering another store, or
// one never attested, is not Ready.
attested func(volumeID, replicaID string) (storage.StoreID, bool)
}
// FencePromotionCandidates is the fencing round of a decision to replace the
// primary at line epoch e: each survivor is asked to make e+1 its durable
// floor on its probed store FIRST and then answer (the answer is its promise
// to refuse the old primary). The answers are read as a probe round's; the
// gate counts only those whose floor is e+1.
func (p *roundEvidenceProvider) FencePromotionCandidates(volumeID string, current authority.AuthorityBasis, survivors []PromotionCandidateEvidence) (PromotionProbeResult, error) {
fence := current.Epoch + 1
candidates := make([]authority.ReplicaCandidate, 0, len(survivors))
stores := map[string]storage.StoreID{}
for _, s := range survivors {
candidates = append(candidates, authority.ReplicaCandidate{ReplicaID: s.ReplicaID})
// The reference store: the one a primary last attested for it.
if p.attested != nil {
if ref, ok := p.attested(volumeID, s.ReplicaID); ok {
stores[s.ReplicaID] = ref
}
}
}
result, err := p.round(volumeID, authority.AuthorityBasis{}, candidates, func(roundID uint64, r *openRound, serverID, replicaID string) bool {
return p.hub.askFence(roundID, r, serverID, replicaID, fence, stores[replicaID])
})
// An answer from another store than the reference, or on an invalid
// table, is no evidence: it carries no floor for the gate to count.
for i := range result.Candidates {
c := &result.Candidates[i]
if ref, ok := stores[c.ReplicaID]; !ok || ref.IsZero() || c.StoreID != ref || !c.TableValid {
c.Floor = 0
}
}
result.FencedEpoch = fence
return result, err
}
func newRoundID() uint64 {
var b [8]byte
for {
if _, err := rand.Read(b[:]); err != nil {
continue
}
if id := binary.BigEndian.Uint64(b[:]); id != 0 {
return id
}
}
}
func (p *roundEvidenceProvider) ProbePromotionCandidates(volumeID string, current authority.AuthorityBasis, candidates []authority.ReplicaCandidate) (PromotionProbeResult, error) {
return p.round(volumeID, current, candidates, p.hub.ask)
}
func (p *roundEvidenceProvider) round(volumeID string, current authority.AuthorityBasis, candidates []authority.ReplicaCandidate, ask func(roundID uint64, r *openRound, serverID, replicaID string) bool) (PromotionProbeResult, error) {
required, requiredKnown := p.required[volumeID]
result := PromotionProbeResult{
AckProfile: p.ackProfile,
SyncAckLSN: required,
SyncAckKnown: requiredKnown,
Candidates: make([]PromotionCandidateEvidence, 0, len(candidates)),
}
roundID := newRoundID()
r := p.hub.open(roundID, volumeID)
defer p.hub.close(roundID)
want := map[string]bool{}
askReplica := func(replicaID, serverID string) {
if serverID == "" {
serverID = p.serverOf(volumeID, replicaID)
}
if serverID != "" && ask(roundID, r, serverID, replicaID) {
want[replicaID] = true
}
}
if current.ReplicaID != "" {
askReplica(current.ReplicaID, "")
}
for _, c := range candidates {
askReplica(c.ReplicaID, c.ServerID)
}
got := map[string]*control.ProbeAnswer{}
timer := time.NewTimer(p.wait)
defer timer.Stop()
for len(got) < len(want) {
select {
case a := <-r.answers:
got[a.GetReplicaId()] = a
case <-timer.C:
goto done
}
}
done:
if current.ReplicaID != "" {
if a := got[current.ReplicaID]; a != nil {
result.CurrentKnown = true
var store storage.StoreID
if len(a.GetStoreId()) == len(store) {
copy(store[:], a.GetStoreId())
}
// The current primary's own evidence (a heal continues it on it):
// ready as a serving primary, on a valid table.
result.Current = PromotionCandidateEvidence{ReplicaID: current.ReplicaID, Ready: a.GetPrimaryReady(), DurableLSN: a.GetDurableEnd(),
LastDataEpoch: a.GetLastDataEpoch(), LastDataFirstLSN: a.GetLastDataFirstLsn(), TableInvalid: a.GetTablePresent() && !a.GetTableValid(), TableValid: a.GetTablePresent() && a.GetTableValid(),
StoreID: store, Floor: a.GetFloor()}
} else {
result.Current = PromotionCandidateEvidence{ReplicaID: current.ReplicaID, ProbeAddr: "no answer"}
}
}
for _, c := range candidates {
a := got[c.ReplicaID]
if a == nil {
result.Candidates = append(result.Candidates, PromotionCandidateEvidence{ReplicaID: c.ReplicaID, ProbeAddr: "no answer"})
continue
}
invalid := a.GetTablePresent() && !a.GetTableValid()
var store storage.StoreID
if len(a.GetStoreId()) == len(store) {
copy(store[:], a.GetStoreId())
}
attested := false
if p.attested != nil && !store.IsZero() {
want, ok := p.attested(volumeID, c.ReplicaID)
attested = ok && want == store
}
result.Candidates = append(result.Candidates, PromotionCandidateEvidence{
ReplicaID: c.ReplicaID,
DurableLSN: a.GetDurableEnd(),
LastDataEpoch: a.GetLastDataEpoch(),
LastDataFirstLSN: a.GetLastDataFirstLsn(),
TableInvalid: invalid,
TableValid: a.GetTablePresent() && a.GetTableValid(),
StoreID: store,
Floor: a.GetFloor(),
// A promotion target answers as a ready replica, from a store
// whose epoch table is present and valid, and whose id is the
// store its primary attested (counted toward its write ACKs).
Ready: a.GetReplicaReady() && a.GetTablePresent() && a.GetTableValid() && attested,
})
}
return result, nil
}
@@ -0,0 +1,95 @@
package master
import (
"context"
"sync"
"time"
"github.com/seaweedfs/seaweed-block/core/auth"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// probeRoundWait bounds how long a round waits for its answers.
const probeRoundWait = 2 * time.Second
// slotServers is the latest replica -> server map per volume, from the
// snapshot the promotion gate walks; the round asks each replica's node.
type slotServers struct {
mu sync.Mutex
m map[string]map[string]string
}
func (h *Host) noteSlotServers(volumeID string, slots []authority.ReplicaCandidate) {
h.probeSlots.mu.Lock()
defer h.probeSlots.mu.Unlock()
if h.probeSlots.m == nil {
h.probeSlots.m = map[string]map[string]string{}
}
m := map[string]string{}
for _, s := range slots {
if s.ReplicaID != "" && s.ServerID != "" {
m[s.ReplicaID] = s.ServerID
}
}
h.probeSlots.m[volumeID] = m
}
func (h *Host) slotServer(volumeID, replicaID string) string {
h.probeSlots.mu.Lock()
defer h.probeSlots.mu.Unlock()
return h.probeSlots.m[volumeID][replicaID]
}
// NewRoundPromotionEvidenceProvider is the promotion evidence of the probe
// round: the ack profile and the required frontier from the workload plans'
// configuration, every candidate's evidence from this round's answers.
func (h *Host) NewRoundPromotionEvidenceProvider(ackProfile string, requiredLSNByVolume map[string]uint64) PromotionEvidenceProvider {
return &roundEvidenceProvider{hub: h.probeHub, serverOf: h.slotServer, ackProfile: ackProfile, required: cloneRequiredLSNMap(requiredLSNByVolume), wait: probeRoundWait, attested: h.AttestedStore}
}
// SubscribeProbeRounds streams the probe rounds for the caller's node.
func (s *services) SubscribeProbeRounds(req *control.ProbeRoundSubscription, stream control.AssignmentService_SubscribeProbeRoundsServer) error {
if err := auth.RequireNode(stream.Context(), req.GetServerId()); err != nil {
return err
}
if req.GetServerId() == "" {
return status.Error(codes.InvalidArgument, "server id is required")
}
rounds, cancel := s.host.probeHub.subscribe(req.GetServerId())
defer cancel()
for {
select {
case <-stream.Context().Done():
return nil
case r := <-rounds:
if err := stream.Send(r); err != nil {
return err
}
}
}
}
// AnswerProbe takes one replica's answer to a probe round. It counts only for
// the open round that asked this node for this replica; anything else is
// dropped (and acknowledged: the answer itself is never an error).
func (s *services) AnswerProbe(ctx context.Context, a *control.ProbeAnswer) (*control.ProbeAck, error) {
if err := auth.RequireNode(ctx, a.GetServerId()); err != nil {
return nil, err
}
if a.GetServerId() == "" || a.GetVolumeId() == "" || a.GetReplicaId() == "" || a.GetRoundId() == 0 {
return nil, status.Error(codes.InvalidArgument, "server, volume, replica and round ids are required")
}
s.host.probeHub.deliver(a)
return &control.ProbeAck{}, nil
}
func cloneRequiredLSNMap(in map[string]uint64) map[string]uint64 {
out := make(map[string]uint64, len(in))
for k, v := range in {
out[k] = v
}
return out
}
@@ -0,0 +1,143 @@
package master
import (
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// roundNode is a node on the hub that answers its rounds with answer(round).
func roundNode(t *testing.T, hub *probeHub, serverID string, answer func(*control.ProbeRound) *control.ProbeAnswer) {
t.Helper()
rounds, cancel := hub.subscribe(serverID)
done := make(chan struct{})
t.Cleanup(func() { cancel(); close(done) })
go func() {
for {
select {
case <-done:
return
case r := <-rounds:
if a := answer(r); a != nil {
hub.deliver(a)
}
}
}
}()
}
// storeOf is the store id a replica's node answers with in these tests.
func storeOf(replicaID string) storage.StoreID {
return storage.StoreID{'s', byte(len(replicaID)), replicaID[len(replicaID)-1]}
}
// attestedAs is the primary's attestation: each replica on storeOf(replica).
func attestedAs(_, replicaID string) (storage.StoreID, bool) { return storeOf(replicaID), true }
func readyAnswer(server string) func(*control.ProbeRound) *control.ProbeAnswer {
return func(r *control.ProbeRound) *control.ProbeAnswer {
id := storeOf(r.ReplicaId)
return &control.ProbeAnswer{ServerId: server, VolumeId: r.VolumeId, ReplicaId: r.ReplicaId, RoundId: r.RoundId, StoreId: id[:],
DurableEnd: 9, LastDataEpoch: 2, LastDataFirstLsn: 5, TablePresent: true, TableValid: true, ReplicaReady: true}
}
}
func TestProbeRound_CountsOnlyThisRoundsAnswersFromTheAskedNode(t *testing.T) {
hub := newProbeHub()
servers := map[string]string{"r2": "s2", "r3": "s3"}
p := &roundEvidenceProvider{hub: hub, serverOf: func(_, r string) string { return servers[r] }, ackProfile: "sync-quorum", wait: 300 * time.Millisecond, attested: attestedAs}
roundNode(t, hub, "s2", readyAnswer("s2"))
// s3 answers with an OLD round id (a report from before this decision),
// and also for r2 from the wrong node: neither may count.
roundNode(t, hub, "s3", func(r *control.ProbeRound) *control.ProbeAnswer {
old := readyAnswer("s3")(r)
old.RoundId = r.RoundId + 1
r2store := storeOf("r2")
hub.deliver(&control.ProbeAnswer{ServerId: "s3", VolumeId: r.VolumeId, ReplicaId: "r2", RoundId: r.RoundId, StoreId: r2store[:], DurableEnd: 99, TablePresent: true, TableValid: true, ReplicaReady: true})
return old
})
res, err := p.ProbePromotionCandidates("v1", authority.AuthorityBasis{}, []authority.ReplicaCandidate{{ReplicaID: "r2", ServerID: "s2"}, {ReplicaID: "r3", ServerID: "s3"}})
if err != nil {
t.Fatal(err)
}
got := map[string]PromotionCandidateEvidence{}
for _, c := range res.Candidates {
got[c.ReplicaID] = c
}
if c := got["r2"]; !c.Ready || c.DurableLSN != 9 || c.LastDataEpoch != 2 || c.LastDataFirstLSN != 5 || c.StoreID != storeOf("r2") {
t.Fatalf("r2 answered this round from its node: %+v", c)
}
if c := got["r3"]; c.Ready || c.DurableLSN != 0 {
t.Fatalf("r3 answered only with another round's id: counted %+v", c)
}
}
func TestProbeRound_InvalidTableOrNoAnswerIsNotReady(t *testing.T) {
hub := newProbeHub()
p := &roundEvidenceProvider{hub: hub, serverOf: func(_, r string) string { return map[string]string{"r2": "s2", "r3": "s3"}[r] }, wait: 200 * time.Millisecond, attested: attestedAs}
roundNode(t, hub, "s2", func(r *control.ProbeRound) *control.ProbeAnswer {
a := readyAnswer("s2")(r)
a.TableValid = false // a recovery left its table invalid
return a
})
// s3 has no round stream at all.
res, _ := p.ProbePromotionCandidates("v1", authority.AuthorityBasis{}, []authority.ReplicaCandidate{{ReplicaID: "r2", ServerID: "s2"}, {ReplicaID: "r3", ServerID: "s3"}})
for _, c := range res.Candidates {
if c.Ready {
t.Fatalf("%s is ready: %+v", c.ReplicaID, c)
}
if c.ReplicaID == "r2" && !c.TableInvalid {
t.Fatalf("r2's invalid table is not reported: %+v", c)
}
}
}
// A candidate is ready only on the store its primary attested (the store
// counted toward its write ACKs): another store (a replaced disk), no store id,
// or a replica never attested is not.
func TestProbeRound_OnlyTheAttestedStoreIsReady(t *testing.T) {
servers := map[string]string{"r2": "s2", "r3": "s3", "r4": "s4"}
for name, c := range map[string]struct {
attested func(string, string) (storage.StoreID, bool)
answer func(*control.ProbeAnswer)
ready bool
}{
"the attested store": {attestedAs, func(*control.ProbeAnswer) {}, true},
"another store": {attestedAs, func(a *control.ProbeAnswer) { a.StoreId = []byte("another-store-16") }, false},
"no store id": {attestedAs, func(a *control.ProbeAnswer) { a.StoreId = nil }, false},
"never attested": {func(string, string) (storage.StoreID, bool) { return storage.StoreID{}, false }, func(*control.ProbeAnswer) {}, false},
"no attestation source": {nil, func(*control.ProbeAnswer) {}, false},
} {
t.Run(name, func(t *testing.T) {
hub := newProbeHub()
p := &roundEvidenceProvider{hub: hub, serverOf: func(_, r string) string { return servers[r] }, wait: 300 * time.Millisecond, attested: c.attested}
roundNode(t, hub, "s2", func(r *control.ProbeRound) *control.ProbeAnswer {
a := readyAnswer("s2")(r)
c.answer(a)
return a
})
res, err := p.ProbePromotionCandidates("v1", authority.AuthorityBasis{}, []authority.ReplicaCandidate{{ReplicaID: "r2", ServerID: "s2"}})
if err != nil {
t.Fatal(err)
}
if len(res.Candidates) != 1 || res.Candidates[0].Ready != c.ready {
t.Fatalf("candidates=%+v; want ready=%t", res.Candidates, c.ready)
}
})
}
}
func TestProbeRound_ALateAnswerAfterTheRoundClosedIsDropped(t *testing.T) {
hub := newProbeHub()
r := hub.open(7, "v1")
hub.ask(7, r, "s2", "r2")
hub.close(7)
if hub.deliver(&control.ProbeAnswer{ServerId: "s2", VolumeId: "v1", ReplicaId: "r2", RoundId: 7}) {
t.Fatal("an answer after its round closed was delivered")
}
}
+260 -5
View File
@@ -5,6 +5,9 @@ import (
"reflect"
"strings"
"github.com/seaweedfs/seaweed-block/core/storage"
"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,11 +29,34 @@ 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
// TableValid: the candidate's evidence was read, on a present and valid
// epoch table. Only such an answer is evidence: one whose table is
// absent or could not be read says nothing about its end.
TableValid bool
// StoreID is the candidate's probed store (its superblock UUID). A
// candidate is Ready only when it equals the store the volume's primary
// last attested for it (Host.AttestedStore): a replaced store, or one
// never attested, is not a survivor.
StoreID storage.StoreID
// Floor is the candidate's durable epoch floor when it answered; in a
// fencing round it is counted only at the round's FencedEpoch.
Floor uint64
}
type PromotionProbeResult struct {
AckProfile string
SyncAckLSN uint64
// FencedEpoch: this is a fencing round's result at that epoch (0: a plain
// probe).
FencedEpoch uint64
AckProfile string
SyncAckLSN uint64
// SyncAckKnown reports that SyncAckLSN is a known required
// acknowledgement frontier, which may be zero. A nonzero SyncAckLSN
// is always a known frontier; a zero SyncAckLSN without SyncAckKnown
@@ -43,6 +69,11 @@ type PromotionProbeResult struct {
type PromotionEvidenceProvider interface {
ProbePromotionCandidates(volumeID string, current authority.AuthorityBasis, candidates []authority.ReplicaCandidate) (PromotionProbeResult, error)
// FencePromotionCandidates runs the fencing round of a decision to
// replace the primary of line current: survivors (ready in the plain
// round, with their probed store) make current.Epoch+1 their durable
// floor, then answer. The result's FencedEpoch is current.Epoch+1.
FencePromotionCandidates(volumeID string, current authority.AuthorityBasis, survivors []PromotionCandidateEvidence) (PromotionProbeResult, error)
}
func (h *Host) SetPromotionEvidenceProvider(p PromotionEvidenceProvider) {
@@ -96,7 +127,10 @@ func (h *Host) RunLifecycleProductTick() (LifecycleProductTickResult, error) {
result.SkippedUnverified++
continue
}
if h.assignmentAskAlreadyCurrent(ask.VolumeID, ask.ReplicaID, ask.DataAddr, ask.CtrlAddr) {
// A fenced reassign is minted only at its fenced epoch (a second
// application is refused there), so it is never "already current":
// the heal of a failed fencing round names the current replica.
if ask.Evidence.FencedEpoch == 0 && h.assignmentAskAlreadyCurrent(ask.VolumeID, ask.ReplicaID, ask.DataAddr, ask.CtrlAddr) {
result.SkippedCurrent++
continue
}
@@ -204,7 +238,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)
@@ -212,6 +248,15 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
continue
}
currentAcceptable := candidateAcceptableForPromotionGate(vol.Slots[currentIdx], serverIndex)
// A fencing round fenced survivors above this line and nothing was
// published: they refuse the primary at its epoch (and may no longer
// look ready), so heal before anything else while it is acceptable.
if pend := h.pendingFence(vol.VolumeID, vol.Authority.Epoch); pend && currentAcceptable {
if heal, ok := h.healAfterFailedFence(vol.VolumeID, vol.Authority); ok {
directAsks = append(directAsks, heal)
continue
}
}
candidates := make([]authority.ReplicaCandidate, 0, len(vol.Slots)-1)
readyCandidate := false
for _, slot := range vol.Slots {
@@ -228,6 +273,35 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
probeCount++
result, ok := h.probePromotionCandidatesCurrent(vol.VolumeID, vol.Authority, candidates)
allowed := promotionAllowedReplicas(result, ok, len(candidates), h.freshPromotionPeers(vol.VolumeID, candidates))
// Replacing the primary (it is not acceptable, or answered not
// ready): the decision is read from a fencing round, never from the
// plain answers, so no write the old primary gets acknowledged after
// a survivor answered can be missing from the target.
// A primary in its boot grace is not replaced, so no fencing round
// cuts it off from its replicas while it starts.
replacing := (!currentAcceptable || (result.CurrentKnown && !result.Current.Ready)) &&
!h.primaryBootGraceHoldsNow(vol.VolumeID, vol.Authority.ReplicaID)
// A survivor answering above the line was fenced by a round that
// published nothing (e.g. before a master restart): heal.
if ok && !replacing && floorAboveLine(result, vol.Authority.Epoch) {
if heal, healed := h.healAfterFailedFence(vol.VolumeID, vol.Authority); healed {
directAsks = append(directAsks, heal)
}
}
if (len(allowed) > 0 || emptyVolumeSurvivors(result, ok)) && replacing {
result, allowed = h.fencedDecision(vol.VolumeID, vol.Authority, result, len(candidates))
if len(allowed) == 0 {
h.noteFencePending(vol.VolumeID, vol.Authority.Epoch+1)
// The fencing round ended without a publication: survivors may
// now refuse the primary at e. Continue that primary at e+1 if
// it answers ready, else the volume waits (visibly).
if heal, ok := h.healAfterFailedFence(vol.VolumeID, vol.Authority); ok {
directAsks = append(directAsks, heal)
} else {
h.recordVolumeBlockedEvent(vol.VolumeID, ops.ReasonFenceRoundIncomplete)
}
}
}
if ok {
h.log.Printf("blockmaster: promotion gate volume=%s current=%s current_known=%t current_ready=%t ack_profile=%s required_lsn=%d candidates=%v allowed=%v",
vol.VolumeID, vol.Authority.ReplicaID, result.CurrentKnown, result.Current.Ready, result.AckProfile, result.SyncAckLSN, result.Candidates, allowed)
@@ -244,9 +318,13 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
}
if allowed[slot.ReplicaID] {
slot.ReadyForPrimary = true
slot.PromotionEvidence = promotionEvidenceFor(result, slot.ReplicaID)
slot.PlannedMoveAllowed = plannedMoveAllowed(result.AckProfile, len(vol.Slots)) == nil
enabledCandidate = true
} else {
slot.ReadyForPrimary = false
slot.PromotionEvidence = adapter.PrimaryEvidence{}
slot.PlannedMoveAllowed = false
}
}
// After the (blocking) probe, judge the current primary from its
@@ -266,6 +344,7 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
DataAddr: target.DataAddr,
CtrlAddr: target.CtrlAddr,
Intent: authority.IntentReassign,
Evidence: promotionEvidenceFor(result, target.ReplicaID),
})
}
}
@@ -277,6 +356,154 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
return probeCount, blockedCount, directAsks
}
// fencedDecision runs the fencing round for every replica that answered the
// plain round, ready or not, and decides on its answers alone. An answer
// counts when it made the line's next epoch its durable floor (a higher
// floor was fenced by a newer decision), from the reference store, on a
// valid epoch table: a lagging replica counts, since it may be the only
// holder of an acknowledged write. At least unknownFrontierSurvivorsNeeded
// must count. The target holds the highest counted end and is ready; when
// only a replica that is not ready holds it, nothing is promoted (a lower
// ready one would drop what only that replica has) and the volume waits.
func (h *Host) fencedDecision(volumeID string, current authority.AuthorityBasis, plain PromotionProbeResult, peerCount int) (PromotionProbeResult, map[string]bool) {
h.promotionMu.RLock()
prober := h.promotionProber
h.promotionMu.RUnlock()
var survivors []PromotionCandidateEvidence
for _, c := range plain.Candidates {
if c.ReplicaID != "" && c.ProbeAddr != "no answer" {
survivors = append(survivors, c)
}
}
fenced, err := prober.FencePromotionCandidates(volumeID, current, survivors)
if err != nil || fenced.FencedEpoch != current.Epoch+1 {
h.log.Printf("blockmaster: promotion gate volume=%s fencing round at %d failed: %v", volumeID, current.Epoch+1, err)
return plain, map[string]bool{}
}
fenced.AckProfile, fenced.SyncAckLSN, fenced.SyncAckKnown = plain.AckProfile, plain.SyncAckLSN, plain.SyncAckKnown
fenced.CurrentKnown, fenced.Current = plain.CurrentKnown, plain.Current
counted := map[string]bool{}
var highest uint64
for i := range fenced.Candidates {
c := &fenced.Candidates[i]
if c.ReplicaID != "" && c.Floor == fenced.FencedEpoch && c.TableValid {
counted[c.ReplicaID] = true
if c.DurableLSN > highest {
highest = c.DurableLSN
}
} else {
c.Ready = false
}
}
if need := unknownFrontierSurvivorsNeeded(plain.AckProfile, peerCount); len(counted) < need {
h.log.Printf("blockmaster: promotion gate volume=%s fencing round at %d: %d fenced survivors, need %d; nothing published", volumeID, fenced.FencedEpoch, len(counted), need)
return fenced, map[string]bool{}
}
allowed := map[string]bool{}
var holders []string
for _, c := range fenced.Candidates {
if !counted[c.ReplicaID] || c.DurableLSN != highest {
continue
}
holders = append(holders, c.ReplicaID)
// highest == 0: N-K+1 fenced answers intersect every acknowledgement
// set and none holds an entry, so nothing was ever acknowledged (an
// empty volume whose primary was lost): a ready survivor may take it.
if c.Ready && (fenced.SyncAckLSN == 0 || c.DurableLSN >= fenced.SyncAckLSN) && (c.DurableLSN > 0 || highest == 0) {
allowed[c.ReplicaID] = true
}
}
if len(allowed) == 0 {
h.log.Printf("blockmaster: promotion gate volume=%s fencing round at %d: the highest fenced end %d is held by %v, none ready; waiting for it", volumeID, fenced.FencedEpoch, highest, holders)
h.recordVolumeWaitingEvent(volumeID, ops.ReasonHighestEndNotReady, fmt.Sprintf("the highest fenced end %d is held by %v, not ready for primary", highest, holders))
}
return fenced, allowed
}
// emptyVolumeSurvivors: the plain round saw a ready replica and every answer
// at end 0 with no required frontier. promotionAllowedReplicas never allows
// an end-0 candidate (no data is no evidence); only a fencing round can show
// that nothing was acknowledged, so this case goes to the fence.
func emptyVolumeSurvivors(result PromotionProbeResult, ok bool) bool {
if !ok || !isKnownAckProfile(result.AckProfile) || result.SyncAckLSN != 0 {
return false
}
ready := false
for _, c := range result.Candidates {
if c.DurableLSN != 0 {
return false
}
ready = ready || c.Ready
}
return ready
}
func floorAboveLine(result PromotionProbeResult, lineEpoch uint64) bool {
for _, c := range result.Candidates {
if c.Floor > lineEpoch {
return true
}
}
return false
}
func (h *Host) noteFencePending(volumeID string, epoch uint64) {
h.promotionMu.Lock()
defer h.promotionMu.Unlock()
if h.fencePending == nil {
h.fencePending = map[string]uint64{}
}
if epoch > h.fencePending[volumeID] {
h.fencePending[volumeID] = epoch
}
}
// pendingFence reports a fencing round above the line at lineEpoch that has
// not been followed by a line; one the line has reached is forgotten.
func (h *Host) pendingFence(volumeID string, lineEpoch uint64) bool {
h.promotionMu.Lock()
defer h.promotionMu.Unlock()
e, ok := h.fencePending[volumeID]
if ok && lineEpoch >= e {
delete(h.fencePending, volumeID)
return false
}
return ok
}
func (h *Host) recordVolumeWaitingEvent(volumeID, reason, message string) {
h.events.append(ops.ClusterEvent{VolumeID: volumeID, Type: "volume_blocked", Severity: "warning", Reason: reason, Message: message})
}
// healAfterFailedFence continues the line's own primary at e+1 after a
// fencing round that published nothing, on that primary's answer to a round
// opened for the heal (a plain one: it needs no fence against itself). The
// current primary holds every write it acknowledged, so continuing it at e+1
// loses nothing; the replicas, at floor e+1 already or later, rejoin by
// reconciliation against its table. Its line is a PROMOTION whose evidence
// is that primary's own answer; the target check is the usual one.
func (h *Host) healAfterFailedFence(volumeID string, current authority.AuthorityBasis) (authority.AssignmentAsk, bool) {
h.promotionMu.RLock()
prober := h.promotionProber
h.promotionMu.RUnlock()
res, err := prober.ProbePromotionCandidates(volumeID, current, nil)
c := res.Current
if err != nil || !res.CurrentKnown || c.ReplicaID != current.ReplicaID || !c.Ready || !c.TableValid || c.StoreID.IsZero() {
h.log.Printf("blockmaster: promotion gate volume=%s heal: primary %s did not answer ready (%v); waiting", volumeID, current.ReplicaID, err)
return authority.AssignmentAsk{}, false
}
h.log.Printf("blockmaster: promotion gate volume=%s heal: continuing %s at epoch %d", volumeID, current.ReplicaID, current.Epoch+1)
return authority.AssignmentAsk{
VolumeID: volumeID,
ReplicaID: current.ReplicaID,
DataAddr: current.DataAddr,
CtrlAddr: current.CtrlAddr,
Intent: authority.IntentReassign,
Evidence: adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion, DurableLSN: c.DurableLSN, DataEpoch: c.LastDataEpoch, DataFirstLSN: c.LastDataFirstLSN,
StoreID: c.StoreID, FencedEpoch: current.Epoch + 1, Basis: adapter.BasisHeal},
}, true
}
func (h *Host) applyUnsupportedPromotionEvidenceGate(placements []lifecycle.PlacementIntent, report authority.SupportabilityReport, supported map[string]bool) (int, int, []authority.AssignmentAsk) {
if len(report.Unsupported) == 0 {
return 0, 0, nil
@@ -297,7 +524,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)
@@ -353,6 +580,18 @@ func (h *Host) applyUnsupportedPromotionEvidenceGate(placements []lifecycle.Plac
h.log.Printf("blockmaster: promotion gate unsupported volume=%s current=%s not ready but in boot grace; no direct reassign", vol.VolumeID, current.ReplicaID)
continue
}
// One decision function: the failover is read from a fencing
// round here too, never from the plain answers.
result, allowed = h.fencedDecision(vol.VolumeID, current, result, len(candidates))
if len(allowed) == 0 {
h.noteFencePending(vol.VolumeID, current.Epoch+1)
if heal, healed := h.healAfterFailedFence(vol.VolumeID, current); healed {
directAsks = append(directAsks, heal)
} else {
h.recordVolumeBlockedEvent(vol.VolumeID, ops.ReasonFenceRoundIncomplete)
}
continue
}
if target, ok := chooseAllowedPromotionTarget(vol, result, allowed); ok {
h.log.Printf("blockmaster: promotion gate unsupported volume=%s direct_reassign=%s current=%s", vol.VolumeID, target.ReplicaID, current.ReplicaID)
directAsks = append(directAsks, authority.AssignmentAsk{
@@ -361,6 +600,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 +908,21 @@ 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 {
ev := adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion, DurableLSN: c.DurableLSN, DataEpoch: c.LastDataEpoch, DataFirstLSN: c.LastDataFirstLSN, StoreID: c.StoreID, FencedEpoch: result.FencedEpoch}
if result.FencedEpoch != 0 {
ev.Basis = adapter.BasisFenced
}
return ev
}
}
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)
@@ -513,6 +521,8 @@ func TestMountedFailover_ProductLoopRF3ProbeCanAuthorizeStaleHeartbeatReadiness(
SyncAckLSN: 52,
Candidates: []PromotionCandidateEvidence{
{ReplicaID: "r2", Ready: true, DurableLSN: 52},
// r3 answers but lags: the fencing round counts it.
{ReplicaID: "r3", DurableLSN: 40},
},
},
})
@@ -982,6 +992,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 {
@@ -0,0 +1,193 @@
package master
import (
"bytes"
"context"
"encoding/hex"
"fmt"
"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)
}
// The primary attests its write-ACK set: each replica with the store
// its barriers reported (the live ship above ran them).
// (the component cluster names its peers replica-0 and replica-1;
// the master's placement names them r2 and r3)
peers := cluster.Primary().RepVol.AttestedStores()
attested := map[string]storage.StoreID{"r1": cluster.Primary().RepVol.LocalStoreID()}
for i, id := range []string{"r2", "r3"} {
got := peers[fmt.Sprintf("replica-%d", i)]
if want := storage.StoreIDOf(cluster.Replica(i).Store); want.IsZero() || got != want {
t.Fatalf("primary attests replica-%d as %x, its store is %x", i, got, want)
}
attested[id] = got
}
if err := h.ingestStoreAttestation("node-a", attestation("vol-rf3", "r1", initial.Epoch, attested)); err != nil {
t.Fatal(err)
}
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()
sid := storage.StoreIDOf(store)
_ = json.NewEncoder(w).Encode(struct{ Volumes []durable.VolumeStatus }{[]durable.VolumeStatus{{VolumeID: "vol-rf3", ReplicaID: id, FrontierKnown: true, DurableLSN: r, StoreID: hex.EncodeToString(sid[:])}}})
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", Attested: h.AttestedStore, 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)
}
@@ -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)
}
})
}
}
@@ -1,7 +1,13 @@
package master
// A test-only promotion evidence provider that reads the replicas' HTTP
// status. Production evidence comes only from the probe round
// (NewRoundPromotionEvidenceProvider); this stays for the tests that drive
// the gate from a workload plan.
import (
"context"
"encoding/hex"
"encoding/json"
"fmt"
"net"
@@ -11,6 +17,8 @@ import (
"strings"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/host/volume"
@@ -22,6 +30,11 @@ type WorkloadPlanPromotionProbeConfig struct {
RequiredLSNByVolume map[string]uint64
ExternalStatus bool
HTTPClient *http.Client
// Attested is the store the volume's primary last attested for a
// replica (Host.AttestedStore). A candidate whose probed store differs,
// or that was never attested, is not Ready; nil attests nothing, so no
// candidate is Ready.
Attested func(volumeID, replicaID string) (storage.StoreID, bool)
}
func NewWorkloadPlanPromotionEvidenceProvider(plans []lifecycle.BlockVolumeWorkloadPlan, cfg WorkloadPlanPromotionProbeConfig) PromotionEvidenceProvider {
@@ -58,6 +71,7 @@ func NewWorkloadPlanPromotionEvidenceProvider(plans []lifecycle.BlockVolumeWorkl
required: cloneRequiredLSNMap(cfg.RequiredLSNByVolume),
status: statusAddrs,
client: httpClient,
attested: cfg.Attested,
}
}
@@ -66,6 +80,7 @@ type workloadPlanPromotionEvidenceProvider struct {
required map[string]uint64
status map[string]map[string]string
client *http.Client
attested func(volumeID, replicaID string) (storage.StoreID, bool)
}
func (p *workloadPlanPromotionEvidenceProvider) ProbePromotionCandidates(volumeID string, current authority.AuthorityBasis, candidates []authority.ReplicaCandidate) (PromotionProbeResult, error) {
@@ -127,15 +142,36 @@ func (p *workloadPlanPromotionEvidenceProvider) probeCandidate(volumeID, replica
best = st
}
}
return PromotionCandidateEvidence{
ReplicaID: replicaID,
ProbeAddr: statusAddr,
Ready: local.VolumeID == volumeID &&
local.ReplicaID == replicaID &&
strings.EqualFold(local.ReplicationRole, "replica_ready") &&
best.FrontierKnown,
ev := PromotionCandidateEvidence{
ReplicaID: replicaID,
ProbeAddr: statusAddr,
DurableLSN: best.DurableLSN,
}, nil
}
if b, err := hex.DecodeString(best.StoreID); err == nil && len(b) == len(ev.StoreID) {
copy(ev.StoreID[:], b)
}
// The candidate's epoch-table row and table validity come from the
// authenticated probe round, not from /status (loopback-only under
// mutual TLS); until then the evidence carries none.
ev.Ready = local.VolumeID == volumeID &&
local.ReplicaID == replicaID &&
strings.EqualFold(local.ReplicationRole, "replica_ready") &&
best.FrontierKnown &&
!ev.TableInvalid &&
p.storeAttested(volumeID, replicaID, ev.StoreID)
return ev, nil
}
// storeAttested reports whether probed is the store the volume's primary
// last attested for replicaID: a store the primary never counted toward its
// write ACKs (never attested, dropped, or a replacement with a new
// superblock) is not a survivor, whatever its own report says.
func (p *workloadPlanPromotionEvidenceProvider) storeAttested(volumeID, replicaID string, probed storage.StoreID) bool {
if p.attested == nil || probed.IsZero() {
return false
}
want, ok := p.attested(volumeID, replicaID)
return ok && want == probed
}
func (p *workloadPlanPromotionEvidenceProvider) probeCurrent(volumeID, replicaID, statusAddr string) (PromotionCandidateEvidence, error) {
@@ -212,11 +248,3 @@ func isLocalhostOrLoopbackHost(host string) bool {
ip := net.ParseIP(host)
return ip != nil && ip.IsLoopback()
}
func cloneRequiredLSNMap(in map[string]uint64) map[string]uint64 {
out := make(map[string]uint64, len(in))
for k, v := range in {
out[k] = v
}
return out
}
@@ -32,7 +32,7 @@ func TestWorkloadPlanPromotionEvidenceProvider_ProbesDurableFrontiers(t *testing
_ = json.NewEncoder(w).Encode(struct {
Volumes []durable.VolumeStatus
}{Volumes: []durable.VolumeStatus{{
VolumeID: "vol-rf3", ReplicaID: "r2", FrontierKnown: true, DurableLSN: 52,
VolumeID: "vol-rf3", ReplicaID: "r2", StoreID: testStoreHex, FrontierKnown: true, DurableLSN: 52,
}}})
default:
http.NotFound(w, r)
@@ -47,6 +47,7 @@ func TestWorkloadPlanPromotionEvidenceProvider_ProbesDurableFrontiers(t *testing
ReplicaID: "r2", ISCSIListenPort: 3260,
}},
}}, WorkloadPlanPromotionProbeConfig{
Attested: attestEvery(testStoreID),
AckProfile: "sync-quorum",
RequiredLSNByVolume: map[string]uint64{"vol-rf3": 52},
HTTPClient: rewriteHTTPClient(server.URL, "127.0.0.1:23260"),
@@ -83,7 +84,7 @@ func TestWorkloadPlanPromotionEvidenceProvider_NotReadyWithoutReplicaReadyRole(t
_ = json.NewEncoder(w).Encode(struct {
Volumes []durable.VolumeStatus
}{Volumes: []durable.VolumeStatus{{
VolumeID: "vol-rf3", ReplicaID: "r2", FrontierKnown: true, DurableLSN: 90,
VolumeID: "vol-rf3", ReplicaID: "r2", StoreID: testStoreHex, FrontierKnown: true, DurableLSN: 90,
}}})
default:
http.NotFound(w, r)
@@ -98,6 +99,7 @@ func TestWorkloadPlanPromotionEvidenceProvider_NotReadyWithoutReplicaReadyRole(t
ReplicaID: "r2", ISCSIListenPort: 3260,
}},
}}, WorkloadPlanPromotionProbeConfig{
Attested: attestEvery(testStoreID),
AckProfile: "sync-quorum",
HTTPClient: rewriteHTTPClient(server.URL, "127.0.0.1:23260"),
})
@@ -114,6 +116,7 @@ func TestWorkloadPlanPromotionEvidenceProvider_NotReadyWithoutReplicaReadyRole(t
func TestWorkloadPlanPromotionEvidenceProvider_CurrentUnknownWithoutProbeAddress(t *testing.T) {
provider := NewWorkloadPlanPromotionEvidenceProvider(nil, WorkloadPlanPromotionProbeConfig{
Attested: attestEvery(testStoreID),
AckProfile: "sync-quorum",
})
result, err := provider.ProbePromotionCandidates("vol-rf3", authority.AuthorityBasis{ReplicaID: "r1"}, nil)
@@ -141,7 +144,7 @@ func TestWorkloadPlanPromotionEvidenceProvider_CurrentKnownAfterSuccessfulProbe(
_ = json.NewEncoder(w).Encode(struct {
Volumes []durable.VolumeStatus
}{Volumes: []durable.VolumeStatus{{
VolumeID: "vol-rf3", ReplicaID: "r1", FrontierKnown: true, DurableLSN: 52,
VolumeID: "vol-rf3", ReplicaID: "r1", StoreID: testStoreHex, FrontierKnown: true, DurableLSN: 52,
}}})
default:
http.NotFound(w, r)
@@ -156,6 +159,7 @@ func TestWorkloadPlanPromotionEvidenceProvider_CurrentKnownAfterSuccessfulProbe(
ReplicaID: "r1", ISCSIListenPort: 3260,
}},
}}, WorkloadPlanPromotionProbeConfig{
Attested: attestEvery(testStoreID),
AckProfile: "sync-quorum",
HTTPClient: rewriteHTTPClient(server.URL, "127.0.0.1:23260"),
})
@@ -180,7 +184,7 @@ func TestNodeLoss_WorkloadPlanPromotionEvidenceProvider_ExternalStatusUsesNodeAd
_ = json.NewEncoder(w).Encode(struct {
Volumes []durable.VolumeStatus
}{Volumes: []durable.VolumeStatus{{
VolumeID: "vol-rf3", ReplicaID: "r2", FrontierKnown: true, DurableLSN: 52,
VolumeID: "vol-rf3", ReplicaID: "r2", StoreID: testStoreHex, FrontierKnown: true, DurableLSN: 52,
}}})
default:
http.NotFound(w, r)
@@ -195,6 +199,7 @@ func TestNodeLoss_WorkloadPlanPromotionEvidenceProvider_ExternalStatusUsesNodeAd
ReplicaID: "r2", DataAddr: "10.0.0.2:19103", ISCSIListenPort: 3260,
}},
}}, WorkloadPlanPromotionProbeConfig{
Attested: attestEvery(testStoreID),
AckProfile: "sync-quorum",
ExternalStatus: true,
HTTPClient: rewriteHTTPClient(server.URL, "10.0.0.2:23260"),
@@ -220,6 +225,7 @@ func TestNodeLoss_WorkloadPlanPromotionEvidenceProvider_ExternalStatusRejectsLoo
ReplicaID: "r2", DataAddr: "127.0.0.1:19103", ISCSIListenPort: 3260,
}},
}}, WorkloadPlanPromotionProbeConfig{
Attested: attestEvery(testStoreID),
AckProfile: "sync-quorum",
ExternalStatus: true,
})
@@ -146,6 +146,27 @@ func TestRecoveryWatchdog_MasterUnhealthyFailsOverToQualifiedPeer(t *testing.T)
}
}
// The lagging r3 holds a higher end than the ready r2 (it may be the only
// holder of an acknowledged write): the fencing round promotes nobody, and
// the volume waits for it.
func TestRecoveryWatchdog_MasterWaitsWhenALaggingReplicaHoldsTheHighestEnd(t *testing.T) {
h, svc := watchdogMaster(t)
defer closeTestMaster(t, h)
h.SetPromotionEvidenceProvider(&switchProbe{r3End: 80})
reportRF3(t, svc, wireSlot{"r1-b", false, "recovery_timeout"}, wireSlot{"r2-a", true, ""}, wireSlot{"r3-a", false, ""})
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatalf("product tick: %v", err)
}
time.Sleep(150 * time.Millisecond)
if line, _ := h.Publisher().VolumeAuthorityLine("vol-rf3"); line.ReplicaID != "r1" || line.Epoch != 1 {
t.Fatalf("promoted below a lagging replica's higher end: line=%+v", line)
}
if !timelineHasEvent(timelineEvents(t, svc), "volume_blocked", "highest_end_not_ready") {
t.Fatalf("the wait is not visible in the timeline")
}
}
// A running primary that was ready and later reports not ready on the
// same incarnation (no unhealthy reason) follows the normal failover
// rules: no boot grace for that incarnation, so it fails over to the
+21 -7
View File
@@ -330,6 +330,12 @@ func (s *services) ReportHeartbeat(ctx context.Context, r *control.HeartbeatRepo
if err := s.host.ingestHeartbeatRecordingHealth(msg); err != nil {
return nil, fmt.Errorf("ingest: %w", err)
}
// A primary's attestation of its write-ACK stores. Only the holder of
// the volume's current line is taken; a failed write fails the report,
// so the primary sends it again with its next heartbeat.
if err := s.host.ingestStoreAttestation(r.GetServerId(), r.GetStoreAttestation()); err != nil {
return nil, status.Error(codes.Unavailable, err.Error())
}
return &control.HeartbeatAck{
AcceptedAt: timestamppb.Now(),
Sequence: s.seq.Add(1),
@@ -995,13 +1001,21 @@ 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,
}
if info.Primary.StoreID != ([16]byte{}) {
id := info.Primary.StoreID
fact.EvidenceStoreId = id[:]
}
// Populate the peer set from publisher LastPublished
// queries for every non-self replica slot in this volume's
@@ -0,0 +1,206 @@
package master
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"sync"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// storeAttestationFile holds every volume's last primary attestation, in
// the authority store directory; it is replaced as a whole by one atomic
// write (temp file, fsync, rename, directory fsync).
const storeAttestationFile = "store-attestations.json"
// attestedStores is one volume's last attestation: the primary line that
// made it and, per replica, the store that counted toward its write ACKs.
type attestedStores struct {
Primary string `json:"primary"`
Epoch uint64 `json:"epoch"`
Stores map[string]string `json:"stores"` // replica id -> store id (hex)
}
// storeAttestations is the master's record of which store each replica
// counted toward write ACKs with, as the volume's primary attested it. It
// is the reference a promotion's probed store must equal: a replica's own
// report of its store never sets it, so a replaced store (an empty disk
// with a new superblock) is not taken for the store that acknowledged.
type storeAttestations struct {
mu sync.Mutex
path string // "" = memory only
vols map[string]attestedStores
}
func loadStoreAttestations(dir string) (*storeAttestations, error) {
s := &storeAttestations{vols: map[string]attestedStores{}}
if dir == "" {
return s, nil
}
s.path = filepath.Join(dir, storeAttestationFile)
b, err := os.ReadFile(s.path)
if errors.Is(err, os.ErrNotExist) {
return s, nil
}
if err != nil {
return nil, fmt.Errorf("store attestations: %w", err)
}
if err := json.Unmarshal(b, &s.vols); err != nil {
return nil, fmt.Errorf("store attestations %s: %w", s.path, err)
}
if s.vols == nil {
s.vols = map[string]attestedStores{}
}
return s, nil
}
// lookup returns the store a primary of the volume last attested for
// replica; false when none ever did. A replica dropped from the write-ACK
// set since keeps it.
func (s *storeAttestations) lookup(volumeID, replicaID string) (storage.StoreID, bool) {
s.mu.Lock()
defer s.mu.Unlock()
h, ok := s.vols[volumeID].Stores[replicaID]
if !ok {
return storage.StoreID{}, false
}
var id storage.StoreID
b, err := hex.DecodeString(h)
if err != nil || len(b) != len(id) {
return storage.StoreID{}, false
}
copy(id[:], b)
return id, !id.IsZero()
}
// record merges att into the volume's record, in one write: each replica it
// names gets that store as its reference; a replica it does not name keeps
// its last one. An attestation from a lower epoch than the recorded one is
// ignored (a deposed primary's late report); an unchanged one writes
// nothing.
func (s *storeAttestations) record(att *control.StoreAttestation) error {
next := attestedStores{Primary: att.GetReplicaId(), Epoch: att.GetEpoch(), Stores: map[string]string{}}
for _, st := range att.GetStores() {
var id storage.StoreID
if st.GetReplicaId() == "" || len(st.GetStoreId()) != len(id) {
return fmt.Errorf("store attestation for %s: malformed entry %q (%d bytes)", att.GetVolumeId(), st.GetReplicaId(), len(st.GetStoreId()))
}
copy(id[:], st.GetStoreId())
if id.IsZero() {
continue
}
next.Stores[st.GetReplicaId()] = hex.EncodeToString(id[:])
}
s.mu.Lock()
defer s.mu.Unlock()
cur, had := s.vols[att.GetVolumeId()]
if had && next.Epoch < cur.Epoch {
return nil
}
// A replica the primary no longer attests keeps its last reference: it
// may be the only holder of an acknowledged write, and only that store
// can still prove it. A new attestation (after a rebuild) replaces it.
for id, sid := range cur.Stores {
if _, again := next.Stores[id]; !again {
next.Stores[id] = sid
}
}
if had && sameAttestation(cur, next) {
return nil
}
vols := make(map[string]attestedStores, len(s.vols)+1)
for k, v := range s.vols {
vols[k] = v
}
vols[att.GetVolumeId()] = next
if err := s.persist(vols); err != nil {
return err
}
s.vols = vols
return nil
}
func sameAttestation(a, b attestedStores) bool {
if a.Primary != b.Primary || a.Epoch != b.Epoch || len(a.Stores) != len(b.Stores) {
return false
}
for k, v := range a.Stores {
if b.Stores[k] != v {
return false
}
}
return true
}
func (s *storeAttestations) persist(vols map[string]attestedStores) error {
if s.path == "" {
return nil
}
payload, err := json.Marshal(vols)
if err != nil {
return err
}
temp := s.path + ".tmp"
f, err := os.OpenFile(temp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
if err != nil {
return fmt.Errorf("store attestations: %w", err)
}
_, werr := f.Write(payload)
if werr == nil {
werr = f.Sync()
}
if cerr := f.Close(); werr == nil {
werr = cerr
}
if werr == nil {
werr = os.Rename(temp, s.path)
}
if werr != nil {
_ = os.Remove(temp)
return fmt.Errorf("store attestations: %w", werr)
}
if runtime.GOOS == "windows" {
return nil // a directory cannot be fsynced there; the rename is the commit
}
d, err := os.Open(filepath.Dir(s.path))
if err != nil {
return fmt.Errorf("store attestations: directory: %w", err)
}
defer d.Close()
if err := d.Sync(); err != nil {
return fmt.Errorf("store attestations: directory fsync: %w", err)
}
return nil
}
// ingestStoreAttestation records a heartbeat's attestation when the
// reporting server holds the volume's published primary line at the
// attested epoch (the line's replica and owner). Anything else is not a
// primary's word and is dropped.
func (h *Host) ingestStoreAttestation(server string, att *control.StoreAttestation) error {
if att == nil || h.attest == nil {
return nil
}
vol := att.GetVolumeId()
line, published := h.Publisher().PublishedAuthorityLine(vol)
if !published || line.ReplicaID != att.GetReplicaId() || line.Epoch != att.GetEpoch() ||
h.workspaceLineOwner(line, vol, line.ReplicaID, line.Epoch) != server {
return nil
}
return h.attest.record(att)
}
// AttestedStore is the store the primary of volumeID last attested for
// replicaID (see storeAttestations).
func (h *Host) AttestedStore(volumeID, replicaID string) (storage.StoreID, bool) {
if h == nil || h.attest == nil {
return storage.StoreID{}, false
}
return h.attest.lookup(volumeID, replicaID)
}
@@ -0,0 +1,264 @@
package master
import (
"encoding/hex"
"encoding/json"
"net/http"
"net/http/httptest"
"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"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func attestation(vol, primary string, epoch uint64, stores map[string]storage.StoreID) *control.StoreAttestation {
att := &control.StoreAttestation{VolumeId: vol, ReplicaId: primary, Epoch: epoch}
for id, sid := range stores {
att.Stores = append(att.Stores, &control.AttestedStore{ReplicaId: id, StoreId: append([]byte(nil), sid[:]...)})
}
return att
}
func storeID(b byte) storage.StoreID {
var id storage.StoreID
for i := range id {
id[i] = b
}
return id
}
// rf3Primary publishes vol-rf3's first line (r1 on node-a) and returns it.
func rf3Primary(t *testing.T, h *Host) authority.AuthorityBasis {
t.Helper()
seedRF3Placement(t, h)
ingestRF3Observation(t, h, true, true, true)
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
line := waitAuthorityLine(t, h.Publisher(), "vol-rf3")
if line.ReplicaID != "r1" {
t.Fatalf("initial line=%+v", line)
}
return line
}
// The reference store of a replica is set only by the volume's primary
// line holder at that line's epoch; a replica's own claim, a stale epoch or
// another server is dropped; a replica the primary stops attesting keeps
// its last reference (it may hold the only copy of an acknowledged write),
// a new attestation after its rebuild replaces it; the record survives a
// master restart.
func TestStoreAttestationOnlyFromThePrimaryLine(t *testing.T) {
dir := t.TempDir()
h, err := New(Config{AuthorityStoreDir: dir, LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0",
ControllerConfig: authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3}})
if err != nil {
t.Fatal(err)
}
h.Start()
t.Cleanup(func() { closeTestMaster(t, h) })
line := rf3Primary(t, h)
s1, s2, t1 := storeID(0x11), storeID(0x22), storeID(0x33)
for _, c := range []struct {
name, server, primary string
epoch uint64
}{
{"a replica's own claim", "node-b", "r2", line.Epoch},
{"the primary's replica id from another server", "node-b", "r1", line.Epoch},
{"another epoch", "node-a", "r1", line.Epoch + 1},
} {
if err := h.ingestStoreAttestation(c.server, attestation("vol-rf3", c.primary, c.epoch, map[string]storage.StoreID{"r2": s2})); err != nil {
t.Fatal(err)
}
if _, ok := h.AttestedStore("vol-rf3", "r2"); ok {
t.Fatalf("%s set the reference", c.name)
}
}
if err := h.ingestStoreAttestation("node-a", attestation("vol-rf3", "r1", line.Epoch, map[string]storage.StoreID{"r1": storeID(1), "r2": s1, "r3": t1})); err != nil {
t.Fatal(err)
}
if got, ok := h.AttestedStore("vol-rf3", "r2"); !ok || got != s1 {
t.Fatalf("primary's attestation: r2 -> %x %t, want %x", got, ok, s1)
}
// r2 left the write-ACK set: its reference stays S1.
if err := h.ingestStoreAttestation("node-a", attestation("vol-rf3", "r1", line.Epoch, map[string]storage.StoreID{"r1": storeID(1), "r3": t1})); err != nil {
t.Fatal(err)
}
if got, ok := h.AttestedStore("vol-rf3", "r2"); !ok || got != s1 {
t.Fatalf("r2 dropped from the ack set: reference %x %t; want its last attested store %x kept", got, ok, s1)
}
// r2 rebuilt onto a new store S2 and rejoined: S2 replaces S1.
if err := h.ingestStoreAttestation("node-a", attestation("vol-rf3", "r1", line.Epoch, map[string]storage.StoreID{"r1": storeID(1), "r2": s2, "r3": t1})); err != nil {
t.Fatal(err)
}
if got, ok := h.AttestedStore("vol-rf3", "r2"); !ok || got != s2 {
t.Fatalf("r2 rebuilt and attested again: reference %x %t; want %x", got, ok, s2)
}
reloaded, err := loadStoreAttestations(dir)
if err != nil {
t.Fatal(err)
}
if got, ok := reloaded.lookup("vol-rf3", "r3"); !ok || got != t1 {
t.Fatalf("after restart: r3 -> %x %t, want %x", got, ok, t1)
}
if got, ok := reloaded.lookup("vol-rf3", "r2"); !ok || got != s2 {
t.Fatalf("after restart: r2 -> %x %t, want %x", got, ok, s2)
}
}
// The loss schedule: r2 counted toward write ACKs with store S1; its disk
// is replaced (S2, empty) and its own reports say S2; the primary dies. The
// probe of r2 shows S2 with a durable LSN as good as r3's, so only the
// store check tells them apart: r2 is not a survivor, r3 (attested T1,
// probed T1) is promoted. With the required frontier unknown, the RF3
// quorum rule needs two survivors, so nothing is promoted.
func TestPromotionRefusesAReplacedStoreThePrimaryNeverAttested(t *testing.T) {
s1, s2, t1 := storeID(0x11), storeID(0x22), storeID(0x33)
for _, c := range []struct {
name string
requiredKnown bool
r2Probed storage.StoreID
want string // "" = no promotion
wantNot string
}{
{"replaced store, frontier known", true, s2, "r3", "r2"},
{"replaced store, frontier unknown", false, s2, "", "r2"},
{"control: the attested store", true, s1, "", ""},
} {
t.Run(c.name, func(t *testing.T) {
h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3})
t.Cleanup(func() { closeTestMaster(t, h) })
line := rf3Primary(t, h)
if err := h.ingestStoreAttestation("node-a", attestation("vol-rf3", "r1", line.Epoch, map[string]storage.StoreID{"r1": storeID(1), "r2": s1, "r3": t1})); err != nil {
t.Fatal(err)
}
// r2's node reports its new store: never the reference.
if err := h.ingestStoreAttestation("node-b", attestation("vol-rf3", "r2", line.Epoch, map[string]storage.StoreID{"r2": s2})); err != nil {
t.Fatal(err)
}
probed := map[string]storage.StoreID{"r2": c.r2Probed, "r3": t1}
plans := []lifecycle.BlockVolumeWorkloadPlan{{VolumeID: "vol-rf3", Protocol: "iscsi"}}
routes := map[string]string{}
for i, id := range []string{"r2", "r3"} {
id, sid := id, probed[id]
srv := 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":
_ = json.NewEncoder(w).Encode(struct{ Volumes []durable.VolumeStatus }{[]durable.VolumeStatus{{VolumeID: "vol-rf3", ReplicaID: id, FrontierKnown: true, DurableLSN: 100, StoreID: hex.EncodeToString(sid[:])}}})
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
plans[0].Replicas = append(plans[0].Replicas, lifecycle.BlockVolumeReplicaWorkload{ReplicaID: id, ISCSIListenPort: 3260 + i})
routes[[]string{"127.0.0.1:23260", "127.0.0.1:23261"}[i]] = srv.URL
}
cfg := WorkloadPlanPromotionProbeConfig{AckProfile: "sync-quorum", Attested: h.AttestedStore,
HTTPClient: &http.Client{Transport: promotionTraceRoutes(routes), Timeout: time.Second}}
if c.requiredKnown {
cfg.RequiredLSNByVolume = map[string]uint64{"vol-rf3": 50}
}
h.SetPromotionEvidenceProvider(NewWorkloadPlanPromotionEvidenceProvider(plans, cfg))
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 := line
deadline := time.Now().Add(2 * time.Second)
for issued.Epoch <= line.Epoch && time.Now().Before(deadline) {
issued, _ = h.Publisher().VolumeAuthorityLine("vol-rf3")
time.Sleep(10 * time.Millisecond)
}
promoted := ""
if issued.Epoch > line.Epoch {
promoted = issued.ReplicaID
}
if c.wantNot != "" && promoted == c.wantNot {
t.Fatalf("promoted %s, whose probed store %x is not the attested %x", promoted, c.r2Probed, s1)
}
if c.want != "" && promoted != c.want {
t.Fatalf("promoted %q, want %s", promoted, c.want)
}
if c.name == "control: the attested store" && promoted != "r2" && promoted != "r3" {
t.Fatalf("control: promoted %q, want a survivor", promoted)
}
if c.want == "" && c.wantNot != "" && promoted != "" {
t.Fatalf("promoted %s with one attested survivor and an unknown frontier", promoted)
}
})
}
}
// A provider without the attestation lookup refuses every candidate.
func TestPromotionProbeWithoutAttestationIsNeverReady(t *testing.T) {
p := &workloadPlanPromotionEvidenceProvider{}
if p.storeAttested("v", "r2", storeID(1)) {
t.Fatal("no attestation lookup: a candidate was taken as attested")
}
p.attested = func(string, string) (storage.StoreID, bool) { return storageZero(), true }
if p.storeAttested("v", "r2", storage.StoreID{}) {
t.Fatal("an unknown probed store was taken as attested")
}
}
func storageZero() storage.StoreID { return storage.StoreID{} }
// testStoreID is the store every probe fixture reports, and attestEvery
// attests it for every replica: fixtures about other rules hold the store
// check true.
var testStoreID = storeID(0x5a)
var testStoreHex = hex.EncodeToString(testStoreID[:])
func attestEvery(id storage.StoreID) func(string, string) (storage.StoreID, bool) {
return func(string, string) (storage.StoreID, bool) { return id, true }
}
// The record merges: a replica an attestation does not name keeps its last
// reference (through a reload); one it names gets the new store; a lower
// epoch changes nothing.
func TestStoreAttestationsKeepADroppedReplicasReference(t *testing.T) {
dir := t.TempDir()
s, err := loadStoreAttestations(dir)
if err != nil {
t.Fatal(err)
}
s1, s2, t1 := storeID(0x11), storeID(0x22), storeID(0x33)
for _, att := range []*control.StoreAttestation{
attestation("v", "r1", 5, map[string]storage.StoreID{"r2": s1, "r3": t1}),
attestation("v", "r1", 5, map[string]storage.StoreID{"r3": t1}), // r2 dropped
attestation("v", "r1", 4, map[string]storage.StoreID{"r3": storeID(0x44)}), // deposed primary
} {
if err := s.record(att); err != nil {
t.Fatal(err)
}
}
if got, ok := s.lookup("v", "r2"); !ok || got != s1 {
t.Fatalf("dropped r2: %x %t; want %x kept", got, ok, s1)
}
if got, _ := s.lookup("v", "r3"); got != t1 {
t.Fatalf("r3 after a lower-epoch report: %x; want %x", got, t1)
}
if err := s.record(attestation("v", "r1", 6, map[string]storage.StoreID{"r2": s2})); err != nil {
t.Fatal(err)
}
reloaded, err := loadStoreAttestations(dir)
if err != nil {
t.Fatal(err)
}
if got, _ := reloaded.lookup("v", "r2"); got != s2 {
t.Fatalf("r2 after its rebuild, reloaded: %x; want %x", got, s2)
}
if got, _ := reloaded.lookup("v", "r3"); got != t1 {
t.Fatalf("r3 not named at epoch 6, reloaded: %x; want %x kept", got, t1)
}
}
@@ -239,7 +239,10 @@ func (h *Host) admitWorkspacePublication(ask authority.AssignmentAsk, publish fu
// A supported snapshot and its direct promotion fallback may both be
// dequeued before either commits. Apply the product loop's existing
// already-current check again here, rather than advancing the epoch twice.
if ask.Intent == authority.IntentReassign && h.assignmentAskAlreadyCurrent(ask.VolumeID, ask.ReplicaID, ask.DataAddr, ask.CtrlAddr) {
// A fenced reassign needs no such check: the mint takes it only at its
// fenced epoch, so it cannot advance twice (and the heal of a failed
// fencing round names the current replica on purpose).
if ask.Intent == authority.IntentReassign && ask.Evidence.FencedEpoch == 0 && h.assignmentAskAlreadyCurrent(ask.VolumeID, ask.ReplicaID, ask.DataAddr, ask.CtrlAddr) {
return nil
}
// The same mutex covers Register/Delete. It stays held through the actual
@@ -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,
+79 -6
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"io"
"log"
"sort"
"sync"
"sync/atomic"
"time"
@@ -16,6 +17,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/replication"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/storeident"
"google.golang.org/grpc"
"google.golang.org/protobuf/proto"
@@ -171,7 +173,9 @@ type Host struct {
conn *grpc.ClientConn
obsCli control.ObservationServiceClient
asnCli control.AssignmentServiceClient
// probeRoles answers the promotion probe round's role fields (probe_round.go).
probeRoles probeRoles
asnCli control.AssignmentServiceClient
cancel context.CancelFunc
wg sync.WaitGroup
@@ -596,9 +600,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
}
@@ -659,9 +664,10 @@ func (h *Host) buildReport() *control.HeartbeatReport {
Reachable: true,
Eligible: true,
// Raw identity facts; the master compares them with its own store.
MachineId: h.cfg.StorageIdentity.MachineID,
DurableRootDev: h.cfg.StorageIdentity.Dev,
DurableRootFsid: h.cfg.StorageIdentity.FSID,
MachineId: h.cfg.StorageIdentity.MachineID,
DurableRootDev: h.cfg.StorageIdentity.Dev,
DurableRootFsid: h.cfg.StorageIdentity.FSID,
StoreAttestation: h.storeAttestation(),
Slots: []*control.HeartbeatSlot{
{
VolumeId: h.cfg.VolumeID,
@@ -679,6 +685,50 @@ func (h *Host) buildReport() *control.HeartbeatReport {
}
}
// storeAttester is the replication slot's view of its write-ACK set
// (replication.ReplicationVolume).
type storeAttester interface {
LocalStoreID() storage.StoreID
AttestedStores() map[string]storage.StoreID
}
// storeAttestation is this node's attestation of its write-ACK set while it
// holds the primary role (admitted, at its current epoch): its own store and
// every Healthy peer's last barrier store. nil on a replica, before the
// role is admitted, or while the local store carries no id.
func (h *Host) storeAttestation() *control.StoreAttestation {
h.selfFenceMu.Lock()
role, epoch := h.selfRole, h.selfEpoch
h.selfFenceMu.Unlock()
if role != selfRolePrimary || epoch == 0 {
return nil
}
if reason, _ := h.roleAdmissionFailed.Load().(string); reason != "" {
return nil
}
rv, ok := h.getReplication().(storeAttester)
if !ok || rv == nil {
return nil
}
own := rv.LocalStoreID()
if own.IsZero() {
return nil
}
att := &control.StoreAttestation{VolumeId: h.cfg.VolumeID, ReplicaId: h.cfg.ReplicaID, Epoch: epoch,
Stores: []*control.AttestedStore{{ReplicaId: h.cfg.ReplicaID, StoreId: append([]byte(nil), own[:]...)}}}
peers := rv.AttestedStores()
ids := make([]string, 0, len(peers))
for id := range peers {
ids = append(ids, id)
}
sort.Strings(ids)
for _, id := range ids {
sid := peers[id]
att.Stores = append(att.Stores, &control.AttestedStore{ReplicaId: id, StoreId: append([]byte(nil), sid[:]...)})
}
return att
}
// newIncarnation returns a random process incarnation id.
func newIncarnation() string {
var b [8]byte
@@ -905,11 +955,34 @@ 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()
}
var store storage.StoreID
if sid, ok := rv.(interface{ LocalStoreID() storage.StoreID }); ok {
store = sid.LocalStoreID()
}
if reason := checkPrimaryEvidence(fact, st, end, floor, floorErr == nil && floor > 0, store); 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 {
@@ -0,0 +1,127 @@
package volume
import (
"fmt"
"github.com/seaweedfs/seaweed-block/core/replication"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// 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, store storage.StoreID) string {
if len(fact.Peers) == 0 {
return ""
}
// A replay of an epoch this node already holds rows at is idempotent,
// except a PROMOTION, whose evidence is checked on every delivery: the
// row this node noted at the epoch starts past the probed LSN, so a
// genuine replay still matches, and a line naming another store or an
// end this store does not hold is refused.
for _, r := range st.Rows {
if r.Epoch == fact.Epoch && fact.PrimaryKind != control.PrimaryKind_PRIMARY_KIND_PROMOTION {
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 }
reaches := false
replay := false
for _, r := range st.Rows {
if r.FirstLSN <= fact.EvidenceDurableLsn {
row.epoch, row.first = r.Epoch, r.FirstLSN
reaches = true
}
if r.Epoch == fact.Epoch {
replay = true
}
}
if len(fact.EvidenceStoreId) != len(store) || string(fact.EvidenceStoreId) != string(store[:]) {
return fmt.Sprintf("promoted at epoch %d on a probed store %x, this node's store is %x", fact.Epoch, fact.EvidenceStoreId, store[:])
}
// A replay on a table that no longer reaches down to the probed LSN
// (its oldest rows trimmed at the row cap) has no row to compare;
// the store id and the end above still hold it to this line.
if replay && !reaches {
return ""
}
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)
}
@@ -0,0 +1,67 @@
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/storage"
"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}
}
local := storage.StoreID{1, 2, 3}
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, EvidenceStoreId: local[:]}
}
onStore := func(f *control.AssignmentFact, id []byte) *control.AssignmentFact { f.EvidenceStoreId = id; return f }
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 without the probed store id", onStore(promo(8, 2, 5), nil), rows(transport.EpochRow{Epoch: 1, FirstLSN: 1}, transport.EpochRow{Epoch: 2, FirstLSN: 5}), 8, 2, "store"},
{"promotion probed on another store", onStore(promo(8, 2, 5), []byte{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9}), rows(transport.EpochRow{Epoch: 1, FirstLSN: 1}, transport.EpochRow{Epoch: 2, FirstLSN: 5}), 8, 2, "store"},
{"promotion replayed after adoption", promo(8, 2, 5), rows(transport.EpochRow{Epoch: 1, FirstLSN: 1}, transport.EpochRow{Epoch: 2, FirstLSN: 5}, transport.EpochRow{Epoch: 3, FirstLSN: 9}), 12, 3, ""},
{"promotion replayed, another store", onStore(promo(8, 2, 5), []byte{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9}), rows(transport.EpochRow{Epoch: 2, FirstLSN: 5}, transport.EpochRow{Epoch: 3, FirstLSN: 9}), 12, 3, "store"},
{"promotion replayed, no store id", onStore(promo(8, 2, 5), nil), rows(transport.EpochRow{Epoch: 2, FirstLSN: 5}, transport.EpochRow{Epoch: 3, FirstLSN: 9}), 12, 3, "store"},
{"promotion replayed, end below the evidence", promo(20, 3, 9), rows(transport.EpochRow{Epoch: 2, FirstLSN: 5}, transport.EpochRow{Epoch: 3, FirstLSN: 9}), 12, 3, "durable end"},
{"promotion replayed on a table trimmed past the probed LSN", promo(8, 2, 5), rows(transport.EpochRow{Epoch: 3, FirstLSN: 9}, transport.EpochRow{Epoch: 4, FirstLSN: 20}), 30, 4, ""},
{"promotion replayed on a trimmed table, another store", onStore(promo(8, 2, 5), nil), rows(transport.EpochRow{Epoch: 3, FirstLSN: 9}, transport.EpochRow{Epoch: 4, FirstLSN: 20}), 30, 4, "store"},
{"first promotion on a table that does not reach the probed LSN", promo(8, 2, 5), rows(transport.EpochRow{Epoch: 2, FirstLSN: 9}), 12, 2, "row"},
{"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, local)
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)
}
})
}
}
@@ -0,0 +1,155 @@
package volume
import (
"bytes"
"context"
"io"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// The replica's side of the promotion probe round: it subscribes to the
// master's rounds for its node and answers each one for this replica from
// the store as it is now (durable end, epoch-table row there, validity) and
// its role. It keeps no state and reports nothing unasked.
//
// A fencing round (fence_epoch > 0) is answered only after its promise: when
// the round names this replica's store, the listener's floor is raised to
// fence_epoch, every mutation admitted before has drained and the floor is
// durable; only then is the evidence read, so the end it reports is final
// for every epoch below. A round naming another store raises nothing; a
// fence that fails is not answered.
// probeRoleSource is this replica's role as the promotion probe reads it
// (StatusServer.ProbeRoles): ready to be promoted, or a primary that serves.
type probeRoleSource func() (replicaReady, primaryReady bool)
// SetProbeRoleSource wires the replica's role for its probe answers.
func (h *Host) SetProbeRoleSource(src func() (replicaReady, primaryReady bool)) {
h.probeRoles.Store(probeRoleSource(src))
}
type probeRoles struct{ atomic.Value }
func (h *Host) runProbeRounds(ctx context.Context) {
defer h.wg.Done()
var backoff time.Duration
for ctx.Err() == nil {
if backoff > 0 {
select {
case <-ctx.Done():
return
case <-time.After(backoff):
}
}
if err := h.probeStreamOnce(ctx); err != nil && err != io.EOF && ctx.Err() == nil {
h.log.Printf("blockvolume: probe round stream: %v", err)
if backoff < 5*time.Second {
backoff = backoff*2 + 200*time.Millisecond
}
continue
}
backoff = 0
}
}
func (h *Host) probeStreamOnce(ctx context.Context) error {
stream, err := h.asnCli.SubscribeProbeRounds(ctx, &control.ProbeRoundSubscription{ServerId: h.cfg.ServerID})
if err != nil {
return err
}
for {
round, err := stream.Recv()
if err != nil {
return err
}
if round.GetVolumeId() != h.cfg.VolumeID || round.GetReplicaId() != h.cfg.ReplicaID {
continue // another replica on this node answers its own rounds
}
answer, ok := h.roundAnswer(round)
if !ok {
continue
}
rpcCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
_, err = h.obsCli.AnswerProbe(rpcCtx, answer)
cancel()
if err != nil {
h.log.Printf("blockvolume: probe answer round=%d: %v", round.GetRoundId(), err)
}
}
}
// floorFencer is the replication listener's fencing-round side
// (transport.ReplicaListener).
type floorFencer interface {
FenceFloor(epoch uint64) error
DurableFloor() uint64
}
func (h *Host) floorFencer() (floorFencer, bool) {
h.selfFenceMu.Lock()
defer h.selfFenceMu.Unlock()
f, ok := h.selfFence.(floorFencer)
return f, ok && f != nil
}
// roundAnswer is the answer to round, or false when none may be sent: a
// fencing round for this store whose fence did not complete.
func (h *Host) roundAnswer(round *control.ProbeRound) (*control.ProbeAnswer, bool) {
fencer, hasFloor := h.floorFencer()
if fe := round.GetFenceEpoch(); fe > 0 && hasFloor && h.roundNamesThisStore(round) {
if err := fencer.FenceFloor(fe); err != nil {
h.log.Printf("blockvolume: fencing round=%d at epoch %d not answered: %v", round.GetRoundId(), fe, err)
return nil, false
}
} else if fe > 0 {
h.log.Printf("blockvolume: fencing round=%d at epoch %d names another store; floor unchanged", round.GetRoundId(), fe)
}
a := h.probeAnswer(round.GetRoundId())
if hasFloor {
a.Floor = fencer.DurableFloor()
}
return a, true
}
// roundNamesThisStore reports whether the round's expected store is this
// replica's store (a store without an id never matches).
func (h *Host) roundNamesThisStore(round *control.ProbeRound) bool {
sid, ok := h.getReplication().(interface{ LocalStoreID() storage.StoreID })
if !ok || sid == nil {
return false
}
id := sid.LocalStoreID()
return !id.IsZero() && bytes.Equal(round.GetExpectedStoreId(), id[:])
}
// probeAnswer is this replica's evidence now, for round.
func (h *Host) probeAnswer(round uint64) *control.ProbeAnswer {
a := &control.ProbeAnswer{ServerId: h.cfg.ServerID, VolumeId: h.cfg.VolumeID, ReplicaId: h.cfg.ReplicaID, RoundId: round}
if src, ok := h.getReplication().(primaryEvidenceSource); ok && src != nil {
if st, end, err := src.LocalPrimaryEvidence(); err == nil {
a.DurableEnd = end
a.TablePresent = st.Present
a.TableValid = st.Present && !st.Invalid
if a.TableValid {
for _, r := range st.Rows {
if r.FirstLSN <= end {
a.LastDataEpoch, a.LastDataFirstLsn = r.Epoch, r.FirstLSN
}
}
}
}
}
if sid, ok := h.getReplication().(interface{ LocalStoreID() storage.StoreID }); ok && sid != nil {
if id := sid.LocalStoreID(); !id.IsZero() {
a.StoreId = id[:]
}
}
if roles, ok := h.probeRoles.Load().(probeRoleSource); ok && roles != nil {
a.ReplicaReady, a.PrimaryReady = roles()
}
return a
}
@@ -0,0 +1,251 @@
package volume
import (
"bytes"
"net"
"os"
"path/filepath"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/replication"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/transport"
)
// The fencing round on the real path: the host's round answer drives a real
// transport.ReplicaListener whose floor lives in a real floor record, and the
// old primary's frames reach that listener over TCP.
const realFenceVol = "v1"
// realProbeLineage is the transient lineage of the handshake probe that
// follows a ship (a probe is not a mutation and raises no floor).
var realProbeLineage = transport.RecoveryLineage{SessionID: 1, Epoch: 1 << 62, EndpointVersion: 1, TargetLSN: 1}
// realEvidence is the replication slot over a real listener: its store, and
// the listener's durable floor at each evidence read.
type realEvidence struct {
id storage.StoreID
ln *transport.ReplicaListener
end uint64
readsAt []uint64
}
func (e *realEvidence) UpdateReplicaSet(uint64, []replication.ReplicaTarget) error { return nil }
func (e *realEvidence) LocalStoreID() storage.StoreID { return e.id }
func (e *realEvidence) LocalPrimaryEvidence() (replication.EpochTableStatus, uint64, error) {
e.readsAt = append(e.readsAt, e.ln.DurableFloor())
return replication.EpochTableStatus{}, e.end, nil
}
func realFloorRecord(t *testing.T) string {
t.Helper()
path := filepath.Join(t.TempDir(), "floors", realFenceVol+".replica-floor")
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
t.Fatal(err)
}
if err := transport.InitReplicaFloor(path, realFenceVol); err != nil {
t.Fatal(err)
}
return path
}
// realFenceHost is a replica host at epoch admitted on a real listener over
// store and the floor record at path.
func realFenceHost(t *testing.T, store storage.LogicalStorage, path string, epoch uint64) (*Host, *transport.ReplicaListener, *realEvidence) {
t.Helper()
ln, err := transport.NewReplicaListenerWithFloor("127.0.0.1:0", store, realFenceVol, path)
if err != nil {
t.Fatal(err)
}
ln.Serve()
t.Cleanup(ln.StopHard)
if err := ln.AdmitAsReplica(epoch); err != nil {
t.Fatal(err)
}
h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "s2", VolumeID: realFenceVol, ReplicaID: "r2", DataAddr: "127.0.0.1:19313", CtrlAddr: "127.0.0.1:19314", EnableT1Readiness: true})
if err != nil {
t.Fatal(err)
}
if err := h.SetSelfFence(ln); err != nil {
t.Fatal(err)
}
ev := &realEvidence{id: storage.StoreID{7, 7, 7}, ln: ln, end: 42}
h.replicationMu.Lock()
h.replication = ev
h.replicationMu.Unlock()
return h, ln, ev
}
func realFencingRound(id, fence uint64, ev *realEvidence) *control.ProbeRound {
return &control.ProbeRound{VolumeId: realFenceVol, ReplicaId: "r2", RoundId: id, FenceEpoch: fence, ExpectedStoreId: ev.id[:]}
}
// realShip sends one epoch ship from an old primary over TCP and reports
// whether the replica applied it (the probe handshake after the ship: an
// accepted ship is applied before the probe is answered; a refused one
// closes the connection).
func realShip(t *testing.T, ln *transport.ReplicaListener, store storage.LogicalStorage, session, epoch, lsn uint64, fill byte) bool {
t.Helper()
l := transport.RecoveryLineage{SessionID: session, Epoch: epoch, EndpointVersion: 1, TargetLSN: lsn}
data := bytes.Repeat([]byte{fill}, 4096)
conn, err := net.DialTimeout("tcp", ln.Addr(), 2*time.Second)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
_ = conn.SetDeadline(time.Now().Add(5 * time.Second))
if err := transport.WriteMsg(conn, transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: l, LBA: 0, LSN: lsn, Data: data})); err != nil {
t.Fatal(err)
}
accepted := transport.WriteMsg(conn, transport.MsgProbeReq, transport.EncodeProbeReq(transport.ProbeRequest{Lineage: realProbeLineage})) == nil
if accepted {
if _, _, err := transport.ReadMsg(conn); err != nil {
accepted = false
}
}
got, err := store.Read(0)
if err != nil {
t.Fatal(err)
}
applied := bytes.Equal(got, data)
if accepted != applied {
t.Fatalf("epoch-%d ship: handshake accepted=%v but bytes applied=%v", epoch, accepted, applied)
}
return applied
}
// refuse <= e: once the host has answered a fencing round at e+1, the old
// primary's frames at e (and below) are refused, here and after a restart;
// the line re-issued at e+1 is admitted. The control shows the same frame
// was admitted before the round.
func TestFencingRoundOnTheRealListenerRefusesTheOldEpochAfterTheAnswer(t *testing.T) {
store := storage.NewBlockStore(16, 4096)
path := realFloorRecord(t)
h, ln, ev := realFenceHost(t, store, path, 3)
if !realShip(t, ln, store, 1, 3, 1, 'a') {
t.Fatal("control: the epoch-3 primary's ship was refused before the fencing round")
}
a, ok := h.roundAnswer(realFencingRound(10, 4, ev))
if !ok || a.GetFloor() != 4 {
t.Fatalf("fencing round at 4: answered=%v floor=%d; want an answer at floor 4", ok, a.GetFloor())
}
if len(ev.readsAt) != 1 || ev.readsAt[0] != 4 {
t.Fatalf("evidence read at durable floors %v; want [4] (read after the durable raise)", ev.readsAt)
}
if got, err := transport.LoadFloorRecord(path, realFenceVol); err != nil || got != 4 {
t.Fatalf("floor record after the answer: %d err=%v; want 4", got, err)
}
if realShip(t, ln, store, 2, 3, 2, 'b') || realShip(t, ln, store, 3, 2, 3, 'c') {
t.Fatal("after the answer at floor 4 the replica applied a ship at epoch 3 or 2")
}
ln.StopHard()
_, restarted, _ := realFenceHost(t, store, path, 3) // the stale line, again
if realShip(t, restarted, store, 4, 3, 4, 'd') {
t.Fatal("after a restart the replica applied an epoch-3 ship below its answered floor 4")
}
if err := restarted.AdmitAsReplica(4); err != nil {
t.Fatal(err)
}
if !realShip(t, restarted, store, 5, 4, 5, 'e') {
t.Fatal("the line re-issued at the fenced epoch 4 was refused")
}
}
// A superseded round: the replica's durable floor is already above the
// round's fence epoch. The answer carries that floor (the master does not
// count it), the floor is not lowered, and the round's own epoch stays
// refused.
func TestFencingRoundOnTheRealListenerAnswersASupersededFloor(t *testing.T) {
store := storage.NewBlockStore(16, 4096)
path := realFloorRecord(t)
h, ln, ev := realFenceHost(t, store, path, 5)
a, ok := h.roundAnswer(realFencingRound(11, 4, ev))
if !ok {
t.Fatal("a superseded fencing round was not answered")
}
if a.GetFloor() != 5 {
t.Fatalf("superseded round at 4: answer floor %d; want 5 (above the fence: not counted)", a.GetFloor())
}
if got, err := transport.LoadFloorRecord(path, realFenceVol); err != nil || got != 5 {
t.Fatalf("floor record after a superseded round: %d err=%v; want 5 (never lowered)", got, err)
}
if realShip(t, ln, store, 1, 4, 1, 'a') {
t.Fatal("after a superseded round at 4 the floor-5 replica applied an epoch-4 ship")
}
}
// Crash before the persist: the floor record cannot be written (its
// directory is read-only), so the fence makes no promise and the round is
// not answered. After the crash the record still holds the old floor (no
// restart is bound by a promise that was never made), and the round asked
// again completes and answers at the fence epoch.
func TestFencingRoundCrashBeforePersistIsNotAnsweredAndBindsNoRestart(t *testing.T) {
store := storage.NewBlockStore(16, 4096)
path := realFloorRecord(t)
dir := filepath.Dir(path)
h, ln, ev := realFenceHost(t, store, path, 3)
if err := os.Chmod(dir, 0o500); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.Chmod(dir, 0o700) })
if f, err := os.CreateTemp(dir, "probe"); err == nil {
f.Close()
os.Remove(f.Name())
t.Skip("the floor directory is still writable (running as root?): the persist failure cannot be produced")
}
if a, ok := h.roundAnswer(realFencingRound(12, 4, ev)); ok {
t.Fatalf("a fencing round whose floor could not be persisted was answered: %+v", a)
}
if len(ev.readsAt) != 0 {
t.Fatalf("the evidence was read (at floors %v) though no promise was made", ev.readsAt)
}
ln.StopHard() // the crash
if err := os.Chmod(dir, 0o700); err != nil {
t.Fatal(err)
}
if got, err := transport.LoadFloorRecord(path, realFenceVol); err != nil || got != 3 {
t.Fatalf("record after the crash: %d err=%v; want 3 (nothing was promised)", got, err)
}
h2, restarted, ev2 := realFenceHost(t, store, path, 3)
if !realShip(t, restarted, store, 1, 3, 1, 'a') {
t.Fatal("control: with no promise made, the restarted replica refused the epoch-3 ship")
}
a, ok := h2.roundAnswer(realFencingRound(13, 4, ev2))
if !ok || a.GetFloor() != 4 {
t.Fatalf("the round asked again after the crash: answered=%v floor=%d; want floor 4", ok, a.GetFloor())
}
if realShip(t, restarted, store, 2, 3, 2, 'b') {
t.Fatal("after the re-asked round's answer an epoch-3 ship was applied")
}
}
// Crash after the persist but before the answer: the floor is durable but no
// answer left. A restart is bound by it (the old epoch is refused), and the
// round asked again answers at the same floor without raising anything.
func TestFencingRoundCrashAfterPersistBeforeTheAnswer(t *testing.T) {
store := storage.NewBlockStore(16, 4096)
path := realFloorRecord(t)
_, ln, _ := realFenceHost(t, store, path, 3)
if err := ln.FenceFloor(4); err != nil { // roundAnswer's fence step; the crash comes before the evidence and the answer
t.Fatal(err)
}
ln.StopHard() // the crash
if got, err := transport.LoadFloorRecord(path, realFenceVol); err != nil || got != 4 {
t.Fatalf("record after a crash after the persist: %d err=%v; want 4", got, err)
}
h, restarted, ev := realFenceHost(t, store, path, 3)
if realShip(t, restarted, store, 1, 3, 1, 'a') {
t.Fatal("restarted on a durable floor 4, the replica applied an epoch-3 ship")
}
a, ok := h.roundAnswer(realFencingRound(14, 4, ev))
if !ok || a.GetFloor() != 4 {
t.Fatalf("the round asked again: answered=%v floor=%d; want floor 4", ok, a.GetFloor())
}
if len(ev.readsAt) != 1 || ev.readsAt[0] != 4 {
t.Fatalf("evidence read at %v; want [4]", ev.readsAt)
}
}
@@ -0,0 +1,137 @@
package volume
import (
"errors"
"testing"
"github.com/seaweedfs/seaweed-block/core/replication"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// fenceListener is the replica listener as a fencing round sees it: its
// durable floor, raised by FenceFloor (or failing).
type fenceListener struct {
floor uint64
fences []uint64
failErr error
}
func (f *fenceListener) FenceAsPrimary(uint64) error { return nil }
func (f *fenceListener) AdmitAsReplica(uint64) error { return nil }
func (f *fenceListener) FenceFloor(e uint64) error {
f.fences = append(f.fences, e)
if f.failErr != nil {
return f.failErr
}
if e > f.floor {
f.floor = e
}
return nil
}
func (f *fenceListener) DurableFloor() uint64 { return f.floor }
// fenceEvidence is the replication slot: its store and its evidence, which
// records the floor it was read under (the read must follow the fence).
type fenceEvidence struct {
id storage.StoreID
ln *fenceListener
end uint64
readsAt []uint64 // the listener's floor at each evidence read
}
func (e *fenceEvidence) UpdateReplicaSet(uint64, []replication.ReplicaTarget) error { return nil }
func (e *fenceEvidence) LocalStoreID() storage.StoreID { return e.id }
func (e *fenceEvidence) LocalPrimaryEvidence() (replication.EpochTableStatus, uint64, error) {
e.readsAt = append(e.readsAt, e.ln.floor)
return replication.EpochTableStatus{}, e.end, nil
}
func fenceHost(t *testing.T) (*Host, *fenceListener, *fenceEvidence) {
t.Helper()
h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "s2", VolumeID: "v1", ReplicaID: "r2", DataAddr: "127.0.0.1:19303", CtrlAddr: "127.0.0.1:19304", EnableT1Readiness: true})
if err != nil {
t.Fatal(err)
}
ln := &fenceListener{floor: 3}
if err := h.SetSelfFence(ln); err != nil {
t.Fatal(err)
}
ev := &fenceEvidence{id: storage.StoreID{7, 7, 7}, ln: ln, end: 42}
h.replicationMu.Lock()
h.replication = ev
h.replicationMu.Unlock()
return h, ln, ev
}
// A fencing round naming this store: the floor is raised and durable
// BEFORE the evidence is read, and the answer carries that floor and the end
// read under it (the model's fence-before shape; reading first is the
// violating fence-after shape).
func TestFencingRoundRaisesTheFloorBeforeTheEvidence(t *testing.T) {
h, ln, ev := fenceHost(t)
a, ok := h.roundAnswer(&control.ProbeRound{VolumeId: "v1", ReplicaId: "r2", RoundId: 9, FenceEpoch: 4, ExpectedStoreId: ev.id[:]})
if !ok {
t.Fatal("a completed fence was not answered")
}
if len(ln.fences) != 1 || ln.fences[0] != 4 {
t.Fatalf("fences %v, want one at 4", ln.fences)
}
if len(ev.readsAt) != 1 || ev.readsAt[0] != 4 {
t.Fatalf("evidence read under floor %v; want read once, after the floor reached 4", ev.readsAt)
}
if a.GetFloor() != 4 || a.GetRoundId() != 9 || a.GetDurableEnd() != 42 || string(a.GetStoreId()) != string(ev.id[:]) {
t.Fatalf("answer %+v; want round 9, floor 4, end 42, this store", a)
}
}
// A fencing round naming another store raises nothing; its answer carries
// the unchanged floor, which the master does not count.
func TestFencingRoundForAnotherStoreRaisesNothing(t *testing.T) {
h, ln, _ := fenceHost(t)
other := storage.StoreID{9}
a, ok := h.roundAnswer(&control.ProbeRound{VolumeId: "v1", ReplicaId: "r2", RoundId: 10, FenceEpoch: 4, ExpectedStoreId: other[:]})
if !ok || len(ln.fences) != 0 || a.GetFloor() != 3 {
t.Fatalf("answered=%t fences=%v floor=%d; want an answer at the unchanged floor 3 and no fence", ok, ln.fences, a.GetFloor())
}
if _, ok := h.roundAnswer(&control.ProbeRound{VolumeId: "v1", ReplicaId: "r2", RoundId: 11, FenceEpoch: 4}); !ok || len(ln.fences) != 0 {
t.Fatalf("a fencing round without an expected store fenced: %v", ln.fences)
}
}
// A fence that fails (drain timeout, floor not durable) is not answered: no
// promise was made, so none may be counted.
func TestFailedFenceIsNotAnswered(t *testing.T) {
h, ln, ev := fenceHost(t)
ln.failErr = errors.New("floor record not written")
if a, ok := h.roundAnswer(&control.ProbeRound{VolumeId: "v1", ReplicaId: "r2", RoundId: 12, FenceEpoch: 4, ExpectedStoreId: ev.id[:]}); ok {
t.Fatalf("a failed fence was answered: %+v", a)
}
if len(ev.readsAt) != 0 {
t.Fatal("the evidence was read for a round whose fence failed")
}
}
// A plain round (fence_epoch 0) raises nothing and reports the floor.
func TestPlainRoundRaisesNothing(t *testing.T) {
h, ln, ev := fenceHost(t)
a, ok := h.roundAnswer(&control.ProbeRound{VolumeId: "v1", ReplicaId: "r2", RoundId: 13, ExpectedStoreId: ev.id[:]})
if !ok || len(ln.fences) != 0 || a.GetFloor() != 3 || a.GetDurableEnd() != 42 {
t.Fatalf("plain round: answered=%t fences=%v answer=%+v", ok, ln.fences, a)
}
}
// A replica that fenced itself still answers ready: readiness comes from its
// assignment lines and engine projection (StatusServer.ProbeRoles), never
// from the floor, so a fencing round cannot make every target unqualified.
func TestFencedReplicaStillAnswersReady(t *testing.T) {
h, _, ev := fenceHost(t)
h.SetProbeRoleSource(func() (bool, bool) { return true, false })
a, ok := h.roundAnswer(&control.ProbeRound{VolumeId: "v1", ReplicaId: "r2", RoundId: 11, FenceEpoch: 4, ExpectedStoreId: ev.id[:]})
if !ok || a.GetFloor() != 4 {
t.Fatalf("fence not answered at floor 4: %+v ok=%t", a, ok)
}
if !a.GetReplicaReady() {
t.Fatalf("a fenced replica answered not ready: %+v", a)
}
}
@@ -578,6 +578,13 @@ func (s *StatusServer) statusProjection() StatusProjection {
return p
}
// ProbeRoles is this replica's role as the promotion probe round reads it:
// a replica ready to be promoted, or a primary that serves.
func (s *StatusServer) ProbeRoles() (replicaReady, primaryReady bool) {
p := s.authorityProjection()
return p.ReplicationRole == ReplicationRoleReady, p.FrontendPrimaryReady
}
// authorityProjection preserves the storage/authority gate used by runtime
// recovery. Listener startup masks presentation only, not recovery admission.
func (s *StatusServer) authorityProjection() StatusProjection {
@@ -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, Basis: adapter.BasisPlanned},
},
})
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, Basis: adapter.BasisPlanned}, nil
}
+32 -25
View File
@@ -21,31 +21,38 @@ const (
ReasonPrimaryNodeLost = "primary_node_lost"
ReasonCandidateCoversRequiredFrontier = "candidate_covers_required_frontier"
ReasonNoPromotionReadyCandidate = "no_promotion_ready_candidate"
ReasonDurableFrontierMissing = "durable_frontier_missing"
ReasonCandidateFrontierBehind = "candidate_frontier_behind"
ReasonStatusEndpointUnreachable = "status_endpoint_unreachable"
ReasonCSINodeImagePullFailed = "csi_node_image_pull_failed"
ReasonCSIDriverNotRegistered = "csi_driver_not_registered"
ReasonCSINodePodNotReady = "csi_node_pod_not_ready"
ReasonImageMissingOnNode = "image_missing_on_node"
ReasonISCSIPrereqMissing = "iscsi_prereq_missing"
ReasonMultipathPrereqMissing = "multipath_prereq_missing"
ReasonNodeReady = "node_ready"
ReasonNodeNotReady = "node_not_ready"
ReasonNodeSchedulingDisabled = "node_scheduling_disabled"
ReasonGeneratedDeploymentMissing = "generated_deployment_missing"
ReasonObservedReplicasBelowDesired = "observed_replicas_below_desired"
ReasonLoopbackFrontendRejected = "loopback_frontend_rejected"
ReasonStalePrimaryFenced = "stale_primary_fenced"
ReasonWALIntegrityFault = "wal_integrity_fault"
ReasonReturnedReplicaFrontendFenced = "returned_replica_frontend_fenced"
ReasonReturnedReplicaUnsafeFrontend = "returned_replica_unsafe_frontend_ready"
ReasonInstallDriftAligned = "install_drift_aligned"
ReasonInstallDriftMismatch = "install_drift_mismatch"
ReasonInstallDriftEvidenceMissing = "install_drift_evidence_missing"
ReasonNVMeIdentityIncomplete = "nvme_identity_incomplete"
ReasonNVMePathIdentityMismatch = "nvme_path_identity_mismatch"
ReasonNVMeMultipathPathMissing = "nvme_multipath_path_missing"
// A fencing round ended without a publication and the line's primary
// did not answer ready to continue: the volume waits for either.
ReasonFenceRoundIncomplete = "fence_round_incomplete"
// The highest end of a fencing round is held only by a replica that is
// not ready for primary: the volume waits for it (or for a ready one to
// catch up from it).
ReasonHighestEndNotReady = "highest_end_not_ready"
ReasonDurableFrontierMissing = "durable_frontier_missing"
ReasonCandidateFrontierBehind = "candidate_frontier_behind"
ReasonStatusEndpointUnreachable = "status_endpoint_unreachable"
ReasonCSINodeImagePullFailed = "csi_node_image_pull_failed"
ReasonCSIDriverNotRegistered = "csi_driver_not_registered"
ReasonCSINodePodNotReady = "csi_node_pod_not_ready"
ReasonImageMissingOnNode = "image_missing_on_node"
ReasonISCSIPrereqMissing = "iscsi_prereq_missing"
ReasonMultipathPrereqMissing = "multipath_prereq_missing"
ReasonNodeReady = "node_ready"
ReasonNodeNotReady = "node_not_ready"
ReasonNodeSchedulingDisabled = "node_scheduling_disabled"
ReasonGeneratedDeploymentMissing = "generated_deployment_missing"
ReasonObservedReplicasBelowDesired = "observed_replicas_below_desired"
ReasonLoopbackFrontendRejected = "loopback_frontend_rejected"
ReasonStalePrimaryFenced = "stale_primary_fenced"
ReasonWALIntegrityFault = "wal_integrity_fault"
ReasonReturnedReplicaFrontendFenced = "returned_replica_frontend_fenced"
ReasonReturnedReplicaUnsafeFrontend = "returned_replica_unsafe_frontend_ready"
ReasonInstallDriftAligned = "install_drift_aligned"
ReasonInstallDriftMismatch = "install_drift_mismatch"
ReasonInstallDriftEvidenceMissing = "install_drift_evidence_missing"
ReasonNVMeIdentityIncomplete = "nvme_identity_incomplete"
ReasonNVMePathIdentityMismatch = "nvme_path_identity_mismatch"
ReasonNVMeMultipathPathMissing = "nvme_multipath_path_missing"
EventTypeCSIReattachObserved = "csi_reattach_observed"
)
@@ -347,8 +347,8 @@ func TestT4b6_BarrierWire_FullLineageEcho_StillEnforced(t *testing.T) {
}
sample.LastDataEpoch, sample.LastDataFirstLSN = 7, 31
encoded := transport.EncodeBarrierResp(sample)
if len(encoded) != 56 {
t.Fatalf("BarrierResp encoded length = %d; wire shape (56B = 32B lineage + 8B achievedLSN + 8B lastDataEpoch + 8B lastDataFirstLSN) regressed",
if len(encoded) != 72 {
t.Fatalf("BarrierResp encoded length = %d; wire shape (72B = 32B lineage + 8B achievedLSN + 8B lastDataEpoch + 8B lastDataFirstLSN + 16B storeID) regressed",
len(encoded))
}
+26
View File
@@ -16,6 +16,7 @@ import (
"sync/atomic"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/transport"
)
@@ -161,6 +162,10 @@ type ReplicaPeer struct {
mu sync.Mutex
state ReplicaState
closed bool
// storeID is the store the peer's last successful barrier reported,
// cleared whenever the peer leaves Healthy: a store is attested only
// by a barrier it answered while counting toward write ACKs.
storeID storage.StoreID
// onHealthy lets the owning ReplicationVolume reopen a terminal work
// queue only after recovery has returned this peer to Healthy.
onHealthy func()
@@ -689,6 +694,9 @@ func (p *ReplicaPeer) Barrier(ctx context.Context, targetLSN uint64) (transport.
}
log.Printf("replication: barrier ack peer=%s targetLSN=%d achievedLSN=%d",
p.target.ReplicaID, targetLSN, ack.AchievedLSN)
p.mu.Lock()
p.storeID = ack.StoreID
p.mu.Unlock()
return ack, nil
}
@@ -762,6 +770,9 @@ func (p *ReplicaPeer) SetState(next ReplicaState) {
return
}
p.state = next
if next != ReplicaHealthy {
p.storeID = storage.StoreID{}
}
onHealthy := p.onHealthy
p.mu.Unlock()
log.Printf("replication: peer %s state %s → %s", p.target.ReplicaID, prev, next)
@@ -770,6 +781,20 @@ func (p *ReplicaPeer) SetState(next ReplicaState) {
}
}
// AttestedStore is the store this peer counts toward write ACKs with: its
// last successful barrier's store id while the peer is Healthy. false while
// the peer is not Healthy, or no barrier has reported a store since it
// became Healthy (a peer healed without a barrier is attested by its next
// one).
func (p *ReplicaPeer) AttestedStore() (storage.StoreID, bool) {
p.mu.Lock()
defer p.mu.Unlock()
if p.closed || p.state != ReplicaHealthy || p.storeID.IsZero() {
return storage.StoreID{}, false
}
return p.storeID, true
}
func (p *ReplicaPeer) setOnHealthy(fn func()) {
p.mu.Lock()
p.onHealthy = fn
@@ -866,6 +891,7 @@ func (p *ReplicaPeer) Invalidate(reason string) {
return
}
p.state = ReplicaDegraded
p.storeID = storage.StoreID{}
p.mu.Unlock()
log.Printf("replication: peer %s invalidated (prev=%s, reason=%s)",
p.target.ReplicaID, prev, reason)
@@ -0,0 +1,64 @@
package replication
import (
"context"
"path/filepath"
"testing"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/transport"
)
// A peer attests the store its barrier reported, only while Healthy: a
// peer that leaves Healthy loses it, and one healed without a barrier is
// not attested until its next barrier answers.
func TestPeerAttestsTheStoreItsBarrierReported(t *testing.T) {
replicaStore, err := storage.CreateWALStore(filepath.Join(t.TempDir(), "r.wal"), 64, 4096)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = replicaStore.Close() })
listener, err := transport.NewReplicaListener("127.0.0.1:0", replicaStore)
if err != nil {
t.Fatal(err)
}
listener.Serve()
t.Cleanup(func() { listener.Stop() })
exec := transport.NewBlockExecutor(storage.NewBlockStore(64, 4096), listener.Addr())
peer, err := NewReplicaPeer(ReplicaTarget{ReplicaID: "r2", DataAddr: listener.Addr(), ControlAddr: listener.Addr(), Epoch: 1, EndpointVersion: 1}, exec)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = peer.Close() })
want := storage.StoreIDOf(replicaStore)
if want.IsZero() {
t.Fatal("a WAL store carries no id")
}
if _, ok := peer.AttestedStore(); ok {
t.Fatal("attested before any barrier")
}
if _, err := peer.Barrier(context.Background(), 0); err != nil {
t.Fatal(err)
}
if got, ok := peer.AttestedStore(); !ok || got != want {
t.Fatalf("after a barrier: %x %t, want %x", got, ok, want)
}
peer.Invalidate("test: shipping failed")
if _, ok := peer.AttestedStore(); ok {
t.Fatal("a Degraded peer is still attested")
}
peer.SetState(ReplicaHealthy)
if peer.State() != ReplicaHealthy {
t.Fatalf("state %s, want Healthy", peer.State())
}
if _, ok := peer.AttestedStore(); ok {
t.Fatal("healed without a barrier, yet attested with the old store")
}
if _, err := peer.Barrier(context.Background(), 0); err != nil {
t.Fatal(err)
}
if got, ok := peer.AttestedStore(); !ok || got != want {
t.Fatalf("after the next barrier: %x %t, want %x", got, ok, want)
}
}
+50
View File
@@ -235,6 +235,35 @@ func (v *ReplicationVolume) SetEpochTable(t *transport.EpochTable) {
v.mu.Unlock()
}
// EpochTableStatus is the volume's epoch table as the promotion probe reads it.
type EpochTableStatus struct {
Rows []transport.EpochRow
Invalid bool // a recovery left the table without a known history
Present bool // the volume keeps a table at all
}
// EpochTableStatus reports the volume's epoch table.
func (v *ReplicationVolume) EpochTableStatus() EpochTableStatus {
v.mu.Lock()
t := v.epochs
v.mu.Unlock()
if t == nil {
return EpochTableStatus{}
}
return EpochTableStatus{Rows: t.Rows(), Invalid: t.Invalid(), Present: true}
}
// LocalPrimaryEvidence is this volume's epoch table and durable end, as a
// primary line's target checks them before adopting the role.
func (v *ReplicationVolume) LocalPrimaryEvidence() (EpochTableStatus, uint64, error) {
// Sync first, then read the table: a row appended in between is then
// read with an end that already covers it (never an old row with a
// newer end).
end, err := v.store.Sync()
st := v.EpochTableStatus()
return st, end, err
}
// reconcilePeer asks the peer for its (last data epoch, end) in a barrier
// to this node's frontier and answers from the epoch table: in sync, diverged
// (entries this primary never had), or neither (behind, or no answer).
@@ -1080,6 +1109,27 @@ func replicationDurationNanos(d time.Duration) uint64 {
return uint64(d.Nanoseconds())
}
// LocalStoreID is the id of the store this volume replicates from (zero
// when the store carries none).
func (v *ReplicationVolume) LocalStoreID() storage.StoreID { return storage.StoreIDOf(v.store) }
// AttestedStores is the primary's attestation of its write-ACK set: each
// Healthy peer with the store its last barrier reported (replica id ->
// store id). A peer that is not Healthy, or has not answered a barrier
// since it became Healthy, is absent: the master never takes it as a
// survivor on this primary's word.
func (v *ReplicationVolume) AttestedStores() map[string]storage.StoreID {
v.mu.Lock()
defer v.mu.Unlock()
out := map[string]storage.StoreID{}
for id, peer := range v.peers {
if sid, ok := peer.AttestedStore(); ok {
out[id] = sid
}
}
return out
}
// PeerStatuses returns a stable, sorted diagnostic snapshot of all
// currently tracked peers. This is intentionally a status surface, not
// a control surface: callers cannot mutate the returned peer state.
File diff suppressed because it is too large. Load diff
@@ -18,7 +18,7 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.3.0
// - protoc v3.12.4
// - protoc v7.34.1
// source: control.proto
package control
@@ -37,6 +37,7 @@ const _ = grpc.SupportPackageIsVersion7
const (
ObservationService_ReportHeartbeat_FullMethodName = "/seaweedfs.block.control.ObservationService/ReportHeartbeat"
ObservationService_AnswerProbe_FullMethodName = "/seaweedfs.block.control.ObservationService/AnswerProbe"
ObservationService_ReportClusterEvent_FullMethodName = "/seaweedfs.block.control.ObservationService/ReportClusterEvent"
)
@@ -48,6 +49,11 @@ type ObservationServiceClient interface {
// authority.HeartbeatMessage, calls ObservationHost.Ingest.
// Ack is diagnostic only.
ReportHeartbeat(ctx context.Context, in *HeartbeatReport, opts ...grpc.CallOption) (*HeartbeatAck, error)
// A replica's answer to the master's promotion probe round (see
// ProbeRound). Only an answer carrying the round id the master minted for
// this decision counts; nothing else a replica says is promotion
// evidence. Under mutual TLS the caller's node id must be server_id.
AnswerProbe(ctx context.Context, in *ProbeAnswer, opts ...grpc.CallOption) (*ProbeAck, error)
// Node/CSI observation event. This appends an operator timeline event only;
// it MUST NOT mutate lifecycle, authority, placement, Kubernetes, or
// replica state.
@@ -71,6 +77,15 @@ func (c *observationServiceClient) ReportHeartbeat(ctx context.Context, in *Hear
return out, nil
}
func (c *observationServiceClient) AnswerProbe(ctx context.Context, in *ProbeAnswer, opts ...grpc.CallOption) (*ProbeAck, error) {
out := new(ProbeAck)
err := c.cc.Invoke(ctx, ObservationService_AnswerProbe_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *observationServiceClient) ReportClusterEvent(ctx context.Context, in *ClusterEvent, opts ...grpc.CallOption) (*ClusterEventAck, error) {
out := new(ClusterEventAck)
err := c.cc.Invoke(ctx, ObservationService_ReportClusterEvent_FullMethodName, in, out, opts...)
@@ -88,6 +103,11 @@ type ObservationServiceServer interface {
// authority.HeartbeatMessage, calls ObservationHost.Ingest.
// Ack is diagnostic only.
ReportHeartbeat(context.Context, *HeartbeatReport) (*HeartbeatAck, error)
// A replica's answer to the master's promotion probe round (see
// ProbeRound). Only an answer carrying the round id the master minted for
// this decision counts; nothing else a replica says is promotion
// evidence. Under mutual TLS the caller's node id must be server_id.
AnswerProbe(context.Context, *ProbeAnswer) (*ProbeAck, error)
// Node/CSI observation event. This appends an operator timeline event only;
// it MUST NOT mutate lifecycle, authority, placement, Kubernetes, or
// replica state.
@@ -102,6 +122,9 @@ type UnimplementedObservationServiceServer struct {
func (UnimplementedObservationServiceServer) ReportHeartbeat(context.Context, *HeartbeatReport) (*HeartbeatAck, error) {
return nil, status.Errorf(codes.Unimplemented, "method ReportHeartbeat not implemented")
}
func (UnimplementedObservationServiceServer) AnswerProbe(context.Context, *ProbeAnswer) (*ProbeAck, error) {
return nil, status.Errorf(codes.Unimplemented, "method AnswerProbe not implemented")
}
func (UnimplementedObservationServiceServer) ReportClusterEvent(context.Context, *ClusterEvent) (*ClusterEventAck, error) {
return nil, status.Errorf(codes.Unimplemented, "method ReportClusterEvent not implemented")
}
@@ -136,6 +159,24 @@ func _ObservationService_ReportHeartbeat_Handler(srv interface{}, ctx context.Co
return interceptor(ctx, in, info, handler)
}
func _ObservationService_AnswerProbe_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ProbeAnswer)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ObservationServiceServer).AnswerProbe(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ObservationService_AnswerProbe_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ObservationServiceServer).AnswerProbe(ctx, req.(*ProbeAnswer))
}
return interceptor(ctx, in, info, handler)
}
func _ObservationService_ReportClusterEvent_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ClusterEvent)
if err := dec(in); err != nil {
@@ -165,6 +206,10 @@ var ObservationService_ServiceDesc = grpc.ServiceDesc{
MethodName: "ReportHeartbeat",
Handler: _ObservationService_ReportHeartbeat_Handler,
},
{
MethodName: "AnswerProbe",
Handler: _ObservationService_AnswerProbe_Handler,
},
{
MethodName: "ReportClusterEvent",
Handler: _ObservationService_ReportClusterEvent_Handler,
@@ -176,6 +221,7 @@ var ObservationService_ServiceDesc = grpc.ServiceDesc{
const (
AssignmentService_SubscribeAssignments_FullMethodName = "/seaweedfs.block.control.AssignmentService/SubscribeAssignments"
AssignmentService_SubscribeProbeRounds_FullMethodName = "/seaweedfs.block.control.AssignmentService/SubscribeProbeRounds"
)
// AssignmentServiceClient is the client API for AssignmentService service.
@@ -191,6 +237,11 @@ type AssignmentServiceClient interface {
// order, while RefreshEndpoint (same Epoch, higher
// EndpointVersion) still flows through.
SubscribeAssignments(ctx context.Context, in *SubscribeRequest, opts ...grpc.CallOption) (AssignmentService_SubscribeAssignmentsClient, error)
// Server-streaming. The master sends a ProbeRound for a volume whose
// replica runs on this node when it decides a promotion; the node
// answers each by AnswerProbe. A round carries no authority. Under
// mutual TLS the caller's node id must be server_id.
SubscribeProbeRounds(ctx context.Context, in *ProbeRoundSubscription, opts ...grpc.CallOption) (AssignmentService_SubscribeProbeRoundsClient, error)
}
type assignmentServiceClient struct {
@@ -233,6 +284,38 @@ func (x *assignmentServiceSubscribeAssignmentsClient) Recv() (*AssignmentFact, e
return m, nil
}
func (c *assignmentServiceClient) SubscribeProbeRounds(ctx context.Context, in *ProbeRoundSubscription, opts ...grpc.CallOption) (AssignmentService_SubscribeProbeRoundsClient, error) {
stream, err := c.cc.NewStream(ctx, &AssignmentService_ServiceDesc.Streams[1], AssignmentService_SubscribeProbeRounds_FullMethodName, opts...)
if err != nil {
return nil, err
}
x := &assignmentServiceSubscribeProbeRoundsClient{stream}
if err := x.ClientStream.SendMsg(in); err != nil {
return nil, err
}
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
return x, nil
}
type AssignmentService_SubscribeProbeRoundsClient interface {
Recv() (*ProbeRound, error)
grpc.ClientStream
}
type assignmentServiceSubscribeProbeRoundsClient struct {
grpc.ClientStream
}
func (x *assignmentServiceSubscribeProbeRoundsClient) Recv() (*ProbeRound, error) {
m := new(ProbeRound)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
// AssignmentServiceServer is the server API for AssignmentService service.
// All implementations must embed UnimplementedAssignmentServiceServer
// for forward compatibility
@@ -246,6 +329,11 @@ type AssignmentServiceServer interface {
// order, while RefreshEndpoint (same Epoch, higher
// EndpointVersion) still flows through.
SubscribeAssignments(*SubscribeRequest, AssignmentService_SubscribeAssignmentsServer) error
// Server-streaming. The master sends a ProbeRound for a volume whose
// replica runs on this node when it decides a promotion; the node
// answers each by AnswerProbe. A round carries no authority. Under
// mutual TLS the caller's node id must be server_id.
SubscribeProbeRounds(*ProbeRoundSubscription, AssignmentService_SubscribeProbeRoundsServer) error
mustEmbedUnimplementedAssignmentServiceServer()
}
@@ -256,6 +344,9 @@ type UnimplementedAssignmentServiceServer struct {
func (UnimplementedAssignmentServiceServer) SubscribeAssignments(*SubscribeRequest, AssignmentService_SubscribeAssignmentsServer) error {
return status.Errorf(codes.Unimplemented, "method SubscribeAssignments not implemented")
}
func (UnimplementedAssignmentServiceServer) SubscribeProbeRounds(*ProbeRoundSubscription, AssignmentService_SubscribeProbeRoundsServer) error {
return status.Errorf(codes.Unimplemented, "method SubscribeProbeRounds not implemented")
}
func (UnimplementedAssignmentServiceServer) mustEmbedUnimplementedAssignmentServiceServer() {}
// UnsafeAssignmentServiceServer may be embedded to opt out of forward compatibility for this service.
@@ -290,6 +381,27 @@ func (x *assignmentServiceSubscribeAssignmentsServer) Send(m *AssignmentFact) er
return x.ServerStream.SendMsg(m)
}
func _AssignmentService_SubscribeProbeRounds_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(ProbeRoundSubscription)
if err := stream.RecvMsg(m); err != nil {
return err
}
return srv.(AssignmentServiceServer).SubscribeProbeRounds(m, &assignmentServiceSubscribeProbeRoundsServer{stream})
}
type AssignmentService_SubscribeProbeRoundsServer interface {
Send(*ProbeRound) error
grpc.ServerStream
}
type assignmentServiceSubscribeProbeRoundsServer struct {
grpc.ServerStream
}
func (x *assignmentServiceSubscribeProbeRoundsServer) Send(m *ProbeRound) error {
return x.ServerStream.SendMsg(m)
}
// AssignmentService_ServiceDesc is the grpc.ServiceDesc for AssignmentService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
@@ -303,6 +415,11 @@ var AssignmentService_ServiceDesc = grpc.ServiceDesc{
Handler: _AssignmentService_SubscribeAssignments_Handler,
ServerStreams: true,
},
{
StreamName: "SubscribeProbeRounds",
Handler: _AssignmentService_SubscribeProbeRounds_Handler,
ServerStreams: true,
},
},
Metadata: "control.proto",
}
+109
View File
@@ -29,6 +29,12 @@ service ObservationService {
// Ack is diagnostic only.
rpc ReportHeartbeat(HeartbeatReport) returns (HeartbeatAck);
// A replica's answer to the master's promotion probe round (see
// ProbeRound). Only an answer carrying the round id the master minted for
// this decision counts; nothing else a replica says is promotion
// evidence. Under mutual TLS the caller's node id must be server_id.
rpc AnswerProbe(ProbeAnswer) returns (ProbeAck);
// Node/CSI observation event. This appends an operator timeline event only;
// it MUST NOT mutate lifecycle, authority, placement, Kubernetes, or
// replica state.
@@ -59,6 +65,12 @@ service AssignmentService {
// order, while RefreshEndpoint (same Epoch, higher
// EndpointVersion) still flows through.
rpc SubscribeAssignments(SubscribeRequest) returns (stream AssignmentFact);
// Server-streaming. The master sends a ProbeRound for a volume whose
// replica runs on this node when it decides a promotion; the node
// answers each by AnswerProbe. A round carries no authority. Under
// mutual TLS the caller's node id must be server_id.
rpc SubscribeProbeRounds(ProbeRoundSubscription) returns (stream ProbeRound);
}
// EvidenceService — operator read-only projection + evidence.
@@ -127,6 +139,29 @@ message HeartbeatReport {
// first). 0 means unknown (older reporters, platforms without statfs):
// the master then compares machine_id and durable_root_dev only.
uint64 durable_root_fsid = 8;
// store_attestation is sent by a volume's primary only: the stores of
// the replicas that count toward its write ACKs. The master takes it as
// the reference a promotion's probed store must match, and only from
// the server that holds the volume's current primary line at that
// epoch. A replica's own report of its store never sets it.
StoreAttestation store_attestation = 9;
}
// StoreAttestation is a primary's attestation of its write-ACK set at one
// epoch: every replica in it with the store id (the store's superblock
// UUID) of the store that answered its barriers, the primary's own store
// included. A replica absent from it is not a survivor on this primary's
// word.
message StoreAttestation {
string volume_id = 1;
string replica_id = 2; // the primary's own replica id
uint64 epoch = 3; // the primary line's epoch
repeated AttestedStore stores = 4;
}
message AttestedStore {
string replica_id = 1;
bytes store_id = 2; // 16 bytes
}
// HeartbeatSlot — per-replica slot fact. local_role_claim is the
@@ -246,6 +281,34 @@ message AssignmentFact {
// Required holder identity. Empty (pre-release master) is never adopted.
string server_id = 9;
// primary_kind says how this line made its primary the primary. The
// target checks it before adopting the role: a PROMOTION carries the
// evidence the master probed on the target (its durable LSN and its
// epoch-table row at that LSN), and the target adopts only if its own
// store still shows it. UNSPECIFIED (a pre-release master) is never
// adopted by a replicated volume's target that holds data at an epoch it
// has no row for.
PrimaryKind primary_kind = 10;
uint64 evidence_durable_lsn = 11;
uint64 evidence_epoch = 12;
uint64 evidence_first_lsn = 13;
// The probed store's id (its superblock UUID, 16 bytes): the target
// adopts a promotion only on that same store.
bytes evidence_store_id = 14;
}
// PrimaryKind is how a line made its primary the primary.
enum PrimaryKind {
PRIMARY_KIND_UNSPECIFIED = 0;
// The volume's first primary: the target holds no data.
PRIMARY_KIND_BOOTSTRAP = 1;
// A replica promoted on the master's probed evidence (automatic
// promotion, failover, failback, a planned move).
PRIMARY_KIND_PROMOTION = 2;
// The operator's forced promotion: no evidence; the lost range is
// reported and the target's epoch table restarts at this epoch.
PRIMARY_KIND_FORCED = 3;
}
message StatusRequest {
@@ -475,3 +538,49 @@ message FailbackResponse {
bool no_cross_volume_identity_change = 6;
repeated string evidence_refs = 7;
}
// ProbeRoundSubscription opens a node's probe round stream.
message ProbeRoundSubscription {
string server_id = 1;
}
// ProbeRound asks the node's replica of volume_id for its promotion evidence
// now. round_id is fresh per decision; an answer counts only for it.
message ProbeRound {
string volume_id = 1;
string replica_id = 2;
uint64 round_id = 3;
// A fencing round (fence_epoch > 0): a replica whose store is
// expected_store_id makes its epoch floor fence_epoch durable FIRST, then
// answers (its answer is the promise: it refuses frames and acks at a
// lower epoch from then on). A replica on another store raises nothing
// and answers its own store id. 0: a plain probe, no fence.
uint64 fence_epoch = 4;
bytes expected_store_id = 5;
}
// ProbeAnswer is one replica's promotion evidence for one round.
message ProbeAnswer {
string server_id = 1;
string volume_id = 2;
string replica_id = 3;
uint64 round_id = 4;
// The store's identity (its superblock UUID); empty = none.
bytes store_id = 5;
// The store's durable end (R) and its epoch-table row there.
uint64 durable_end = 6;
uint64 last_data_epoch = 7;
uint64 last_data_first_lsn = 8;
bool table_present = 9;
bool table_valid = 10;
// The replica's role as it sees it: a replica ready to be promoted, or a
// primary that serves.
bool replica_ready = 11;
bool primary_ready = 12;
// The replica's durable epoch floor when it answered (after a fencing
// round's raise). Above the round's fence_epoch: superseded, not counted.
uint64 floor = 13;
}
message ProbeAck {}
@@ -563,3 +563,6 @@ func (s *Store) SyncCount() uint64 { return s.syncs.Load() }
// Compile-time assertion: Store satisfies the LogicalStorage contract.
var _ storage.LogicalStorage = (*Store)(nil)
// StoreID returns the header UUID written when the store was created.
func (s *Store) StoreID() storage.StoreID { return storage.StoreID(s.hdr.UUID) }
+27
View File
@@ -0,0 +1,27 @@
package storage
// StoreID is a local store's identity: the 16 random bytes its superblock
// was given when the store was created. A store re-created at the same path
// has a new one, so equal ids mean the same store, never a copy or a
// replacement. The zero value means unknown.
type StoreID [16]byte
// IsZero reports whether the id is unknown.
func (id StoreID) IsZero() bool { return id == StoreID{} }
// storeIdentified is implemented by stores that carry a superblock UUID.
type storeIdentified interface {
StoreID() StoreID
}
// StoreIDOf returns s's store id, or the zero id when s does not carry one.
func StoreIDOf(s LogicalStorage) StoreID {
if si, ok := s.(storeIdentified); ok {
return si.StoreID()
}
return StoreID{}
}
// StoreID returns the superblock UUID written when the store was created
// (both on-disk formats carry it).
func (s *WALStore) StoreID() StoreID { return StoreID(s.sb.UUID) }
+30 -12
View File
@@ -6,6 +6,8 @@ import (
"fmt"
"net"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// BarrierAck is the validated per-peer barrier outcome surfaced to
@@ -17,12 +19,15 @@ import (
// Reason is populated by higher-layer aggregation (DurabilityCoordinator)
// and is empty on successful Barrier returns.
type BarrierAck struct {
Lineage RecoveryLineage
AchievedLSN uint64
Lineage RecoveryLineage
AchievedLSN uint64
LastDataEpoch uint64 // the replica's last data row's epoch; 0 = no table (see BarrierResponse)
LastDataFirstLSN uint64 // that row's first LSN
Success bool
Reason string
// StoreID is the replica's store identity (its superblock UUID); zero
// from a replica that does not report one.
StoreID storage.StoreID
Success bool
Reason string
}
// ErrBarrierLineageMismatch is returned by BlockExecutor.Barrier when
@@ -43,8 +48,10 @@ var ErrBarrierLineageMismatch = errors.New("transport: barrier: response lineage
// rule, INV-REPL-LINEAGE-BORNE-ON-BARRIER-ACK).
//
// Wire: [32B lineage][8B achievedLSN][8B lastDataEpoch][8B lastDataFirstLSN]
// — 56 bytes. A 40-byte response (a replica from before the epoch table)
// decodes with LastDataEpoch 0, which the primary reads as "no table".
// [16B storeID] — 72 bytes. A 40-byte response (a replica from before the
// epoch table) decodes with LastDataEpoch 0, which the primary reads as "no
// table"; a 56-byte one (before the store id) with a zero StoreID, which the
// primary reads as "unknown store" and never attests.
// Lineage field order inside the 32B slab is strictly
// SessionID, Epoch, EndpointVersion, frontierHint (matches
// EncodeLineage). Any deviation MUST be rejected at decode.
@@ -58,27 +65,35 @@ type BarrierResponse struct {
// LastDataFirstLSN is that row's first LSN: the primary requires it to
// equal its own first LSN for the epoch (the receiver check).
LastDataFirstLSN uint64
// StoreID is the replica's store identity: the superblock UUID of the
// store that synced AchievedLSN. The primary reports it to the master
// when this replica counts toward write ACKs; zero = unknown.
StoreID storage.StoreID
}
// barrierRespSize is the exact byte length of a valid encoded
// BarrierResponse. Short, over-long, or field-misordered payloads
// are rejected by DecodeBarrierResp and MUST NOT contribute to
// correctness decisions (round-21 rule).
const barrierRespSize = 56
const barrierRespSize = 72
// barrierRespV0Size is the response of a replica from before the epoch table.
const barrierRespV0Size = 40
// barrierRespV1Size is the response of a replica from before the store id.
const barrierRespV1Size = 56
// EncodeBarrierResp serializes a barrier response.
// Wire: [32B lineage (SessionID, Epoch, EndpointVersion, frontierHint)]
//
// [8B achievedLSN][8B lastDataEpoch][8B lastDataFirstLSN]
// [8B achievedLSN][8B lastDataEpoch][8B lastDataFirstLSN][16B storeID]
func EncodeBarrierResp(r BarrierResponse) []byte {
buf := make([]byte, barrierRespSize)
copy(buf[0:32], EncodeLineage(r.Lineage))
binary.BigEndian.PutUint64(buf[32:40], r.AchievedLSN)
binary.BigEndian.PutUint64(buf[40:48], r.LastDataEpoch)
binary.BigEndian.PutUint64(buf[48:56], r.LastDataFirstLSN)
copy(buf[56:72], r.StoreID[:])
return buf
}
@@ -93,9 +108,9 @@ func EncodeBarrierResp(r BarrierResponse) []byte {
// Callers MUST treat any error return as "no valid ack" and MUST NOT
// fabricate a frontier or count the ack toward durability.
func DecodeBarrierResp(buf []byte) (BarrierResponse, error) {
if len(buf) < barrierRespV0Size || (len(buf) > barrierRespV0Size && len(buf) < barrierRespSize) {
return BarrierResponse{}, fmt.Errorf("transport: short barrier response: %d bytes, want %d (or %d from a replica without the epoch table)",
len(buf), barrierRespSize, barrierRespV0Size)
if len(buf) != barrierRespV0Size && len(buf) != barrierRespV1Size && len(buf) < barrierRespSize {
return BarrierResponse{}, fmt.Errorf("transport: short barrier response: %d bytes, want %d (or %d without the store id, %d without the epoch table)",
len(buf), barrierRespSize, barrierRespV1Size, barrierRespV0Size)
}
lineage, err := DecodeLineage(buf[0:32])
if err != nil {
@@ -114,10 +129,13 @@ func DecodeBarrierResp(buf []byte) (BarrierResponse, error) {
Lineage: lineage,
AchievedLSN: binary.BigEndian.Uint64(buf[32:40]),
}
if len(buf) >= barrierRespSize {
if len(buf) >= barrierRespV1Size {
resp.LastDataEpoch = binary.BigEndian.Uint64(buf[40:48])
resp.LastDataFirstLSN = binary.BigEndian.Uint64(buf[48:56])
}
if len(buf) >= barrierRespSize {
copy(resp.StoreID[:], buf[56:72])
}
return resp, nil
}
+21 -1
View File
@@ -5,6 +5,7 @@ package transport
import (
"encoding/binary"
"github.com/seaweedfs/seaweed-block/core/storage"
"strings"
"testing"
)
@@ -83,11 +84,30 @@ func TestBarrierResp_FullLineageEcho_RoundTrip(t *testing.T) {
// callers could count toward durability.
//
// Required test per mini-plan §2 T4b-1.
// The barrier reply carries the replica's store id; a 56-byte reply (a
// replica from before the store id) decodes with the zero id, "unknown".
func TestBarrierResp_StoreID(t *testing.T) {
lin := RecoveryLineage{SessionID: 7, Epoch: 3, EndpointVersion: 2, TargetLSN: 40}
id := storage.StoreID{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
buf := EncodeBarrierResp(BarrierResponse{Lineage: lin, AchievedLSN: 40, LastDataEpoch: 3, LastDataFirstLSN: 9, StoreID: id})
if len(buf) != barrierRespSize {
t.Fatalf("encoded %d bytes, want %d", len(buf), barrierRespSize)
}
got, err := DecodeBarrierResp(buf)
if err != nil || got.StoreID != id || got.AchievedLSN != 40 || got.LastDataFirstLSN != 9 {
t.Fatalf("round trip: %+v %v", got, err)
}
old, err := DecodeBarrierResp(buf[:barrierRespV1Size])
if err != nil || !old.StoreID.IsZero() || old.LastDataEpoch != 3 {
t.Fatalf("56-byte reply: %+v %v; want the rows and a zero store id", old, err)
}
}
func TestBarrierResp_ShortPayload_Rejected(t *testing.T) {
// Every length below the full response except the 40-byte response of
// a replica from before the epoch table (TestT4b6 decodes that one).
for n := 0; n < barrierRespSize; n++ {
if n == barrierRespV0Size {
if n == barrierRespV0Size || n == barrierRespV1Size {
continue
}
t.Run("", func(t *testing.T) {
+4 -3
View File
@@ -571,11 +571,12 @@ func (e *BlockExecutor) Barrier(replicaID string, lineage RecoveryLineage, front
}
return BarrierAck{
Lineage: resp.Lineage,
AchievedLSN: resp.AchievedLSN,
Lineage: resp.Lineage,
AchievedLSN: resp.AchievedLSN,
LastDataEpoch: resp.LastDataEpoch,
LastDataFirstLSN: resp.LastDataFirstLSN,
Success: true,
StoreID: resp.StoreID,
Success: true,
}, nil
}
@@ -0,0 +1,117 @@
package transport
import (
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// A fencing round's promise is FenceFloor returning nil, and it is made only
// with the floor durable. Interrupt the persist at each step and restart:
// the record holds the old floor or the fence epoch, never anything else,
// and no step that failed returned a promise. The rename that landed before
// a failed directory sync binds the restart (floor e+1) without a promise
// having been made: conservative, never the reverse.
func TestFenceFloor_InterruptedAtEachPersistStepThenRestart(t *testing.T) {
for _, tc := range []struct {
step string
afterCrash uint64 // the record a restart loads
}{
{"write", 3},
{"rename", 3},
{"dirsync", 4},
} {
t.Run(tc.step, func(t *testing.T) {
store := storage.NewBlockStore(16, 4096)
floor := g1Fresh(t)
ln := g1Listener(t, store, floor)
if err := ln.AdmitAsReplica(3); err != nil {
t.Fatal(err)
}
failAt(t, ln, tc.step)
if err := ln.FenceFloor(4); err == nil {
t.Fatalf("FenceFloor returned a promise though the %s step of the persist failed", tc.step)
}
if got := ln.DurableFloor(); got != 3 {
t.Fatalf("durable floor after the interrupted fence: %d, want 3 (no promise)", got)
}
// the crash: the process dies here; the disk is whatever the step left
ln.StopHard()
floorFS = osFloorOps
if got := g1Persisted(t, floor); got != tc.afterCrash {
t.Fatalf("record after a crash at %s: %d, want %d", tc.step, got, tc.afterCrash)
}
restarted := g1Listener(t, store, floor)
if err := restarted.AdmitAsReplica(3); err != nil {
t.Fatal(err)
}
if got := restarted.DurableFloor(); got != tc.afterCrash {
t.Fatalf("restarted durable floor %d, want %d", got, tc.afterCrash)
}
below := g1Ship(t, restarted, store, g1Lineage(1, 3), 1, 'a')
if tc.afterCrash == 4 && below {
t.Fatal("restarted on a floor-4 record, the replica applied an epoch-3 ship")
}
if tc.afterCrash == 3 && !below {
t.Fatal("control: restarted on a floor-3 record (no promise made), the epoch-3 ship was refused")
}
// the round is asked again and now completes: the promise is durable
if err := restarted.FenceFloor(4); err != nil {
t.Fatal(err)
}
if got := restarted.DurableFloor(); got != 4 || g1Persisted(t, floor) != 4 {
t.Fatalf("re-asked fence: durable floor %d, record %d; want 4", got, g1Persisted(t, floor))
}
if g1Ship(t, restarted, store, g1Lineage(2, 3), 2, 'b') {
t.Fatal("after the re-asked fence an epoch-3 ship was applied")
}
})
}
}
// A drain that does not finish in time makes no promise: FenceFloor fails,
// the durable floor is unchanged, and a new frame below the fence epoch is
// still refused in this process.
func TestFenceFloor_DrainTimeoutMakesNoPromise(t *testing.T) {
listener, store := g2PausedShip(t)
defer close(store.release)
listener.fenceDrainTimeout = 200 * time.Millisecond
before := listener.DurableFloor()
if err := listener.FenceFloor(2); err == nil {
t.Fatal("FenceFloor returned a promise while an admitted epoch-1 ship was still applying")
}
if got := listener.DurableFloor(); got != before {
t.Fatalf("durable floor after a drain timeout: %d, want %d (no promise)", got, before)
}
old := RecoveryLineage{SessionID: 6, Epoch: 1, EndpointVersion: 1, TargetLSN: 1}
if !g2Refused(t, listener.Addr(), MsgShipEntry, g2ShipPayload(old, 3)) {
t.Fatal("after a timed-out fence a new epoch-1 ship was admitted")
}
}
// Two fencing rounds race (a superseded round and its successor): both
// promises hold, the floor ends at the higher epoch and is never lowered,
// whatever order they finish in.
func TestFenceFloor_ConcurrentRoundsNeverLowerTheFloor(t *testing.T) {
for i := 0; i < 20; i++ {
store := storage.NewBlockStore(16, 4096)
floor := g1Fresh(t)
ln := g1Listener(t, store, floor)
if err := ln.AdmitAsReplica(3); err != nil {
t.Fatal(err)
}
errs := make(chan error, 2)
go func() { errs <- ln.FenceFloor(4) }()
go func() { errs <- ln.FenceFloor(5) }()
for j := 0; j < 2; j++ {
if err := <-errs; err != nil {
t.Fatal(err)
}
}
if got := ln.DurableFloor(); got != 5 || g1Persisted(t, floor) != 5 {
t.Fatalf("iteration %d: durable floor %d, record %d; want 5", i, got, g1Persisted(t, floor))
}
ln.StopHard()
}
}
@@ -0,0 +1,163 @@
package transport
import (
"errors"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// The replica's half of a fencing round: FenceFloor(e+1) is a durable
// promise. From its return nothing below e+1 is applied or ACKed, across a
// restart; a failed round heals by the same primary's line re-issued at e+1.
func TestFenceFloor_PromiseRefusesBelowAndSurvivesRestart(t *testing.T) {
store := storage.NewBlockStore(16, 4096)
floor := g1Fresh(t)
ln := g1Listener(t, store, floor)
if err := ln.AdmitAsReplica(3); err != nil {
t.Fatal(err)
}
if !g1Ship(t, ln, store, g1Lineage(1, 3), 1, 'a') || !g1Barrier(t, ln, g1Lineage(1, 3)) {
t.Fatal("fixture: the epoch-3 primary's ship and barrier were refused before the fence")
}
if err := ln.FenceFloor(4); err != nil {
t.Fatal(err)
}
if got := ln.DurableFloor(); got != 4 || g1Persisted(t, floor) != 4 {
t.Fatalf("after the fence: durable floor %d, record %d; want 4", got, g1Persisted(t, floor))
}
// the model's violating row: the old primary acknowledged after the promise
if g1Barrier(t, ln, g1Lineage(2, 3)) {
t.Fatal("an epoch-3 barrier was ACKed after the replica promised floor 4")
}
if g1Ship(t, ln, store, g1Lineage(3, 3), 2, 'b') || g1Rebuild(t, ln, store, g1Lineage(4, 3), 'r') {
t.Fatal("an epoch-3 mutation was applied after the replica promised floor 4")
}
ln.StopHard()
restarted := g1Listener(t, store, floor)
if err := restarted.AdmitAsReplica(3); err != nil { // the stale line, again
t.Fatal(err)
}
if g1Barrier(t, restarted, g1Lineage(5, 3)) || g1Ship(t, restarted, store, g1Lineage(6, 3), 3, 'c') {
t.Fatal("after a restart the replica took the epoch-3 primary below its promised floor 4")
}
// closure: the round failed, the master re-issues the same primary at 4
if err := restarted.AdmitAsReplica(4); err != nil {
t.Fatal(err)
}
if !g1Ship(t, restarted, store, g1Lineage(7, 4), 4, 'd') || !g1Barrier(t, restarted, g1Lineage(7, 4)) {
t.Fatal("the line re-issued at the fenced epoch 4 was refused: a failed round would degrade the volume for ever")
}
}
// A ship admitted before the fence is still applying when FenceFloor is
// called: the promise is not made until it has applied, so it can never
// apply (or ACK) after the replica answered.
func TestFenceFloor_WaitsForAMutationAlreadyPastTheGate(t *testing.T) {
listener, store := g2PausedShip(t)
type result struct {
at time.Time
err error
}
fenced := make(chan result, 1)
go func() {
err := listener.FenceFloor(2)
fenced <- result{time.Now(), err}
}()
select {
case r := <-fenced:
close(store.release)
t.Fatalf("FenceFloor returned (err=%v) while an admitted epoch-1 ship was still applying", r.err)
case <-time.After(300 * time.Millisecond):
}
// a new epoch-1 frame is refused at once, while the fence drains
old := RecoveryLineage{SessionID: 5, Epoch: 1, EndpointVersion: 1, TargetLSN: 1}
if !g2Refused(t, listener.Addr(), MsgShipEntry, g2ShipPayload(old, 2)) {
close(store.release)
t.Fatal("a new epoch-1 ship was admitted while the floor-2 fence was draining")
}
close(store.release)
appliedAt := <-store.applied
select {
case r := <-fenced:
if r.err != nil {
t.Fatalf("fence: %v", r.err)
}
if r.at.Before(appliedAt) {
t.Fatalf("FenceFloor returned %v before the in-flight apply finished", appliedAt.Sub(r.at))
}
case <-time.After(5 * time.Second):
t.Fatal("FenceFloor never returned after the in-flight apply finished")
}
}
// A fence whose floor cannot be made durable is an error: no promise, the
// record keeps the old floor (a restart is not bound), while this process
// keeps refusing below the fence epoch. A fence never lowers the floor.
func TestFenceFloor_PersistFailureMakesNoPromise(t *testing.T) {
other := g1Listener(t, storage.NewBlockStore(16, 4096), g1Fresh(t))
if err := other.AdmitAsReplica(5); err != nil {
t.Fatal(err)
}
if err := other.FenceFloor(4); err != nil {
t.Fatal(err)
}
if got := other.DurableFloor(); got != 5 {
t.Fatalf("a fence at 4 over floor 5: durable floor %d, want 5 (never lowered)", got)
}
store := storage.NewBlockStore(16, 4096)
floor := g1Fresh(t)
ln := g1Listener(t, store, floor)
if err := ln.AdmitAsReplica(3); err != nil {
t.Fatal(err)
}
failAt(t, ln, "write")
if err := ln.FenceFloor(4); err == nil {
t.Fatal("FenceFloor returned nil though the floor record could not be written")
}
if got := ln.DurableFloor(); got != 3 || g1Persisted(t, floor) != 3 {
t.Fatalf("after a failed fence: durable floor %d, record %d; want 3", got, g1Persisted(t, floor))
}
if g1Barrier(t, ln, g1Lineage(1, 3)) {
t.Fatal("after a failed fence the epoch-3 barrier was ACKed")
}
}
// A fencing round that reaches the volume's primary is refused: the
// primary's floor stays at the epoch it serves (a higher floor would fence
// its own writes), and the caller sends no answer.
func TestFenceFloor_NeverFencesThePrimary(t *testing.T) {
store := storage.NewBlockStore(16, 4096)
floor := g1Fresh(t)
ln := g1Listener(t, store, floor)
if err := ln.FenceAsPrimary(3); err != nil {
t.Fatal(err)
}
if err := ln.FenceFloor(4); !errors.Is(err, ErrFencePrimary) {
t.Fatalf("a fencing round on the primary: %v; want ErrFencePrimary", err)
}
if got := ln.DurableFloor(); got != 3 || g1Persisted(t, floor) != 3 {
t.Fatalf("the primary's floor after a refused fence: %d (record %d); want 3", got, g1Persisted(t, floor))
}
}
// A replica fenced at 4 promised to take nothing below 4: a primary role at
// 3 (a stale line) is refused, and the listener stays a replica.
func TestFenceFloor_APrimaryFenceBelowTheFloorIsRefused(t *testing.T) {
store := storage.NewBlockStore(16, 4096)
floor := g1Fresh(t)
ln := g1Listener(t, store, floor)
if err := ln.FenceFloor(4); err != nil {
t.Fatal(err)
}
if err := ln.FenceAsPrimary(3); !errors.Is(err, ErrFenceBelowFloor) {
t.Fatalf("a primary role at 3 under floor 4: %v; want ErrFenceBelowFloor", err)
}
if err := ln.FenceFloor(5); err != nil {
t.Fatalf("the refused primary fence left the listener a primary: %v", err)
}
}
+3
View File
@@ -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) {
+58 -2
View File
@@ -3,6 +3,7 @@ package transport
import (
"crypto/rand"
"encoding/binary"
"errors"
"fmt"
"log"
"net"
@@ -637,6 +638,7 @@ func (r *ReplicaListener) handleConn(conn net.Conn) {
AchievedLSN: frontier,
LastDataEpoch: r.epochs.LastDataRowAt(frontier).Epoch,
LastDataFirstLSN: r.epochs.LastDataRowAt(frontier).FirstLSN,
StoreID: storage.StoreIDOf(r.store),
})
replyType, reply = MsgBarrierResp, resp
return true
@@ -690,6 +692,7 @@ func (r *ReplicaListener) handleConn(conn net.Conn) {
AchievedLSN: frontier,
LastDataEpoch: r.epochs.LastDataRowAt(frontier).Epoch,
LastDataFirstLSN: r.epochs.LastDataRowAt(frontier).FirstLSN,
StoreID: storage.StoreIDOf(r.store),
})
replyType, reply = MsgBarrierResp, resp
@@ -784,9 +787,62 @@ func (r *ReplicaListener) FenceAsPrimary(epoch uint64) error {
}
func (r *ReplicaListener) fenceAndDrain(epoch uint64) error {
return r.floorAndDrain(epoch, true)
}
// FenceFloor is this replica's half of a fencing round (the ack fence): its
// promise that nothing below epoch is applied or acknowledged any more,
// durable before it returns. Order: the floor in memory first (every new
// frame below epoch is refused at once), then the drain of every mutation
// admitted before it (none of them applies or ACKs after the promise), then
// the floor persisted. A drain timeout or a persist error is returned and the
// caller must not answer the round (no promise was made); frames below epoch
// stay refused. The role is unchanged: a line re-issued at epoch to the same
// primary (a failed round's heal) is admitted by AdmitAsReplica as usual.
// A listener in the primary role refuses the fence (ErrFencePrimary) and
// changes nothing: the primary serves its epoch, and a floor above it would
// fence the volume's own writes; whatever the master sends, the node
// decides this itself.
func (r *ReplicaListener) FenceFloor(epoch uint64) error {
if err := r.floorAndDrain(epoch, false); err != nil {
return err
}
return r.raiseFloor(epoch)
}
// ErrFenceBelowFloor: a primary role below this replica's floor.
var ErrFenceBelowFloor = errors.New("replica listener: a primary role below the epoch floor")
// ErrFencePrimary: a fencing round reached the volume's primary.
var ErrFencePrimary = errors.New("replica listener: a fencing round never fences the primary")
// DurableFloor is the floor persisted in the volume's floor record (in
// memory for a listener without one): the epoch below which this replica
// has promised to apply and acknowledge nothing.
func (r *ReplicaListener) DurableFloor() uint64 {
r.floorMu.Lock()
defer r.floorMu.Unlock()
return r.persisted
}
// floorAndDrain raises the in-memory floor to epoch (and, for a primary
// fence, refuses every mutation), then waits until no mutation admitted
// before it is still in flight.
func (r *ReplicaListener) floorAndDrain(epoch uint64, primary bool) error {
r.mu.Lock()
defer r.mu.Unlock()
r.primary = true
if primary && epoch < r.epochFloor {
// the floor is a promise to take nothing below it: a primary role
// at a lower epoch is a stale line
return fmt.Errorf("%w: primary at epoch %d under floor %d", ErrFenceBelowFloor, epoch, r.epochFloor)
}
if primary {
r.primary = true
} else if r.primary {
// checked under the lock that raises the floor: a concurrent
// FenceAsPrimary cannot slip between the check and the raise
return fmt.Errorf("%w at epoch %d", ErrFencePrimary, epoch)
}
if epoch > r.epochFloor {
r.epochFloor = epoch
}
@@ -810,7 +866,7 @@ func (r *ReplicaListener) fenceAndDrain(epoch uint64) error {
drained.Wait()
}
if r.inFlight > 0 {
return fmt.Errorf("replica listener: %d replication mutation(s) still in flight %v after fencing as primary at epoch %d", r.inFlight, timeout, epoch)
return fmt.Errorf("replica listener: %d replication mutation(s) still in flight %v after fencing at epoch %d", r.inFlight, timeout, epoch)
}
return nil
}
+3 -3
View File
@@ -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.
+1
View File
@@ -77,6 +77,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`.
| `Volumes[].Path` | string | its store path under --durable-root |
| `Volumes[].Impl` | string | the durable implementation (walstore, smartwal, walstore-chunk, ...) |
| `Volumes[].ReplicaID` | string | the replica this store holds |
| `Volumes[].StoreID` | string | the store's superblock UUID (hex); empty when it carries none (omitted when empty) |
| `Volumes[].Epoch` | uint64 | the epoch the store is latched to; 0 before an assignment |
| `Volumes[].EndpointVersion` | uint64 | the endpoint version it is latched to |
| `Volumes[].Latched` | bool | an assignment latched the store (epoch and endpoint version set) |