From a837a67ec618c335ba75dd0db9e6cefd20a12e69 Mon Sep 17 00:00:00 2001 From: wzcheng99 Date: Sun, 19 Apr 2026 21:33:42 -0700 Subject: [PATCH] P14 S6: convergence institution (bounded wait + stuck evidence) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Turns controller desired assignments into a bounded-fate closure: confirmed, retried (passively), superseded, or surfaced as stuck evidence — without minting new authority. - DesiredAssignment: +ProposedBasis/DesiredAt/LastRetryAt/Stuck. - TopologyControllerConfig: +RetryWindow (default 5s). - convergence.go: ConvergenceStuckEvidence (distinct map from UnsupportedEvidence), supersedeDesiredLocked (case 1 only: publisher epoch > ProposedBasis AND different target — case 2 dropped because it misclassified every in-flight Reassign), evaluateStuckLocked (passive; does NOT re-emit). - controller.go: unified processSupportedVolumeLocked; confirm routes through clearDesiredLocked so late post-Stuck confirmations drop stuck evidence; supported-recovery clears prior UnsupportedEvidence. L0 (convergence_test.go): 15 targeted proofs — confirmation (both-sources, stale-observation guard), stuck (after window, no Reassign churn, clears on late confirm), supersede (publisher moved elsewhere, normal-lag is NOT supersede, decision-table differs), pending/unsupported clearing, per-volume isolation, supported-recovery evidence cleanup. L1 (convergence_route_test.go): 3 component-route proofs through ObservationHost -> TopologyController -> Publisher -> VolumeBridge -> Consumer: observation-fed failover confirms, publish-but-not-observed reaches Stuck with no duplicate bridge delivery, supersede drops stale desired. No engine/adapter/transport changes. S2 non-forgeability and S5 store-write guards still pass. Co-Authored-By: Claude Opus 4.7 (1M context) --- seaweed-block/core/authority/controller.go | 262 ++++--- seaweed-block/core/authority/convergence.go | 142 ++++ .../core/authority/convergence_route_test.go | 484 ++++++++++++ .../core/authority/convergence_test.go | 698 ++++++++++++++++++ seaweed-block/core/authority/topology.go | 49 +- 5 files changed, 1538 insertions(+), 97 deletions(-) create mode 100644 seaweed-block/core/authority/convergence.go create mode 100644 seaweed-block/core/authority/convergence_route_test.go create mode 100644 seaweed-block/core/authority/convergence_test.go diff --git a/seaweed-block/core/authority/controller.go b/seaweed-block/core/authority/controller.go index 8d9ef7fd04..c0f65daf8d 100644 --- a/seaweed-block/core/authority/controller.go +++ b/seaweed-block/core/authority/controller.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "sync" + "time" ) // TopologyController is the multi-volume, cluster-scoped directive @@ -24,21 +25,34 @@ type TopologyController struct { reader AuthorityBasisReader queue *assignmentQueue - mu sync.Mutex - desired map[string]DesiredAssignment - unsupported map[string]UnsupportedEvidence + mu sync.Mutex + desired map[string]DesiredAssignment + unsupported map[string]UnsupportedEvidence + convergenceStuck map[string]*ConvergenceStuckEvidence + now func() time.Time } func NewTopologyController(config TopologyControllerConfig, reader AuthorityBasisReader) *TopologyController { return &TopologyController{ - config: config.withDefaults(), - reader: reader, - queue: newAssignmentQueue(), - desired: make(map[string]DesiredAssignment), - unsupported: make(map[string]UnsupportedEvidence), + config: config.withDefaults(), + reader: reader, + queue: newAssignmentQueue(), + desired: make(map[string]DesiredAssignment), + unsupported: make(map[string]UnsupportedEvidence), + convergenceStuck: make(map[string]*ConvergenceStuckEvidence), + now: time.Now, } } +// SetNowForTest overrides the controller's clock source. Tests +// use this to drive RetryWindow / Stuck transitions deterministically. +// Production code MUST NOT call this. +func (c *TopologyController) SetNowForTest(now func() time.Time) { + c.mu.Lock() + defer c.mu.Unlock() + c.now = now +} + // SubmitClusterSnapshot is the cluster-scoped entry point for // topology, health, and convergence observations. Rejects empty // snapshots to preserve the "supported truth only" invariant on @@ -74,46 +88,7 @@ func (c *TopologyController) SubmitClusterSnapshot(snap ClusterSnapshot) error { for _, vol := range volumes { currentLine, hasLine := c.reader.VolumeAuthorityLine(vol.VolumeID) - c.confirmDesiredLocked(vol, currentLine, hasLine) - - // Snapshot-side topology honesty. - 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) - continue - } - // Publisher-side out-of-topology authority. - if hasLine && !volumeIncludesReplica(vol, currentLine.ReplicaID) { - c.recordUnsupportedLocked(vol.VolumeID, snap, currentLine, "publisher authority outside accepted topology: "+currentLine.ReplicaID) - c.clearDesiredLocked(vol.VolumeID) - continue - } - // Stale snapshot: do not emit from a stale basis. - if !basisMatchesLine(vol.Authority, currentLine, hasLine) { - // Keep any existing desired state. A stale snapshot often - // means the publisher has already advanced the line but the - // collector has not yet observed it; clearing desired here - // would drop the publish-until-observed convergence record - // too early. - continue - } - - ask, reason, emit := c.decideVolume(vol, serverIndex, currentLine, hasLine, currentLoad, projectedLoad) - if !emit { - c.clearDesiredLocked(vol.VolumeID) - continue - } - desired := DesiredAssignment{ - Ask: ask, - Reason: reason, - Revision: snap.CollectedRevision, - } - if prev, ok := c.desired[vol.VolumeID]; ok && sameAsk(prev.Ask, ask) { - continue - } - c.desired[vol.VolumeID] = desired - c.queue.enqueue(ask) - applyProjectedMove(projectedLoad, vol, currentLine, hasLine, ask) + c.processSupportedVolumeLocked(vol, snap, serverIndex, currentLine, hasLine, currentLoad, projectedLoad) } return nil } @@ -211,53 +186,112 @@ func (c *TopologyController) SubmitObservedState(snap ClusterSnapshot, report Su projectedLoad := cloneLoad(currentLoad) for _, vol := range volumes { currentLine, hasLine := c.reader.VolumeAuthorityLine(vol.VolumeID) - c.confirmDesiredLocked(vol, currentLine, hasLine) - - 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) - continue - } - 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) - continue - } - // Stale snapshot: do not emit from a stale basis, but keep - // any existing desired state (publish-until-observed - // convergence record). Mirrors SubmitClusterSnapshot. - if !basisMatchesLine(vol.Authority, currentLine, hasLine) { - continue - } - - ask, reason, emit := c.decideVolume(vol, serverIndex, currentLine, hasLine, currentLoad, projectedLoad) - // No action needed under this snapshot (e.g. current slot - // recovered, rebalance no longer desired). Clear any prior - // desired ask so a stale queued move cannot survive - // supported recovery. - if !emit { - c.clearDesiredLocked(vol.VolumeID) - continue - } - desired := DesiredAssignment{ - Ask: ask, - Reason: reason, - Revision: snap.CollectedRevision, - } - // Same-ask dedupe: if the identical ask is already queued - // and desired, do not re-enqueue. Without this guard, - // repeated 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) { - continue - } - c.desired[vol.VolumeID] = desired - c.queue.enqueue(ask) - applyProjectedMove(projectedLoad, vol, currentLine, hasLine, ask) + c.processSupportedVolumeLocked(vol, snap, serverIndex, currentLine, hasLine, currentLoad, projectedLoad) } return nil } +// processSupportedVolumeLocked is the shared supported-volume +// convergence loop used by both SubmitClusterSnapshot and +// SubmitObservedState. Per-iteration order (§5.2): +// +// 1. confirmDesiredLocked — if confirmation contract is +// satisfied, clear desired + stuck evidence (Active→None). +// 2. supersedeDesiredLocked — §9 case 1/2: drop desired if +// publisher itself has moved past the proposed basis to a +// different replica, or observation and publisher agree on a +// different outcome. Case 3 ("decision produces different +// ask") is covered by the same-ask dedupe further below. +// 3. Topology-honesty checks (clear desired on out-of-topology +// authority from either side). +// 4. evaluateStuckLocked — if desired still outstanding, mark +// Stuck when DesiredAt + RetryWindow has elapsed. Runs +// before the stale-basis continue so publish-but-not- +// observed scenarios can surface Stuck evidence. +// 5. Stale-basis continue — keep desired, no decide this tick. +// 6. decideVolume + same-ask dedupe + enqueue. On enqueue, +// DesiredAt is anchored (or re-anchored) to c.now(). +func (c *TopologyController) processSupportedVolumeLocked( + vol VolumeTopologySnapshot, + snap ClusterSnapshot, + serverIndex map[string]ServerObservation, + currentLine AuthorityBasis, + hasLine bool, + currentLoad map[string]int, + projectedLoad map[string]int, +) { + // A volume appearing in the supported set means observation + // cleared every supportability rule for it. Any prior + // unsupported evidence for this volume must drop — otherwise + // LastUnsupported() would keep reporting a stale fault after + // the volume is healthy. (Regression from the pre-refactor + // S4 behavior; stuck evidence has its own lifecycle and is + // NOT cleared here — §10 clearing rule 4.) + delete(c.unsupported, vol.VolumeID) + + c.confirmDesiredLocked(vol, currentLine, hasLine) + + if c.supersedeDesiredLocked(vol, currentLine, hasLine) { + // fall through — decideVolume may emit a new ask this tick. + } + + 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) + 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) + return + } + + // Evaluate stuck state for any still-outstanding desired. This + // must run before the stale-basis continue so "publish-but- + // not-observed" — which shows up here as a stale basis — can + // surface ConvergenceStuckEvidence after the retry window. + c.evaluateStuckLocked(vol.VolumeID) + + // 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) { + return + } + + ask, reason, emit := c.decideVolume(vol, serverIndex, currentLine, hasLine, currentLoad, projectedLoad) + if !emit { + c.clearDesiredLocked(vol.VolumeID) + return + } + // Same-ask dedupe: if the identical ask is already the current + // desired, do not re-enqueue. Without this guard, repeated + // 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) { + return + } + + // A different ask (or a new desired from None) replaces any + // prior stuck evidence — the old stuck record no longer + // describes the currently-outstanding desired (§10 clearing + // rule 2). + c.clearConvergenceStuckLocked(vol.VolumeID) + + desired := DesiredAssignment{ + Ask: ask, + Reason: reason, + Revision: snap.CollectedRevision, + ProposedBasis: currentLine, + DesiredAt: c.now(), + } + if !hasLine { + desired.ProposedBasis = AuthorityBasis{} + } + c.desired[vol.VolumeID] = desired + c.queue.enqueue(ask) + applyProjectedMove(projectedLoad, vol, currentLine, hasLine, ask) +} + // joinReasons returns a stable comma-joined reason string from // the observation-layer vocabulary. Used to carry the observation // reason set into the controller's per-volume evidence slot. @@ -287,9 +321,45 @@ func (c *TopologyController) LastUnsupported(volumeID string) (UnsupportedEviden return ev, ok } +// LastConvergenceStuck returns the per-volume +// ConvergenceStuckEvidence if the desired assignment for this +// volume is currently Stuck. Returns (_, false) when no desired +// is outstanding, when a desired is outstanding but still within +// the retry window, or when the desired was confirmed / +// superseded / cleared. +// +// Returned value is a copy: mutating it does not affect +// controller state. +func (c *TopologyController) LastConvergenceStuck(volumeID string) (ConvergenceStuckEvidence, bool) { + c.mu.Lock() + defer c.mu.Unlock() + ev, ok := c.convergenceStuck[volumeID] + if !ok { + return ConvergenceStuckEvidence{}, false + } + return *ev, true +} + +// DesiredFor returns a copy of the current DesiredAssignment for +// one volume, if any. Test-surface accessor; production code +// should observe convergence outcomes through the publisher +// stream and snapshot feeds, not by reading desired state. +func (c *TopologyController) DesiredFor(volumeID string) (DesiredAssignment, bool) { + c.mu.Lock() + defer c.mu.Unlock() + d, ok := c.desired[volumeID] + return d, ok +} + func (c *TopologyController) clearDesiredLocked(volumeID string) { delete(c.desired, volumeID) c.queue.discard(volumeID) + // §10 clearing rule 1 / 2 / 3: whenever the desired clears + // (confirmed, superseded, supportability-driven), the stuck + // evidence clears with it. Supportability regaining does NOT + // invoke this path — that is handled by the supported-volume + // loop (§10 clearing rule 4). + c.clearConvergenceStuckLocked(volumeID) } func (c *TopologyController) recordUnsupportedLocked(volumeID string, snap ClusterSnapshot, basis AuthorityBasis, reason string) { @@ -307,8 +377,14 @@ func (c *TopologyController) confirmDesiredLocked(vol VolumeTopologySnapshot, cu return } if desiredObserved(desired, vol, currentLine, hasLine) { - delete(c.desired, vol.VolumeID) - c.queue.discard(vol.VolumeID) + // Route through clearDesiredLocked so §10 clearing rule 1 + // (stuck evidence clears with the desired) applies to + // late confirmations that happen AFTER the volume had + // already transitioned into Stuck. Deleting the desired + // entry directly here would leave c.convergenceStuck[vid] + // populated, reporting a volume as still stuck after + // convergence had actually completed. + c.clearDesiredLocked(vol.VolumeID) } } diff --git a/seaweed-block/core/authority/convergence.go b/seaweed-block/core/authority/convergence.go new file mode 100644 index 0000000000..e762e05204 --- /dev/null +++ b/seaweed-block/core/authority/convergence.go @@ -0,0 +1,142 @@ +package authority + +import "time" + +// ============================================================ +// P14 S6 — Convergence Institution +// +// This file contains the bookkeeping types and helpers for the +// convergence loop: supersede detection, bounded-wait stuck +// evaluation, and per-volume ConvergenceStuckEvidence. +// +// S6 scope (sw-block/design/v3-phase-14-s6-sketch.md): +// - convergence NEVER mints authority — only the publisher does +// - retry is PASSIVE (§7.1): the controller does not re-emit +// into the publisher; it waits for the next observation and +// re-evaluates via the existing decision + same-ask-dedupe +// path. Bounded-wait + stuck evidence is the surface, not +// re-drive. +// - ConvergenceStuck evidence lives in its OWN map, distinct +// from UnsupportedEvidence (§10). Supported-volume paths +// clear the unsupported map; clearing stuck evidence is +// driven by the desired lifecycle, not by supportability. +// ============================================================ + +// ReasonConvergenceStuck is the pinned reason constant recorded +// on every ConvergenceStuckEvidence value. Distinct from the S4 +// supportability reasons (PartialInventory, etc.) so consumers +// cannot blur "do not act because topology unsupported" with +// "desired still wanted but not observed yet". +const ReasonConvergenceStuck = "ConvergenceStuck" + +// ConvergenceStuckEvidence is the per-volume record that a +// desired assignment remained unconfirmed past RetryWindow. It +// is surfaced to 14A review / future operator diagnostics, but +// the desired entry itself is NOT cleared by going Stuck — the +// controller still wants that outcome and a later observation +// can still confirm it. +// +// A volume's ConvergenceStuckEvidence is cleared when: +// 1. The desired entry clears (Confirmed, Cleared by +// supportability transition, or Superseded). +// 2. A new desired entry replaces the old one (the new entry +// starts its own DesiredAt clock — the prior stuck record +// no longer describes outstanding convergence). +// +// Supportability regaining does NOT touch stuck evidence. +type ConvergenceStuckEvidence struct { + VolumeID string + Ask AssignmentAsk + ProposedBasis AuthorityBasis + DesiredAt time.Time + StuckAt time.Time + Reason string +} + +// supersedeDesiredLocked applies §9 supersede case 1 for one +// supported volume: publisher line is strictly newer than +// ProposedBasis AND targets a replica other than the desired +// target. This is the "publisher itself has moved past the +// basis we authored against, to somewhere else" case — genuine +// supersede. +// +// Sketch §9 case 2 (observation and publisher agree on a +// different replica) is intentionally NOT implemented: during a +// normal in-flight Reassign from r1→r2, both observation and +// publisher correctly still report r1 up until the publisher +// applies the ask. A literal case-2 rule would mis-classify +// every Reassign as "superseded before it could publish." Case +// 1's strict-epoch-advance gate already captures every real +// supersede: if publisher has moved elsewhere, its Epoch has +// advanced past ProposedBasis. +// +// Rule 3 (decision table produces a different ask) is handled +// implicitly by the same-ask dedupe in the supported-volume +// loop: a differing ask simply overwrites the desired entry at +// enqueue time, and clearConvergenceStuckLocked is called to +// drop any prior stuck record. Rule 4 (supportability +// transition) is handled by the pending/unsupported intake +// path, which calls clearDesiredLocked. +// +// Normal-lag cases that are NOT supersede (confirmation waits +// them out): +// +// - observed ReplicaID ≠ desired target while publisher still +// matches ProposedBasis (publisher hasn't applied yet) +// - publisher matches desired target while observation still +// reports old authority (observation lags publisher) +// - publisher matches desired target and observation matches +// publisher (Active → None via confirmDesiredLocked) +// +// Returns true if the desired was superseded (and removed). +func (c *TopologyController) supersedeDesiredLocked(vol VolumeTopologySnapshot, currentLine AuthorityBasis, hasLine bool) bool { + desired, ok := c.desired[vol.VolumeID] + if !ok { + return false + } + if hasLine && + currentLine.Epoch > desired.ProposedBasis.Epoch && + currentLine.ReplicaID != desired.Ask.ReplicaID { + c.clearDesiredLocked(vol.VolumeID) + return true + } + return false +} + +// evaluateStuckLocked transitions an unconfirmed desired entry +// to Stuck once DesiredAt + RetryWindow has elapsed. Stuck does +// not re-emit; it records evidence and updates the desired entry +// in place so future observations can still confirm / supersede. +// +// LastRetryAt is updated on every call (even before Stuck fires) +// so §13 proof row 12 "retry state is per-volume" can observe +// that the clock is per-desired, not global. +func (c *TopologyController) evaluateStuckLocked(volumeID string) { + desired, ok := c.desired[volumeID] + if !ok { + return + } + now := c.now() + desired.LastRetryAt = now + if !desired.Stuck && !desired.DesiredAt.IsZero() && + now.Sub(desired.DesiredAt) >= c.config.RetryWindow { + desired.Stuck = true + c.convergenceStuck[volumeID] = &ConvergenceStuckEvidence{ + VolumeID: volumeID, + Ask: desired.Ask, + ProposedBasis: desired.ProposedBasis, + DesiredAt: desired.DesiredAt, + StuckAt: now, + Reason: ReasonConvergenceStuck, + } + } + c.desired[volumeID] = desired +} + +// clearConvergenceStuckLocked removes the stuck evidence for one +// volume. Called from every desired-clearing path (confirmed, +// superseded, supportability-cleared) so evidence never outlives +// the outstanding desired. +func (c *TopologyController) clearConvergenceStuckLocked(volumeID string) { + delete(c.convergenceStuck, volumeID) +} diff --git a/seaweed-block/core/authority/convergence_route_test.go b/seaweed-block/core/authority/convergence_route_test.go new file mode 100644 index 0000000000..7b90b47ef8 --- /dev/null +++ b/seaweed-block/core/authority/convergence_route_test.go @@ -0,0 +1,484 @@ +package authority + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" +) + +// ============================================================ +// P14 S6 — L1 Component Route Tests +// +// These tests exercise the full observation-fed convergence +// pipeline end-to-end: +// +// ObservationHost → TopologyController → Publisher +// → VolumeBridge → Consumer +// +// L0 unit tests in convergence_test.go cover the controller's +// lifecycle / retry / supersede / clearing rules in isolation +// with direct SubmitObservedState calls. These L1 tests verify +// that the SAME rules hold when driven through the real +// observation host and real publisher mint path — i.e. that +// confirmation clearing, Stuck evidence, and supersede dropping +// survive the routing layer. +// +// Architect requested three routes (plus an optional fourth): +// +// 1. Observation-fed failover is confirmed end-to-end and +// clears desired. +// 2. Publish-but-not-observed: publisher advances, observation +// stays stale → desired Active, RetryWindow expiry produces +// ConvergenceStuckEvidence, no duplicate Reassign emitted. +// 3. Supersede: publisher advances to a replica other than +// desired target → old desired cleared, no stale ask +// published. +// ============================================================ + +// ============================================================ +// Shared helpers for L1 route tests +// ============================================================ + +// snapshottingReader wraps an AuthorityBasisReader but can be +// frozen at a point in time. While frozen it returns the view +// captured at Freeze() time; while thawed it delegates to the +// underlying reader (live publisher state). +// +// Used by the publish-but-not-observed test to simulate an +// observation layer that has not yet caught up to the publisher. +// The controller still holds the live publisher as its own +// reader — only the observation-host builder is stalled, which +// is the production-realistic shape. +type snapshottingReader struct { + underlying AuthorityBasisReader + + mu sync.Mutex + frozen bool + perVol map[string]AuthorityBasis + perSlot map[string]AuthorityBasis +} + +func newSnapshottingReader(u AuthorityBasisReader) *snapshottingReader { + return &snapshottingReader{ + underlying: u, + perVol: map[string]AuthorityBasis{}, + perSlot: map[string]AuthorityBasis{}, + } +} + +func (s *snapshottingReader) Freeze(volumeIDs ...string) { + s.mu.Lock() + defer s.mu.Unlock() + s.frozen = true + for _, vid := range volumeIDs { + if b, ok := s.underlying.VolumeAuthorityLine(vid); ok { + s.perVol[vid] = b + s.perSlot[vid+"/"+b.ReplicaID] = b + } + } +} + +func (s *snapshottingReader) Thaw() { + s.mu.Lock() + s.frozen = false + s.perVol = map[string]AuthorityBasis{} + s.perSlot = map[string]AuthorityBasis{} + s.mu.Unlock() +} + +func (s *snapshottingReader) LastAuthorityBasis(volumeID, replicaID string) (AuthorityBasis, bool) { + s.mu.Lock() + if s.frozen { + b, ok := s.perSlot[volumeID+"/"+replicaID] + s.mu.Unlock() + return b, ok + } + s.mu.Unlock() + return s.underlying.LastAuthorityBasis(volumeID, replicaID) +} + +func (s *snapshottingReader) VolumeAuthorityLine(volumeID string) (AuthorityBasis, bool) { + s.mu.Lock() + if s.frozen { + b, ok := s.perVol[volumeID] + s.mu.Unlock() + return b, ok + } + s.mu.Unlock() + return s.underlying.VolumeAuthorityLine(volumeID) +} + +// buildV1Heartbeats returns the three-server heartbeat set for +// a volume "v1" with r1/r2/r3 slots. The caller picks which +// slot(s) are unreachable via the unreachable map. +func buildV1Heartbeats(at time.Time, unreachable map[string]bool) []HeartbeatMessage { + replicas := []struct{ server, replica string }{ + {"s1", "r1"}, + {"s2", "r2"}, + {"s3", "r3"}, + } + out := make([]HeartbeatMessage, 0, len(replicas)) + for _, r := range replicas { + slot := healthySlot("v1", r.replica) + if unreachable[r.replica] { + slot.Reachable = false + slot.ReadyForPrimary = false + } + out = append(out, serverObs(r.server, at, slot)) + } + return out +} + +// waitForConsumerMatch polls consumer until pred returns true on +// the most recent delivery, or deadlines out. +func waitForConsumerMatch(t *testing.T, cons *recordingConsumer, pred func(adapter.AssignmentInfo) bool) adapter.AssignmentInfo { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + seen := cons.snapshot() + if len(seen) > 0 && pred(seen[len(seen)-1]) { + return seen[len(seen)-1] + } + time.Sleep(10 * time.Millisecond) + } + seen := cons.snapshot() + t.Fatalf("consumer did not see matching assignment within deadline, last=%+v", seen) + return adapter.AssignmentInfo{} +} + +// waitForDesiredCleared polls until ctrl.DesiredFor(vid) is +// empty, or deadlines out. +func waitForDesiredCleared(t *testing.T, ctrl *TopologyController, vid string) { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if _, ok := ctrl.DesiredFor(vid); !ok { + return + } + time.Sleep(10 * time.Millisecond) + } + d, _ := ctrl.DesiredFor(vid) + t.Fatalf("desired for %s not cleared within deadline, got %+v", vid, d) +} + +// ============================================================ +// Route 1: ObservationHost → Controller → Publisher → +// VolumeBridge → Consumer. Happy path: failover confirms and +// desired clears. +// ============================================================ + +func TestConvergenceRoute_ObservationFedFailover_ConfirmsAndClearsDesired(t *testing.T) { + start := time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + + holder := &basisReaderHolder{} + ctrl := NewTopologyController(TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + RebalanceSkew: 100, // keep rebalance out of the picture + RetryWindow: 5 * time.Second, + }, holder) + ctrl.SetNowForTest(clk.Now) + + pub := NewPublisher(ctrl) + holder.set(pub) + + host := NewObservationHost(ObservationHostConfig{ + Freshness: FreshnessConfig{FreshnessWindow: 30 * time.Second, PendingGrace: 10 * time.Millisecond}, + Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}}, + Sink: ctrl, + Reader: holder, + Now: clk.Now, + }) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + cons := &recordingConsumer{} + go pub.Run(ctx) + go VolumeBridge(ctx, pub, cons, "v1", "r1", "r2", "r3") + host.Start(ctx) + defer host.Stop() + + // Phase 1: all three slots healthy. Controller must bind v1 + // to r1 (tiebreak by replica ID), publisher mints r1@1, bridge + // delivers to consumer. + for _, hb := range buildV1Heartbeats(start, nil) { + if err := host.IngestHeartbeat(hb); err != nil { + t.Fatalf("ingest: %v", err) + } + } + r1Line := waitForConsumerMatch(t, cons, func(info adapter.AssignmentInfo) bool { + return info.ReplicaID == "r1" && info.Epoch == 1 + }) + // Note: Bind(r1) desired does NOT clear between phases. + // Confirmation requires a subsequent host rebuild (next + // ingest) to observe Authority=r1@1 and run the confirmation + // contract. Phase 2's first ingest will both confirm Bind + // AND emit Reassign(r2) in the same SubmitObservedState call + // — that's the correct S6 semantic. + + // Phase 2: r1 becomes unreachable. Controller decides failover + // to r2, publisher mints r2@2 (per-volume monotonic), bridge + // delivers. Desired remains Active until observation catches up. + clk.Advance(1 * time.Second) + for _, hb := range buildV1Heartbeats(clk.Now(), map[string]bool{"r1": true}) { + if err := host.IngestHeartbeat(hb); err != nil { + t.Fatalf("ingest: %v", err) + } + } + _ = waitForConsumerMatch(t, cons, func(info adapter.AssignmentInfo) bool { + return info.ReplicaID == "r2" && info.Epoch == r1Line.Epoch+1 + }) + + // Phase 3: observation catches up — next heartbeat with r2 + // healthy AND publisher now at r2@2, so the next rebuild + // stamps Authority=r2@2 on the supported snapshot. The + // controller's confirmation contract matches and clears + // desired. + clk.Advance(1 * time.Second) + for _, hb := range buildV1Heartbeats(clk.Now(), map[string]bool{"r1": true}) { + if err := host.IngestHeartbeat(hb); err != nil { + t.Fatalf("ingest: %v", err) + } + } + waitForDesiredCleared(t, ctrl, "v1") + if _, ok := ctrl.LastConvergenceStuck("v1"); ok { + t.Fatal("stuck evidence must not be present after confirmation") + } +} + +// ============================================================ +// Route 2: publish-but-not-observed. Publisher advances to the +// new line (consumer sees it), but observation stays frozen on +// the old line. Desired must remain Active; RetryWindow expiry +// must produce ConvergenceStuckEvidence; no duplicate Reassign +// is ever emitted. +// ============================================================ + +func TestConvergenceRoute_PublishNotObserved_StuckWithoutChurn(t *testing.T) { + start := time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + + holder := &basisReaderHolder{} + ctrl := NewTopologyController(TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + RebalanceSkew: 100, + RetryWindow: 2 * time.Second, + }, holder) + ctrl.SetNowForTest(clk.Now) + + pub := NewPublisher(ctrl) + holder.set(pub) + + // Host's builder reads Authority through a snapshotting + // reader. When frozen, it reports the captured pre-failover + // line even though the underlying publisher has already + // advanced. + hostReader := newSnapshottingReader(holder) + host := NewObservationHost(ObservationHostConfig{ + Freshness: FreshnessConfig{FreshnessWindow: 30 * time.Second, PendingGrace: 10 * time.Millisecond}, + Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}}, + Sink: ctrl, + Reader: hostReader, + Now: clk.Now, + }) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + cons := &recordingConsumer{} + go pub.Run(ctx) + go VolumeBridge(ctx, pub, cons, "v1", "r1", "r2", "r3") + host.Start(ctx) + defer host.Stop() + + // Phase 1: initial bind to r1. + for _, hb := range buildV1Heartbeats(start, nil) { + _ = host.IngestHeartbeat(hb) + } + _ = waitForConsumerMatch(t, cons, func(info adapter.AssignmentInfo) bool { + return info.ReplicaID == "r1" && info.Epoch == 1 + }) + + // Freeze host.Reader view at r1@1 BEFORE any further phase. + // Every subsequent rebuild will stamp supported snapshots with + // Authority=r1@1 regardless of what the publisher actually + // holds. The controller still uses the live publisher as its + // own reader, so its currentLine reflects reality — only the + // observation-fed Authority stays stale, which is the + // production-realistic "observation layer lags publisher" shape. + hostReader.Freeze("v1") + + // Phase 2: r1 unreachable → failover to r2. Publisher mints + // r2@2, consumer sees it. + clk.Advance(500 * time.Millisecond) + for _, hb := range buildV1Heartbeats(clk.Now(), map[string]bool{"r1": true}) { + _ = host.IngestHeartbeat(hb) + } + _ = waitForConsumerMatch(t, cons, func(info adapter.AssignmentInfo) bool { + return info.ReplicaID == "r2" && info.Epoch == 2 + }) + + // Record the current count of consumer deliveries; no new + // delivery should appear while we wait for Stuck. + baseline := len(cons.snapshot()) + + // Phase 3: drive ingests past RetryWindow while observation + // stays frozen. Stuck must fire; no duplicate Reassign may be + // emitted (the bridge would deliver one if it were). + for i := 0; i < 6; i++ { + clk.Advance(500 * time.Millisecond) + for _, hb := range buildV1Heartbeats(clk.Now(), map[string]bool{"r1": true}) { + _ = host.IngestHeartbeat(hb) + } + } + + // Poll for Stuck. Desired must still be present (bounded + // wait + evidence, not re-drive). + deadline := time.Now().Add(2 * time.Second) + stuck := false + for time.Now().Before(deadline) { + if _, ok := ctrl.LastConvergenceStuck("v1"); ok { + stuck = true + break + } + time.Sleep(10 * time.Millisecond) + } + if !stuck { + t.Fatal("expected ConvergenceStuckEvidence after RetryWindow with frozen observation") + } + if _, ok := ctrl.DesiredFor("v1"); !ok { + t.Fatal("desired must REMAIN Active while Stuck — passive retry only records evidence") + } + + // No new consumer delivery since baseline. If the controller + // had actively re-emitted, publisher would have minted a new + // epoch and bridge would have delivered it. + if delta := len(cons.snapshot()) - baseline; delta != 0 { + t.Fatalf("consumer saw %d additional deliveries during Stuck — indicates re-emission churn", delta) + } +} + +// ============================================================ +// Route 3: supersede. Controller has a desired Reassign(r2) +// outstanding. Publisher is independently advanced to r3 (as a +// second authority author would) past ProposedBasis. On the next +// observation, supersede must drop the old desired; no stale +// Reassign(r2) may leak to the consumer afterward. +// ============================================================ + +func TestConvergenceRoute_Supersede_PublisherMovedElsewhere_DropsStaleDesired(t *testing.T) { + start := time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + + holder := &basisReaderHolder{} + ctrl := NewTopologyController(TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + RebalanceSkew: 100, + RetryWindow: 30 * time.Second, // keep Stuck out of this test + }, holder) + ctrl.SetNowForTest(clk.Now) + + pub := NewPublisher(ctrl) + holder.set(pub) + + hostReader := newSnapshottingReader(holder) + host := NewObservationHost(ObservationHostConfig{ + Freshness: FreshnessConfig{FreshnessWindow: 30 * time.Second, PendingGrace: 10 * time.Millisecond}, + Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}}, + Sink: ctrl, + Reader: hostReader, + Now: clk.Now, + }) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + cons := &recordingConsumer{} + go pub.Run(ctx) + go VolumeBridge(ctx, pub, cons, "v1", "r1", "r2", "r3") + host.Start(ctx) + defer host.Stop() + + // Phase 1: initial bind to r1. + for _, hb := range buildV1Heartbeats(start, nil) { + _ = host.IngestHeartbeat(hb) + } + _ = waitForConsumerMatch(t, cons, func(info adapter.AssignmentInfo) bool { + return info.ReplicaID == "r1" && info.Epoch == 1 + }) + + // Freeze host reader at r1@1 — same rationale as the publish- + // but-not-observed route. + hostReader.Freeze("v1") + + // Phase 2: r1 unreachable → controller emits Reassign(r2). + // Publisher mints r2@2, consumer sees it. ProposedBasis + // captured by the controller is r1@1. + clk.Advance(500 * time.Millisecond) + for _, hb := range buildV1Heartbeats(clk.Now(), map[string]bool{"r1": true}) { + _ = host.IngestHeartbeat(hb) + } + _ = waitForConsumerMatch(t, cons, func(info adapter.AssignmentInfo) bool { + return info.ReplicaID == "r2" && info.Epoch == 2 + }) + + // Wait for desired to reflect the outstanding Reassign(r2). + deadline := time.Now().Add(1 * time.Second) + for time.Now().Before(deadline) { + if d, ok := ctrl.DesiredFor("v1"); ok && d.Ask.ReplicaID == "r2" { + break + } + time.Sleep(10 * time.Millisecond) + } + if d, ok := ctrl.DesiredFor("v1"); !ok || d.Ask.ReplicaID != "r2" { + t.Fatalf("precondition: desired must be Reassign(r2), got ok=%v d=%+v", ok, d) + } + + // Phase 3: another authority author advances the publisher to + // r3@3 (simulated via pub.apply — the publisher is still the + // sole minter; we're simulating a second in-process decision + // path writing through the same publisher, which is the + // supersede-relevant shape). + if err := pub.apply(AssignmentAsk{ + VolumeID: "v1", ReplicaID: "r3", DataAddr: "data-r3", CtrlAddr: "ctrl-r3", + Intent: IntentReassign, + }); err != nil { + t.Fatalf("pub.apply r3 Reassign: %v", err) + } + _ = waitForConsumerMatch(t, cons, func(info adapter.AssignmentInfo) bool { + return info.ReplicaID == "r3" && info.Epoch == 3 + }) + + // Record consumer count — no further Reassign(r2) may appear + // after supersede. + consBefore := len(cons.snapshot()) + + // Phase 4: next ingest → host rebuild. Controller's reader + // (the live publisher) now returns r3@3, which is strictly + // newer than ProposedBasis (r1@1) and targets a different + // replica than the desired target r2 → supersede fires. The + // host's frozen view still reports r2@2 as Authority so the + // stale-basis path doesn't short-circuit supersede (supersede + // is evaluated BEFORE basisMatchesLine per §9 / §7.2). + clk.Advance(500 * time.Millisecond) + for _, hb := range buildV1Heartbeats(clk.Now(), map[string]bool{"r1": true}) { + _ = host.IngestHeartbeat(hb) + } + waitForDesiredCleared(t, ctrl, "v1") + + // Sanity: stuck evidence was never recorded (RetryWindow is + // long) AND no stale Reassign(r2) leaked to the consumer + // after supersede. + if _, ok := ctrl.LastConvergenceStuck("v1"); ok { + t.Fatal("stuck evidence must not be present — supersede cleared desired before window elapsed") + } + // Give the publisher/bridge a moment to deliver anything + // queued before we read the final consumer count. + time.Sleep(60 * time.Millisecond) + for _, info := range cons.snapshot()[consBefore:] { + if info.ReplicaID == "r2" { + t.Fatalf("stale Reassign(r2) leaked to consumer after supersede: %+v", info) + } + } +} diff --git a/seaweed-block/core/authority/convergence_test.go b/seaweed-block/core/authority/convergence_test.go new file mode 100644 index 0000000000..f051c3082d --- /dev/null +++ b/seaweed-block/core/authority/convergence_test.go @@ -0,0 +1,698 @@ +package authority + +import ( + "context" + "testing" + "time" +) + +// ============================================================ +// P14 S6 — Convergence Institution proof tests +// +// Each test maps to a row in sw-block/design/v3-phase-14-s6- +// sketch.md §13 (Proof Matrix). The tests exercise the +// controller's convergence surface directly (no observation +// host) so the bounded-wait + stuck + supersede contracts can +// be verified independently of S4 plumbing. +// ============================================================ + +// convTestCtrl builds a controller wired to a fake clock and +// fake reader with an explicit retry window (explicit to keep +// the tests insensitive to default changes). Returns controller, +// reader, and clock. +func convTestCtrl(t *testing.T, retryWindow time.Duration) (*TopologyController, *fakeReaderForHost, *fakeClock) { + t.Helper() + reader := newFakeReaderForHost() + ctrl := NewTopologyController(TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + RetryWindow: retryWindow, + }, reader) + clk := newFakeClock(time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC)) + ctrl.SetNowForTest(clk.Now) + return ctrl, reader, clk +} + +// failoverSnapForV1 builds a v1 snapshot where r1 is +// 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). +func failoverSnapForV1(authority AuthorityBasis, rev uint64) ClusterSnapshot { + return ClusterSnapshot{ + CollectedRevision: rev, + CollectedAt: time.Now(), + Servers: []ServerObservation{ + {ServerID: "s1", Reachable: true, Eligible: true}, + {ServerID: "s2", Reachable: true, Eligible: true}, + {ServerID: "s3", Reachable: true, Eligible: true}, + }, + Volumes: []VolumeTopologySnapshot{{ + VolumeID: "v1", + 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}, + }, + }}, + } +} + +// healthySnapForV1 builds a v1 snapshot where ALL three slots +// are healthy. Used after a successful move to let the decision +// table settle (no emit). +func healthySnapForV1(authority AuthorityBasis, rev uint64) ClusterSnapshot { + snap := failoverSnapForV1(authority, rev) + snap.Volumes[0].Slots[0].Reachable = true + snap.Volumes[0].Slots[0].ReadyForPrimary = true + return snap +} + +// drainOneAsk returns the single ask currently queued or fails. +func drainOneAsk(t *testing.T, ctrl *TopologyController) AssignmentAsk { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + ask, err := ctrl.Next(ctx) + if err != nil { + t.Fatalf("expected one ask, got err: %v", err) + } + return ask +} + +// expectNoQueuedAsk asserts that no ask is currently queued. +func expectNoQueuedAsk(t *testing.T, ctrl *TopologyController) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Millisecond) + defer cancel() + if ask, err := ctrl.Next(ctx); err == nil { + t.Fatalf("expected no queued ask, got %+v", ask) + } +} + +// Row 1: observed confirmation clears desired (Active → None). +func TestConvergence_Confirmation_ClearsDesired(t *testing.T) { + ctrl, reader, _ := convTestCtrl(t, 5*time.Second) + + // Publisher holds r1@5. First submit produces Reassign to r2. + reader.SetVolume("v1", AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, + DataAddr: "d1", CtrlAddr: "c1", + }) + if err := ctrl.SubmitObservedState(failoverSnapForV1(AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, + DataAddr: "d1", CtrlAddr: "c1", + }, 1), SupportabilityReport{}); err != nil { + t.Fatalf("submit 1: %v", err) + } + _ = drainOneAsk(t, ctrl) + if _, ok := ctrl.DesiredFor("v1"); !ok { + t.Fatal("expected desired entry after emit") + } + + // Publisher applies: r2@6. Observation catches up to r2@6. + applied := AuthorityBasis{Assigned: true, ReplicaID: "r2", Epoch: 6, EndpointVersion: 1, DataAddr: "d2", CtrlAddr: "c2"} + reader.SetVolume("v1", applied) + if err := ctrl.SubmitObservedState(healthySnapForV1(applied, 2), SupportabilityReport{}); err != nil { + t.Fatalf("submit 2: %v", err) + } + if _, ok := ctrl.DesiredFor("v1"); ok { + t.Fatal("expected desired cleared after confirmation") + } + if _, ok := ctrl.LastConvergenceStuck("v1"); ok { + t.Fatal("expected stuck evidence cleared on confirmation") + } +} + +// Row 2: confirmation requires BOTH observation and publisher +// to agree. Publisher applied, observation still stale → NOT +// confirmed. +func TestConvergence_Confirmation_RequiresBothSources(t *testing.T) { + ctrl, reader, _ := convTestCtrl(t, 5*time.Second) + + reader.SetVolume("v1", AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, + DataAddr: "d1", CtrlAddr: "c1", + }) + stale := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"} + if err := ctrl.SubmitObservedState(failoverSnapForV1(stale, 1), SupportabilityReport{}); err != nil { + t.Fatalf("submit 1: %v", err) + } + _ = drainOneAsk(t, ctrl) + + // Publisher advances to r2@6 but observation still reports r1@5. + reader.SetVolume("v1", AuthorityBasis{ + Assigned: true, ReplicaID: "r2", Epoch: 6, EndpointVersion: 1, DataAddr: "d2", CtrlAddr: "c2", + }) + if err := ctrl.SubmitObservedState(failoverSnapForV1(stale, 2), SupportabilityReport{}); err != nil { + t.Fatalf("submit 2: %v", err) + } + if _, ok := ctrl.DesiredFor("v1"); !ok { + t.Fatal("desired must remain until observation confirms (not publisher alone)") + } +} + +// Row 3: stale observation cannot confirm. +func TestConvergence_StaleObservation_NoConfirmation(t *testing.T) { + ctrl, reader, _ := convTestCtrl(t, 5*time.Second) + + reader.SetVolume("v1", AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1", + }) + if err := ctrl.SubmitObservedState(failoverSnapForV1(AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1", + }, 1), SupportabilityReport{}); err != nil { + t.Fatalf("submit 1: %v", err) + } + _ = drainOneAsk(t, ctrl) + + // Publisher applied r2@6. Observation reports r2@5 (wrong + // epoch) — mismatch, not fresh. + reader.SetVolume("v1", AuthorityBasis{ + Assigned: true, ReplicaID: "r2", Epoch: 6, EndpointVersion: 1, DataAddr: "d2", CtrlAddr: "c2", + }) + obs := AuthorityBasis{Assigned: true, ReplicaID: "r2", Epoch: 5, EndpointVersion: 1, DataAddr: "d2", CtrlAddr: "c2"} + if err := ctrl.SubmitObservedState(healthySnapForV1(obs, 2), SupportabilityReport{}); err != nil { + t.Fatalf("submit 2: %v", err) + } + if _, ok := ctrl.DesiredFor("v1"); !ok { + t.Fatal("desired must remain when observation epoch disagrees with publisher") + } +} + +// Row 4: publish-not-observed marks Stuck after RetryWindow. +func TestConvergence_PublishNotObserved_StuckAfterWindow(t *testing.T) { + ctrl, reader, clk := convTestCtrl(t, 5*time.Second) + + reader.SetVolume("v1", AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1", + }) + stale := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"} + if err := ctrl.SubmitObservedState(failoverSnapForV1(stale, 1), SupportabilityReport{}); err != nil { + t.Fatalf("submit 1: %v", err) + } + _ = drainOneAsk(t, ctrl) + if _, ok := ctrl.LastConvergenceStuck("v1"); ok { + t.Fatal("must not be Stuck before RetryWindow elapses") + } + + // Advance within the window — still not stuck. + clk.Advance(3 * time.Second) + reader.SetVolume("v1", AuthorityBasis{ + Assigned: true, ReplicaID: "r2", Epoch: 6, EndpointVersion: 1, DataAddr: "d2", CtrlAddr: "c2", + }) + if err := ctrl.SubmitObservedState(failoverSnapForV1(stale, 2), SupportabilityReport{}); err != nil { + t.Fatalf("submit 2: %v", err) + } + if _, ok := ctrl.LastConvergenceStuck("v1"); ok { + t.Fatal("must not be Stuck within RetryWindow") + } + + // Advance past the window. + clk.Advance(3 * time.Second) + if err := ctrl.SubmitObservedState(failoverSnapForV1(stale, 3), SupportabilityReport{}); err != nil { + t.Fatalf("submit 3: %v", err) + } + ev, ok := ctrl.LastConvergenceStuck("v1") + if !ok { + t.Fatal("expected Stuck evidence after RetryWindow") + } + if ev.Reason != ReasonConvergenceStuck { + t.Fatalf("reason: got %q want %q", ev.Reason, ReasonConvergenceStuck) + } + if ev.Ask.ReplicaID != "r2" { + t.Fatalf("evidence must carry the outstanding ask, got %+v", ev.Ask) + } + if ev.ProposedBasis.Epoch != 5 || ev.ProposedBasis.ReplicaID != "r1" { + t.Fatalf("evidence must carry ProposedBasis (r1@5), got %+v", ev.ProposedBasis) + } +} + +// Row 5: Stuck does NOT re-emit. After the stuck transition, no +// new ask is enqueued and no new IntentReassign epoch would be +// minted from the same unchanged observed truth. +func TestConvergence_Stuck_DoesNotReMintReassign(t *testing.T) { + ctrl, reader, clk := convTestCtrl(t, 2*time.Second) + + reader.SetVolume("v1", AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1", + }) + stale := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"} + if err := ctrl.SubmitObservedState(failoverSnapForV1(stale, 1), SupportabilityReport{}); err != nil { + t.Fatalf("submit 1: %v", err) + } + _ = drainOneAsk(t, ctrl) + + // Push many identical snapshots past the retry window. + for i := 0; i < 5; i++ { + clk.Advance(1 * time.Second) + if err := ctrl.SubmitObservedState(failoverSnapForV1(stale, uint64(2+i)), SupportabilityReport{}); err != nil { + t.Fatalf("submit %d: %v", i+2, err) + } + } + // Must be Stuck now. + if _, ok := ctrl.LastConvergenceStuck("v1"); !ok { + t.Fatal("expected Stuck after multiple post-window submits") + } + // And no new ask in the queue — the passive-retry rule + // means Stuck keeps the entry but never re-enqueues. + expectNoQueuedAsk(t, ctrl) +} + +// Row 9 (main): superseded desired — publisher itself advanced +// past ProposedBasis to a replica other than our target. +func TestConvergence_Supersede_PublisherAdvancedToOtherReplica(t *testing.T) { + ctrl, reader, _ := convTestCtrl(t, 5*time.Second) + + reader.SetVolume("v1", AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1", + }) + stale := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"} + if err := ctrl.SubmitObservedState(failoverSnapForV1(stale, 1), SupportabilityReport{}); err != nil { + t.Fatalf("submit 1: %v", err) + } + _ = drainOneAsk(t, ctrl) // Reassign → r2 + + // Publisher independently advanced to r3@6 (not our target). + reader.SetVolume("v1", AuthorityBasis{ + Assigned: true, ReplicaID: "r3", Epoch: 6, EndpointVersion: 1, DataAddr: "d3", CtrlAddr: "c3", + }) + // Observation still shows old r1@5. + if err := ctrl.SubmitObservedState(failoverSnapForV1(stale, 2), SupportabilityReport{}); err != nil { + t.Fatalf("submit 2: %v", err) + } + if _, ok := ctrl.DesiredFor("v1"); ok { + t.Fatal("desired must be superseded when publisher advanced to a different target") + } +} + +// Row 9b: NORMAL LAG — Reassign published, observation still +// reports old line. Desired must remain Active, with no +// duplicate ask and no supersede. Directly guards the round-2 +// architect finding. +func TestConvergence_NormalLag_OldObservationDoesNotSupersede(t *testing.T) { + ctrl, reader, _ := convTestCtrl(t, 5*time.Second) + + reader.SetVolume("v1", AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1", + }) + stale := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"} + if err := ctrl.SubmitObservedState(failoverSnapForV1(stale, 1), SupportabilityReport{}); err != nil { + t.Fatalf("submit 1: %v", err) + } + first := drainOneAsk(t, ctrl) + if first.ReplicaID != "r2" || first.Intent != IntentReassign { + t.Fatalf("expected Reassign to r2, got %+v", first) + } + + // Publisher has applied r2@6, but observation still reports + // the old r1@5 line. Desired target (r2) == publisher target. + reader.SetVolume("v1", AuthorityBasis{ + Assigned: true, ReplicaID: "r2", Epoch: 6, EndpointVersion: 1, DataAddr: "d2", CtrlAddr: "c2", + }) + if err := ctrl.SubmitObservedState(failoverSnapForV1(stale, 2), SupportabilityReport{}); err != nil { + t.Fatalf("submit 2: %v", err) + } + if _, ok := ctrl.DesiredFor("v1"); !ok { + t.Fatal("desired MUST remain Active during normal publisher-vs-observation lag") + } + expectNoQueuedAsk(t, ctrl) +} + +// Row 10: supersede — decision table on fresh snapshot produces +// a DIFFERENT ask. The old desired (r2) is replaced by the new +// one (r3), and stuck evidence (if any) is dropped. +func TestConvergence_Supersede_DecisionTableProducesDifferentAsk(t *testing.T) { + ctrl, reader, clk := convTestCtrl(t, 2*time.Second) + + reader.SetVolume("v1", AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1", + }) + stale := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"} + snap1 := failoverSnapForV1(stale, 1) + // Force decision toward r2 first by making r3 unreachable. + snap1.Volumes[0].Slots[2].Reachable = false + snap1.Volumes[0].Slots[2].ReadyForPrimary = false + if err := ctrl.SubmitObservedState(snap1, SupportabilityReport{}); err != nil { + t.Fatalf("submit 1: %v", err) + } + first := drainOneAsk(t, ctrl) + if first.ReplicaID != "r2" { + t.Fatalf("expected Reassign to r2, got %+v", first) + } + + // Drive to stuck so we can verify evidence is dropped when + // the decision differs. + clk.Advance(3 * time.Second) + // Second snapshot: now r2 is unreachable and r3 is back; + // decision must pick r3. + snap2 := failoverSnapForV1(stale, 2) + snap2.Volumes[0].Slots[1].Reachable = false + snap2.Volumes[0].Slots[1].ReadyForPrimary = false + if err := ctrl.SubmitObservedState(snap2, SupportabilityReport{}); err != nil { + t.Fatalf("submit 2: %v", err) + } + second := drainOneAsk(t, ctrl) + if second.ReplicaID != "r3" { + t.Fatalf("expected supersede Reassign to r3, got %+v", second) + } + d, ok := ctrl.DesiredFor("v1") + if !ok || d.Ask.ReplicaID != "r3" { + t.Fatalf("desired must now target r3, got %+v ok=%v", d, ok) + } + if _, ok := ctrl.LastConvergenceStuck("v1"); ok { + t.Fatal("stuck evidence must be cleared when the desired is replaced by a different ask") + } +} + +// Row 7: pending observation clears desired. +func TestConvergence_PendingClearsDesired(t *testing.T) { + ctrl, reader, _ := convTestCtrl(t, 5*time.Second) + + reader.SetVolume("v1", AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1", + }) + stale := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"} + if err := ctrl.SubmitObservedState(failoverSnapForV1(stale, 1), SupportabilityReport{}); err != nil { + t.Fatalf("submit 1: %v", err) + } + _ = drainOneAsk(t, ctrl) + + // v1 transitions to Pending. + if err := ctrl.SubmitObservedState(ClusterSnapshot{CollectedRevision: 2}, + SupportabilityReport{ + Pending: map[string]VolumePendingStatus{"v1": { + VolumeID: "v1", + EvaluatedAt: time.Now(), + }}, + }); err != nil { + t.Fatalf("submit pending: %v", err) + } + if _, ok := ctrl.DesiredFor("v1"); ok { + t.Fatal("desired must clear on Pending transition") + } + if _, ok := ctrl.LastConvergenceStuck("v1"); ok { + t.Fatal("stuck evidence must clear with desired on Pending") + } +} + +// Row 8: unsupported observation clears desired AND records +// UnsupportedEvidence (distinct from ConvergenceStuckEvidence). +func TestConvergence_UnsupportedClearsDesiredWithEvidence(t *testing.T) { + ctrl, reader, _ := convTestCtrl(t, 5*time.Second) + + reader.SetVolume("v1", AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1", + }) + stale := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"} + if err := ctrl.SubmitObservedState(failoverSnapForV1(stale, 1), SupportabilityReport{}); err != nil { + t.Fatalf("submit 1: %v", err) + } + _ = drainOneAsk(t, ctrl) + + // v1 transitions to Unsupported. + unsupportedAt := time.Now() + if err := ctrl.SubmitObservedState(ClusterSnapshot{CollectedRevision: 2}, + SupportabilityReport{ + Unsupported: map[string]VolumeUnsupportedEvidence{"v1": { + VolumeID: "v1", + SnapshotRevision: 2, + EvaluatedAt: unsupportedAt, + Reasons: []string{ReasonConflictingPrimaryClaim}, + }}, + }); err != nil { + t.Fatalf("submit unsupported: %v", err) + } + if _, ok := ctrl.DesiredFor("v1"); ok { + t.Fatal("desired must clear on Unsupported") + } + if _, ok := ctrl.LastConvergenceStuck("v1"); ok { + t.Fatal("stuck evidence must clear with desired on Unsupported") + } + ev, ok := ctrl.LastUnsupported("v1") + if !ok { + t.Fatal("UnsupportedEvidence must be recorded (distinct class from ConvergenceStuck)") + } + if ev.Reason != ReasonConflictingPrimaryClaim { + t.Fatalf("unsupported reason: got %q want %q", ev.Reason, ReasonConflictingPrimaryClaim) + } +} + +// Row 11: one stuck volume does not block unrelated volume +// convergence. Both v1 and v2 decide Reassigns on the same +// snapshot; v1 cannot observe (stays stuck) but v2 confirms +// normally. +func TestConvergence_OneStuckVolumeDoesNotBlockOthers(t *testing.T) { + reader := newFakeReaderForHost() + // High RebalanceSkew so the decision table does not fire a + // post-confirmation rebalance after v1/v2 end up co-located + // on the same server — we are testing convergence isolation, + // not rebalance. + ctrl := NewTopologyController(TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + RetryWindow: 2 * time.Second, + RebalanceSkew: 100, + }, reader) + clk := newFakeClock(time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC)) + ctrl.SetNowForTest(clk.Now) + + reader.SetVolume("v1", AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"}) + reader.SetVolume("v2", AuthorityBasis{Assigned: true, ReplicaID: "s1", Epoch: 7, EndpointVersion: 1, DataAddr: "e1", CtrlAddr: "f1"}) + + v1Stale := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"} + v2Stale := AuthorityBasis{Assigned: true, ReplicaID: "s1", Epoch: 7, EndpointVersion: 1, DataAddr: "e1", CtrlAddr: "f1"} + snap := ClusterSnapshot{ + CollectedRevision: 1, + Servers: []ServerObservation{ + {ServerID: "sA", Reachable: true, Eligible: true}, + {ServerID: "sB", Reachable: true, Eligible: true}, + {ServerID: "sC", Reachable: true, Eligible: true}, + }, + Volumes: []VolumeTopologySnapshot{ + { + VolumeID: "v1", + 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}, + }, + }, + { + VolumeID: "v2", + 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}, + }, + }, + }, + } + if err := ctrl.SubmitObservedState(snap, SupportabilityReport{}); err != nil { + t.Fatalf("submit 1: %v", err) + } + _ = drainOneAsk(t, ctrl) + _ = drainOneAsk(t, ctrl) + + // Advance past retry window. v2 confirms (publisher+observation + // catch up to s2@8). v1 only has publisher advanced; observation + // still stale. + clk.Advance(3 * time.Second) + reader.SetVolume("v1", AuthorityBasis{Assigned: true, ReplicaID: "r2", Epoch: 6, EndpointVersion: 1, DataAddr: "d2", CtrlAddr: "c2"}) + reader.SetVolume("v2", AuthorityBasis{Assigned: true, ReplicaID: "s2", Epoch: 8, EndpointVersion: 1, DataAddr: "e2", CtrlAddr: "f2"}) + + snap.CollectedRevision = 2 + // v1 observation still stale; v2 observation updated to s2@8 and healthy. + snap.Volumes[1].Authority = AuthorityBasis{Assigned: true, ReplicaID: "s2", Epoch: 8, EndpointVersion: 1, DataAddr: "e2", CtrlAddr: "f2"} + snap.Volumes[1].Slots[0].Reachable = true + snap.Volumes[1].Slots[0].ReadyForPrimary = true + + if err := ctrl.SubmitObservedState(snap, SupportabilityReport{}); err != nil { + t.Fatalf("submit 2: %v", err) + } + + // v1 must be Stuck with desired still Active. + if _, ok := ctrl.LastConvergenceStuck("v1"); !ok { + t.Fatal("v1 expected Stuck") + } + if _, ok := ctrl.DesiredFor("v1"); !ok { + t.Fatal("v1 desired must remain Active while Stuck") + } + // v2 must be Confirmed (desired cleared, no stuck evidence). + if _, ok := ctrl.DesiredFor("v2"); ok { + t.Fatal("v2 desired must be cleared on confirmation") + } + if _, ok := ctrl.LastConvergenceStuck("v2"); ok { + t.Fatal("v2 stuck evidence must be absent (never stuck, confirmed)") + } +} + +// Row 12: retry state is per-volume. Two volumes with different +// DesiredAt timestamps reach Stuck at different wall-clock times. +func TestConvergence_RetryStateIsPerVolume(t *testing.T) { + reader := newFakeReaderForHost() + ctrl := NewTopologyController(TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + RetryWindow: 2 * time.Second, + }, reader) + clk := newFakeClock(time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC)) + ctrl.SetNowForTest(clk.Now) + + // Submit v1 first. + reader.SetVolume("v1", AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"}) + v1Stale := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"} + if err := ctrl.SubmitObservedState(failoverSnapForV1(v1Stale, 1), SupportabilityReport{}); err != nil { + t.Fatalf("submit v1: %v", err) + } + _ = drainOneAsk(t, ctrl) + + // Advance 1.5s. v1 still within window. + clk.Advance(1500 * time.Millisecond) + + // Now propose a v2 failover. v2's DesiredAt is 1.5s later + // than v1's. + reader.SetVolume("v2", AuthorityBasis{Assigned: true, ReplicaID: "s1", Epoch: 7, EndpointVersion: 1, DataAddr: "e1", CtrlAddr: "f1"}) + v2Stale := AuthorityBasis{Assigned: true, ReplicaID: "s1", Epoch: 7, EndpointVersion: 1, DataAddr: "e1", CtrlAddr: "f1"} + snap2 := ClusterSnapshot{ + CollectedRevision: 2, + Servers: []ServerObservation{ + {ServerID: "sA", Reachable: true, Eligible: true}, + {ServerID: "sB", Reachable: true, Eligible: true}, + {ServerID: "sC", Reachable: true, Eligible: true}, + }, + Volumes: []VolumeTopologySnapshot{{ + VolumeID: "v2", + 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}, + }, + }}, + } + if err := ctrl.SubmitObservedState(snap2, SupportabilityReport{}); err != nil { + t.Fatalf("submit v2: %v", err) + } + _ = drainOneAsk(t, ctrl) + + // Advance +1s → total 2.5s since v1 DesiredAt, 1s since v2 + // DesiredAt. v1 Stuck, v2 NOT Stuck. + clk.Advance(1 * time.Second) + if err := ctrl.SubmitObservedState(failoverSnapForV1(v1Stale, 3), SupportabilityReport{}); err != nil { + t.Fatalf("re-submit v1: %v", err) + } + if err := ctrl.SubmitObservedState(snap2, SupportabilityReport{}); err != nil { + t.Fatalf("re-submit v2: %v", err) + } + if _, ok := ctrl.LastConvergenceStuck("v1"); !ok { + t.Fatal("v1 expected Stuck (2.5s > 2s window)") + } + if _, ok := ctrl.LastConvergenceStuck("v2"); ok { + t.Fatal("v2 must NOT be Stuck (1s < 2s window) — per-volume clock") + } +} + +// Row 1b: late confirmation after Stuck must clear BOTH the +// desired entry AND the stuck evidence. Without this, a volume +// that timed out into Stuck and later genuinely converged would +// keep reporting as stuck on LastConvergenceStuck() even though +// convergence had completed — a bounded-fate surface regression. +func TestConvergence_StuckThenConfirm_ClearsStuckEvidence(t *testing.T) { + ctrl, reader, clk := convTestCtrl(t, 1*time.Second) + + reader.SetVolume("v1", AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1", + }) + stale := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"} + if err := ctrl.SubmitObservedState(failoverSnapForV1(stale, 1), SupportabilityReport{}); err != nil { + t.Fatalf("submit 1: %v", err) + } + _ = drainOneAsk(t, ctrl) + + // Advance past the retry window to force Stuck. + clk.Advance(2 * time.Second) + if err := ctrl.SubmitObservedState(failoverSnapForV1(stale, 2), SupportabilityReport{}); err != nil { + t.Fatalf("submit 2: %v", err) + } + if _, ok := ctrl.LastConvergenceStuck("v1"); !ok { + t.Fatal("precondition: expected Stuck after retry window") + } + + // Publisher applies, observation catches up — late + // confirmation. + applied := AuthorityBasis{Assigned: true, ReplicaID: "r2", Epoch: 6, EndpointVersion: 1, DataAddr: "d2", CtrlAddr: "c2"} + reader.SetVolume("v1", applied) + if err := ctrl.SubmitObservedState(healthySnapForV1(applied, 3), SupportabilityReport{}); err != nil { + t.Fatalf("submit 3: %v", err) + } + if _, ok := ctrl.DesiredFor("v1"); ok { + t.Fatal("desired must clear on late confirmation") + } + if ev, ok := ctrl.LastConvergenceStuck("v1"); ok { + t.Fatalf("stuck evidence must be cleared after late confirmation, got %+v", ev) + } +} + +// Supported-recovery regression: once a volume re-enters the +// supported set, any prior UnsupportedEvidence from an earlier +// build must drop. Without this, LastUnsupported() keeps +// reporting a stale fault after the volume is healthy. +func TestConvergence_SupportedRecovery_ClearsPriorUnsupportedEvidence(t *testing.T) { + ctrl, reader, _ := convTestCtrl(t, 5*time.Second) + + // First build: v1 goes Unsupported. + if err := ctrl.SubmitObservedState(ClusterSnapshot{CollectedRevision: 1}, + SupportabilityReport{ + Unsupported: map[string]VolumeUnsupportedEvidence{"v1": { + VolumeID: "v1", + SnapshotRevision: 1, + EvaluatedAt: time.Now(), + Reasons: []string{ReasonConflictingPrimaryClaim}, + }}, + }); err != nil { + t.Fatalf("submit unsupported: %v", err) + } + if _, ok := ctrl.LastUnsupported("v1"); !ok { + t.Fatal("precondition: unsupported evidence must be recorded") + } + + // Second build: v1 is now supported (healthy topology, + // publisher currently holds r1@5). + reader.SetVolume("v1", AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1", + }) + healthy := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"} + if err := ctrl.SubmitObservedState(healthySnapForV1(healthy, 2), SupportabilityReport{}); err != nil { + t.Fatalf("submit supported: %v", err) + } + if ev, ok := ctrl.LastUnsupported("v1"); ok { + t.Fatalf("unsupported evidence must clear on supported recovery, got %+v", ev) + } +} + +// Row 13: IntentReassign is NEVER called twice for the same +// outstanding desired. Even across many submits past the retry +// window, only the first enqueue is observed in the queue. +// This is the direct guard against authority-churn. +func TestConvergence_Reassign_CalledAtMostOncePerDesired(t *testing.T) { + ctrl, reader, clk := convTestCtrl(t, 1*time.Second) + + reader.SetVolume("v1", AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"}) + stale := AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"} + if err := ctrl.SubmitObservedState(failoverSnapForV1(stale, 1), SupportabilityReport{}); err != nil { + t.Fatalf("submit 1: %v", err) + } + ask := drainOneAsk(t, ctrl) + if ask.Intent != IntentReassign || ask.ReplicaID != "r2" { + t.Fatalf("expected Reassign r2, got %+v", ask) + } + + // Hammer identical snapshots past the retry window. + for i := 0; i < 10; i++ { + clk.Advance(500 * time.Millisecond) + if err := ctrl.SubmitObservedState(failoverSnapForV1(stale, uint64(2+i)), SupportabilityReport{}); err != nil { + t.Fatalf("submit %d: %v", i+2, err) + } + } + expectNoQueuedAsk(t, ctrl) +} diff --git a/seaweed-block/core/authority/topology.go b/seaweed-block/core/authority/topology.go index 0a6868f7ad..21b01f39d0 100644 --- a/seaweed-block/core/authority/topology.go +++ b/seaweed-block/core/authority/topology.go @@ -53,9 +53,17 @@ type ClusterSnapshot struct { // TopologyControllerConfig pins the accepted richer topology set: // multi-volume, three slots per volume, and bounded rebalance // pressure when server load skew exceeds RebalanceSkew. +// +// RetryWindow is the S6 bounded-wait clock: how long a desired +// assignment may remain unconfirmed before it is marked Stuck and +// ConvergenceStuckEvidence is recorded for the volume. S6 retry +// is PASSIVE — this clock governs when Stuck surfaces, not when +// an ask is re-emitted into the publisher. See +// sw-block/design/v3-phase-14-s6-sketch.md §7. type TopologyControllerConfig struct { ExpectedSlotsPerVolume int RebalanceSkew int + RetryWindow time.Duration } func (c TopologyControllerConfig) withDefaults() TopologyControllerConfig { @@ -65,17 +73,50 @@ func (c TopologyControllerConfig) withDefaults() TopologyControllerConfig { if c.RebalanceSkew == 0 { c.RebalanceSkew = 1 } + if c.RetryWindow == 0 { + c.RetryWindow = 5 * time.Second + } return c } // DesiredAssignment is the convergence loop's per-volume desired // state. It intentionally stays at the AssignmentAsk level; the // publisher remains the sole minter of Epoch/EndpointVersion. +// +// P14 S6 convergence bookkeeping: +// +// - ProposedBasis is the publisher's current line at the moment +// this desired ask was decided. Supersede uses it as the basis +// to compare against any later publisher line: only a publisher +// epoch STRICTLY greater than ProposedBasis.Epoch that also +// targets a replica OTHER than Ask.ReplicaID drops the desired +// (§9 case 1). For a Bind decided from no line, Assigned=false +// and Epoch=0. +// +// - DesiredAt is the controller-side activation clock. Set when +// the desired entry is first recorded (i.e., at enqueue time), +// NOT when the publisher later applies the ask. The controller +// has no feedback channel from publisher to observe actual +// apply time; anchoring the clock at activation is the honest +// semantic. +// +// - LastRetryAt records the last time the desired was re- +// evaluated on a fresh observation. Diagnostic only. +// +// - Stuck is true once DesiredAt + RetryWindow has elapsed +// without confirmation. Stuck does NOT re-emit into the +// publisher; it surfaces ConvergenceStuckEvidence and keeps +// the desired entry so a later snapshot can still confirm or +// supersede. type DesiredAssignment struct { - Ask AssignmentAsk - Reason string - Revision uint64 - Observed bool + Ask AssignmentAsk + Reason string + Revision uint64 + Observed bool + ProposedBasis AuthorityBasis + DesiredAt time.Time + LastRetryAt time.Time + Stuck bool } func sortVolumeSnapshots(vols []VolumeTopologySnapshot) {