authority, master: keep a restarted primary through one bounded boot grace

A freshly started volume reports ReadyForPrimary=false until its engine
has a promotion fact, so any restart of the current primary failed over
at the first heartbeat whenever a ready peer existed (#128; T1/T2).

The controller now keeps the current primary while it is placeable and
inside its boot grace: the grace starts at the first heartbeat of a new
incarnation and lasts PrimaryBootGrace (the master sets it to its
freshness window). Only its endpoint may be refreshed meanwhile. The
grace never covers an explicit unhealthy report (unreachable,
ineligible, withdrawn); ends for good once the replica reports ready or
the grace expires (no extension by repeated not-ready heartbeats); and
is refused to a replica with PrimaryBootFlapRestarts process starts
within PrimaryBootFlapWindow (defaults 3 in 10 min). No incarnation (an
older volume binary) means no grace.

The promotion gate's direct reassign skips a current primary that is
placeable by its own report and inside its boot grace.

Lock order: grace state lives under TopologyController.mu, written only
by observeIncarnationsLocked inside the existing snapshot path; the
controller calls nothing outward while holding it. The gate calls
PrimaryInBootGrace (takes c.mu) holding no controller-visible lock, the
same direction as its existing controller calls.

Fixes #128

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-15 11:10:32 -08:00
1 parent fc10f148ff
commit b342e8f21f
5 files changed
+190 -2

No files matched your search

@@ -29,6 +29,7 @@ type TopologyController struct {
desired map[string]DesiredAssignment
unsupported map[string]UnsupportedEvidence
convergenceStuck map[string]*ConvergenceStuckEvidence
bootGrace map[string]*primaryBootGrace // volume/replica -> current incarnation's grace
now func() time.Time
}
@@ -40,6 +41,7 @@ func NewTopologyController(config TopologyControllerConfig, reader AuthorityBasi
desired: make(map[string]DesiredAssignment),
unsupported: make(map[string]UnsupportedEvidence),
convergenceStuck: make(map[string]*ConvergenceStuckEvidence),
bootGrace: make(map[string]*primaryBootGrace),
now: time.Now,
}
}
@@ -228,6 +230,7 @@ func (c *TopologyController) processSupportedVolumeLocked(
// S4 behavior; stuck evidence has its own lifecycle and is
// NOT cleared here — §10 clearing rule 4.)
delete(c.unsupported, vol.VolumeID)
c.observeIncarnationsLocked(vol)
c.confirmDesiredLocked(vol, currentLine, hasLine)
@@ -491,6 +494,22 @@ func (c *TopologyController) decideVolume(
return AssignmentAsk{}, "", false
}
// A restarted current primary that is placeable but not ready yet
// keeps its authority through its boot grace; only its endpoint
// may be refreshed.
if candidatePlaceable(current, serverIndex) && c.inPrimaryBootGraceLocked(vol.VolumeID, current) {
if current.DataAddr != currentLine.DataAddr || current.CtrlAddr != currentLine.CtrlAddr {
return AssignmentAsk{
VolumeID: vol.VolumeID,
ReplicaID: current.ReplicaID,
DataAddr: current.DataAddr,
CtrlAddr: current.CtrlAddr,
Intent: IntentRefreshEndpoint,
}, "endpoint refresh (primary boot grace)", true
}
return AssignmentAsk{}, "", false
}
other := acceptableCandidatesExcept(vol, serverIndex, current.ReplicaID)
if len(other) > 0 {
best := chooseFailoverCandidate(other, projectedLoad)
@@ -0,0 +1,114 @@
package authority
import "time"
// Primary boot grace (#128).
//
// A freshly started volume process reports ReadyForPrimary=false until
// its engine has a promotion fact, so a plain restart of the current
// primary would otherwise fail over the moment a ready peer exists.
// The controller keeps the CURRENT primary through one boot grace:
//
// 1. the grace starts when the controller first sees a new process
// incarnation for the replica, and lasts at most PrimaryBootGrace
// (the master wires it to its freshness window);
// 2. it covers only "not ready yet": the replica must stay placeable
// (reachable, eligible, not withdrawn, on a reachable eligible
// server). Any explicit unhealthy report fails over at once;
// 3. once it expires with the replica still unready, failover
// proceeds as before;
// 4. it is granted at most once per incarnation (repeated not-ready
// heartbeats never extend it), ends for good the moment the
// replica reports ready, and is refused to a flapping replica
// (PrimaryBootFlapRestarts incarnations within
// PrimaryBootFlapWindow).
//
// A replica that reports no incarnation (an older volume binary) gets
// no grace. All state is guarded by TopologyController.mu.
type primaryBootGrace struct {
incarnation string
graceStart time.Time
ended bool // reported ready, expired, or never granted
starts []time.Time // incarnation starts within the flap window
}
func bootGraceKey(volumeID, replicaID string) string { return volumeID + "/" + replicaID }
// observeIncarnationsLocked records each slot's incarnation. It is the
// only writer of bootGrace and runs once per supported snapshot.
func (c *TopologyController) observeIncarnationsLocked(vol VolumeTopologySnapshot) {
now := c.now()
for _, slot := range vol.Slots {
if slot.Incarnation == "" {
continue
}
key := bootGraceKey(vol.VolumeID, slot.ReplicaID)
g := c.bootGrace[key]
if g == nil || g.incarnation != slot.Incarnation {
g = c.startIncarnation(g, slot.Incarnation, now)
c.bootGrace[key] = g
}
if slot.ReadyForPrimary {
g.ended = true
}
}
}
// startIncarnation returns the grace record for a newly seen
// incarnation: its start is counted, and the grace is refused when
// that makes the replica a flapper.
func (c *TopologyController) startIncarnation(prev *primaryBootGrace, incarnation string, now time.Time) *primaryBootGrace {
var starts []time.Time
if prev != nil {
for _, t := range prev.starts {
if now.Sub(t) < c.config.PrimaryBootFlapWindow {
starts = append(starts, t)
}
}
}
starts = append(starts, now)
return &primaryBootGrace{
incarnation: incarnation,
graceStart: now,
ended: len(starts) >= c.config.PrimaryBootFlapRestarts,
starts: starts,
}
}
// inPrimaryBootGraceLocked reports whether the current primary's slot
// is inside its boot grace now. Expiry ends the grace for good.
func (c *TopologyController) inPrimaryBootGraceLocked(volumeID string, current ReplicaCandidate) bool {
if current.Incarnation == "" || current.ReadyForPrimary {
return false
}
g := c.bootGrace[bootGraceKey(volumeID, current.ReplicaID)]
if g == nil || g.incarnation != current.Incarnation || g.ended {
return false
}
if c.now().Sub(g.graceStart) >= c.config.PrimaryBootGrace {
g.ended = true
return false
}
return true
}
// PrimaryInBootGrace reports whether a direct reassignment away from
// the current primary must wait: the slot is, or on this observation
// would become, inside its boot grace. It does not record anything.
// The master's promotion gate calls it before a direct reassign; the
// gate holds no controller-visible lock while calling.
func (c *TopologyController) PrimaryInBootGrace(volumeID string, current ReplicaCandidate) bool {
c.mu.Lock()
defer c.mu.Unlock()
if current.Incarnation == "" || current.ReadyForPrimary {
return false
}
g := c.bootGrace[bootGraceKey(volumeID, current.ReplicaID)]
if g == nil || g.incarnation != current.Incarnation {
// Not seen yet: the grace this observation would start.
next := c.startIncarnation(g, current.Incarnation, c.now())
return !next.ended
}
return c.inPrimaryBootGraceLocked(volumeID, current)
}
+7 -1
View File
@@ -178,7 +178,13 @@ func New(cfg Config) (*Host, error) {
}
holder := &publisherHolder{}
ctrl := authority.NewTopologyController(cfg.ControllerConfig, holder)
ctrlCfg := cfg.ControllerConfig
if ctrlCfg.PrimaryBootGrace == 0 && cfg.Freshness.FreshnessWindow > 0 {
// A restarted primary may stay not-ready for at most the
// window in which its observations are trusted (#128).
ctrlCfg.PrimaryBootGrace = cfg.Freshness.FreshnessWindow
}
ctrl := authority.NewTopologyController(ctrlCfg, holder)
h := &Host{
cfg: cfg,
@@ -0,0 +1,36 @@
package master
import (
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
)
// The promotion gate's direct reassign waits only for a restarted primary
// that is placeable by its own report and inside its boot grace (#128).
func TestPrimaryBootGraceHolds_OnlyForPlaceableRestartedPrimary(t *testing.T) {
ctrl := authority.NewTopologyController(authority.TopologyControllerConfig{PrimaryBootGrace: 30 * time.Second}, nil)
restarted := authority.ReplicaCandidate{
ReplicaID: "r1", ServerID: "s1", Reachable: true, Eligible: true, Incarnation: "r1-b",
}
if !primaryBootGraceHolds(ctrl, "v1", restarted) {
t.Fatal("restarted, placeable, not-ready primary: want the boot grace to hold")
}
for name, mut := range map[string]func(*authority.ReplicaCandidate){
"ready": func(c *authority.ReplicaCandidate) { c.ReadyForPrimary = true },
"unreachable": func(c *authority.ReplicaCandidate) { c.Reachable = false },
"ineligible": func(c *authority.ReplicaCandidate) { c.Eligible = false },
"withdrawn": func(c *authority.ReplicaCandidate) { c.Withdrawn = true },
"no incarnation": func(c *authority.ReplicaCandidate) { c.Incarnation = "" },
} {
c := restarted
mut(&c)
if primaryBootGraceHolds(ctrl, "v1", c) {
t.Errorf("%s: the boot grace must not hold", name)
}
}
if primaryBootGraceHolds(nil, "v1", restarted) {
t.Error("nil controller: must not hold")
}
}
+14 -1
View File
@@ -183,7 +183,9 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
slot.ReadyForPrimary = false
}
}
if enabledCandidate && result.CurrentKnown && !result.Current.Ready {
if enabledCandidate && result.CurrentKnown && !result.Current.Ready && primaryBootGraceHolds(h.ctrl, vol.VolumeID, vol.Slots[currentIdx]) {
h.log.Printf("blockmaster: promotion gate volume=%s current=%s not ready but in boot grace; no direct reassign", vol.VolumeID, vol.Authority.ReplicaID)
} else if enabledCandidate && result.CurrentKnown && !result.Current.Ready {
current := &vol.Slots[currentIdx]
current.Reachable = false
current.ReadyForPrimary = false
@@ -562,3 +564,14 @@ func (h *Host) assignmentAskAlreadyCurrent(volumeID, replicaID, dataAddr, ctrlAd
line.DataAddr == dataAddr &&
line.CtrlAddr == ctrlAddr
}
// primaryBootGraceHolds reports whether the current primary's slot is
// placeable by its own report and inside its boot grace (#128): a
// restarted primary that is merely not ready yet. An explicit unhealthy
// report (unreachable, ineligible, withdrawn) never holds.
func primaryBootGraceHolds(ctrl *authority.TopologyController, volumeID string, current authority.ReplicaCandidate) bool {
if ctrl == nil || !current.Reachable || !current.Eligible || current.Withdrawn {
return false
}
return ctrl.PrimaryInBootGrace(volumeID, current)
}