Merge branch 'master' into block/unified-answer-policy

This commit is contained in:
Ping Qiu authored and GitHub committed 2026-12-05 16:04:50 -08:00
commit b5e4406f84
7 files changed
+360 -12

No files matched your search

@@ -26,6 +26,13 @@ import (
// refuses an interval above half the freshness window (a longer loop gap
// reads as the master's own pause), so the window is 60 s: the dead
// primary's loss then comes at most a window after its last report.
//
// The failover is predicted within gapLoop + gapWindow + gapLoop of the
// kill: the tick that ends creation comes at most a loop after it, the
// loss a window after that tick's silence floor, and the tick that reads
// the loss at most a loop later. The test waits twice that.
const gapLoop, gapWindow = 30 * time.Second, 60 * time.Second
func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
bins := buildG54Binaries(t)
h := &plannedHandoffHarness{dir: t.TempDir(), t: t}
@@ -48,8 +55,8 @@ func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
}
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", "30s",
"--freshness-window", "60s", "--launcher-replication-ack", "sync-quorum", "--listen", h.masterAddr)
"--cluster-spec", spec, "--expected-slots-per-volume", "3", "--lifecycle-product-loop-interval", gapLoop.String(),
"--freshness-window", gapWindow.String(), "--launcher-replication-ack", "sync-quorum", "--listen", h.masterAddr)
master.waitLog(t, 30*time.Second, "blockmaster: lock acquired")
for _, b := range hosts {
lockDir := b.root + ".locks"
@@ -84,7 +91,8 @@ func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
// 3. The next tick reads the survivors' write: creation ended, and the
// gate fails the volume over.
var p2 *host
poll(t, 120*time.Second, "no survivor became primary at epoch 2 (the volume held as creating?)", func() bool {
predicted := gapLoop + gapWindow + gapLoop
poll(t, 2*predicted, fmt.Sprintf("no survivor became primary at epoch 2 within %v, twice the predicted %v (the volume held as creating, or the gate's replace not acted on: see the master's 'decision=replace' lines)", 2*predicted, predicted), func() bool {
for _, b := range survivors {
if statusIsPrimaryAt(b.status, 2) {
p2 = b
+58 -6
View File
@@ -32,6 +32,7 @@ type TopologyController struct {
unsupported map[string]UnsupportedEvidence
convergenceStuck map[string]*ConvergenceStuckEvidence
bootGrace map[string]*primaryBootGrace // volume/replica -> current incarnation's grace
outcome map[string]string // volume -> what the last intake did with it (LastOutcome); kept like bootGrace
now func() time.Time
}
@@ -44,10 +45,21 @@ func NewTopologyController(config TopologyControllerConfig, reader AuthorityBasi
unsupported: make(map[string]UnsupportedEvidence),
convergenceStuck: make(map[string]*ConvergenceStuckEvidence),
bootGrace: make(map[string]*primaryBootGrace),
outcome: make(map[string]string),
now: time.Now,
}
}
// LastOutcome says what the last snapshot intake that carried the volume
// as supported did with it: the ask it enqueued, or why it enqueued none
// ("" before any). The master logs it beside a promotion gate's replace
// decision, so a decision the controller did not act on says why.
func (c *TopologyController) LastOutcome(volumeID string) string {
c.mu.Lock()
defer c.mu.Unlock()
return c.outcome[volumeID]
}
// SetNowForTest overrides the controller's clock source. Tests
// use this to drive RetryWindow / Stuck transitions deterministically.
// Production code MUST NOT call this.
@@ -125,6 +137,21 @@ func (c *TopologyController) SubmitClusterSnapshot(snap ClusterSnapshot) error {
// desired state live; SubmitObservedState always processes the
// report.
func (c *TopologyController) SubmitObservedState(snap ClusterSnapshot, report SupportabilityReport) error {
return c.submitObservedState(snap, report, nil)
}
// SubmitObservedStateOutcomes is SubmitObservedState that also returns what
// this intake did with each volume it carried (supported, pending or
// unsupported), read while the intake still holds the controller's lock: a
// later intake (the background observation host shares the controller)
// cannot change it. A volume this intake did not carry has no entry.
func (c *TopologyController) SubmitObservedStateOutcomes(snap ClusterSnapshot, report SupportabilityReport) (map[string]string, error) {
out := map[string]string{}
err := c.submitObservedState(snap, report, out)
return out, err
}
func (c *TopologyController) submitObservedState(snap ClusterSnapshot, report SupportabilityReport, outcomes map[string]string) error {
// Validate non-empty supported snapshots the same way
// SubmitClusterSnapshot does. Empty supported + empty report
// is allowed (no-op).
@@ -163,6 +190,7 @@ func (c *TopologyController) SubmitObservedState(snap ClusterSnapshot, report Su
// stale unsupported record from a prior build is cleared,
// because pending is a transitional state, not a fault.
delete(c.unsupported, vid)
c.outcome[vid] = "no ask: supportability pending"
}
for vid, ev := range report.Unsupported {
c.clearDesiredLocked(vid)
@@ -180,6 +208,7 @@ func (c *TopologyController) SubmitObservedState(snap ClusterSnapshot, report Su
Basis: AuthorityBasis{},
Reason: joinReasons(ev.Reasons),
}
c.outcome[vid] = "no ask: unsupported: " + joinReasons(ev.Reasons)
}
// Process supported volumes via the existing decision path.
@@ -196,6 +225,17 @@ func (c *TopologyController) SubmitObservedState(snap ClusterSnapshot, report Su
currentLine, hasLine := c.reader.VolumeAuthorityLine(vol.VolumeID)
c.processSupportedVolumeLocked(vol, snap, serverIndex, currentLine, hasLine, currentLoad, projectedLoad)
}
if outcomes != nil {
for vid := range report.Pending {
outcomes[vid] = c.outcome[vid]
}
for vid := range report.Unsupported {
outcomes[vid] = c.outcome[vid]
}
for _, vol := range volumes {
outcomes[vol.VolumeID] = c.outcome[vol.VolumeID]
}
}
return nil
}
@@ -252,11 +292,13 @@ func (c *TopologyController) processSupportedVolumeLocked(
if vol.Authority.Assigned && !volumeIncludesReplica(vol, vol.Authority.ReplicaID) {
c.recordUnsupportedLocked(vol.VolumeID, snap, vol.Authority, "snapshot authority outside accepted topology: "+vol.Authority.ReplicaID)
c.clearDesiredLocked(vol.VolumeID)
c.outcome[vol.VolumeID] = "no ask: snapshot authority outside accepted topology"
return
}
if hasLine && !volumeIncludesReplica(vol, currentLine.ReplicaID) {
c.recordUnsupportedLocked(vol.VolumeID, snap, currentLine, "publisher authority on replica outside accepted topology: "+currentLine.ReplicaID)
c.clearDesiredLocked(vol.VolumeID)
c.outcome[vol.VolumeID] = "no ask: publisher authority outside accepted topology"
return
}
@@ -269,17 +311,20 @@ func (c *TopologyController) processSupportedVolumeLocked(
// Stale snapshot: do not emit from a stale basis, but keep any
// existing desired (publish-until-observed convergence record).
if !basisMatchesLine(vol.Authority, currentLine, hasLine) {
c.outcome[vol.VolumeID] = fmt.Sprintf("no ask: stale snapshot basis %s@%d, line %s@%d", vol.Authority.ReplicaID, vol.Authority.Epoch, currentLine.ReplicaID, currentLine.Epoch)
return
}
// Stale slot facts: likewise keep any existing desired and emit
// nothing from this snapshot.
if staleFacts {
c.outcome[vol.VolumeID] = "no ask: superseded slot facts"
return
}
ask, reason, emit := c.decideVolume(vol, serverIndex, currentLine, hasLine, currentLoad, projectedLoad)
if !emit {
c.clearDesiredLocked(vol.VolumeID)
c.outcome[vol.VolumeID] = "no ask: " + reason
return
}
// Same-ask dedupe: if the identical ask is already the current
@@ -287,6 +332,7 @@ func (c *TopologyController) processSupportedVolumeLocked(
// identical supported feeds would mint a new Reassign epoch
// each iteration — authority churn.
if prev, ok := c.desired[vol.VolumeID]; ok && sameAsk(prev.Ask, ask) {
c.outcome[vol.VolumeID] = fmt.Sprintf("already desired since %s: %s %s (%s)", prev.DesiredAt.UTC().Format(time.RFC3339Nano), ask.Intent, ask.ReplicaID, prev.Reason)
return
}
@@ -308,6 +354,7 @@ func (c *TopologyController) processSupportedVolumeLocked(
}
c.desired[vol.VolumeID] = desired
c.queue.enqueue(ask)
c.outcome[vol.VolumeID] = fmt.Sprintf("enqueued %s %s (%s)", ask.Intent, ask.ReplicaID, reason)
applyProjectedMove(projectedLoad, vol, currentLine, hasLine, ask)
}
@@ -472,7 +519,7 @@ func (c *TopologyController) decideVolume(
if !hasLine {
cands := placeableCandidates(vol, serverIndex)
if len(cands) == 0 {
return AssignmentAsk{}, "", false
return AssignmentAsk{}, "no placeable candidate for the first line", false
}
best := choosePlacementCandidate(cands, projectedLoad)
return AssignmentAsk{
@@ -487,7 +534,7 @@ func (c *TopologyController) decideVolume(
current, ok := candidateByReplica(vol, currentLine.ReplicaID)
if !ok {
return AssignmentAsk{}, "", false
return AssignmentAsk{}, "the line's replica is not in the snapshot", false
}
if candidateAcceptable(current, serverIndex) {
@@ -500,7 +547,7 @@ func (c *TopologyController) decideVolume(
// 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{}, "the current primary is acceptable; rebalance target " + target.ReplicaID + " has no planned-move evidence", false
}
return AssignmentAsk{
VolumeID: vol.VolumeID,
@@ -512,7 +559,7 @@ func (c *TopologyController) decideVolume(
Incarnation: target.Incarnation,
}, "rebalance", true
}
return AssignmentAsk{}, "", false
return AssignmentAsk{}, "the current primary is acceptable", false
}
// A restarted current primary that is placeable but not ready yet
@@ -522,9 +569,13 @@ func (c *TopologyController) decideVolume(
if !superseded && endpointStale(current, currentLine) {
return refreshAsk(vol.VolumeID, current, currentLine), "endpoint refresh (primary boot grace)", true
}
return AssignmentAsk{}, "", false
if superseded {
return AssignmentAsk{}, "the current primary holds its boot grace (by its newer recorded fact)", false
}
return AssignmentAsk{}, "the current primary holds its boot grace", false
}
why := "no acceptable candidate besides the current primary"
other := acceptableCandidatesExcept(vol, serverIndex, current.ReplicaID)
if len(other) > 0 {
best := chooseFailoverCandidate(other, projectedLoad)
@@ -541,6 +592,7 @@ func (c *TopologyController) decideVolume(
Incarnation: best.Incarnation,
}, "failover", true
}
why = "failover target " + best.ReplicaID + " has no promotion evidence"
}
// No promotion-ready peer exists. Keep the current authority endpoint fresh
// when the current replica is still reachable/eligible; this preserves
@@ -548,7 +600,7 @@ func (c *TopologyController) decideVolume(
if candidatePlaceable(current, serverIndex) && endpointStale(current, currentLine) {
return refreshAsk(vol.VolumeID, current, currentLine), "endpoint refresh", true
}
return AssignmentAsk{}, "", false
return AssignmentAsk{}, why, false
}
// endpointStale reports whether the current primary's line needs a new
@@ -0,0 +1,72 @@
package master
import (
"log"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"testing"
"github.com/seaweedfs/seaweed-block/core/authority"
)
// bindingFailingProbe is switchProbe whose fencing round first makes the
// master's workspace binding store fail a write (its file replaced by a
// directory, so the write's rename fails), which latches the store
// uncertain: every later read answers restart-required. It does this once.
type bindingFailingProbe struct {
*switchProbe
once sync.Once
fault func()
}
func (p *bindingFailingProbe) FencePromotionCandidates(volume string, current authority.AuthorityBasis, survivors []PromotionCandidateEvidence) (PromotionProbeResult, error) {
p.once.Do(p.fault)
return p.switchProbe.FencePromotionCandidates(volume, current, survivors)
}
// A binding store that turns uncertain while the gate probes (the probe runs
// without the workspace lock) makes the tick's post-probe binding read fail.
// The tick returns the error and its replace decision is reported as not
// submitted, with the error, instead of vanishing with the tick.
func TestABindingReadFailureAfterTheProbeReportsTheDecisionNotSubmitted(t *testing.T) {
buf := &lockedBuffer{}
dir := t.TempDir()
h := newBootGraceMaster(t, Config{Logger: log.New(buf, "", 0), LifecycleStoreDir: dir})
defer closeTestMaster(t, h)
base, ok := h.promotionProber.(*switchProbe)
if !ok {
t.Fatalf("fixture: the master's prober is %T, want *switchProbe", h.promotionProber)
}
var faultErr error
h.SetPromotionEvidenceProvider(&bindingFailingProbe{switchProbe: base, fault: func() {
file := filepath.Join(dir, "workspace-bindings", "bindings.json")
if err := os.RemoveAll(file); err != nil {
faultErr = err
return
}
if err := os.MkdirAll(file, 0o755); err != nil {
faultErr = err
return
}
if err := h.lifecycle.WorkspaceBindings.Retire("vol-other", "node-x", 1); err == nil {
faultErr = os.ErrInvalid // the write was expected to fail
}
}})
ineligible := restarting
ineligible.eligible = false
ingestRF3Incarnations(t, h, ineligible, readySlot("r2-a"), readySlot("r3-a"))
_, err := h.RunLifecycleProductTick()
if faultErr != nil {
t.Fatalf("fixture: the binding store did not fail its write: %v", faultErr)
}
if err == nil || !strings.Contains(err.Error(), "restart required") {
t.Fatalf("tick error %v, want the binding store's restart-required error", err)
}
pattern := `promotion gate volume=vol-rf3 decision=replace\(fenced_at=2\) not submitted: the workspace bindings could not be read after the probe: .*restart required`
if !regexp.MustCompile(pattern).MatchString(buf.String()) {
t.Fatalf("no log line matching %q:\n%s", pattern, buf.String())
}
}
@@ -0,0 +1,150 @@
package master
import (
"log"
"regexp"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/authority"
)
// A replace decision of the promotion gate is followed, on the master's
// log, by what became of it: the ask the controller enqueued, why it
// enqueued none, or that it was not submitted. A replace the controller
// does not act on is otherwise silent until the volume fails to fail over.
func TestAReplaceDecisionLogsWhatTheControllerDidWithIt(t *testing.T) {
// The gate's replace of the lost r1, fed to a controller bound to r1@1.
replaced := func(t *testing.T) (*Host, *lockedBuffer, *authority.TopologyController, authority.ClusterSnapshot) {
t.Helper()
ctrl, pub, stop := lossCluster(t, authority.TopologyControllerConfig{})
stop() // the enqueued ask stays queued: the outcome is the controller's alone
h, buf := lossMaster(t, &fenceProbe{plain: lossPlain, fenced: lossFenced})
h.ctrl = ctrl
snap := lossTicks(h)
snap.Volumes[0].Authority, _ = pub.VolumeAuthorityLine("vol-rf3")
return h, buf, ctrl, snap
}
submit := func(t *testing.T, h *Host, ctrl *authority.TopologyController, snap authority.ClusterSnapshot) {
t.Helper()
outcomes, err := ctrl.SubmitObservedStateOutcomes(snap, authority.SupportabilityReport{})
if err != nil {
t.Fatal(err)
}
h.reportReplaces("", nil, outcomes)
}
want := func(t *testing.T, buf *lockedBuffer, pattern string) {
t.Helper()
if !regexp.MustCompile(pattern).MatchString(buf.String()) {
t.Fatalf("no log line matching %q:\n%s", pattern, buf.String())
}
}
t.Run("enqueued", func(t *testing.T) {
h, buf, ctrl, snap := replaced(t)
submit(t, h, ctrl, snap)
want(t, buf, `promotion gate volume=vol-rf3 decision=replace\(fenced_at=2\) controller: enqueued Reassign r[23] \(failover\)`)
})
t.Run("the same decision again: already desired", func(t *testing.T) {
h, buf, ctrl, snap := replaced(t)
submit(t, h, ctrl, snap)
h.noteGateReplace("vol-rf3", "replace(fenced_at=2)") // the next tick decides the same
submit(t, h, ctrl, snap)
want(t, buf, `decision=replace\(fenced_at=2\) controller: already desired since \S+: Reassign r[23] \(failover\)`)
})
t.Run("not acted on: says why", func(t *testing.T) {
h, buf, ctrl, snap := replaced(t)
for i := range snap.Volumes[0].Slots {
snap.Volumes[0].Slots[i].PromotionEvidence = adapter.PrimaryEvidence{}
}
submit(t, h, ctrl, snap)
want(t, buf, `decision=replace\(fenced_at=2\) controller: no ask: failover target r[23] has no promotion evidence`)
})
t.Run("not submitted", func(t *testing.T) {
h, buf, _, _ := replaced(t)
h.reportReplaces("not submitted: the placements changed during the probe", nil, nil)
want(t, buf, `decision=replace\(fenced_at=2\) not submitted: the placements changed during the probe`)
})
t.Run("an intake after the submission does not change its report", func(t *testing.T) {
// The background observation host shares the controller: its intake
// may land between the tick's submit and the report.
h, buf, ctrl, snap := replaced(t)
outcomes, err := ctrl.SubmitObservedStateOutcomes(snap, authority.SupportabilityReport{})
if err != nil {
t.Fatal(err)
}
stale := snap
stale.Volumes = append([]authority.VolumeTopologySnapshot(nil), snap.Volumes...)
stale.Volumes[0].Authority.Epoch++ // a basis the publisher does not hold
if err := ctrl.SubmitClusterSnapshot(stale); err != nil {
t.Fatal(err)
}
if o := ctrl.LastOutcome("vol-rf3"); !strings.HasPrefix(o, "no ask: stale snapshot basis") {
t.Fatalf("fixture: the intervening intake did not record its own outcome: %q", o)
}
h.reportReplaces("", nil, outcomes)
want(t, buf, `decision=replace\(fenced_at=2\) controller: enqueued Reassign r[23] \(failover\)`)
if strings.Contains(buf.String(), "decision=replace(fenced_at=2) controller: no ask: stale") {
t.Fatalf("the report took the later intake's outcome:\n%s", buf.String())
}
})
t.Run("a submission that did not carry the volume", func(t *testing.T) {
h, buf, _, _ := replaced(t)
h.reportReplaces("", nil, map[string]string{})
want(t, buf, `decision=replace\(fenced_at=2\) controller: no outcome \(the submission did not carry the volume\)`)
})
t.Run("one report per decision", func(t *testing.T) {
h, buf, ctrl, snap := replaced(t)
submit(t, h, ctrl, snap)
h.reportReplaces("", nil, nil) // nothing decided since: nothing to report
if n := strings.Count(buf.String(), "decision=replace(fenced_at=2) controller:"); n != 1 {
t.Fatalf("%d reports of one decision:\n%s", n, buf.String())
}
})
}
// The same through the production tick on the supported gate: an
// established volume whose primary turns ineligible is replaced by a fencing
// round; the gate's replace is reported with the controller's enqueued
// failover, and the publication is logged. The publication line comes from
// the publisher's observer after the line is visible, so it is waited for
// (bounded); the two lines are not ordered against each other.
func TestAProductTickReplaceLogsTheControllerOutcomeAndThePublication(t *testing.T) {
buf := &lockedBuffer{}
h := newBootGraceMaster(t, Config{Logger: log.New(buf, "", 0)})
defer closeTestMaster(t, h)
ineligible := restarting
ineligible.eligible = false
supportedCreatingTick(t, h, ineligible)
expectFailoverToR2(t, h, "fenced survivors")
for _, pattern := range []string{
`promotion gate volume=vol-rf3 decision=replace\(fenced_at=2\) controller: enqueued Reassign r2 \(failover\)`,
`blockmaster: volume=vol-rf3 authority reassigned to replica r2 epoch=2 endpoint_version=1 \(Reassign\)`,
} {
waitLogLine(t, buf, pattern, 5*time.Second)
}
}
// waitLogLine waits up to limit for a line of buf matching pattern.
func waitLogLine(t *testing.T, buf *lockedBuffer, pattern string, limit time.Duration) {
t.Helper()
re := regexp.MustCompile(pattern)
for end := time.Now().Add(limit); !re.MatchString(buf.String()); time.Sleep(10 * time.Millisecond) {
if time.Now().After(end) {
t.Fatalf("no log line matching %q within %v:\n%s", pattern, limit, buf.String())
}
}
}
// Every publication is on the master's log, with or without an event log.
func TestAPublicationIsLogged(t *testing.T) {
h, buf := lossMaster(t, &fenceProbe{})
h.recordAuthorityPublishedEvent(authority.PublishEvent{
Info: adapter.AssignmentInfo{VolumeID: "vol-rf3", ReplicaID: "r2", Epoch: 2, EndpointVersion: 1},
Ask: authority.AssignmentAsk{VolumeID: "vol-rf3", ReplicaID: "r2", Intent: authority.IntentReassign},
})
if !strings.Contains(buf.String(), "blockmaster: volume=vol-rf3 authority reassigned to replica r2 epoch=2 endpoint_version=1 (Reassign)") {
t.Fatalf("publication not logged:\n%s", buf.String())
}
}
+2 -1
View File
@@ -152,8 +152,9 @@ type Host struct {
attest *storeAttestations // primaries' attested write-ACK stores
healthMu sync.Mutex // orders replica health events with their accepted heartbeats (#128 rule 6)
log *log.Logger
gateNoteMu sync.Mutex // guards gateNoteLast
gateNoteMu sync.Mutex // guards gateNoteLast and gateReplaces
gateNoteLast map[string]string // per kind, the last skip or drop a product-loop tick logged (noteGate)
gateReplaces []gateReplace // this tick's replace decisions, reported after the submit (reportReplaces)
primaryLossMu sync.Mutex // guards primaryLoss
primaryLoss primaryLosses // per volume, the recorded loss of the current primary (primary_loss.go)
boot *bootstrap.DurableAuthorityBootstrap
+64 -2
View File
@@ -263,6 +263,7 @@ func (h *Host) submitPlacementSnapshots(placements []lifecycle.PlacementIntent)
receipts := h.obs.Store().Snapshot()
build := authority.BuildSnapshot(receipts, topology, h.Publisher())
h.notePrimaryLosses(receipts, &build.Snapshot)
h.takeGateReplaces() // only this tick's decisions are reported
probeCount, blockedCount, directAsks := h.applyPromotionEvidenceGate(&build.Snapshot)
supported := supportedSnapshotVolumes(build.Snapshot)
unsupportedProbeCount, unsupportedBlockedCount, unsupportedDirectAsks := h.applyUnsupportedPromotionEvidenceGate(placements, build.Report, supported)
@@ -275,13 +276,16 @@ func (h *Host) submitPlacementSnapshots(placements []lifecycle.PlacementIntent)
defer h.workspaceMu.Unlock()
if !reflect.DeepEqual(captured, h.lifecycle.Placements.ListPlacements()) {
h.noteGate(gateNoteTick, "decisions not submitted: the placements changed during the probe")
h.reportReplaces("not submitted: the placements changed during the probe", nil, nil)
return false, probeCount, blockedCount, nil, nil
}
for _, p := range placements {
if _, bound, err := h.lifecycle.WorkspaceBindings.Get(p.VolumeID); err != nil {
h.reportReplaces("not submitted: the workspace bindings could not be read after the probe: "+err.Error(), nil, nil)
return false, probeCount, blockedCount, nil, err
} else if bound {
h.noteGate(gateNoteTick, "decisions not submitted: volume "+p.VolumeID+" got a workspace binding during the probe")
h.reportReplaces("not submitted: volume "+p.VolumeID+" got a workspace binding during the probe", nil, nil)
return false, probeCount, blockedCount, nil, nil
}
}
@@ -289,12 +293,58 @@ func (h *Host) submitPlacementSnapshots(placements []lifecycle.PlacementIntent)
for _, slot := range v.Slots {
if err := h.lifecycle.WorkspaceBindings.CheckAvailable(lifecycle.WorkspaceBinding{VolumeID: v.VolumeID, DataAddr: slot.DataAddr, CtrlAddr: slot.CtrlAddr}); err != nil {
h.noteGate(gateNoteTick, fmt.Sprintf("decisions not submitted: volume %s replica %s endpoints are bound elsewhere: %v", v.VolumeID, slot.ReplicaID, err))
h.reportReplaces(fmt.Sprintf("not submitted: volume %s replica %s endpoints are bound elsewhere", v.VolumeID, slot.ReplicaID), nil, nil)
return false, probeCount, blockedCount, nil, nil
}
}
}
h.noteGate(gateNoteTick, "")
return true, probeCount, blockedCount, directAsks, h.ctrl.SubmitObservedState(build.Snapshot, build.Report)
// The outcomes are this submission's own, read under the controller's
// lock: the background observation host may submit right after it.
outcomes, err := h.ctrl.SubmitObservedStateOutcomes(build.Snapshot, build.Report)
h.reportReplaces("", err, outcomes)
return true, probeCount, blockedCount, directAsks, err
}
// gateReplace is one replace decision of a tick's promotion gate.
type gateReplace struct{ volumeID, decision string }
func (h *Host) noteGateReplace(volumeID, decision string) {
h.gateNoteMu.Lock()
h.gateReplaces = append(h.gateReplaces, gateReplace{volumeID, decision})
h.gateNoteMu.Unlock()
}
func (h *Host) takeGateReplaces() []gateReplace {
h.gateNoteMu.Lock()
defer h.gateNoteMu.Unlock()
out := h.gateReplaces
h.gateReplaces = nil
return out
}
// reportReplaces logs what became of each replace decision of this tick:
// not submitted (notSubmitted says why), a failed submit, or what the
// controller did with the volume (an enqueued ask, or why none). A decision
// the controller does not act on is otherwise silent until the volume is
// seen not to fail over.
func (h *Host) reportReplaces(notSubmitted string, submitErr error, outcomes map[string]string) {
for _, d := range h.takeGateReplaces() {
outcome := ""
switch {
case notSubmitted != "":
outcome = notSubmitted
case submitErr != nil:
outcome = "submit failed: " + submitErr.Error()
default:
if o, ok := outcomes[d.volumeID]; ok {
outcome = "controller: " + o
} else {
outcome = "controller: no outcome (the submission did not carry the volume)"
}
}
h.log.Printf("blockmaster: promotion gate volume=%s decision=%s %s", d.volumeID, d.decision, outcome)
}
}
func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int, int, []authority.AssignmentAsk) {
@@ -376,6 +426,7 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
// decision names, on the gate's line, the branch this tick took, so a
// volume that keeps a lost primary says why.
decision := ""
replaceDecided := false // the gate decided to replace the primary (reported after the submit)
switch {
case !replaceWanted:
decision = "keep_current(" + gateAcceptance(vol.Slots[currentIdx], serverIndex, h.placementEligible(vol.Slots[currentIdx].ServerID)) + ")"
@@ -402,6 +453,7 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
} else if (len(allowed) > 0 || emptyVolumeSurvivors(result, ok)) && replacing {
result, allowed = h.fencedDecision(vol.VolumeID, vol.Authority, result, len(candidates))
fencedReplace = len(allowed) > 0
replaceDecided = true
decision = fmt.Sprintf("replace(fenced_at=%d)", vol.Authority.Epoch+1)
if len(allowed) == 0 {
decision = "replace(fencing_round_published_nothing)"
@@ -417,8 +469,12 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
}
}
if decision == "" && replacing {
replaceDecided = true
decision = "replace(no_candidate_to_fence)"
}
if replaceDecided {
h.noteGateReplace(vol.VolumeID, decision)
}
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 primary_lost=%t decision=%s",
vol.VolumeID, vol.Authority.ReplicaID, result.CurrentKnown, result.Current.Ready, result.AckProfile, result.SyncAckLSN, result.Candidates, allowed, lost, decision)
@@ -957,13 +1013,19 @@ func (h *Host) recordVolumeBlockedEvent(volumeID, reason string) {
}
func (h *Host) recordAuthorityPublishedEvent(event authority.PublishEvent) {
if h == nil || h.events == nil {
if h == nil {
return
}
message := fmt.Sprintf("authority published replica %s epoch=%d endpoint_version=%d", event.Info.ReplicaID, event.Info.Epoch, event.Info.EndpointVersion)
if event.Ask.Intent == authority.IntentReassign {
message = fmt.Sprintf("authority reassigned to replica %s epoch=%d endpoint_version=%d", event.Info.ReplicaID, event.Info.Epoch, event.Info.EndpointVersion)
}
if h.log != nil {
h.log.Printf("blockmaster: volume=%s %s (%s)", event.Info.VolumeID, message, event.Ask.Intent)
}
if h.events == nil {
return
}
h.events.append(ops.ClusterEvent{
VolumeID: event.Info.VolumeID,
ReplicaID: event.Info.ReplicaID,
+3
View File
@@ -1377,6 +1377,8 @@ Notes:
| `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` | The automatic path never replaces a lost primary of a `best_effort` volume (a write may be on the primary alone, as for the operator's move): both gates hold it before any fencing round and show `best_effort_no_automatic_failover`. | M3 Supporting → promotion candidate (both gates) | `core/host/master/product_loop.go` `automaticFailoverHold` (supported gate before `fencedDecision`; unsupported gate before its candidates); `promotionAllowedReplicas` | `TestTheAutomaticPathHoldsABestEffortVolume` (`core/host/master/best_effort_hold_test.go`); `TestMountedFailover_ProductLoopRF3BestEffortIsHeldDespiteAHighestDurableSurvivor`, `TestMountedFailover_ProductLoopRF3RejectsBestEffortProbeForHA` (`core/host/master/product_loop_test.go`); `TestPromotionAllowedReplicas_RequiredFrontierCoverage` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE |
| `INV-PROMOTE-ACK-PROFILE-MATCH-001` | The automatic path holds a lost primary's volume, before any fencing round and showing `ack_profile_mismatch`, when a probe answer names no ack profile or another than blockmaster's `--launcher-replication-ack`; blockmaster refuses to start with an unknown one. | M3 Supporting → promotion candidate (both gates) | `core/host/master/probe_round.go` `profileMismatch`; `core/host/master/product_loop.go` `automaticFailoverHold` (plain round), `fencedDecision` (fencing round); `core/host/volume/probe_round.go` `probeAnswer`; `cmd/blockvolume/main.go` `hostConfig`; `cmd/blockmaster/main.go` `parseFlags` | `TestTheAutomaticPathHoldsOnAnAckProfileMismatch`, `TestProbeRound_ReportsAnAckProfileMismatch`, `TestTheFencingRoundsAckProfileIsCheckedToo` (`core/host/master/ack_profile_mismatch_test.go`); `TestProbeAnswerNamesTheVolumesAckProfile` (`core/host/volume/probe_ack_profile_test.go`); `TestHostConfigAnswersTheVolumesOwnAckProfile` (`cmd/blockvolume/probe_ack_profile_test.go`); `TestBlockmasterRefusesAnUnknownLauncherReplicationAck` (`cmd/blockmaster/launcher_replication_ack_flag_test.go`) | — | ACTIVE |
| `INV-PROMOTE-DECISION-REPORTED-001` | Every replace decision of the supported promotion gate is logged once after its tick: with the controller's outcome from the same submission (read under its lock, so a later intake cannot change it), as not submitted and why, or as a failed submit. Diagnostics only: no decision changes. | M3 Supporting → promotion candidate (supported gate → controller → publisher) | `core/host/master/product_loop.go` `submitPlacementSnapshots`, `noteGateReplace`, `reportReplaces`; `core/authority/controller.go` `SubmitObservedStateOutcomes`, `LastOutcome` | `TestAReplaceDecisionLogsWhatTheControllerDidWithIt` (cases: enqueued, already desired, no ask with why, not submitted, an intake after the submission does not change its report, a submission that did not carry the volume, one report per decision), `TestAProductTickReplaceLogsTheControllerOutcomeAndThePublication`, `TestABindingReadFailureAfterTheProbeReportsTheDecisionNotSubmitted` (`core/host/master/gate_controller_outcome_test.go`, `core/host/master/gate_binding_read_failure_test.go`) | — (diagnostics; no published specification models the log) | ACTIVE |
| `INV-AUTHORITY-PUBLICATION-LOGGED-001` | Every authority publication is logged on the master's log with its volume, replica, epoch, endpoint version and intent, also when no event sink is set. Diagnostics only: no decision changes. | M3 controller → publisher (publication observer) | `core/host/master/product_loop.go` `recordAuthorityPublishedEvent` | `TestAPublicationIsLogged`, `TestAProductTickReplaceLogsTheControllerOutcomeAndThePublication` (`core/host/master/gate_controller_outcome_test.go`) | — (diagnostics; no published specification models the log) | ACTIVE |
| `INV-PRIMARY-ACK-PROFILE-001` | A primary of a replicated line serves only when its own `--replication-ack` is the profile its assignment names (blockmaster's); otherwise its frontend is not Healthy and status names both profiles. So a lost primary, which does not answer, acknowledged under the master's profile. | M1 Primary → Serving (replicated line) | `core/host/master/services.go` `assignmentFact` (`ack_profile`); `core/host/volume/workspace_startup.go` `noteAckProfile`; `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/host/volume/status_server.go` | `TestPrimaryOfAReplicatedLineServesOnlyUnderTheMastersAckProfile` (`core/host/volume/ack_profile_refusal_test.go`); `TestAssignmentNamesTheMastersAckProfile` (`core/host/master/ack_profile_mismatch_test.go`) | — | ACTIVE |
| `INV-CSI-CONSUMES-AUTHORITY-001` | CSI never imports authority code or builds assignment facts; it takes the publish target from blockmaster and refreshes it before a stage, and blockmaster mints the IDs of the events CSI reports. | M2 (read side) | `core/csi/master_backend.go` `LookupPublishTarget`; `core/csi/node.go` `refreshPublishContext`; `core/host/master/observation_service.go` `ReportClusterEvent` | `TestG15a_CSI_DoesNotImportAuthorityOrConstructAssignmentFacts` (`core/csi/boundary_guard_test.go`); `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestObservationService_ReportClusterEventAppearsInVolumeTimeline` (`core/host/master/observation_service_test.go`) | — | ACTIVE |
| `INV-K8S-NONLOOPBACK-001` | Generated multi-node Helm values enable external iSCSI, external status and loopback rejection; with rejection enabled CSI never publishes a loopback target and fails closed when only loopback targets exist. | M2 (read side) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`; `core/csi/master_backend.go` `rejectFrontendAddr` | `TestOpsGenerateHelmValuesMultiNodeExternalISCSI` (`cmd/sw-block/main_test.go`); `TestNodeLoss_ControlStatusLookup_RejectsLoopbackPublishTargetsWhenEnabled`, `TestNodeLoss_ControlStatusLookup_FailClosedWhenOnlyLoopbackTargets` (`core/csi/master_backend_test.go`) | — | ACTIVE |
@@ -1398,6 +1400,7 @@ Notes:
- `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 every volume with two or more slots (RF=2 included); a primary change is published only with its evidence.
- `INV-PROMOTE-DECISION-REPORTED-001`: a decision is not submitted when the placements changed during the probe, a volume got a workspace binding, a replica's endpoints are bound elsewhere, or the workspace bindings could not be read after the probe; the line names which. `INV-AUTHORITY-PUBLICATION-LOGGED-001` was split from it.
- `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.