From 60c5ff5db404de97d26ea84d67c76dccac640456 Mon Sep 17 00:00:00 2001 From: wzcheng99 Date: Sun, 19 Apr 2026 16:36:17 -0700 Subject: [PATCH] P14 S4: observation institution + multi-volume topology controller MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Lands two related pieces that make late-Phase-14 observation-to- authority truth system-owned: 1. Multi-volume TopologyController (accepted P14 topology set: per-volume three-slot on distinct servers). This was the "consumer baseline" staged earlier as full-topology scaffolding and is committed here as the foundation S4 feeds. 2. Observation institution: heartbeat / inventory -> stable ClusterSnapshot producer, per the S4 assignment (sw-block/design/v3-phase-14-s4-assignment.md and v3-phase-14-s4-sketch.md). Load-bearing boundary held across both pieces: * observation institution may withhold supportability, but it may NOT mint authority (sketch §3) * Publisher stays the sole minter of Epoch/EndpointVersion * adapter.OnAssignment stays the one and only consumer ingress * no new engine event, command, or projection field Observation-side deliverables (core/authority/): * observation_types.go — Observation, ServerFact, SlotFact, LocalRoleClaim, FreshnessConfig, Supportability enum (pending / supported / unsupported kept VISIBLY distinct per architect execution note), AcceptedTopology, six reason constants. * observation_store.go — push-ingest latest-wins per ServerID, derived ServerFreshness (never-observed / bootstrapping / missing / fresh / expired), immutable storeSnapshot for builder input, configurable GC. * observation_wire.go — V2 heartbeat wire shape port (block_heartbeat / block_heartbeat_proto / block_heartbeat_loop analogues) as mechanism only. HeartbeatToObservation is a pure field-shape copy. * unsupported_evidence.go — per-volume VolumeUnsupportedEvidence (latest-wins per VolumeID), separate VolumePendingStatus, SupportabilityReport with Pending + Unsupported as distinct maps, BuildResult. * snapshot_builder.go — pure BuildSnapshot(store, topology, reader) -> BuildResult. Reads publisher's current per-volume line via the read-only AuthorityBasisReader and stamps it in VolumeTopologySnapshot.Authority for supported volumes, so the controller's stale-resistance check can match on subsequent feeds. Observation never mints authority. * observation_host.go — owns store lifecycle, push-ingest entry points, reactive rebuild (build-on-change + coalescing wake), GC sweep honoring configured retain window, ControllerSink atomic submission (snapshot + report together so supportability transitions propagate even when supported volumes drop to zero). Controller-side intake (core/authority/controller.go): * SubmitClusterSnapshot kept as the test-scaffolding entry. * NEW SubmitObservedState(snap, report) — the observation-fed intake. Mirrors SubmitClusterSnapshot's convergence discipline line-for-line (stale-basis preserves desired, no-emit clears desired, same-ask dedupe prevents authority churn) and adds pending/unsupported transition handling. Under this intake, the controller hears every supportability transition, including "zero supported volumes now", which clears stale desired state. V2 muscles ported (mechanism only): * block_heartbeat / block_heartbeat_proto field layout (observation_wire.go) * block_heartbeat_loop shape concept (host owns the loop) Explicitly NOT ported (per assignment denylist): * weed/storage/blockvol/promotion.go * old HandleAssignment / promote / demote ownership * master_block_plan / master_block_failover / master_block_registry / master_block_assignment_queue (reference only for S5/S6) * any V2 path where heartbeat timing or local status becomes failover truth Proof matrix (observation_test.go — 35 tests covering all sketch §16 rows + architect-round regressions): Authoring: - PartialInventory_PendingThenUnsupported - MissingServerObservation_NeverOrdinaryIneligible - EndToEnd_SystemFedSnapshotReachesController - ConflictingPrimaryClaim_Unsupported - ConflictingPrimaryClaim_NoWinnerEverChosen - ExpiredFact_SemanticallyIneligible - ExpiredDoesNotReachController - BadVolumeDoesNotBlockHealthyVolume_Isolation - VolumeUnsupportedEvidence_IsolatedPerVolume - DuplicateServerTopology_UnsupportedAndEvidenceRecorded - DuplicateServerTopology_NotControllerInput Host-level: - IngestMutation_TriggersSnapshotRebuild - FreshnessWindowHonored_NotTickMultiples - GCRetainWindow_Honored Boundary (AST-based, sketch §16a): - NeverMintsAuthority_BoundaryGuard - SupportabilityDoesNotReadClusterSnapshotOutput Architect round-2 regressions: - BuilderStampsAuthorityFromReader - SupportabilityCollapsePropagatesToController - SupportabilityCollapseClearsControllerDesired - UnknownObservedVolume_ProducesUnsupportedEvidence Architect round-3 regressions: - IdenticalSupportedSnapshots_NoDuplicateAsks - VolumeRecovers_ClearsStaleDesired No changes to engine, adapter, transport, ops, storage, or sparrow. 91 authority tests pass. Full module: 12 packages pass. Design docs in sw-block/design/ external repo: * v3-phase-14-s4-assignment.md * v3-phase-14-s4-observation-institution.md * v3-phase-14-s4-sketch.md * v3-phase-14-s4-closure-gaps.md (architect-round boundary notes) * v3-phase-14-full-topology-design.md * v3-phase-14-placement-rebalance-policy.md Co-Authored-By: Claude Opus 4.7 (1M context) --- seaweed-block/core/authority/controller.go | 577 +++++++ .../core/authority/controller_e2e_test.go | 221 +++ .../core/authority/controller_test.go | 374 +++++ .../core/authority/observation_host.go | 248 +++ .../core/authority/observation_store.go | 249 +++ .../core/authority/observation_test.go | 1447 +++++++++++++++++ .../core/authority/observation_types.go | 206 +++ .../core/authority/observation_wire.go | 106 ++ seaweed-block/core/authority/queue.go | 67 + seaweed-block/core/authority/queue_test.go | 42 + .../core/authority/snapshot_builder.go | 426 +++++ seaweed-block/core/authority/topology.go | 124 ++ .../core/authority/unsupported_evidence.go | 72 + 13 files changed, 4159 insertions(+) create mode 100644 seaweed-block/core/authority/controller.go create mode 100644 seaweed-block/core/authority/controller_e2e_test.go create mode 100644 seaweed-block/core/authority/controller_test.go create mode 100644 seaweed-block/core/authority/observation_host.go create mode 100644 seaweed-block/core/authority/observation_store.go create mode 100644 seaweed-block/core/authority/observation_test.go create mode 100644 seaweed-block/core/authority/observation_types.go create mode 100644 seaweed-block/core/authority/observation_wire.go create mode 100644 seaweed-block/core/authority/queue.go create mode 100644 seaweed-block/core/authority/queue_test.go create mode 100644 seaweed-block/core/authority/snapshot_builder.go create mode 100644 seaweed-block/core/authority/topology.go create mode 100644 seaweed-block/core/authority/unsupported_evidence.go diff --git a/seaweed-block/core/authority/controller.go b/seaweed-block/core/authority/controller.go new file mode 100644 index 0000000000..8d9ef7fd04 --- /dev/null +++ b/seaweed-block/core/authority/controller.go @@ -0,0 +1,577 @@ +package authority + +import ( + "context" + "fmt" + "sync" +) + +// TopologyController is the multi-volume, cluster-scoped directive +// for the full P14 close target. It converts cluster snapshots into +// bounded desired AssignmentAsk values, then feeds those asks to the +// publisher through the existing Directive seam. +// +// The controller owns: +// - accepted topology validation for the richer P14 set +// - cluster-scoped placement / failover / rebalance decisions +// - convergence state ("desired per volume" until observed current) +// +// It does NOT mint Epoch / EndpointVersion and does not call the +// adapter directly. Publisher remains the sole minter and the +// adapter remains the only consumer ingress. +type TopologyController struct { + config TopologyControllerConfig + reader AuthorityBasisReader + queue *assignmentQueue + + mu sync.Mutex + desired map[string]DesiredAssignment + unsupported map[string]UnsupportedEvidence +} + +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), + } +} + +// SubmitClusterSnapshot is the cluster-scoped entry point for +// topology, health, and convergence observations. Rejects empty +// snapshots to preserve the "supported truth only" invariant on +// this path. +// +// For the observation-fed intake that also carries pending / +// unsupported transitions, see SubmitObservedState. +func (c *TopologyController) SubmitClusterSnapshot(snap ClusterSnapshot) error { + if len(snap.Volumes) == 0 { + return fmt.Errorf("topology: cluster snapshot has no volumes") + } + serverIndex := indexServers(snap.Servers) + volumes := make([]VolumeTopologySnapshot, len(snap.Volumes)) + copy(volumes, snap.Volumes) + sortVolumeSnapshots(volumes) + + seenVolumes := make(map[string]struct{}, len(volumes)) + for _, v := range volumes { + if _, ok := seenVolumes[v.VolumeID]; ok { + return fmt.Errorf("topology: duplicate volume snapshot %s", v.VolumeID) + } + seenVolumes[v.VolumeID] = struct{}{} + if err := validateVolumeTopology(v, c.config.ExpectedSlotsPerVolume); err != nil { + return err + } + } + + c.mu.Lock() + defer c.mu.Unlock() + + currentLoad := c.currentServerLoad(volumes) + projectedLoad := cloneLoad(currentLoad) + + 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) + } + return nil +} + +// SubmitObservedState is the observation-institution intake. It +// accepts one synthesized ClusterSnapshot together with the +// per-volume supportability report for the same build. This is +// the intake the observation host calls every rebuild, including +// when snap.Volumes is empty but report carries transitions. +// +// Contract: +// 1. snap.Volumes carries ONLY supported volumes. They drive the +// decision table the same way SubmitClusterSnapshot does. +// 2. For every volume in report.Pending or report.Unsupported, +// any previously-desired assignment is cleared, and the +// per-volume unsupported evidence is updated (Unsupported +// only — Pending does NOT produce evidence; it records that +// action is paused). +// 3. An entirely-empty intake (no Volumes, no Pending, +// no Unsupported) is a no-op rather than an error — a single +// tick with nothing new is not a contract violation. +// +// This is the intake fix for the architect finding that +// supportability transitions could not propagate to the +// controller. Suppressing submission on empty Volumes left old +// desired state live; SubmitObservedState always processes the +// report. +func (c *TopologyController) SubmitObservedState(snap ClusterSnapshot, report SupportabilityReport) error { + // Validate non-empty supported snapshots the same way + // SubmitClusterSnapshot does. Empty supported + empty report + // is allowed (no-op). + if len(snap.Volumes) == 0 && len(report.Pending) == 0 && len(report.Unsupported) == 0 { + return nil + } + + // Pre-validate supported volumes (if any). + serverIndex := indexServers(snap.Servers) + volumes := make([]VolumeTopologySnapshot, len(snap.Volumes)) + copy(volumes, snap.Volumes) + sortVolumeSnapshots(volumes) + + seen := make(map[string]struct{}, len(volumes)) + for _, v := range volumes { + if _, ok := seen[v.VolumeID]; ok { + return fmt.Errorf("topology: duplicate volume snapshot %s", v.VolumeID) + } + seen[v.VolumeID] = struct{}{} + if err := validateVolumeTopology(v, c.config.ExpectedSlotsPerVolume); err != nil { + return err + } + } + + c.mu.Lock() + defer c.mu.Unlock() + + // Process pending / unsupported transitions first. Clearing + // desired state for these volumes before decision logic runs + // means any NEWLY-supported volume in snap.Volumes gets fresh + // decision treatment, while any transitioned-away volume is + // no longer held as "desired" by the controller. + for vid := range report.Pending { + c.clearDesiredLocked(vid) + // Pending does not produce unsupported evidence. Any + // stale unsupported record from a prior build is cleared, + // because pending is a transitional state, not a fault. + delete(c.unsupported, vid) + } + for vid, ev := range report.Unsupported { + c.clearDesiredLocked(vid) + // Record per-volume unsupported evidence. The joined + // reasons string preserves the observation-layer reason + // vocabulary in the controller's existing per-volume + // evidence shape. The Basis is left at zero — the + // observation layer already captured the offending basis + // in its own VolumeUnsupportedEvidence; the controller's + // evidence exists to surface "this volume is not acted + // on" at the cluster-scope level. + c.unsupported[vid] = UnsupportedEvidence{ + SnapshotRevision: ev.SnapshotRevision, + CollectedAt: ev.EvaluatedAt, + Basis: AuthorityBasis{}, + Reason: joinReasons(ev.Reasons), + } + } + + // Process supported volumes via the existing decision path. + // A volume appearing here means observation cleared all the + // supportability rules; any prior unsupported evidence for + // this volume is dropped. + for _, v := range volumes { + delete(c.unsupported, v.VolumeID) + } + + currentLoad := c.currentServerLoad(volumes) + 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) + } + return nil +} + +// 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. +func joinReasons(reasons []string) string { + if len(reasons) == 0 { + return "" + } + out := reasons[0] + for i := 1; i < len(reasons); i++ { + out += "," + reasons[i] + } + return out +} + +// Next satisfies Directive by draining the per-volume latest-wins +// assignment queue. +func (c *TopologyController) Next(ctx context.Context) (AssignmentAsk, error) { + return c.queue.next(ctx) +} + +// LastUnsupported returns the most recent unsupported evidence for +// one volume, if any. +func (c *TopologyController) LastUnsupported(volumeID string) (UnsupportedEvidence, bool) { + c.mu.Lock() + defer c.mu.Unlock() + ev, ok := c.unsupported[volumeID] + return ev, ok +} + +func (c *TopologyController) clearDesiredLocked(volumeID string) { + delete(c.desired, volumeID) + c.queue.discard(volumeID) +} + +func (c *TopologyController) recordUnsupportedLocked(volumeID string, snap ClusterSnapshot, basis AuthorityBasis, reason string) { + c.unsupported[volumeID] = UnsupportedEvidence{ + SnapshotRevision: snap.CollectedRevision, + CollectedAt: snap.CollectedAt, + Basis: basis, + Reason: reason, + } +} + +func (c *TopologyController) confirmDesiredLocked(vol VolumeTopologySnapshot, currentLine AuthorityBasis, hasLine bool) { + desired, ok := c.desired[vol.VolumeID] + if !ok { + return + } + if desiredObserved(desired, vol, currentLine, hasLine) { + delete(c.desired, vol.VolumeID) + c.queue.discard(vol.VolumeID) + } +} + +func desiredObserved(desired DesiredAssignment, vol VolumeTopologySnapshot, currentLine AuthorityBasis, hasLine bool) bool { + if !hasLine || !vol.Authority.Assigned { + return false + } + if vol.Authority.ReplicaID != currentLine.ReplicaID || + vol.Authority.Epoch != currentLine.Epoch || + vol.Authority.EndpointVersion != currentLine.EndpointVersion { + return false + } + if currentLine.ReplicaID != desired.Ask.ReplicaID { + return false + } + switch desired.Ask.Intent { + case IntentRefreshEndpoint: + return vol.Authority.DataAddr == desired.Ask.DataAddr && + vol.Authority.CtrlAddr == desired.Ask.CtrlAddr + case IntentBind, IntentReassign: + return true + default: + return false + } +} + +func (c *TopologyController) currentServerLoad(volumes []VolumeTopologySnapshot) map[string]int { + load := make(map[string]int) + for _, vol := range volumes { + line, ok := c.reader.VolumeAuthorityLine(vol.VolumeID) + if !ok { + continue + } + slot, ok := candidateByReplica(vol, line.ReplicaID) + if !ok { + continue + } + load[slot.ServerID]++ + } + return load +} + +func (c *TopologyController) decideVolume( + vol VolumeTopologySnapshot, + serverIndex map[string]ServerObservation, + currentLine AuthorityBasis, + hasLine bool, + currentLoad map[string]int, + projectedLoad map[string]int, +) (AssignmentAsk, string, bool) { + if !hasLine { + cands := acceptableCandidates(vol, serverIndex) + if len(cands) == 0 { + return AssignmentAsk{}, "", false + } + best := choosePlacementCandidate(cands, projectedLoad) + return AssignmentAsk{ + VolumeID: vol.VolumeID, + ReplicaID: best.ReplicaID, + DataAddr: best.DataAddr, + CtrlAddr: best.CtrlAddr, + Intent: IntentBind, + }, "initial placement", true + } + + current, ok := candidateByReplica(vol, currentLine.ReplicaID) + if !ok { + return AssignmentAsk{}, "", false + } + + if candidateAcceptable(current, serverIndex) { + if current.DataAddr != currentLine.DataAddr || current.CtrlAddr != currentLine.CtrlAddr { + return AssignmentAsk{ + VolumeID: vol.VolumeID, + ReplicaID: current.ReplicaID, + DataAddr: current.DataAddr, + CtrlAddr: current.CtrlAddr, + Intent: IntentRefreshEndpoint, + }, "endpoint refresh", true + } + if target, ok := chooseRebalanceCandidate(vol, current, serverIndex, currentLoad, projectedLoad, c.config.RebalanceSkew); ok { + return AssignmentAsk{ + VolumeID: vol.VolumeID, + ReplicaID: target.ReplicaID, + DataAddr: target.DataAddr, + CtrlAddr: target.CtrlAddr, + Intent: IntentReassign, + }, "rebalance", true + } + return AssignmentAsk{}, "", false + } + + other := acceptableCandidatesExcept(vol, serverIndex, current.ReplicaID) + if len(other) == 0 { + return AssignmentAsk{}, "", false + } + best := chooseFailoverCandidate(other, projectedLoad) + return AssignmentAsk{ + VolumeID: vol.VolumeID, + ReplicaID: best.ReplicaID, + DataAddr: best.DataAddr, + CtrlAddr: best.CtrlAddr, + Intent: IntentReassign, + }, "failover", true +} + +func volumeIncludesReplica(vol VolumeTopologySnapshot, replicaID string) bool { + for _, slot := range vol.Slots { + if slot.ReplicaID == replicaID { + return true + } + } + return false +} + +func candidateByReplica(vol VolumeTopologySnapshot, replicaID string) (ReplicaCandidate, bool) { + for _, slot := range vol.Slots { + if slot.ReplicaID == replicaID { + return slot, true + } + } + return ReplicaCandidate{}, false +} + +func candidateAcceptable(slot ReplicaCandidate, servers map[string]ServerObservation) bool { + server, ok := servers[slot.ServerID] + if !ok { + return false + } + return slot.Reachable && + slot.ReadyForPrimary && + slot.Eligible && + !slot.Withdrawn && + server.Reachable && + server.Eligible +} + +func acceptableCandidates(vol VolumeTopologySnapshot, servers map[string]ServerObservation) []ReplicaCandidate { + var out []ReplicaCandidate + for _, slot := range vol.Slots { + if candidateAcceptable(slot, servers) { + out = append(out, slot) + } + } + return out +} + +func acceptableCandidatesExcept(vol VolumeTopologySnapshot, servers map[string]ServerObservation, excludeReplica string) []ReplicaCandidate { + var out []ReplicaCandidate + for _, slot := range vol.Slots { + if slot.ReplicaID == excludeReplica { + continue + } + if candidateAcceptable(slot, servers) { + out = append(out, slot) + } + } + return out +} + +func choosePlacementCandidate(cands []ReplicaCandidate, load map[string]int) ReplicaCandidate { + best := cands[0] + for _, cand := range cands[1:] { + if load[cand.ServerID] < load[best.ServerID] { + best = cand + continue + } + if load[cand.ServerID] == load[best.ServerID] && cand.EvidenceScore > best.EvidenceScore { + best = cand + continue + } + if load[cand.ServerID] == load[best.ServerID] && cand.EvidenceScore == best.EvidenceScore && cand.ReplicaID < best.ReplicaID { + best = cand + } + } + return best +} + +func chooseFailoverCandidate(cands []ReplicaCandidate, load map[string]int) ReplicaCandidate { + best := cands[0] + for _, cand := range cands[1:] { + if cand.EvidenceScore > best.EvidenceScore { + best = cand + continue + } + if cand.EvidenceScore == best.EvidenceScore && load[cand.ServerID] < load[best.ServerID] { + best = cand + continue + } + if cand.EvidenceScore == best.EvidenceScore && load[cand.ServerID] == load[best.ServerID] && cand.ReplicaID < best.ReplicaID { + best = cand + } + } + return best +} + +func chooseRebalanceCandidate( + vol VolumeTopologySnapshot, + current ReplicaCandidate, + servers map[string]ServerObservation, + currentLoad map[string]int, + projectedLoad map[string]int, + skew int, +) (ReplicaCandidate, bool) { + lightest := currentLoad[current.ServerID] + for _, slot := range vol.Slots { + if !candidateAcceptable(slot, servers) { + continue + } + if currentLoad[slot.ServerID] < lightest { + lightest = currentLoad[slot.ServerID] + } + } + if currentLoad[current.ServerID]-lightest <= skew { + return ReplicaCandidate{}, false + } + best := ReplicaCandidate{} + ok := false + for _, slot := range vol.Slots { + if slot.ReplicaID == current.ReplicaID || !candidateAcceptable(slot, servers) { + continue + } + if !ok || + projectedLoad[slot.ServerID] < projectedLoad[best.ServerID] || + (projectedLoad[slot.ServerID] == projectedLoad[best.ServerID] && slot.EvidenceScore > best.EvidenceScore) || + (projectedLoad[slot.ServerID] == projectedLoad[best.ServerID] && slot.EvidenceScore == best.EvidenceScore && slot.ReplicaID < best.ReplicaID) { + best = slot + ok = true + } + } + return best, ok +} + +func cloneLoad(src map[string]int) map[string]int { + dst := make(map[string]int, len(src)) + for k, v := range src { + dst[k] = v + } + return dst +} + +func applyProjectedMove(projected map[string]int, vol VolumeTopologySnapshot, currentLine AuthorityBasis, hasLine bool, ask AssignmentAsk) { + target, ok := candidateByReplica(vol, ask.ReplicaID) + if !ok { + return + } + switch ask.Intent { + case IntentBind: + projected[target.ServerID]++ + case IntentReassign: + if hasLine { + if current, ok := candidateByReplica(vol, currentLine.ReplicaID); ok && projected[current.ServerID] > 0 { + projected[current.ServerID]-- + } + } + projected[target.ServerID]++ + } +} + +func sameAsk(a, b AssignmentAsk) bool { + return a.VolumeID == b.VolumeID && + a.ReplicaID == b.ReplicaID && + a.DataAddr == b.DataAddr && + a.CtrlAddr == b.CtrlAddr && + a.Intent == b.Intent +} diff --git a/seaweed-block/core/authority/controller_e2e_test.go b/seaweed-block/core/authority/controller_e2e_test.go new file mode 100644 index 0000000000..985c88b04a --- /dev/null +++ b/seaweed-block/core/authority/controller_e2e_test.go @@ -0,0 +1,221 @@ +package authority + +import ( + "context" + "sync" + "testing" + "time" +) + +type basisReaderHolder struct { + mu sync.Mutex + reader AuthorityBasisReader +} + +func (h *basisReaderHolder) set(reader AuthorityBasisReader) { + h.mu.Lock() + h.reader = reader + h.mu.Unlock() +} + +func (h *basisReaderHolder) LastAuthorityBasis(volumeID, replicaID string) (AuthorityBasis, bool) { + h.mu.Lock() + r := h.reader + h.mu.Unlock() + if r == nil { + return AuthorityBasis{}, false + } + return r.LastAuthorityBasis(volumeID, replicaID) +} + +func (h *basisReaderHolder) VolumeAuthorityLine(volumeID string) (AuthorityBasis, bool) { + h.mu.Lock() + r := h.reader + h.mu.Unlock() + if r == nil { + return AuthorityBasis{}, false + } + return r.VolumeAuthorityLine(volumeID) +} + +func waitForLine(t *testing.T, pub *Publisher, volumeID string, pred func(AuthorityBasis) bool) AuthorityBasis { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + line, ok := pub.VolumeAuthorityLine(volumeID) + if ok && pred(line) { + return line + } + time.Sleep(10 * time.Millisecond) + } + line, _ := pub.VolumeAuthorityLine(volumeID) + t.Fatalf("volume %s did not reach expected line, last=%+v", volumeID, line) + return AuthorityBasis{} +} + +func waitForConsumerAtLeast(t *testing.T, cons *recordingConsumer, n int) { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if len(cons.snapshot()) >= n { + return + } + time.Sleep(10 * time.Millisecond) + } + t.Fatalf("consumer did not reach %d deliveries, got %d", n, len(cons.snapshot())) +} + +func observedAuthorityFrom(pub *Publisher, volumeID string) AuthorityBasis { + line, ok := pub.VolumeAuthorityLine(volumeID) + if !ok { + return AuthorityBasis{} + } + return line +} + +func TestTopologyControllerToPublisher_E2E_MultiVolumePlacementAndFailover(t *testing.T) { + holder := &basisReaderHolder{} + ctrl := NewTopologyController(TopologyControllerConfig{}, holder) + pub := NewPublisher(ctrl) + holder.set(pub) + + v1Consumer := &recordingConsumer{} + v2Consumer := &recordingConsumer{} + v3Consumer := &recordingConsumer{} + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go pub.Run(ctx) + go VolumeBridge(ctx, pub, v1Consumer, "v1", "v1r1", "v1r2", "v1r3") + go VolumeBridge(ctx, pub, v2Consumer, "v2", "v2r1", "v2r2", "v2r3") + go VolumeBridge(ctx, pub, v3Consumer, "v3", "v3r1", "v3r2", "v3r3") + + initial := ClusterSnapshot{ + CollectedRevision: 1, + Servers: []ServerObservation{ + {ServerID: "s1", Reachable: true, Eligible: true}, + {ServerID: "s2", Reachable: true, Eligible: true}, + {ServerID: "s3", Reachable: true, Eligible: true}, + }, + Volumes: []VolumeTopologySnapshot{ + clusterVolume("v1", AuthorityBasis{}, candidate("v1r1", "s1", "d11", "c11", 10), candidate("v1r2", "s2", "d12", "c12", 10), candidate("v1r3", "s3", "d13", "c13", 10)), + clusterVolume("v2", AuthorityBasis{}, candidate("v2r1", "s1", "d21", "c21", 10), candidate("v2r2", "s2", "d22", "c22", 10), candidate("v2r3", "s3", "d23", "c23", 10)), + clusterVolume("v3", AuthorityBasis{}, candidate("v3r1", "s1", "d31", "c31", 10), candidate("v3r2", "s2", "d32", "c32", 10), candidate("v3r3", "s3", "d33", "c33", 10)), + }, + } + if err := ctrl.SubmitClusterSnapshot(initial); err != nil { + t.Fatalf("SubmitClusterSnapshot initial: %v", err) + } + v1Line := waitForLine(t, pub, "v1", func(line AuthorityBasis) bool { return line.Assigned }) + v2Line := waitForLine(t, pub, "v2", func(line AuthorityBasis) bool { return line.Assigned }) + v3Line := waitForLine(t, pub, "v3", func(line AuthorityBasis) bool { return line.Assigned }) + + waitForConsumerAtLeast(t, v1Consumer, 1) + waitForConsumerAtLeast(t, v2Consumer, 1) + waitForConsumerAtLeast(t, v3Consumer, 1) + + servers := map[string]string{ + "v1": mustReplicaServer(t, initial.Volumes[0], v1Line.ReplicaID), + "v2": mustReplicaServer(t, initial.Volumes[1], v2Line.ReplicaID), + "v3": mustReplicaServer(t, initial.Volumes[2], v3Line.ReplicaID), + } + seen := map[string]struct{}{servers["v1"]: {}, servers["v2"]: {}, servers["v3"]: {}} + if len(seen) != 3 { + t.Fatalf("initial placement should balance across 3 servers, got %+v", servers) + } + + failover := initial + failover.CollectedRevision = 2 + failover.Volumes[0].Authority = observedAuthorityFrom(pub, "v1") + failover.Volumes[1].Authority = observedAuthorityFrom(pub, "v2") + failover.Volumes[2].Authority = observedAuthorityFrom(pub, "v3") + currentV1 := failover.Volumes[0].Authority.ReplicaID + for i := range failover.Volumes[0].Slots { + slot := &failover.Volumes[0].Slots[i] + if slot.ReplicaID == currentV1 { + slot.Reachable = false + slot.ReadyForPrimary = false + } + if slot.ServerID == "s3" { + slot.EvidenceScore = 50 + } + } + if err := ctrl.SubmitClusterSnapshot(failover); err != nil { + t.Fatalf("SubmitClusterSnapshot failover: %v", err) + } + newV1 := waitForLine(t, pub, "v1", func(line AuthorityBasis) bool { + return line.ReplicaID != currentV1 && line.Epoch == v1Line.Epoch+1 + }) + if newV1.ReplicaID == currentV1 { + t.Fatalf("expected v1 to fail over, still on %s", currentV1) + } + waitForConsumerAtLeast(t, v1Consumer, 2) +} + +func TestTopologyControllerToPublisher_E2E_Rebalance(t *testing.T) { + holder := &basisReaderHolder{} + ctrl := NewTopologyController(TopologyControllerConfig{RebalanceSkew: 1}, holder) + pub := NewPublisher(ctrl) + holder.set(pub) + + if err := pub.apply(AssignmentAsk{VolumeID: "v1", ReplicaID: "v1r1", DataAddr: "d11", CtrlAddr: "c11", Intent: IntentBind}); err != nil { + t.Fatalf("seed v1: %v", err) + } + if err := pub.apply(AssignmentAsk{VolumeID: "v2", ReplicaID: "v2r1", DataAddr: "d21", CtrlAddr: "c21", Intent: IntentBind}); err != nil { + t.Fatalf("seed v2: %v", err) + } + if err := pub.apply(AssignmentAsk{VolumeID: "v3", ReplicaID: "v3r2", DataAddr: "d32", CtrlAddr: "c32", Intent: IntentBind}); err != nil { + t.Fatalf("seed v3: %v", err) + } + + v1Consumer := &recordingConsumer{} + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go pub.Run(ctx) + go VolumeBridge(ctx, pub, v1Consumer, "v1", "v1r1", "v1r2", "v1r3") + + snap := ClusterSnapshot{ + CollectedRevision: 1, + Servers: []ServerObservation{ + {ServerID: "s1", Reachable: true, Eligible: true}, + {ServerID: "s2", Reachable: true, Eligible: true}, + {ServerID: "s3", Reachable: true, Eligible: true}, + }, + Volumes: []VolumeTopologySnapshot{ + clusterVolume("v1", observedAuthorityFrom(pub, "v1"), + candidate("v1r1", "s1", "d11", "c11", 10), + candidate("v1r2", "s2", "d12", "c12", 10), + candidate("v1r3", "s3", "d13", "c13", 30), + ), + clusterVolume("v2", observedAuthorityFrom(pub, "v2"), + candidate("v2r1", "s1", "d21", "c21", 10), + candidate("v2r2", "s2", "d22", "c22", 10), + candidate("v2r3", "s3", "d23", "c23", 10), + ), + clusterVolume("v3", observedAuthorityFrom(pub, "v3"), + candidate("v3r1", "s1", "d31", "c31", 10), + candidate("v3r2", "s2", "d32", "c32", 10), + candidate("v3r3", "s3", "d33", "c33", 10), + ), + }, + } + if err := ctrl.SubmitClusterSnapshot(snap); err != nil { + t.Fatalf("SubmitClusterSnapshot: %v", err) + } + line := waitForLine(t, pub, "v1", func(line AuthorityBasis) bool { + return line.ReplicaID == "v1r3" && line.Epoch == 2 + }) + if line.ReplicaID != "v1r3" { + t.Fatalf("expected rebalance to v1r3, got %+v", line) + } + waitForConsumerAtLeast(t, v1Consumer, 2) +} + +func mustReplicaServer(t *testing.T, vol VolumeTopologySnapshot, replicaID string) string { + t.Helper() + slot, ok := candidateByReplica(vol, replicaID) + if !ok { + t.Fatalf("replica %s not found in volume %s", replicaID, vol.VolumeID) + } + return slot.ServerID +} diff --git a/seaweed-block/core/authority/controller_test.go b/seaweed-block/core/authority/controller_test.go new file mode 100644 index 0000000000..d311f7708f --- /dev/null +++ b/seaweed-block/core/authority/controller_test.go @@ -0,0 +1,374 @@ +package authority + +import ( + "context" + "errors" + "testing" + "time" +) + +func clusterVolume(volumeID string, authority AuthorityBasis, slots ...ReplicaCandidate) VolumeTopologySnapshot { + return VolumeTopologySnapshot{ + VolumeID: volumeID, + Authority: authority, + Slots: slots, + } +} + +func candidate(replicaID, serverID, dataAddr, ctrlAddr string, evidence uint64) ReplicaCandidate { + return ReplicaCandidate{ + ReplicaID: replicaID, + ServerID: serverID, + DataAddr: dataAddr, + CtrlAddr: ctrlAddr, + Reachable: true, + ReadyForPrimary: true, + Eligible: true, + EvidenceScore: evidence, + } +} + +func nextAskOrFail(t *testing.T, d Directive) AssignmentAsk { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + ask, err := d.Next(ctx) + if err != nil { + t.Fatalf("Next: %v", err) + } + return ask +} + +func expectNoNext(t *testing.T, d Directive) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + if _, err := d.Next(ctx); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("expected deadline exceeded, got %v", err) + } +} + +func TestTopologyController_InitialPlacementBalancesAcrossVolumes(t *testing.T) { + reader := newFakeBasisReader() + ctrl := NewTopologyController(TopologyControllerConfig{}, reader) + snap := ClusterSnapshot{ + CollectedRevision: 1, + Servers: []ServerObservation{ + {ServerID: "s1", Reachable: true, Eligible: true}, + {ServerID: "s2", Reachable: true, Eligible: true}, + {ServerID: "s3", Reachable: true, Eligible: true}, + }, + Volumes: []VolumeTopologySnapshot{ + clusterVolume("v1", AuthorityBasis{}, candidate("v1r1", "s1", "d11", "c11", 10), candidate("v1r2", "s2", "d12", "c12", 10), candidate("v1r3", "s3", "d13", "c13", 10)), + clusterVolume("v2", AuthorityBasis{}, candidate("v2r1", "s1", "d21", "c21", 10), candidate("v2r2", "s2", "d22", "c22", 10), candidate("v2r3", "s3", "d23", "c23", 10)), + clusterVolume("v3", AuthorityBasis{}, candidate("v3r1", "s1", "d31", "c31", 10), candidate("v3r2", "s2", "d32", "c32", 10), candidate("v3r3", "s3", "d33", "c33", 10)), + }, + } + if err := ctrl.SubmitClusterSnapshot(snap); err != nil { + t.Fatalf("SubmitClusterSnapshot: %v", err) + } + seenServers := make(map[string]struct{}) + for i := 0; i < 3; i++ { + ask := nextAskOrFail(t, ctrl) + var gotServer string + for _, vol := range snap.Volumes { + if vol.VolumeID != ask.VolumeID { + continue + } + slot, ok := candidateByReplica(vol, ask.ReplicaID) + if ok { + gotServer = slot.ServerID + } + } + seenServers[gotServer] = struct{}{} + } + if len(seenServers) != 3 { + t.Fatalf("initial placement should spread across 3 servers, got %d", len(seenServers)) + } +} + +func TestTopologyController_InitialPlacementUsesEvidenceTieBreakOnEqualLoad(t *testing.T) { + reader := newFakeBasisReader() + ctrl := NewTopologyController(TopologyControllerConfig{}, reader) + snap := ClusterSnapshot{ + CollectedRevision: 1, + Servers: []ServerObservation{ + {ServerID: "s1", Reachable: true, Eligible: true}, + {ServerID: "s2", Reachable: true, Eligible: true}, + {ServerID: "s3", Reachable: true, Eligible: true}, + }, + Volumes: []VolumeTopologySnapshot{ + clusterVolume("v1", AuthorityBasis{}, + candidate("r1", "s1", "d1", "c1", 10), + candidate("r2", "s2", "d2", "c2", 30), + candidate("r3", "s3", "d3", "c3", 20), + ), + }, + } + if err := ctrl.SubmitClusterSnapshot(snap); err != nil { + t.Fatalf("SubmitClusterSnapshot: %v", err) + } + ask := nextAskOrFail(t, ctrl) + if ask.Intent != IntentBind || ask.ReplicaID != "r2" { + t.Fatalf("equal-load placement should prefer highest evidence candidate, got %+v", ask) + } +} + +func TestTopologyController_FailoverUsesHighestEvidenceCandidate(t *testing.T) { + reader := newFakeBasisReader() + reader.Set("v1", "r1", AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, + DataAddr: "d1", CtrlAddr: "c1", + }) + ctrl := NewTopologyController(TopologyControllerConfig{}, reader) + snap := ClusterSnapshot{ + CollectedRevision: 2, + Servers: []ServerObservation{ + {ServerID: "s1", Reachable: true, Eligible: true}, + {ServerID: "s2", Reachable: true, Eligible: true}, + {ServerID: "s3", Reachable: true, Eligible: true}, + }, + Volumes: []VolumeTopologySnapshot{ + clusterVolume("v1", + AuthorityBasis{Assigned: true, ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d1", CtrlAddr: "c1"}, + func() ReplicaCandidate { c := candidate("r1", "s1", "d1", "c1", 10); c.Reachable = false; return c }(), + candidate("r2", "s2", "d2", "c2", 20), + candidate("r3", "s3", "d3", "c3", 10), + ), + }, + } + if err := ctrl.SubmitClusterSnapshot(snap); err != nil { + t.Fatalf("SubmitClusterSnapshot: %v", err) + } + ask := nextAskOrFail(t, ctrl) + if ask.Intent != IntentReassign || ask.ReplicaID != "r2" { + t.Fatalf("want Reassign to r2, got %+v", ask) + } +} + +func TestTopologyController_RebalanceMovesToLighterServer(t *testing.T) { + reader := newFakeBasisReader() + reader.Set("v1", "v1r1", AuthorityBasis{Assigned: true, ReplicaID: "v1r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d11", CtrlAddr: "c11"}) + reader.Set("v2", "v2r1", AuthorityBasis{Assigned: true, ReplicaID: "v2r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d21", CtrlAddr: "c21"}) + reader.Set("v3", "v3r2", AuthorityBasis{Assigned: true, ReplicaID: "v3r2", Epoch: 1, EndpointVersion: 1, DataAddr: "d32", CtrlAddr: "c32"}) + ctrl := NewTopologyController(TopologyControllerConfig{RebalanceSkew: 1}, reader) + snap := ClusterSnapshot{ + CollectedRevision: 3, + Servers: []ServerObservation{ + {ServerID: "s1", Reachable: true, Eligible: true}, + {ServerID: "s2", Reachable: true, Eligible: true}, + {ServerID: "s3", Reachable: true, Eligible: true}, + }, + Volumes: []VolumeTopologySnapshot{ + clusterVolume("v1", + AuthorityBasis{Assigned: true, ReplicaID: "v1r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d11", CtrlAddr: "c11"}, + candidate("v1r1", "s1", "d11", "c11", 10), + candidate("v1r2", "s2", "d12", "c12", 10), + candidate("v1r3", "s3", "d13", "c13", 30), + ), + clusterVolume("v2", + AuthorityBasis{Assigned: true, ReplicaID: "v2r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d21", CtrlAddr: "c21"}, + candidate("v2r1", "s1", "d21", "c21", 10), + candidate("v2r2", "s2", "d22", "c22", 10), + candidate("v2r3", "s3", "d23", "c23", 10), + ), + clusterVolume("v3", + AuthorityBasis{Assigned: true, ReplicaID: "v3r2", Epoch: 1, EndpointVersion: 1, DataAddr: "d32", CtrlAddr: "c32"}, + candidate("v3r1", "s1", "d31", "c31", 10), + candidate("v3r2", "s2", "d32", "c32", 10), + candidate("v3r3", "s3", "d33", "c33", 10), + ), + }, + } + if err := ctrl.SubmitClusterSnapshot(snap); err != nil { + t.Fatalf("SubmitClusterSnapshot: %v", err) + } + ask := nextAskOrFail(t, ctrl) + if ask.VolumeID != "v1" || ask.Intent != IntentReassign || ask.ReplicaID != "v1r3" { + t.Fatalf("want v1 rebalance to v1r3 on s3, got %+v", ask) + } +} + +func TestTopologyController_RebalanceSkipsWhenLoadAlreadyWithinBound(t *testing.T) { + reader := newFakeBasisReader() + reader.Set("v1", "v1r1", AuthorityBasis{Assigned: true, ReplicaID: "v1r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d11", CtrlAddr: "c11"}) + reader.Set("v2", "v2r2", AuthorityBasis{Assigned: true, ReplicaID: "v2r2", Epoch: 1, EndpointVersion: 1, DataAddr: "d22", CtrlAddr: "c22"}) + ctrl := NewTopologyController(TopologyControllerConfig{RebalanceSkew: 1}, reader) + snap := ClusterSnapshot{ + CollectedRevision: 5, + Servers: []ServerObservation{ + {ServerID: "s1", Reachable: true, Eligible: true}, + {ServerID: "s2", Reachable: true, Eligible: true}, + {ServerID: "s3", Reachable: true, Eligible: true}, + }, + Volumes: []VolumeTopologySnapshot{ + clusterVolume("v1", + AuthorityBasis{Assigned: true, ReplicaID: "v1r1", Epoch: 1, EndpointVersion: 1, DataAddr: "d11", CtrlAddr: "c11"}, + candidate("v1r1", "s1", "d11", "c11", 10), + candidate("v1r2", "s2", "d12", "c12", 30), + candidate("v1r3", "s3", "d13", "c13", 20), + ), + clusterVolume("v2", + AuthorityBasis{Assigned: true, ReplicaID: "v2r2", Epoch: 1, EndpointVersion: 1, DataAddr: "d22", CtrlAddr: "c22"}, + candidate("v2r1", "s1", "d21", "c21", 10), + candidate("v2r2", "s2", "d22", "c22", 10), + candidate("v2r3", "s3", "d23", "c23", 10), + ), + }, + } + if err := ctrl.SubmitClusterSnapshot(snap); err != nil { + t.Fatalf("SubmitClusterSnapshot: %v", err) + } + expectNoNext(t, ctrl) +} + +func TestTopologyController_OutOfTopologyAuthority_NoAskPlusEvidence(t *testing.T) { + reader := newFakeBasisReader() + reader.Set("v1", "r99", AuthorityBasis{ + Assigned: true, ReplicaID: "r99", Epoch: 5, EndpointVersion: 1, + DataAddr: "dx", CtrlAddr: "cx", + }) + ctrl := NewTopologyController(TopologyControllerConfig{}, reader) + snap := ClusterSnapshot{ + CollectedRevision: 4, + Servers: []ServerObservation{ + {ServerID: "s1", Reachable: true, Eligible: true}, + {ServerID: "s2", Reachable: true, Eligible: true}, + {ServerID: "s3", Reachable: true, Eligible: true}, + }, + Volumes: []VolumeTopologySnapshot{ + clusterVolume("v1", AuthorityBasis{}, candidate("r1", "s1", "d1", "c1", 10), candidate("r2", "s2", "d2", "c2", 10), candidate("r3", "s3", "d3", "c3", 10)), + }, + } + if err := ctrl.SubmitClusterSnapshot(snap); err != nil { + t.Fatalf("SubmitClusterSnapshot: %v", err) + } + expectNoNext(t, ctrl) + ev, ok := ctrl.LastUnsupported("v1") + if !ok { + t.Fatal("expected unsupported evidence") + } + if ev.Basis.ReplicaID != "r99" { + t.Fatalf("evidence replicaID: got %q want r99", ev.Basis.ReplicaID) + } +} + +func TestTopologyController_UnsupportedVolumeDoesNotBlockOtherVolumes(t *testing.T) { + reader := newFakeBasisReader() + reader.Set("v1", "r99", AuthorityBasis{ + Assigned: true, ReplicaID: "r99", Epoch: 5, EndpointVersion: 1, + DataAddr: "dx", CtrlAddr: "cx", + }) + ctrl := NewTopologyController(TopologyControllerConfig{}, reader) + snap := ClusterSnapshot{ + CollectedRevision: 4, + Servers: []ServerObservation{ + {ServerID: "s1", Reachable: true, Eligible: true}, + {ServerID: "s2", Reachable: true, Eligible: true}, + {ServerID: "s3", Reachable: true, Eligible: true}, + }, + Volumes: []VolumeTopologySnapshot{ + clusterVolume("v1", AuthorityBasis{}, candidate("r1", "s1", "d1", "c1", 10), candidate("r2", "s2", "d2", "c2", 10), candidate("r3", "s3", "d3", "c3", 10)), + clusterVolume("v2", AuthorityBasis{}, candidate("x1", "s1", "d4", "c4", 10), candidate("x2", "s2", "d5", "c5", 20), candidate("x3", "s3", "d6", "c6", 15)), + }, + } + if err := ctrl.SubmitClusterSnapshot(snap); err != nil { + t.Fatalf("SubmitClusterSnapshot: %v", err) + } + ask := nextAskOrFail(t, ctrl) + if ask.VolumeID != "v2" || ask.Intent != IntentBind { + t.Fatalf("want v2 Bind while v1 stays unsupported, got %+v", ask) + } + ev, ok := ctrl.LastUnsupported("v1") + if !ok || ev.Basis.ReplicaID != "r99" { + t.Fatalf("expected unsupported evidence for v1, got %+v ok=%v", ev, ok) + } +} + +func TestTopologyController_ObservedAuthorityClearsPending(t *testing.T) { + reader := newFakeBasisReader() + ctrl := NewTopologyController(TopologyControllerConfig{}, reader) + initial := ClusterSnapshot{ + CollectedRevision: 1, + Servers: []ServerObservation{ + {ServerID: "s1", Reachable: true, Eligible: true}, + {ServerID: "s2", Reachable: true, Eligible: true}, + {ServerID: "s3", Reachable: true, Eligible: true}, + }, + Volumes: []VolumeTopologySnapshot{ + clusterVolume("v1", AuthorityBasis{}, candidate("r1", "s1", "d1", "c1", 10), candidate("r2", "s2", "d2", "c2", 10), candidate("r3", "s3", "d3", "c3", 10)), + }, + } + if err := ctrl.SubmitClusterSnapshot(initial); err != nil { + t.Fatalf("SubmitClusterSnapshot initial: %v", err) + } + ask := nextAskOrFail(t, ctrl) + if ask.Intent != IntentBind { + t.Fatalf("want Bind, got %+v", ask) + } + + // Simulate publisher/cluster observation converging on the desired line. + reader.Set("v1", ask.ReplicaID, AuthorityBasis{ + Assigned: true, ReplicaID: ask.ReplicaID, Epoch: 1, EndpointVersion: 1, + DataAddr: ask.DataAddr, CtrlAddr: ask.CtrlAddr, + }) + observed := initial + observed.CollectedRevision = 2 + observed.Volumes[0].Authority = AuthorityBasis{ + Assigned: true, ReplicaID: ask.ReplicaID, Epoch: 1, EndpointVersion: 1, + DataAddr: ask.DataAddr, CtrlAddr: ask.CtrlAddr, + } + if err := ctrl.SubmitClusterSnapshot(observed); err != nil { + t.Fatalf("SubmitClusterSnapshot observed: %v", err) + } + expectNoNext(t, ctrl) +} + +func TestTopologyController_StalePreConfirmSnapshotDoesNotDuplicateQueuedMove(t *testing.T) { + reader := newFakeBasisReader() + ctrl := NewTopologyController(TopologyControllerConfig{}, reader) + snap := ClusterSnapshot{ + CollectedRevision: 1, + Servers: []ServerObservation{ + {ServerID: "s1", Reachable: true, Eligible: true}, + {ServerID: "s2", Reachable: true, Eligible: true}, + {ServerID: "s3", Reachable: true, Eligible: true}, + }, + Volumes: []VolumeTopologySnapshot{ + clusterVolume("v1", AuthorityBasis{}, candidate("r1", "s1", "d1", "c1", 10), candidate("r2", "s2", "d2", "c2", 10), candidate("r3", "s3", "d3", "c3", 10)), + }, + } + if err := ctrl.SubmitClusterSnapshot(snap); err != nil { + t.Fatalf("SubmitClusterSnapshot 1: %v", err) + } + ask := nextAskOrFail(t, ctrl) + if ask.Intent != IntentBind { + t.Fatalf("want Bind, got %+v", ask) + } + + // Publisher has already advanced, but the collector is still + // stale and reports Authority.Assigned=false. The controller + // must NOT enqueue the same move again; the desired state stays + // pending until an observed snapshot confirms it. + reader.Set("v1", ask.ReplicaID, AuthorityBasis{ + Assigned: true, ReplicaID: ask.ReplicaID, Epoch: 1, EndpointVersion: 1, + DataAddr: ask.DataAddr, CtrlAddr: ask.CtrlAddr, + }) + staleAgain := snap + staleAgain.CollectedRevision = 2 + if err := ctrl.SubmitClusterSnapshot(staleAgain); err != nil { + t.Fatalf("SubmitClusterSnapshot stale: %v", err) + } + expectNoNext(t, ctrl) + + observed := snap + observed.CollectedRevision = 3 + observed.Volumes[0].Authority = AuthorityBasis{ + Assigned: true, ReplicaID: ask.ReplicaID, Epoch: 1, EndpointVersion: 1, + DataAddr: ask.DataAddr, CtrlAddr: ask.CtrlAddr, + } + if err := ctrl.SubmitClusterSnapshot(observed); err != nil { + t.Fatalf("SubmitClusterSnapshot observed: %v", err) + } + expectNoNext(t, ctrl) +} diff --git a/seaweed-block/core/authority/observation_host.go b/seaweed-block/core/authority/observation_host.go new file mode 100644 index 0000000000..3b23409a5d --- /dev/null +++ b/seaweed-block/core/authority/observation_host.go @@ -0,0 +1,248 @@ +package authority + +import ( + "context" + "sync" + "time" +) + +// ============================================================ +// P14 S4 — Observation Host +// +// Owns the ObservationStore, wires push-ingest endpoints, +// runs reactive snapshot rebuild, and feeds synthesized +// ClusterSnapshot values into the TopologyController. +// +// Institution logic lives here, not in cmd/sparrow. The cmd +// layer is only allowed to construct, start, and stop the host. +// +// Default operation is build-on-change (sketch §11): every +// successful Ingest fires a non-blocking signal that wakes the +// rebuild goroutine. The goroutine drains the signal, takes one +// store snapshot, runs BuildSnapshot, and hands the +// ClusterSnapshot to the controller's SubmitClusterSnapshot. +// Pending / Unsupported volumes are surfaced via the last +// build's SupportabilityReport — NOT by mutating the controller. +// ============================================================ + +// ControllerSink is the narrow sink interface the host uses to +// feed synthesized observations into the topology controller. +// Kept as an interface so the host does not depend on the +// concrete TopologyController type and so tests can provide a +// fake. +// +// The sink receives BOTH the supported snapshot AND the +// supportability report in one atomic call. This is intentional: +// the controller must hear pending / unsupported transitions +// even when the supported-volumes set shrinks to zero. An +// earlier draft suppressed submission on empty snapshots, which +// left stale desired state live in the controller after a +// supportability collapse — an architect-blocker finding. +// +// This interface also keeps the boundary-guard check +// deterministic (sketch §16a): observation code only calls +// read-only authority surfaces and this single controller +// intake surface, which is a cluster-state submission, not an +// authority mint. +type ControllerSink interface { + SubmitObservedState(snap ClusterSnapshot, report SupportabilityReport) error +} + +// ObservationHost is the institution host for P14 S4. +type ObservationHost struct { + store *ObservationStore + topology AcceptedTopology + sink ControllerSink + reader AuthorityBasisReader + + mu sync.Mutex + lastBuild *BuildResult + sinkErrors []error + + wake chan struct{} + stop chan struct{} + done chan struct{} + gcTick time.Duration + gcRetain time.Duration +} + +// ObservationHostConfig pins host-wide knobs. GCInterval is +// optional; zero means no periodic GC sweep. +// +// Reader is a read-only authority view (*Publisher satisfies it). +// It is used by BuildSnapshot to stamp the per-volume current +// authority basis into supported VolumeTopologySnapshots so the +// controller's stale-resistance check can succeed on subsequent +// feeds. Reader may be nil for early-boot tests that do not yet +// have a publisher wired up; in production it must be set. +type ObservationHostConfig struct { + Freshness FreshnessConfig + Topology AcceptedTopology + Sink ControllerSink + Reader AuthorityBasisReader + Now func() time.Time + GCInterval time.Duration + GCRetainWindow time.Duration +} + +// NewObservationHost constructs a host. It does NOT start the +// rebuild goroutine — call Start for that. +func NewObservationHost(cfg ObservationHostConfig) *ObservationHost { + now := cfg.Now + if now == nil { + now = time.Now + } + store := NewObservationStore(cfg.Freshness, now) + gcRetain := cfg.GCRetainWindow + if gcRetain <= 0 { + // Reasonable default: four times the freshness window. + // Long enough that an expired observation stays visible + // across several diagnosis cycles; short enough to bound + // memory. + gcRetain = cfg.Freshness.withDefaults().FreshnessWindow * 4 + } + h := &ObservationHost{ + store: store, + topology: cfg.Topology, + sink: cfg.Sink, + reader: cfg.Reader, + wake: make(chan struct{}, 1), + stop: make(chan struct{}), + done: make(chan struct{}), + gcTick: cfg.GCInterval, + gcRetain: gcRetain, + } + store.SetOnMutation(h.signalRebuild) + return h +} + +// Store returns the underlying store. Exposed for tests and for +// downstream diagnosis; the host does not expect external code +// to manipulate it beyond Ingest. +func (h *ObservationHost) Store() *ObservationStore { + return h.store +} + +// Ingest is the primary push entry point. Source adapters call +// this with a translated Observation (typically via +// HeartbeatToObservation). Ingest delegates to the store and +// returns its error, if any. +func (h *ObservationHost) Ingest(obs Observation) error { + return h.store.Ingest(obs) +} + +// IngestHeartbeat is a convenience entry for sources that still +// speak the V2-shaped wire. It translates and then calls Ingest. +func (h *ObservationHost) IngestHeartbeat(msg HeartbeatMessage) error { + obs, err := HeartbeatToObservation(msg) + if err != nil { + return err + } + return h.Ingest(obs) +} + +// LastBuild returns the most recent BuildResult produced by the +// rebuild loop, if any. Safe for concurrent readers; returns a +// value copy. +func (h *ObservationHost) LastBuild() (BuildResult, bool) { + h.mu.Lock() + defer h.mu.Unlock() + if h.lastBuild == nil { + return BuildResult{}, false + } + return *h.lastBuild, true +} + +// signalRebuild is the mutation callback registered with the +// store. It must be non-blocking: a pending wake is coalesced +// with the new mutation, so build-on-change stays reactive +// without piling up goroutines (sketch §11 coalescing +// allowance). +func (h *ObservationHost) signalRebuild() { + select { + case h.wake <- struct{}{}: + default: + } +} + +// Start launches the rebuild goroutine. The goroutine runs until +// Stop is called or ctx is cancelled, whichever happens first. +// Returns immediately. +func (h *ObservationHost) Start(ctx context.Context) { + go h.run(ctx) +} + +// Stop requests the rebuild goroutine to exit and waits for it. +// Idempotent. +func (h *ObservationHost) Stop() { + select { + case <-h.stop: + // already stopped + default: + close(h.stop) + } + <-h.done +} + +func (h *ObservationHost) run(ctx context.Context) { + defer close(h.done) + var gcC <-chan time.Time + if h.gcTick > 0 { + ticker := time.NewTicker(h.gcTick) + defer ticker.Stop() + gcC = ticker.C + } + + // First build on start — so consumers see an initial empty + // snapshot rather than waiting for the first ingest. + h.rebuildOnce() + + for { + select { + case <-ctx.Done(): + return + case <-h.stop: + return + case <-h.wake: + h.rebuildOnce() + case <-gcC: + h.store.GC(h.gcRetain) + // GC may have set the mutation flag; that is OK — the + // next iteration will pick up the wake. + } + } +} + +// rebuildOnce takes one store snapshot, runs BuildSnapshot, and +// pushes the result (supported snapshot + supportability report) +// to the sink atomically. +// +// Unlike an earlier draft that suppressed submission when no +// supported volumes existed, this method ALWAYS submits if the +// sink is set and the build produced something the controller +// should hear — supported volumes, pending transitions, or +// unsupported transitions. A build with no supported volumes +// AND no report entries is a genuine no-op (e.g. start-up +// before any ingest) and is skipped. +func (h *ObservationHost) rebuildOnce() { + snap := h.store.Snapshot() + result := BuildSnapshot(snap, h.topology, h.reader) + + h.mu.Lock() + h.lastBuild = &result + h.mu.Unlock() + + if h.sink == nil { + return + } + hasSupported := len(result.Snapshot.Volumes) > 0 + hasReport := len(result.Report.Pending) > 0 || len(result.Report.Unsupported) > 0 + if !hasSupported && !hasReport { + return + } + if err := h.sink.SubmitObservedState(result.Snapshot, result.Report); err != nil { + h.mu.Lock() + h.sinkErrors = append(h.sinkErrors, err) + h.mu.Unlock() + } +} diff --git a/seaweed-block/core/authority/observation_store.go b/seaweed-block/core/authority/observation_store.go new file mode 100644 index 0000000000..a52379353e --- /dev/null +++ b/seaweed-block/core/authority/observation_store.go @@ -0,0 +1,249 @@ +package authority + +import ( + "errors" + "sort" + "sync" + "time" +) + +// ============================================================ +// P14 S4 — Observation Store +// +// Push-ingested latest-wins observation store per ServerID. The +// store computes derived freshness on read, based on wall-clock +// time vs ObservedAt + FreshnessWindow. Expired observations stay +// visible; they are just semantically ineligible for supported +// snapshot synthesis. See sketch §6. +// ============================================================ + +// ObservationStore holds the latest observation per reporting +// ServerID, plus a bootstrap timestamp used by the snapshot +// builder for the "never-observed-yet within grace" case. +// +// Push ingest only (sketch §10). The store does not pull from +// runtime or adapter state. Mutation triggers a registered +// rebuild hook so the host can re-synthesize reactively +// (sketch §11). +type ObservationStore struct { + config FreshnessConfig + now func() time.Time + startedAt time.Time + + mu sync.Mutex + observations map[string]Observation // key: ServerID + revision uint64 + onMutation func() +} + +// NewObservationStore constructs a store with the given freshness +// configuration. `now` is injected for deterministic testing; pass +// time.Now in production. +func NewObservationStore(config FreshnessConfig, now func() time.Time) *ObservationStore { + if now == nil { + now = time.Now + } + cfg := config.withDefaults() + return &ObservationStore{ + config: cfg, + now: now, + startedAt: now(), + observations: map[string]Observation{}, + } +} + +// SetOnMutation registers a callback that fires whenever a +// successful ingest changes store contents. The callback must +// NOT block; typical use is a non-blocking signal into the host's +// rebuild goroutine. +// +// Registered after construction rather than at construction so +// the host can assemble store and controller before wiring. +func (s *ObservationStore) SetOnMutation(fn func()) { + s.mu.Lock() + s.onMutation = fn + s.mu.Unlock() +} + +// ErrInvalidObservation is returned from Ingest for clearly +// malformed observations. Valid observations may still be +// semantically ineligible (expired, conflicting) — that is the +// builder's job, not the store's. +var ErrInvalidObservation = errors.New("observation_store: invalid observation") + +// Ingest validates and stores an observation, computes its +// ExpiresAt, and fires the registered mutation callback if +// anything changed. +// +// Latest-wins per ServerID. If an incoming observation has an +// ObservedAt strictly older than the currently-stored one from +// the same server, the store keeps the newer one (ignores the +// stale ingest). No error is returned for that case; it's a +// routine ordering event, not a bug. +func (s *ObservationStore) Ingest(obs Observation) error { + if obs.ServerID == "" { + return ErrInvalidObservation + } + if obs.ObservedAt.IsZero() { + return ErrInvalidObservation + } + + // Always compute ExpiresAt from store config — do not trust + // caller-supplied ExpiresAt to prevent out-of-band freshness + // fabrication. + obs.ExpiresAt = obs.ObservedAt.Add(s.config.FreshnessWindow) + + var fn func() + s.mu.Lock() + if prev, ok := s.observations[obs.ServerID]; ok { + if prev.ObservedAt.After(obs.ObservedAt) { + // Out-of-order ingest: keep the newer one already + // stored. No mutation fired. + s.mu.Unlock() + return nil + } + } + s.observations[obs.ServerID] = obs + s.revision++ + fn = s.onMutation + s.mu.Unlock() + + if fn != nil { + fn() + } + return nil +} + +// storeSnapshot is the immutable per-call value consumed by the +// snapshot builder. It deliberately DOES NOT reference the live +// store; the builder operates on this value alone. This is the +// API boundary that keeps supportability logic off the +// synthesized-output back-edge (sketch §12 one-way pipeline). +type storeSnapshot struct { + observations map[string]Observation + serverFreshness map[string]ServerFreshness + revision uint64 + evaluatedAt time.Time + startedAt time.Time + pendingGrace time.Duration + freshnessWindow time.Duration +} + +// ServerFreshness is the derived freshness state of one ServerID +// at evaluation time. Kept distinct from an implicit bool so +// pending-vs-unsupported remains explicit through the API. +// (Architect execution note.) +type ServerFreshness uint8 + +const ( + // ServerNeverObserved: the store has no observation for this + // ServerID. Within PendingGrace of store start time, this is + // pending; otherwise it surfaces as missing. + ServerNeverObserved ServerFreshness = iota + // ServerBootstrapping: never observed AND the store has been + // running for less than PendingGrace. The consumer treats + // this as pending, not unsupported. + ServerBootstrapping + // ServerMissing: never observed AND past the bootstrap grace. + // The consumer treats this as unsupported with reason + // ReasonMissingServerObservation. + ServerMissing + // ServerFresh: observed within FreshnessWindow. + ServerFresh + // ServerExpired: observed, but now > ExpiresAt. The fact + // stays visible for diagnosis but is ineligible for + // supported synthesis. + ServerExpired +) + +// Snapshot returns an immutable per-call snapshot of the store +// plus pre-computed per-server freshness state. The builder +// receives this and performs all supportability logic against it +// without ever touching the live store or synthesized output. +func (s *ObservationStore) Snapshot() storeSnapshot { + s.mu.Lock() + defer s.mu.Unlock() + + now := s.now() + obsCopy := make(map[string]Observation, len(s.observations)) + freshness := make(map[string]ServerFreshness, len(s.observations)) + for id, obs := range s.observations { + obsCopy[id] = obs + if now.After(obs.ExpiresAt) { + freshness[id] = ServerExpired + } else { + freshness[id] = ServerFresh + } + } + return storeSnapshot{ + observations: obsCopy, + serverFreshness: freshness, + revision: s.revision, + evaluatedAt: now, + startedAt: s.startedAt, + pendingGrace: s.config.PendingGrace, + freshnessWindow: s.config.FreshnessWindow, + } +} + +// freshnessFor returns the ServerFreshness of a given ServerID +// at evaluation time. If the ServerID is not present in the +// observations map, it returns either ServerBootstrapping or +// ServerMissing depending on whether the store is still within +// its bootstrap pending-grace window. +func (ss storeSnapshot) freshnessFor(serverID string) ServerFreshness { + if f, ok := ss.serverFreshness[serverID]; ok { + return f + } + if ss.evaluatedAt.Sub(ss.startedAt) < ss.pendingGrace { + return ServerBootstrapping + } + return ServerMissing +} + +// freshServerInventory returns the sorted set of ServerIDs with +// a fresh observation. This is the PRE-SNAPSHOT input used by +// supportability rules to decide missing-server cases — it is +// NOT ClusterSnapshot.Servers (which is an output; sketch §12). +func (ss storeSnapshot) freshServerInventory() []string { + out := make([]string, 0, len(ss.serverFreshness)) + for id, f := range ss.serverFreshness { + if f == ServerFresh { + out = append(out, id) + } + } + sort.Strings(out) + return out +} + +// GC removes observations strictly older than retain. Typically +// called periodically by the host to bound store memory. GC only +// removes entries that cannot meaningfully influence any future +// decision; expired entries that are still within retain are +// kept visible. +// +// Returns the number of entries removed. A non-zero return fires +// the mutation callback, since supportability of some volume may +// have changed. +func (s *ObservationStore) GC(retain time.Duration) int { + var fn func() + var removed int + s.mu.Lock() + now := s.now() + for id, obs := range s.observations { + if now.Sub(obs.ObservedAt) > retain { + delete(s.observations, id) + removed++ + } + } + if removed > 0 { + s.revision++ + fn = s.onMutation + } + s.mu.Unlock() + + if fn != nil { + fn() + } + return removed +} diff --git a/seaweed-block/core/authority/observation_test.go b/seaweed-block/core/authority/observation_test.go new file mode 100644 index 0000000000..f3305b9205 --- /dev/null +++ b/seaweed-block/core/authority/observation_test.go @@ -0,0 +1,1447 @@ +package authority + +import ( + "context" + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "testing" + "time" +) + +// ============================================================ +// P14 S4 — Observation Institution Tests +// +// Proof matrix from sw-block/design/v3-phase-14-s4-sketch.md §16: +// +// # | Claim | Test +// ---+-------------------------------------------------------------+--------------------------- +// 1 | Missing inventory -> unsupported, not failover input | PartialInventory_PendingThenUnsupported + +// | | Unsupported_NotInControllerInput +// 2 | Conflicting primary claims -> unsupported, not rebalance | ConflictingPrimaryClaim_Unsupported + +// | | ConflictingVolume_NotInControllerInput +// 3 | Stale observation cannot mint fresh authority | ExpiredFact_SemanticallyIneligible + +// | | ExpiredDoesNotReachController +// 4 | Bad volume does not block healthy volumes | BadVolumeDoesNotBlockHealthyVolume_Isolation +// 5 | Route into TopologyController is system-fed | EndToEnd_SystemFedSnapshotReachesController +// 6 | Missing-server inventory -> pending then unsupported, | MissingServerObservation_NeverOrdinaryIneligible +// | never ordinary ineligible | +// 7 | Conflict resolution never picks a winner | ConflictingPrimaryClaim_NoWinnerEverChosen +// 8 | Per-volume evidence isolation | VolumeUnsupportedEvidence_IsolatedPerVolume +// 9 | Push ingest triggers reactive rebuild | IngestMutation_TriggersSnapshotRebuild +// 10 | FreshnessWindow honored, not tick multiples | FreshnessWindowHonored_NotTickMultiples +// 11 | Observation withholds supportability, does not mint | NeverMintsAuthority_BoundaryGuard +// | authority | +// 12 | Duplicate-server topology -> unsupported | DuplicateServerTopology_UnsupportedAndEvidenceRecorded + +// | | DuplicateServerTopology_NotControllerInput +// 13 | Supportability reads only pre-snapshot input, never output | SupportabilityDoesNotReadClusterSnapshotOutput +// ============================================================ + +// fakeClock returns a controllable clock for deterministic tests. +type fakeClock struct { + mu sync.Mutex + t time.Time +} + +func newFakeClock(t time.Time) *fakeClock { return &fakeClock{t: t} } +func (c *fakeClock) Now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.t } +func (c *fakeClock) Advance(d time.Duration) { c.mu.Lock(); defer c.mu.Unlock(); c.t = c.t.Add(d) } +func (c *fakeClock) Set(t time.Time) { c.mu.Lock(); defer c.mu.Unlock(); c.t = t } + +// recordingSink captures submitted observed-state calls for +// assertions. Implements ControllerSink's SubmitObservedState — +// both the supported snapshot and the supportability report are +// captured per call, so tests can observe transitions (e.g. a +// volume moving into report.Unsupported) even when the snapshot +// has no supported volumes. +type recordingSink struct { + mu sync.Mutex + calls []observedStateCall + err error +} + +type observedStateCall struct { + Snapshot ClusterSnapshot + Report SupportabilityReport +} + +func (r *recordingSink) SubmitObservedState(snap ClusterSnapshot, report SupportabilityReport) error { + r.mu.Lock() + r.calls = append(r.calls, observedStateCall{Snapshot: snap, Report: report}) + err := r.err + r.mu.Unlock() + return err +} + +func (r *recordingSink) records() []observedStateCall { + r.mu.Lock() + defer r.mu.Unlock() + cp := make([]observedStateCall, len(r.calls)) + copy(cp, r.calls) + return cp +} + +// snapshot returns just the ClusterSnapshots from recorded calls, +// for tests that only care about the supported-volumes sequence. +func (r *recordingSink) snapshot() []ClusterSnapshot { + r.mu.Lock() + defer r.mu.Unlock() + cp := make([]ClusterSnapshot, len(r.calls)) + for i, c := range r.calls { + cp[i] = c.Snapshot + } + return cp +} + +// threeSlotVolume is the accepted topology for a single volume +// used across the S4 tests. Three slots on distinct servers. +func threeSlotVolume(volumeID string) VolumeExpected { + return VolumeExpected{ + VolumeID: volumeID, + Slots: []ExpectedSlot{ + {ReplicaID: "r1", ServerID: "s1"}, + {ReplicaID: "r2", ServerID: "s2"}, + {ReplicaID: "r3", ServerID: "s3"}, + }, + } +} + +// healthySlot builds a fresh well-formed SlotFact. +func healthySlot(volumeID, replicaID string) SlotFact { + return SlotFact{ + VolumeID: volumeID, + ReplicaID: replicaID, + DataAddr: "data-" + replicaID, + CtrlAddr: "ctrl-" + replicaID, + Reachable: true, + ReadyForPrimary: true, + Eligible: true, + } +} + +// serverObs assembles a HeartbeatMessage for one server listing +// the given slots. The assertion tests use HeartbeatToObservation +// to make sure the wire port is exercised alongside the direct +// Ingest path. +func serverObs(serverID string, at time.Time, slots ...SlotFact) HeartbeatMessage { + return HeartbeatMessage{ + ServerID: serverID, + SentAt: at, + Reachable: true, + Eligible: true, + Slots: func() []HeartbeatSlot { + out := make([]HeartbeatSlot, len(slots)) + for i, s := range slots { + out[i] = HeartbeatSlot{ + VolumeID: s.VolumeID, + ReplicaID: s.ReplicaID, + DataAddr: s.DataAddr, + CtrlAddr: s.CtrlAddr, + Reachable: s.Reachable, + ReadyForPrimary: s.ReadyForPrimary, + Eligible: s.Eligible, + Withdrawn: s.Withdrawn, + EvidenceScore: s.EvidenceScore, + LocalRoleClaim: s.LocalRoleClaim, + } + } + return out + }(), + } +} + +// ============================================================ +// Rows 1 + 6: partial inventory / missing-server +// ============================================================ + +func TestObservation_PartialInventory_PendingThenUnsupported(t *testing.T) { + start := time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + store := NewObservationStore(FreshnessConfig{ + FreshnessWindow: 5 * time.Second, + PendingGrace: 5 * time.Second, + }, clk.Now) + + topo := AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}} + + // Within bootstrap grace: submit only s1's observation. s2, s3 missing. + obs, err := HeartbeatToObservation(serverObs("s1", start, healthySlot("v1", "r1"))) + if err != nil { + t.Fatalf("translate: %v", err) + } + if err := store.Ingest(obs); err != nil { + t.Fatalf("ingest: %v", err) + } + + result := BuildSnapshot(store.Snapshot(), topo, nil) + if _, supported := findSupported(result, "v1"); supported { + t.Fatal("partial-inventory volume should not be supported within grace") + } + if _, ok := result.Report.Pending["v1"]; !ok { + t.Fatal("partial-inventory volume within grace should be pending, got none") + } + if _, ok := result.Report.Unsupported["v1"]; ok { + t.Fatal("partial-inventory volume within grace must NOT be unsupported") + } + + // Advance past pending grace. Still only s1 observed. Now unsupported. + clk.Advance(10 * time.Second) + // Re-ingest to refresh s1's observation (so its freshness is current). + obs2, _ := HeartbeatToObservation(serverObs("s1", clk.Now(), healthySlot("v1", "r1"))) + if err := store.Ingest(obs2); err != nil { + t.Fatalf("ingest 2: %v", err) + } + + result2 := BuildSnapshot(store.Snapshot(), topo, nil) + if _, ok := result2.Report.Unsupported["v1"]; !ok { + t.Fatal("past pending grace, partial inventory must be unsupported") + } + if _, ok := result2.Report.Pending["v1"]; ok { + t.Fatal("past pending grace, volume must NOT still be pending") + } + reasons := result2.Report.Unsupported["v1"].Reasons + if !contains(reasons, ReasonMissingServerObservation) { + t.Fatalf("expected ReasonMissingServerObservation, got %v", reasons) + } +} + +func TestObservation_MissingServerObservation_NeverOrdinaryIneligible(t *testing.T) { + // A slot whose ServerID is not observed must NOT appear in + // ClusterSnapshot.Volumes[].Slots as an ordinary candidate. + // It must either make the whole volume pending or make it + // unsupported — never silently enter as "ineligible". + start := time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + store := NewObservationStore(FreshnessConfig{ + FreshnessWindow: 5 * time.Second, + PendingGrace: 100 * time.Millisecond, + }, clk.Now) + topo := AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}} + + // Observe s1 and s2 only. s3 is missing. + _ = ingest(t, store, serverObs("s1", start, healthySlot("v1", "r1"))) + _ = ingest(t, store, serverObs("s2", start, healthySlot("v1", "r2"))) + + clk.Advance(200 * time.Millisecond) // past pending grace + // Re-ingest to refresh freshness of s1/s2. + _ = ingest(t, store, serverObs("s1", clk.Now(), healthySlot("v1", "r1"))) + _ = ingest(t, store, serverObs("s2", clk.Now(), healthySlot("v1", "r2"))) + + result := BuildSnapshot(store.Snapshot(), topo, nil) + if _, ok := result.Report.Unsupported["v1"]; !ok { + t.Fatal("missing-server volume must be unsupported past grace") + } + for _, v := range result.Snapshot.Volumes { + if v.VolumeID != "v1" { + continue + } + for _, slot := range v.Slots { + if slot.ReplicaID == "r3" { + t.Fatal("missing-server slot must NOT appear as ordinary candidate in ClusterSnapshot") + } + } + } +} + +// ============================================================ +// Row 5: end-to-end system-fed route +// ============================================================ + +func TestObservation_EndToEnd_SystemFedSnapshotReachesController(t *testing.T) { + start := time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + sink := &recordingSink{} + host := NewObservationHost(ObservationHostConfig{ + Freshness: FreshnessConfig{FreshnessWindow: 5 * time.Second, PendingGrace: 100 * time.Millisecond}, + Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}}, + Sink: sink, + Now: clk.Now, + }) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + host.Start(ctx) + defer host.Stop() + + // All three servers observed fresh. + _ = host.IngestHeartbeat(serverObs("s1", start, healthySlot("v1", "r1"))) + _ = host.IngestHeartbeat(serverObs("s2", start, healthySlot("v1", "r2"))) + _ = host.IngestHeartbeat(serverObs("s3", start, healthySlot("v1", "r3"))) + + // Wait for a synthesized snapshot to reach the sink. + deadline := time.Now().Add(1 * time.Second) + for time.Now().Before(deadline) { + if len(sink.snapshot()) > 0 { + break + } + time.Sleep(10 * time.Millisecond) + } + got := sink.snapshot() + if len(got) == 0 { + t.Fatal("sink never received a synthesized ClusterSnapshot") + } + final := got[len(got)-1] + if len(final.Volumes) != 1 || final.Volumes[0].VolumeID != "v1" { + t.Fatalf("expected v1 in final snapshot, got %+v", final.Volumes) + } + if len(final.Volumes[0].Slots) != 3 { + t.Fatalf("expected 3 slots for v1, got %d", len(final.Volumes[0].Slots)) + } +} + +// ============================================================ +// Rows 2 + 7: conflicting primary claim +// ============================================================ + +func TestObservation_ConflictingPrimaryClaim_Unsupported(t *testing.T) { + start := time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + store := NewObservationStore(FreshnessConfig{FreshnessWindow: 5 * time.Second}, clk.Now) + topo := AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}} + + // Two fresh slots each claim LocalRolePrimary for v1. + s1slot := healthySlot("v1", "r1") + s1slot.LocalRoleClaim = LocalRolePrimary + s2slot := healthySlot("v1", "r2") + s2slot.LocalRoleClaim = LocalRolePrimary + _ = ingest(t, store, serverObs("s1", start, s1slot)) + _ = ingest(t, store, serverObs("s2", start, s2slot)) + _ = ingest(t, store, serverObs("s3", start, healthySlot("v1", "r3"))) + + result := BuildSnapshot(store.Snapshot(), topo, nil) + ev, ok := result.Report.Unsupported["v1"] + if !ok { + t.Fatal("conflicting primary claim must produce unsupported evidence") + } + if !contains(ev.Reasons, ReasonConflictingPrimaryClaim) { + t.Fatalf("expected ConflictingPrimaryClaim in reasons, got %v", ev.Reasons) + } + if len(ev.OffendingFacts) < 2 { + t.Fatalf("expected both offending facts recorded, got %d", len(ev.OffendingFacts)) + } + // Volume must not be in snapshot. + for _, v := range result.Snapshot.Volumes { + if v.VolumeID == "v1" { + t.Fatal("conflicting volume must NOT appear in ClusterSnapshot") + } + } +} + +func TestObservation_ConflictingPrimaryClaim_NoWinnerEverChosen(t *testing.T) { + start := time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + store := NewObservationStore(FreshnessConfig{FreshnessWindow: 5 * time.Second}, clk.Now) + topo := AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}} + + // Three primary claims with differing evidence-score and + // differing observed-at. The observation layer must NOT + // arbitrate — regardless of rankings. + s1slot := healthySlot("v1", "r1") + s1slot.LocalRoleClaim = LocalRolePrimary + s1slot.EvidenceScore = 100 // highest + s2slot := healthySlot("v1", "r2") + s2slot.LocalRoleClaim = LocalRolePrimary + s2slot.EvidenceScore = 50 + s3slot := healthySlot("v1", "r3") + s3slot.LocalRoleClaim = LocalRolePrimary + s3slot.EvidenceScore = 1 // lowest + + _ = ingest(t, store, serverObs("s1", start.Add(2*time.Second), s1slot)) + _ = ingest(t, store, serverObs("s2", start.Add(3*time.Second), s2slot)) // newest + _ = ingest(t, store, serverObs("s3", start.Add(1*time.Second), s3slot)) // oldest + + result := BuildSnapshot(store.Snapshot(), topo, nil) + + if _, supported := findSupported(result, "v1"); supported { + t.Fatal("volume must not be supported; any 'winner' choice is an authority mint") + } + if _, ok := result.Report.Unsupported["v1"]; !ok { + t.Fatal("expected unsupported evidence for three-way primary conflict") + } +} + +// ============================================================ +// Row 3: stale observation cannot mint fresh authority +// ============================================================ + +func TestObservation_ExpiredFact_SemanticallyIneligible(t *testing.T) { + start := time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + store := NewObservationStore(FreshnessConfig{FreshnessWindow: 2 * time.Second}, clk.Now) + topo := AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}} + + _ = ingest(t, store, serverObs("s1", start, healthySlot("v1", "r1"))) + _ = ingest(t, store, serverObs("s2", start, healthySlot("v1", "r2"))) + _ = ingest(t, store, serverObs("s3", start, healthySlot("v1", "r3"))) + + // Now advance well past FreshnessWindow. All three observations + // are expired. They remain visible in the store but are + // semantically ineligible for supported snapshot synthesis. + clk.Advance(10 * time.Second) + + // Store still holds them (visibility). + snap := store.Snapshot() + if len(snap.observations) != 3 { + t.Fatalf("expected expired observations to remain visible, got %d", len(snap.observations)) + } + // But none are ServerFresh. + for _, f := range snap.serverFreshness { + if f == ServerFresh { + t.Fatal("expired observation must not be ServerFresh") + } + } + // Build: volume must be unsupported with StaleObservation. + result := BuildSnapshot(snap, topo, nil) + ev, ok := result.Report.Unsupported["v1"] + if !ok { + t.Fatal("expired-only volume must be unsupported") + } + if !contains(ev.Reasons, ReasonStaleObservation) { + t.Fatalf("expected ReasonStaleObservation, got %v", ev.Reasons) + } +} + +func TestObservation_ExpiredDoesNotReachController(t *testing.T) { + start := time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + sink := &recordingSink{} + host := NewObservationHost(ObservationHostConfig{ + Freshness: FreshnessConfig{FreshnessWindow: 2 * time.Second}, + Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}}, + Sink: sink, + Now: clk.Now, + }) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + host.Start(ctx) + defer host.Stop() + + _ = host.IngestHeartbeat(serverObs("s1", start, healthySlot("v1", "r1"))) + _ = host.IngestHeartbeat(serverObs("s2", start, healthySlot("v1", "r2"))) + _ = host.IngestHeartbeat(serverObs("s3", start, healthySlot("v1", "r3"))) + + // Let initial publish land. + time.Sleep(50 * time.Millisecond) + initialCalls := len(sink.snapshot()) + + // Advance time so observations expire. + clk.Advance(10 * time.Second) + // Submit a spurious GC to re-trigger rebuild at the advanced + // time so the builder re-evaluates with everything expired. + host.Store().GC(1 * time.Hour) // no-op remove (everything within retain) + + // Force a rebuild: re-ingest a trivially-newer "s1" with the + // SAME local inventory so the store records a mutation and + // triggers a rebuild at the advanced clock. + _ = host.IngestHeartbeat(serverObs("s1", clk.Now(), healthySlot("v1", "r1"))) + time.Sleep(50 * time.Millisecond) + + // The last build's report must reflect the expired state, and + // the sink must NOT have received any supported snapshot for + // v1 after expiry (prior supported snapshots are allowed + // since they were valid at submission time; we assert the + // latest BuildResult did not publish a supported v1). + final, ok := host.LastBuild() + if !ok { + t.Fatal("host produced no BuildResult") + } + for _, v := range final.Snapshot.Volumes { + if v.VolumeID == "v1" { + t.Fatalf("expired-only v1 must NOT be in latest synthesized snapshot; got slots=%d", len(v.Slots)) + } + } + // Confirm no NEW sink publish happened for an unsupported v1. + // (We only check that no supported v1 snapshot emerged after + // the clock advance — any snapshot before the advance is OK.) + _ = initialCalls +} + +// ============================================================ +// Row 4: bad volume does not block healthy volumes +// ============================================================ + +func TestObservation_BadVolumeDoesNotBlockHealthyVolume_Isolation(t *testing.T) { + start := time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + store := NewObservationStore(FreshnessConfig{FreshnessWindow: 5 * time.Second}, clk.Now) + + // Two volumes, same server set. v1 healthy, v2 has conflicting + // primary claims. + topo := AcceptedTopology{Volumes: []VolumeExpected{ + threeSlotVolume("v1"), + threeSlotVolume("v2"), + }} + + v2r1 := healthySlot("v2", "r1") + v2r1.LocalRoleClaim = LocalRolePrimary + v2r2 := healthySlot("v2", "r2") + v2r2.LocalRoleClaim = LocalRolePrimary + v2r3 := healthySlot("v2", "r3") + + _ = ingest(t, store, serverObs("s1", start, + healthySlot("v1", "r1"), v2r1)) + _ = ingest(t, store, serverObs("s2", start, + healthySlot("v1", "r2"), v2r2)) + _ = ingest(t, store, serverObs("s3", start, + healthySlot("v1", "r3"), v2r3)) + + result := BuildSnapshot(store.Snapshot(), topo, nil) + + // v1 must be supported. + v1, supported := findSupported(result, "v1") + if !supported { + t.Fatalf("v1 must be supported; got report=%+v", result.Report) + } + if len(v1.Slots) != 3 { + t.Fatalf("v1 must have 3 slots, got %d", len(v1.Slots)) + } + + // v2 must be unsupported. + if _, ok := result.Report.Unsupported["v2"]; !ok { + t.Fatal("v2 must be unsupported") + } + + // Isolation: v2's unsupported status must not erase v1's + // supported status (per-volume evidence key; sketch §9). + for _, v := range result.Snapshot.Volumes { + if v.VolumeID == "v2" { + t.Fatal("v2 must NOT appear in ClusterSnapshot alongside v1") + } + } +} + +// ============================================================ +// Row 8: per-volume evidence isolation +// ============================================================ + +func TestObservation_VolumeUnsupportedEvidence_IsolatedPerVolume(t *testing.T) { + start := time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + store := NewObservationStore(FreshnessConfig{ + FreshnessWindow: 5 * time.Second, + PendingGrace: 50 * time.Millisecond, + }, clk.Now) + topo := AcceptedTopology{Volumes: []VolumeExpected{ + threeSlotVolume("v1"), + threeSlotVolume("v2"), + }} + + // Two different volumes, two different unsupported reasons. + // v1 → conflicting primary; v2 → partial inventory past grace. + v1r1 := healthySlot("v1", "r1") + v1r1.LocalRoleClaim = LocalRolePrimary + v1r2 := healthySlot("v1", "r2") + v1r2.LocalRoleClaim = LocalRolePrimary + + _ = ingest(t, store, serverObs("s1", start, v1r1, healthySlot("v2", "r1"))) + _ = ingest(t, store, serverObs("s2", start, v1r2 /* v2 partial: no v2 slots */)) + _ = ingest(t, store, serverObs("s3", start, healthySlot("v1", "r3") /* no v2 slots */)) + + clk.Advance(100 * time.Millisecond) + _ = ingest(t, store, serverObs("s1", clk.Now(), v1r1, healthySlot("v2", "r1"))) + _ = ingest(t, store, serverObs("s2", clk.Now(), v1r2)) + _ = ingest(t, store, serverObs("s3", clk.Now(), healthySlot("v1", "r3"))) + + result := BuildSnapshot(store.Snapshot(), topo, nil) + + // Each volume must have its OWN evidence; they must not + // overwrite each other. + if _, ok := result.Report.Unsupported["v1"]; !ok { + t.Fatal("v1 evidence missing (should be ConflictingPrimaryClaim)") + } + if _, ok := result.Report.Unsupported["v2"]; !ok { + t.Fatal("v2 evidence missing (should be PartialInventory)") + } + if !contains(result.Report.Unsupported["v1"].Reasons, ReasonConflictingPrimaryClaim) { + t.Fatalf("v1 reasons: %v", result.Report.Unsupported["v1"].Reasons) + } + if !contains(result.Report.Unsupported["v2"].Reasons, ReasonPartialInventory) && + !contains(result.Report.Unsupported["v2"].Reasons, ReasonMissingServerObservation) { + t.Fatalf("v2 reasons: %v", result.Report.Unsupported["v2"].Reasons) + } +} + +// ============================================================ +// Row 9: push ingest triggers reactive rebuild +// ============================================================ + +func TestObservationHost_IngestMutation_TriggersSnapshotRebuild(t *testing.T) { + start := time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + sink := &recordingSink{} + host := NewObservationHost(ObservationHostConfig{ + Freshness: FreshnessConfig{FreshnessWindow: 5 * time.Second}, + Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}}, + Sink: sink, + Now: clk.Now, + }) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + host.Start(ctx) + defer host.Stop() + + // With v1 configured but no observations yet, the initial + // rebuild produces a Pending report entry for v1 and submits + // it — supportability transitions propagate even without + // supported volumes. (This behavior is the fix for the + // architect finding that pending/unsupported did not reach + // the controller.) + time.Sleep(50 * time.Millisecond) + initialCalls := sink.records() + if len(initialCalls) == 0 { + t.Fatal("initial rebuild must submit (pending for v1) after host Start") + } + if _, ok := initialCalls[0].Report.Pending["v1"]; !ok { + t.Fatalf("initial call must carry Pending[v1]; got report=%+v", initialCalls[0].Report) + } + if len(initialCalls[0].Snapshot.Volumes) != 0 { + t.Fatalf("initial call must have no supported volumes; got %d", len(initialCalls[0].Snapshot.Volumes)) + } + + // Ingest one full volume's worth of observations one at a + // time. Each ingest must wake the rebuild loop. + _ = host.IngestHeartbeat(serverObs("s1", start, healthySlot("v1", "r1"))) + _ = host.IngestHeartbeat(serverObs("s2", start, healthySlot("v1", "r2"))) + _ = host.IngestHeartbeat(serverObs("s3", start, healthySlot("v1", "r3"))) + + // Eventually, a supported-v1 snapshot should reach the sink. + deadline := time.Now().Add(1 * time.Second) + sawSupported := false + for time.Now().Before(deadline) { + for _, c := range sink.records() { + for _, v := range c.Snapshot.Volumes { + if v.VolumeID == "v1" { + sawSupported = true + } + } + } + if sawSupported { + break + } + time.Sleep(10 * time.Millisecond) + } + if !sawSupported { + t.Fatal("push ingest did not produce a supported-v1 submission") + } +} + +// ============================================================ +// Row 10: freshness window is honored, not tick multiples +// ============================================================ + +func TestObservation_FreshnessWindowHonored_NotTickMultiples(t *testing.T) { + start := time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + store := NewObservationStore(FreshnessConfig{FreshnessWindow: 3 * time.Second}, clk.Now) + + obs, _ := HeartbeatToObservation(serverObs("s1", start, healthySlot("v1", "r1"))) + _ = store.Ingest(obs) + + // Before window elapses: fresh. + clk.Advance(2 * time.Second) + if store.Snapshot().serverFreshness["s1"] != ServerFresh { + t.Fatal("within window, must be fresh") + } + + // At exact window: still fresh (`now > ExpiresAt`). + clk.Set(start.Add(3 * time.Second)) + if store.Snapshot().serverFreshness["s1"] != ServerFresh { + t.Fatal("exactly at window, must still be fresh") + } + + // One nanosecond past window: expired. + clk.Set(start.Add(3*time.Second + 1)) + if store.Snapshot().serverFreshness["s1"] != ServerExpired { + t.Fatal("one nanosecond past window, must be expired") + } +} + +// ============================================================ +// Rows 11 + 13: boundary-guard (AST-based) +// ============================================================ + +// TestObservation_NeverMintsAuthority_BoundaryGuard enforces the +// sketch §16a claim that observation code may not construct +// authority requests, may not call authority write surfaces, and +// may not take a wider-than-needed dependency on Publisher. +func TestObservation_NeverMintsAuthority_BoundaryGuard(t *testing.T) { + files := observationFiles(t) + fset := token.NewFileSet() + + for _, path := range files { + src, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read %s: %v", path, err) + } + file, err := parser.ParseFile(fset, path, src, parser.ParseComments) + if err != nil { + t.Fatalf("parse %s: %v", path, err) + } + + ast.Inspect(file, func(n ast.Node) bool { + // Forbid composite literal construction of AssignmentAsk + // or adapter.AssignmentInfo in any form. + if cl, ok := n.(*ast.CompositeLit); ok && cl.Type != nil { + if typeNameMatches(cl.Type, "AssignmentAsk") || + isAdapterAssignmentInfo(cl.Type) { + t.Errorf("%s: observation code constructed %s", fset.Position(cl.Pos()), exprString(cl.Type)) + } + } + // Forbid AddressOf on such composite literals: &AssignmentAsk{...}. + if ue, ok := n.(*ast.UnaryExpr); ok && ue.Op == token.AND { + if cl, ok := ue.X.(*ast.CompositeLit); ok && cl.Type != nil { + if typeNameMatches(cl.Type, "AssignmentAsk") || + isAdapterAssignmentInfo(cl.Type) { + t.Errorf("%s: observation code took &%s{...}", fset.Position(ue.Pos()), exprString(cl.Type)) + } + } + } + // Forbid *Publisher as a field or parameter type — + // observation code must take a narrow read-only + // interface, not the concrete publisher. + if star, ok := n.(*ast.StarExpr); ok { + if id, ok := star.X.(*ast.Ident); ok && id.Name == "Publisher" { + t.Errorf("%s: observation code depends on *Publisher concrete type — must use narrow read-only interface", fset.Position(star.Pos())) + } + } + return true + }) + } +} + +// TestObservation_SupportabilityDoesNotReadClusterSnapshotOutput +// is the pipeline-direction guard (row 13). Supportability code +// lives in observation_store.go + snapshot_builder.go. Those +// files must not take a `ClusterSnapshot` as INPUT (parameter). +// ClusterSnapshot is an OUTPUT type here. +func TestObservation_SupportabilityDoesNotReadClusterSnapshotOutput(t *testing.T) { + files := []string{"observation_store.go", "snapshot_builder.go"} + fset := token.NewFileSet() + + for _, name := range files { + path := resolveAuthorityFile(t, name) + src, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read %s: %v", path, err) + } + file, err := parser.ParseFile(fset, path, src, parser.ParseComments) + if err != nil { + t.Fatalf("parse %s: %v", path, err) + } + ast.Inspect(file, func(n ast.Node) bool { + fn, ok := n.(*ast.FuncDecl) + if !ok || fn.Type == nil || fn.Type.Params == nil { + return true + } + for _, p := range fn.Type.Params.List { + if typeNameMatches(p.Type, "ClusterSnapshot") { + t.Errorf("%s: function %s takes ClusterSnapshot as input — supportability must not read synthesized output", + fset.Position(p.Pos()), fn.Name.Name) + } + } + return true + }) + } +} + +// ============================================================ +// Row 12: duplicate-server topology +// ============================================================ + +func TestObservation_DuplicateServerTopology_UnsupportedAndEvidenceRecorded(t *testing.T) { + start := time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + store := NewObservationStore(FreshnessConfig{FreshnessWindow: 5 * time.Second}, clk.Now) + + // Accepted topology claims r1@s1, r2@s2, r3@s3. But s1 also + // observes a fact claiming r2 lives on s1. Same-server + // duplicate. + topo := AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}} + badR2 := healthySlot("v1", "r2") + _ = ingest(t, store, serverObs("s1", start, + healthySlot("v1", "r1"), + badR2, // s1 ALSO claims r2 — topology violation + )) + _ = ingest(t, store, serverObs("s2", start, healthySlot("v1", "r2"))) + _ = ingest(t, store, serverObs("s3", start, healthySlot("v1", "r3"))) + + result := BuildSnapshot(store.Snapshot(), topo, nil) + ev, ok := result.Report.Unsupported["v1"] + if !ok { + t.Fatal("duplicate-server topology must produce unsupported evidence") + } + if !contains(ev.Reasons, ReasonDuplicateServerTopology) { + t.Fatalf("expected ReasonDuplicateServerTopology, got %v", ev.Reasons) + } + if len(ev.OffendingFacts) == 0 { + t.Fatal("offending facts must record the duplicated server observation") + } +} + +func TestObservation_DuplicateServerTopology_NotControllerInput(t *testing.T) { + start := time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + sink := &recordingSink{} + host := NewObservationHost(ObservationHostConfig{ + Freshness: FreshnessConfig{FreshnessWindow: 5 * time.Second}, + Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}}, + Sink: sink, + Now: clk.Now, + }) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + host.Start(ctx) + defer host.Stop() + + _ = host.IngestHeartbeat(serverObs("s1", start, + healthySlot("v1", "r1"), healthySlot("v1", "r2"))) + _ = host.IngestHeartbeat(serverObs("s2", start, healthySlot("v1", "r2"))) + _ = host.IngestHeartbeat(serverObs("s3", start, healthySlot("v1", "r3"))) + + time.Sleep(100 * time.Millisecond) + // Sink must not see v1 — the supported-volumes set was empty, + // so no SubmitClusterSnapshot call fires for it. + for _, s := range sink.snapshot() { + for _, v := range s.Volumes { + if v.VolumeID == "v1" { + t.Fatal("duplicate-server volume must NOT reach the controller") + } + } + } +} + +// ============================================================ +// Helpers +// ============================================================ + +func ingest(t *testing.T, store *ObservationStore, msg HeartbeatMessage) error { + t.Helper() + obs, err := HeartbeatToObservation(msg) + if err != nil { + t.Fatalf("translate: %v", err) + } + if err := store.Ingest(obs); err != nil { + t.Fatalf("ingest: %v", err) + } + return nil +} + +func contains(xs []string, x string) bool { + for _, v := range xs { + if v == x { + return true + } + } + return false +} + +func findSupported(result BuildResult, volumeID string) (VolumeTopologySnapshot, bool) { + for _, v := range result.Snapshot.Volumes { + if v.VolumeID == volumeID { + return v, true + } + } + return VolumeTopologySnapshot{}, false +} + +// observationFiles returns every production .go file under +// core/authority/ whose name starts with "observation_". +func observationFiles(t *testing.T) []string { + t.Helper() + dir := resolveAuthorityDir(t) + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatalf("readdir: %v", err) + } + var out []string + for _, e := range entries { + name := e.Name() + if e.IsDir() { + continue + } + if !strings.HasPrefix(name, "observation_") { + continue + } + if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { + continue + } + out = append(out, filepath.Join(dir, name)) + } + sort.Strings(out) + if len(out) == 0 { + t.Fatal("no observation_*.go files found") + } + return out +} + +func resolveAuthorityDir(t *testing.T) string { + t.Helper() + cwd, err := os.Getwd() + if err != nil { + t.Fatalf("getwd: %v", err) + } + // Tests run in package dir. + return cwd +} + +func resolveAuthorityFile(t *testing.T, name string) string { + t.Helper() + return filepath.Join(resolveAuthorityDir(t), name) +} + +// typeNameMatches reports whether an AST type expression names a +// given identifier, possibly via a selector (e.g. pkg.Name). +func typeNameMatches(expr ast.Expr, name string) bool { + switch t := expr.(type) { + case *ast.Ident: + return t.Name == name + case *ast.SelectorExpr: + return t.Sel.Name == name + case *ast.StarExpr: + return typeNameMatches(t.X, name) + case *ast.ArrayType: + return typeNameMatches(t.Elt, name) + } + return false +} + +func isAdapterAssignmentInfo(expr ast.Expr) bool { + switch t := expr.(type) { + case *ast.SelectorExpr: + if id, ok := t.X.(*ast.Ident); ok { + return id.Name == "adapter" && t.Sel.Name == "AssignmentInfo" + } + case *ast.StarExpr: + return isAdapterAssignmentInfo(t.X) + case *ast.ArrayType: + return isAdapterAssignmentInfo(t.Elt) + } + return false +} + +func exprString(e ast.Expr) string { + switch t := e.(type) { + case *ast.Ident: + return t.Name + case *ast.SelectorExpr: + return exprString(t.X) + "." + t.Sel.Name + case *ast.StarExpr: + return "*" + exprString(t.X) + } + return "?" +} + +// ============================================================ +// Architect-round regressions (v3-phase-14-s4 review #2) +// ============================================================ + +// fakeBasisReader is a minimal AuthorityBasisReader for tests +// that need to drive observation-fed snapshots with controlled +// per-volume authority basis values. +type fakeReaderForHost struct { + mu sync.Mutex + perVol map[string]AuthorityBasis + perSlot map[string]AuthorityBasis +} + +func newFakeReaderForHost() *fakeReaderForHost { + return &fakeReaderForHost{ + perVol: map[string]AuthorityBasis{}, + perSlot: map[string]AuthorityBasis{}, + } +} +func (r *fakeReaderForHost) LastAuthorityBasis(volumeID, replicaID string) (AuthorityBasis, bool) { + r.mu.Lock() + defer r.mu.Unlock() + b, ok := r.perSlot[volumeID+"/"+replicaID] + return b, ok +} +func (r *fakeReaderForHost) VolumeAuthorityLine(volumeID string) (AuthorityBasis, bool) { + r.mu.Lock() + defer r.mu.Unlock() + b, ok := r.perVol[volumeID] + return b, ok +} +func (r *fakeReaderForHost) SetVolume(volumeID string, b AuthorityBasis) { + r.mu.Lock() + defer r.mu.Unlock() + r.perVol[volumeID] = b + r.perSlot[volumeID+"/"+b.ReplicaID] = b +} + +// TestObservation_BuilderStampsAuthorityFromReader is the direct +// regression for architect finding #1: observation-fed supported +// VolumeTopologySnapshots must carry the publisher's current +// per-volume authority basis so the controller's stale-resistance +// check can match. A snapshot that always says Assigned=false +// would make the controller drop every observation-fed volume +// once a publisher line exists. +func TestObservation_BuilderStampsAuthorityFromReader(t *testing.T) { + start := time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + store := NewObservationStore(FreshnessConfig{FreshnessWindow: 5 * time.Second}, clk.Now) + topo := AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}} + + // All three slots observed fresh. + _ = ingest(t, store, serverObs("s1", start, healthySlot("v1", "r1"))) + _ = ingest(t, store, serverObs("s2", start, healthySlot("v1", "r2"))) + _ = ingest(t, store, serverObs("s3", start, healthySlot("v1", "r3"))) + + reader := newFakeReaderForHost() + // Publisher currently holds r1@5 for v1 (simulated). + reader.SetVolume("v1", AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, + DataAddr: "data-r1", CtrlAddr: "ctrl-r1", + }) + + result := BuildSnapshot(store.Snapshot(), topo, reader) + v, ok := findSupported(result, "v1") + if !ok { + t.Fatal("v1 must be supported") + } + if !v.Authority.Assigned { + t.Fatal("supported volume must carry publisher's current authority basis; Authority.Assigned=false") + } + if v.Authority.ReplicaID != "r1" || v.Authority.Epoch != 5 { + t.Fatalf("Authority basis wrong: got %+v", v.Authority) + } + + // Without a reader, default is Assigned=false (initial-bind + // case). That is still the honest "no view" default. + resultNoReader := BuildSnapshot(store.Snapshot(), topo, nil) + vn, ok := findSupported(resultNoReader, "v1") + if !ok { + t.Fatal("v1 must be supported without reader") + } + if vn.Authority.Assigned { + t.Fatalf("nil reader must leave Authority.Assigned=false, got %+v", vn.Authority) + } +} + +// TestObservation_SupportabilityCollapsePropagatesToController +// is the direct regression for architect finding #2: when all +// supported volumes disappear (e.g. observations expire), the +// host must still propagate pending/unsupported transitions to +// the controller, and the controller must clear its prior +// desired state for those volumes. +func TestObservation_SupportabilityCollapsePropagatesToController(t *testing.T) { + start := time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + sink := &recordingSink{} + host := NewObservationHost(ObservationHostConfig{ + Freshness: FreshnessConfig{FreshnessWindow: 2 * time.Second, PendingGrace: 100 * time.Millisecond}, + Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}}, + Sink: sink, + Now: clk.Now, + }) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + host.Start(ctx) + defer host.Stop() + + // Reach supported for v1. + _ = host.IngestHeartbeat(serverObs("s1", start, healthySlot("v1", "r1"))) + _ = host.IngestHeartbeat(serverObs("s2", start, healthySlot("v1", "r2"))) + _ = host.IngestHeartbeat(serverObs("s3", start, healthySlot("v1", "r3"))) + deadline := time.Now().Add(1 * time.Second) + for time.Now().Before(deadline) { + for _, c := range sink.records() { + if len(c.Snapshot.Volumes) > 0 { + goto reachedSupported + } + } + time.Sleep(10 * time.Millisecond) + } + t.Fatal("did not reach supported state") +reachedSupported: + preCount := len(sink.records()) + + // Collapse: advance clock past freshness window so every + // observation expires. Then trigger a rebuild by re-ingesting + // a single fresh observation for a DIFFERENT, unconfigured + // volume — this mutates the store (triggering rebuild) but + // does not restore v1's fresh observations. + clk.Advance(10 * time.Second) + // Trigger a mutation. Use GC or a fresh observation for a + // non-v1 replica. Easiest: a fresh s1 observation claiming a + // DIFFERENT (unknown) volume so v1 itself stays expired. + _ = host.IngestHeartbeat(serverObs("s1", clk.Now(), SlotFact{ + VolumeID: "v-unknown", ReplicaID: "x", + DataAddr: "d", CtrlAddr: "c", + Reachable: true, ReadyForPrimary: true, Eligible: true, + })) + + // Wait for a submission where v1 is NOT in supported volumes + // but IS in the unsupported report. + deadline = time.Now().Add(1 * time.Second) + sawCollapse := false + for time.Now().Before(deadline) { + records := sink.records() + if len(records) > preCount { + for _, c := range records[preCount:] { + // Collapse: v1 is either in Unsupported or not + // anywhere in supported. + inSupported := false + for _, v := range c.Snapshot.Volumes { + if v.VolumeID == "v1" { + inSupported = true + } + } + _, inUnsupported := c.Report.Unsupported["v1"] + if !inSupported && inUnsupported { + sawCollapse = true + break + } + } + } + if sawCollapse { + break + } + time.Sleep(10 * time.Millisecond) + } + if !sawCollapse { + t.Fatal("supportability collapse did not propagate to sink as Unsupported[v1]") + } +} + +// TestObservation_SupportabilityCollapseClearsControllerDesired +// is the controller-side half of finding #2: the controller's +// SubmitObservedState intake must clear the desired-assignment +// map for any volume that appears in report.Unsupported, so old +// desired state does not linger after supportability collapses. +func TestObservation_SupportabilityCollapseClearsControllerDesired(t *testing.T) { + reader := newFakeReaderForHost() + ctrl := NewTopologyController(TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }, reader) + + // Seed a desired assignment via a supported submission. + snap := ClusterSnapshot{ + CollectedRevision: 1, + 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", + Slots: []ReplicaCandidate{ + {ReplicaID: "r1", ServerID: "s1", DataAddr: "d1", CtrlAddr: "c1", Reachable: true, ReadyForPrimary: true, 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}, + }, + }}, + } + if err := ctrl.SubmitObservedState(snap, SupportabilityReport{}); err != nil { + t.Fatalf("initial: %v", err) + } + // Drain the ask (should be a Bind for v1). + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + if _, err := ctrl.Next(ctx); err != nil { + t.Fatalf("expected initial Bind ask: %v", err) + } + + // Now submit an observed state where v1 is unsupported (e.g. + // observations collapsed). No supported volumes. Report has + // v1 in Unsupported. + report := SupportabilityReport{ + Unsupported: map[string]VolumeUnsupportedEvidence{ + "v1": { + VolumeID: "v1", + SnapshotRevision: 2, + EvaluatedAt: time.Now(), + Reasons: []string{ReasonStaleObservation}, + }, + }, + } + if err := ctrl.SubmitObservedState(ClusterSnapshot{CollectedRevision: 2}, report); err != nil { + t.Fatalf("collapse submit: %v", err) + } + + // Controller must expose per-volume unsupported evidence now. + if _, ok := ctrl.LastUnsupported("v1"); !ok { + t.Fatal("controller must record unsupported evidence from observation report") + } + + // And it must have no outstanding desired ask for v1 — + // draining Next must block, not return a stale Reassign or + // similar. + ctx2, cancel2 := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel2() + if ask, err := ctrl.Next(ctx2); err == nil { + t.Fatalf("expected no ask after collapse; got %+v", ask) + } +} + +// TestObservation_UnknownObservedVolume_ProducesUnsupportedEvidence +// is the regression for architect finding #3: observed VolumeIDs +// outside the accepted topology must not be silently dropped; +// they must appear in the supportability report as unsupported. +func TestObservation_UnknownObservedVolume_ProducesUnsupportedEvidence(t *testing.T) { + start := time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + store := NewObservationStore(FreshnessConfig{FreshnessWindow: 5 * time.Second}, clk.Now) + + // Accepted topology knows only v1. But a server reports a + // slot for "v-rogue" — outside the accepted set. + topo := AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}} + + // Fresh, well-formed observation for a volume the operator + // has not configured. + _ = ingest(t, store, serverObs("s1", start, + healthySlot("v1", "r1"), + healthySlot("v-rogue", "r1"), + )) + + result := BuildSnapshot(store.Snapshot(), topo, nil) + ev, ok := result.Report.Unsupported["v-rogue"] + if !ok { + t.Fatal("unknown observed volume must surface as unsupported evidence, not silent drop") + } + if !contains(ev.Reasons, ReasonUnknownReplicaClaim) { + t.Fatalf("expected ReasonUnknownReplicaClaim, got %v", ev.Reasons) + } + if len(ev.OffendingFacts) == 0 { + t.Fatal("unknown-volume evidence must carry offending observation facts") + } + // And v-rogue must not appear in the synthesized Volumes list. + for _, v := range result.Snapshot.Volumes { + if v.VolumeID == "v-rogue" { + t.Fatal("unknown volume must NOT appear in ClusterSnapshot.Volumes") + } + } +} + +// TestObservationHost_IdenticalSupportedSnapshots_NoDuplicateAsks +// is the regression for the architect's round-3 finding #1: the +// observation-fed controller intake must dedupe repeated +// identical supported snapshots. Without dedupe, each feed of the +// same supported state would enqueue another Reassign, and +// Reassign mints a new authority epoch — authority churn, not +// convergence. +func TestObservationHost_IdenticalSupportedSnapshots_NoDuplicateAsks(t *testing.T) { + reader := newFakeReaderForHost() + ctrl := NewTopologyController(TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }, reader) + + // Publisher currently holds r1@5 for v1. + reader.SetVolume("v1", AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, + DataAddr: "d1", CtrlAddr: "c1", + }) + + // A supported snapshot where the current primary r1 is NOT + // acceptable (Reachable=false). That forces the controller's + // decision table to emit a failover Reassign to r2. + primarySlot := ReplicaCandidate{ + ReplicaID: "r1", ServerID: "s1", DataAddr: "d1", CtrlAddr: "c1", + Reachable: false, ReadyForPrimary: false, Eligible: true, + } + secondarySlot := ReplicaCandidate{ + ReplicaID: "r2", ServerID: "s2", DataAddr: "d2", CtrlAddr: "c2", + Reachable: true, ReadyForPrimary: true, Eligible: true, + } + tertiarySlot := ReplicaCandidate{ + ReplicaID: "r3", ServerID: "s3", DataAddr: "d3", CtrlAddr: "c3", + Reachable: true, ReadyForPrimary: true, Eligible: true, + } + snap := ClusterSnapshot{ + CollectedRevision: 1, + 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: AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, + DataAddr: "d1", CtrlAddr: "c1", + }, + Slots: []ReplicaCandidate{primarySlot, secondarySlot, tertiarySlot}, + }}, + } + + // First submit: should enqueue one Reassign. + if err := ctrl.SubmitObservedState(snap, SupportabilityReport{}); err != nil { + t.Fatalf("submit 1: %v", err) + } + ctx1, cancel1 := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel1() + ask1, err := ctrl.Next(ctx1) + if err != nil { + t.Fatalf("expected initial Reassign ask: %v", err) + } + if ask1.Intent != IntentReassign || ask1.ReplicaID != "r2" { + t.Fatalf("expected Reassign to r2, got %+v", ask1) + } + + // Now submit the SAME supported snapshot again, and again. + // The decision table still wants to Reassign to r2 because + // the publisher hasn't advanced yet (r1@5 still current); + // without dedupe this re-enqueues every time. + for i := 0; i < 3; i++ { + // Bump revision to prove dedupe is based on ask content, + // not just revision equality. + snap.CollectedRevision = uint64(2 + i) + if err := ctrl.SubmitObservedState(snap, SupportabilityReport{}); err != nil { + t.Fatalf("submit %d: %v", i+2, err) + } + } + + // Next must block — no new ask should have been enqueued + // despite three more identical-intent submissions. + ctx2, cancel2 := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancel2() + if ask, err := ctrl.Next(ctx2); err == nil { + t.Fatalf("same-ask dedupe failed: got churning ask %+v", ask) + } +} + +// TestObservationHost_VolumeRecovers_ClearsStaleDesired is the +// regression for the architect's round-3 finding #2: when a +// supported snapshot shows the current primary is acceptable +// again, any prior-queued failover/rebalance ask must be +// cleared. Otherwise the controller can publish a move it no +// longer wants. +func TestObservationHost_VolumeRecovers_ClearsStaleDesired(t *testing.T) { + reader := newFakeReaderForHost() + ctrl := NewTopologyController(TopologyControllerConfig{ + ExpectedSlotsPerVolume: 3, + }, reader) + + reader.SetVolume("v1", AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, + DataAddr: "d1", CtrlAddr: "c1", + }) + + servers := []ServerObservation{ + {ServerID: "s1", Reachable: true, Eligible: true}, + {ServerID: "s2", Reachable: true, Eligible: true}, + {ServerID: "s3", Reachable: true, Eligible: true}, + } + authMatchesLine := AuthorityBasis{ + Assigned: true, ReplicaID: "r1", Epoch: 5, EndpointVersion: 1, + DataAddr: "d1", CtrlAddr: "c1", + } + okSlotR1 := ReplicaCandidate{ + ReplicaID: "r1", ServerID: "s1", DataAddr: "d1", CtrlAddr: "c1", + Reachable: true, ReadyForPrimary: true, Eligible: true, + } + badSlotR1 := ReplicaCandidate{ + ReplicaID: "r1", ServerID: "s1", DataAddr: "d1", CtrlAddr: "c1", + Reachable: false, ReadyForPrimary: false, Eligible: true, + } + slotR2 := ReplicaCandidate{ + ReplicaID: "r2", ServerID: "s2", DataAddr: "d2", CtrlAddr: "c2", + Reachable: true, ReadyForPrimary: true, Eligible: true, + } + slotR3 := ReplicaCandidate{ + ReplicaID: "r3", ServerID: "s3", DataAddr: "d3", CtrlAddr: "c3", + Reachable: true, ReadyForPrimary: true, Eligible: true, + } + + // Snapshot A: r1 is unacceptable -> controller queues a + // failover Reassign to r2. We do NOT drain it here — this + // simulates the "queued ask has not drained yet" window the + // architect flagged. + snapA := ClusterSnapshot{ + CollectedRevision: 1, + CollectedAt: time.Now(), + Servers: servers, + Volumes: []VolumeTopologySnapshot{{ + VolumeID: "v1", + Authority: authMatchesLine, + Slots: []ReplicaCandidate{badSlotR1, slotR2, slotR3}, + }}, + } + if err := ctrl.SubmitObservedState(snapA, SupportabilityReport{}); err != nil { + t.Fatalf("submit A: %v", err) + } + + // Snapshot B: r1 has recovered, is acceptable again. The + // decision table now returns no-emit. The previously-queued + // Reassign must be cleared, not left live in the queue. + snapB := ClusterSnapshot{ + CollectedRevision: 2, + CollectedAt: time.Now(), + Servers: servers, + Volumes: []VolumeTopologySnapshot{{ + VolumeID: "v1", + Authority: authMatchesLine, + Slots: []ReplicaCandidate{okSlotR1, slotR2, slotR3}, + }}, + } + if err := ctrl.SubmitObservedState(snapB, SupportabilityReport{}); err != nil { + t.Fatalf("submit B: %v", err) + } + + // Next must block — the prior Reassign ask must have been + // discarded when snapshot B showed recovery. + ctx, cancel := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancel() + if ask, err := ctrl.Next(ctx); err == nil { + t.Fatalf("expected no ask after recovery; got stale move %+v", ask) + } +} + +// TestObservationHost_GCRetainWindow_Honored covers finding #4: +// the host's configured GCRetainWindow must be used by the +// periodic GC sweep. Previously the sweep hardcoded +// FreshnessWindow*4. +func TestObservationHost_GCRetainWindow_Honored(t *testing.T) { + start := time.Date(2026, 4, 19, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + host := NewObservationHost(ObservationHostConfig{ + Freshness: FreshnessConfig{FreshnessWindow: 10 * time.Second}, + Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}}, + Now: clk.Now, + // Small explicit retain window — a default would have + // been 40s (10s * 4). + GCRetainWindow: 3 * time.Second, + }) + + // Ingest one observation, then advance past GCRetainWindow + // and call Store().GC with the host's retain window. + _ = host.IngestHeartbeat(serverObs("s1", start, healthySlot("v1", "r1"))) + if got := len(host.Store().Snapshot().observations); got != 1 { + t.Fatalf("expected 1 observation stored, got %d", got) + } + + // Advance 5 seconds — past GCRetainWindow=3s but NOT past + // the default 40s. If the host honored the configured + // retain window, a direct GC(hostRetain) would evict. We + // prove the wiring by reading the internal field: the host + // retained the configured value. + clk.Advance(5 * time.Second) + + // Call GC directly with the host's retain window — this is + // what the host's run-loop does on the GC tick. We assert + // the observation was evicted, which only happens if the + // retain value was truthfully 3s, not the hardcoded 40s. + if removed := host.Store().GC(host.gcRetain); removed != 1 { + t.Fatalf("expected GC to evict 1 observation with retain=%v; removed=%d", host.gcRetain, removed) + } + if got := len(host.Store().Snapshot().observations); got != 0 { + t.Fatalf("expected observation evicted by GC, %d remain", got) + } + + // Sanity: explicit honor — if we omit GCRetainWindow, the + // default must still be derived from FreshnessWindow*4, not + // something smaller. + host2 := NewObservationHost(ObservationHostConfig{ + Freshness: FreshnessConfig{FreshnessWindow: 10 * time.Second}, + Now: clk.Now, + }) + if host2.gcRetain != 40*time.Second { + t.Fatalf("default GC retain must be 4x FreshnessWindow (40s), got %v", host2.gcRetain) + } +} diff --git a/seaweed-block/core/authority/observation_types.go b/seaweed-block/core/authority/observation_types.go new file mode 100644 index 0000000000..17c1015478 --- /dev/null +++ b/seaweed-block/core/authority/observation_types.go @@ -0,0 +1,206 @@ +package authority + +import "time" + +// ============================================================ +// P14 S4 — Observation Institution Contracts +// +// Normalized observation contract types consumed by the +// observation store and the snapshot builder. This file defines +// pure data shapes; it has no logic that interprets observations +// as authority. +// +// See sw-block/design/v3-phase-14-s4-sketch.md §5. +// ============================================================ + +// Observation is one point-in-time fact, supplied by one source, +// about one server and its locally-known slot inventory. +// +// Observation carries raw facts only. It never carries: +// - an instruction to the authority layer +// - an epoch or EndpointVersion proposal +// - a "promote me" flag +// The observation institution records observations; it does not +// interpret them as authority. (Load-bearing: sketch §3.) +type Observation struct { + ServerID string + ObservedAt time.Time + // ExpiresAt is ObservedAt + FreshnessWindow, computed at + // ingest. Freshness is checked against wall-clock now against + // ExpiresAt, never against "heartbeat interval multiples". + ExpiresAt time.Time + Server ServerFact + Slots []SlotFact +} + +// ServerFact is the cluster-visible state of the reporting server. +type ServerFact struct { + Reachable bool + Eligible bool +} + +// SlotFact is one locally-observed replica slot the reporting +// server thinks it hosts for some volume. All fields are raw +// facts; the observation layer does not rank or aggregate them. +type SlotFact struct { + VolumeID string + ReplicaID string + DataAddr string + CtrlAddr string + Reachable bool + ReadyForPrimary bool + Eligible bool + Withdrawn bool + EvidenceScore uint64 + // LocalRoleClaim is what the reporting server thinks its own + // role is right now. Recorded as raw fact only; never + // interpreted as authority. Two servers both claiming + // Primary for the same volume is the + // ReasonConflictingPrimaryClaim trigger. + LocalRoleClaim LocalRoleClaim +} + +// LocalRoleClaim is the raw role claim a server makes about +// itself. Not authority — the authority layer is the only thing +// that mints primary/candidate facts. +type LocalRoleClaim uint8 + +const ( + LocalRoleNone LocalRoleClaim = iota + LocalRoleCandidate + LocalRolePrimary +) + +func (r LocalRoleClaim) String() string { + switch r { + case LocalRoleNone: + return "none" + case LocalRoleCandidate: + return "candidate" + case LocalRolePrimary: + return "primary" + default: + return "unknown" + } +} + +// FreshnessConfig pins the freshness and pending-grace windows. +// Both values are explicit configuration; neither is a tick +// multiple nor a hidden constant. +type FreshnessConfig struct { + // FreshnessWindow is how long an observation remains fresh + // after its ObservedAt. `ExpiresAt = ObservedAt + FreshnessWindow`. + FreshnessWindow time.Duration + // PendingGrace is how long the store tolerates bootstrap / + // missing observations in the "pending" state before a volume + // escalates to "unsupported" with an explicit reason. Kept + // distinct from FreshnessWindow at the API level so future + // 14A review can tune them independently. + PendingGrace time.Duration +} + +func (c FreshnessConfig) withDefaults() FreshnessConfig { + out := c + if out.FreshnessWindow <= 0 { + out.FreshnessWindow = 10 * time.Second + } + if out.PendingGrace <= 0 { + out.PendingGrace = out.FreshnessWindow + } + return out +} + +// Supportability is the explicit per-volume supportability state +// computed by the snapshot builder. Kept as a four-value enum +// rather than a boolean so that the API exposes pending and +// unsupported as VISIBLY DISTINCT paths — the 14A reopen will +// review them independently. +type Supportability uint8 + +const ( + SupportabilityUnknown Supportability = iota + // SupportabilityPending: the accepted topology set cannot be + // confirmed for this volume yet, but the pending grace has not + // elapsed. The volume is omitted from the ClusterSnapshot and + // omitted from Unsupported; it appears only in the Pending + // collection of BuildResult. + SupportabilityPending + // SupportabilitySupported: all pinned rules pass for this + // volume; it enters ClusterSnapshot.Volumes. + SupportabilitySupported + // SupportabilityUnsupported: one or more pinned rules fail + // past the pending grace; the volume is omitted from the + // ClusterSnapshot and appears in Unsupported with evidence. + SupportabilityUnsupported +) + +func (s Supportability) String() string { + switch s { + case SupportabilityPending: + return "pending" + case SupportabilitySupported: + return "supported" + case SupportabilityUnsupported: + return "unsupported" + default: + return "unknown" + } +} + +// Reason codes for VolumeUnsupportedEvidence. Pinned vocabulary +// — see sketch §9. Implementations must not invent synonyms; new +// reasons require an explicit sketch / architect round. +const ( + ReasonPartialInventory = "PartialInventory" + ReasonMissingServerObservation = "MissingServerObservation" + ReasonStaleObservation = "StaleObservation" + ReasonConflictingPrimaryClaim = "ConflictingPrimaryClaim" + ReasonUnknownReplicaClaim = "UnknownReplicaClaim" + ReasonDuplicateServerTopology = "DuplicateServerTopology" +) + +// AcceptedTopology is the operator-configured expected slot layout +// for the accepted P14 topology set. This is static configuration, +// NOT authority: it describes which slot-to-server mapping the +// operator has promised to provide. The observation institution +// compares live observations against this to decide supportability. +type AcceptedTopology struct { + Volumes []VolumeExpected +} + +// VolumeExpected pins the three expected slots of one volume. +type VolumeExpected struct { + VolumeID string + Slots []ExpectedSlot +} + +// ExpectedSlot is one accepted (ReplicaID, ServerID) pair. +type ExpectedSlot struct { + ReplicaID string + ServerID string +} + +// lookupVolume returns the accepted expected slots for a volume, +// or (_, false) if the volume is not in the accepted topology. +// Callers treat "not found" the same as "no expected topology"; +// any observation for an unknown volume is unsupported by reason +// UnknownReplicaClaim. +func (t AcceptedTopology) lookupVolume(volumeID string) (VolumeExpected, bool) { + for _, v := range t.Volumes { + if v.VolumeID == volumeID { + return v, true + } + } + return VolumeExpected{}, false +} + +// allVolumeIDs returns every configured volume's ID in a stable +// order. Used by the snapshot builder to iterate volumes +// deterministically. +func (t AcceptedTopology) allVolumeIDs() []string { + out := make([]string, 0, len(t.Volumes)) + for _, v := range t.Volumes { + out = append(out, v.VolumeID) + } + return out +} diff --git a/seaweed-block/core/authority/observation_wire.go b/seaweed-block/core/authority/observation_wire.go new file mode 100644 index 0000000000..fa7661e954 --- /dev/null +++ b/seaweed-block/core/authority/observation_wire.go @@ -0,0 +1,106 @@ +package authority + +import ( + "fmt" + "time" +) + +// ============================================================ +// P14 S4 — V2 Heartbeat Wire Shape (Ported Mechanism Only) +// +// Wire / proto-shape types ported from V2's block-volume +// heartbeat path as MECHANISM only. They carry the same fields +// V2 sends, so an ingest source can translate them into the +// V3 Observation shape without inventing new wire semantics. +// +// What is ported (sketch §10 / §15): +// - the per-server, per-volume field layout V2 sends +// (analogue of weed/storage/blockvol/block_heartbeat.go) +// - the loop-driver shape (analogue of +// weed/server/block_heartbeat_loop.go) — mechanism only; +// host wiring owns the loop lifecycle, not the wire types. +// +// What is NOT ported (sketch §10 / §15): +// - weed/storage/blockvol/promotion.go +// - HandleAssignment / promote / demote +// - any path where heartbeat timing or local status becomes +// failover or authority truth +// +// These types are plain data. They have no authority meaning. +// Translating a HeartbeatMessage into an Observation is a +// field-shape copy; nothing more. +// ============================================================ + +// HeartbeatMessage is the V2-shaped heartbeat payload one +// reporting server sends. Ported as wire mechanism only. +type HeartbeatMessage struct { + ServerID string + SentAt time.Time + Reachable bool + Eligible bool + Slots []HeartbeatSlot +} + +// HeartbeatSlot is the per-slot portion of HeartbeatMessage. +// Shape mirrors V2's block-volume heartbeat slot subset that +// the observation institution needs; omits V2 fields that +// relate to promotion policy (see denylist). +type HeartbeatSlot struct { + VolumeID string + ReplicaID string + DataAddr string + CtrlAddr string + Reachable bool + ReadyForPrimary bool + Eligible bool + Withdrawn bool + EvidenceScore uint64 + // LocalRoleClaim is the V2 "I think I am" role flag, mapped + // one-to-one into the V3 Observation shape without + // reinterpretation. Two servers each sending LocalRolePrimary + // for the same VolumeID triggers + // ReasonConflictingPrimaryClaim at the builder. + LocalRoleClaim LocalRoleClaim +} + +// HeartbeatToObservation translates a V2-shaped heartbeat into +// the V3 Observation contract. Pure field-level mapping; no +// policy, no filtering, no aggregation. +// +// ExpiresAt is NOT set here — the store always derives it from +// its own FreshnessConfig at Ingest time, to prevent callers +// from fabricating freshness out-of-band (observation_store.go). +func HeartbeatToObservation(msg HeartbeatMessage) (Observation, error) { + if msg.ServerID == "" { + return Observation{}, fmt.Errorf("observation_wire: empty ServerID") + } + if msg.SentAt.IsZero() { + return Observation{}, fmt.Errorf("observation_wire: zero SentAt") + } + + slots := make([]SlotFact, 0, len(msg.Slots)) + for _, s := range msg.Slots { + slots = append(slots, SlotFact{ + VolumeID: s.VolumeID, + ReplicaID: s.ReplicaID, + DataAddr: s.DataAddr, + CtrlAddr: s.CtrlAddr, + Reachable: s.Reachable, + ReadyForPrimary: s.ReadyForPrimary, + Eligible: s.Eligible, + Withdrawn: s.Withdrawn, + EvidenceScore: s.EvidenceScore, + LocalRoleClaim: s.LocalRoleClaim, + }) + } + + return Observation{ + ServerID: msg.ServerID, + ObservedAt: msg.SentAt, + Server: ServerFact{ + Reachable: msg.Reachable, + Eligible: msg.Eligible, + }, + Slots: slots, + }, nil +} diff --git a/seaweed-block/core/authority/queue.go b/seaweed-block/core/authority/queue.go new file mode 100644 index 0000000000..619de07b42 --- /dev/null +++ b/seaweed-block/core/authority/queue.go @@ -0,0 +1,67 @@ +package authority + +import ( + "context" + "sync" +) + +// assignmentQueue is the bounded "latest desired state per volume" +// publication queue. It is intentionally not a history-preserving +// log: the convergence package cares about the latest desired +// authority move per volume, not every intermediate planning thought. +type assignmentQueue struct { + mu sync.Mutex + items map[string]AssignmentAsk + order []string + wake chan struct{} +} + +func newAssignmentQueue() *assignmentQueue { + return &assignmentQueue{ + items: make(map[string]AssignmentAsk), + wake: make(chan struct{}, 1), + } +} + +func (q *assignmentQueue) enqueue(ask AssignmentAsk) { + q.mu.Lock() + defer q.mu.Unlock() + if _, exists := q.items[ask.VolumeID]; !exists { + q.order = append(q.order, ask.VolumeID) + } + q.items[ask.VolumeID] = ask + select { + case q.wake <- struct{}{}: + default: + } +} + +func (q *assignmentQueue) discard(volumeID string) { + q.mu.Lock() + defer q.mu.Unlock() + delete(q.items, volumeID) +} + +func (q *assignmentQueue) next(ctx context.Context) (AssignmentAsk, error) { + for { + q.mu.Lock() + if len(q.order) > 0 { + vid := q.order[0] + q.order = q.order[1:] + ask, ok := q.items[vid] + if !ok { + q.mu.Unlock() + continue + } + delete(q.items, vid) + q.mu.Unlock() + return ask, nil + } + q.mu.Unlock() + select { + case <-q.wake: + case <-ctx.Done(): + return AssignmentAsk{}, ctx.Err() + } + } +} diff --git a/seaweed-block/core/authority/queue_test.go b/seaweed-block/core/authority/queue_test.go new file mode 100644 index 0000000000..40adf17c85 --- /dev/null +++ b/seaweed-block/core/authority/queue_test.go @@ -0,0 +1,42 @@ +package authority + +import ( + "context" + "errors" + "testing" + "time" +) + +func TestAssignmentQueue_ReplacesLatestPerVolume(t *testing.T) { + q := newAssignmentQueue() + q.enqueue(AssignmentAsk{ + VolumeID: "v1", ReplicaID: "r1", DataAddr: "d1", CtrlAddr: "c1", Intent: IntentBind, + }) + q.enqueue(AssignmentAsk{ + VolumeID: "v1", ReplicaID: "r2", DataAddr: "d2", CtrlAddr: "c2", Intent: IntentReassign, + }) + + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + ask, err := q.next(ctx) + if err != nil { + t.Fatalf("next: %v", err) + } + if ask.ReplicaID != "r2" || ask.Intent != IntentReassign { + t.Fatalf("queue must keep latest ask for volume, got %+v", ask) + } +} + +func TestAssignmentQueue_DiscardRemovesPendingVolume(t *testing.T) { + q := newAssignmentQueue() + q.enqueue(AssignmentAsk{ + VolumeID: "v1", ReplicaID: "r1", DataAddr: "d1", CtrlAddr: "c1", Intent: IntentBind, + }) + q.discard("v1") + + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + if _, err := q.next(ctx); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("expected deadline after discard, got %v", err) + } +} diff --git a/seaweed-block/core/authority/snapshot_builder.go b/seaweed-block/core/authority/snapshot_builder.go new file mode 100644 index 0000000000..e9dbf0770c --- /dev/null +++ b/seaweed-block/core/authority/snapshot_builder.go @@ -0,0 +1,426 @@ +package authority + +import ( + "fmt" + "sort" + "time" +) + +// ============================================================ +// P14 S4 — ClusterSnapshot Synthesizer +// +// Pure function: (storeSnapshot, AcceptedTopology) -> BuildResult. +// +// Supportability decisions read ONLY from the storeSnapshot input +// and the AcceptedTopology config. They never read from the +// synthesized output (sketch §12 one-way pipeline). +// +// Pending and Unsupported are VISIBLY DISTINCT in the result: +// - Supported volumes appear in BuildResult.Snapshot.Volumes +// - Pending volumes appear in BuildResult.Report.Pending only +// - Unsupported volumes appear in BuildResult.Report.Unsupported only +// No volume appears in more than one of these three places. +// ============================================================ + +// BuildSnapshot synthesizes one ClusterSnapshot + per-volume +// supportability report from the given store view and accepted +// topology. +// +// reader is a read-only authority view. It is consulted ONLY to +// stamp the per-volume current authority basis into +// VolumeTopologySnapshot.Authority for supported volumes, so the +// controller's stale-resistance check (basisMatchesLine) can +// succeed under the widened intake contract. Observation +// institution does not MINT authority here — it reads what the +// publisher currently holds (sketch §3 / §16a). reader may be +// nil; in that case Authority.Assigned=false, which is the +// honest "observation has no view" default. +// +// Pure function. Safe to call as often as needed. Callers +// typically invoke it from the host's reactive rebuild path, +// once per store mutation. +func BuildSnapshot(store storeSnapshot, topology AcceptedTopology, reader AuthorityBasisReader) BuildResult { + result := BuildResult{ + Report: *newSupportabilityReport(), + BuiltAt: store.evaluatedAt, + InputRev: store.revision, + } + + // Server list is computed from FRESH observations only. + // Expired observations stay in the store (visible for + // diagnosis, sketch §6) but must not contribute to the + // supported server inventory. + var servers []ServerObservation + for id, obs := range store.observations { + if store.serverFreshness[id] != ServerFresh { + continue + } + servers = append(servers, ServerObservation{ + ServerID: obs.ServerID, + Reachable: obs.Server.Reachable, + Eligible: obs.Server.Eligible, + }) + } + sort.Slice(servers, func(i, j int) bool { + return servers[i].ServerID < servers[j].ServerID + }) + + // Collect per-volume fresh slot facts (keyed by VolumeID). + // Expired-server facts are excluded here; they are + // semantically ineligible for supported synthesis (§6). + freshSlotsByVolume := map[string][]slotWithServer{} + for id, obs := range store.observations { + if store.serverFreshness[id] != ServerFresh { + continue + } + for _, s := range obs.Slots { + freshSlotsByVolume[s.VolumeID] = append(freshSlotsByVolume[s.VolumeID], + slotWithServer{slot: s, serverID: obs.ServerID, observedAt: obs.ObservedAt}) + } + } + + // Walk configured volumes in order for deterministic output. + configuredIDs := topology.allVolumeIDs() + sort.Strings(configuredIDs) + var volumes []VolumeTopologySnapshot + configured := map[string]bool{} + for _, vid := range configuredIDs { + configured[vid] = true + } + + for _, vid := range configuredIDs { + expected, _ := topology.lookupVolume(vid) + verdict := evaluateVolume(vid, expected, freshSlotsByVolume[vid], store) + + switch verdict.state { + case SupportabilitySupported: + // Stamp the per-volume current authority basis from + // the reader (read-only). This lets the controller's + // stale-resistance check match on subsequent feeds. + if reader != nil { + if basis, ok := reader.VolumeAuthorityLine(vid); ok { + verdict.topology.Authority = basis + } + } + volumes = append(volumes, verdict.topology) + case SupportabilityPending: + result.Report.Pending[vid] = VolumePendingStatus{ + VolumeID: vid, + EvaluatedAt: store.evaluatedAt, + PendingReasons: verdict.reasons, + Note: verdict.note, + } + case SupportabilityUnsupported: + result.Report.Unsupported[vid] = VolumeUnsupportedEvidence{ + VolumeID: vid, + SnapshotRevision: store.revision, + EvaluatedAt: store.evaluatedAt, + Reasons: verdict.reasons, + OffendingFacts: verdict.offendingFacts, + Note: verdict.note, + } + } + } + + // Unknown observed volumes — any VolumeID that appears in + // freshSlotsByVolume but is NOT in the configured topology. + // These must surface as explicit unsupported evidence, not + // silent drop, so operators and 14A review can see that + // observation reported extra volumes the system does not + // accept. + var unknownIDs []string + for vid := range freshSlotsByVolume { + if !configured[vid] { + unknownIDs = append(unknownIDs, vid) + } + } + sort.Strings(unknownIDs) + for _, vid := range unknownIDs { + offenders := make([]Observation, 0) + seen := map[string]bool{} + for _, f := range freshSlotsByVolume[vid] { + if seen[f.serverID] { + continue + } + seen[f.serverID] = true + if obs, ok := store.observations[f.serverID]; ok { + offenders = append(offenders, obs) + } + } + result.Report.Unsupported[vid] = VolumeUnsupportedEvidence{ + VolumeID: vid, + SnapshotRevision: store.revision, + EvaluatedAt: store.evaluatedAt, + Reasons: []string{ReasonUnknownReplicaClaim}, + OffendingFacts: offenders, + Note: "observed volume not in accepted topology", + } + } + + result.Snapshot = ClusterSnapshot{ + CollectedRevision: store.revision, + CollectedAt: store.evaluatedAt, + Servers: servers, + Volumes: volumes, + } + return result +} + +// slotWithServer is a per-volume fresh slot fact together with +// its reporting ServerID and ObservedAt, so the builder can tell +// which server contributed a given slot claim. +type slotWithServer struct { + slot SlotFact + serverID string + observedAt time.Time +} + +// volumeVerdict is the internal per-volume decision from +// evaluateVolume. Unsupported / pending states carry reasons and +// offending facts; supported carries the assembled +// VolumeTopologySnapshot for inclusion in ClusterSnapshot. +type volumeVerdict struct { + state Supportability + reasons []string + offendingFacts []Observation + note string + topology VolumeTopologySnapshot +} + +// evaluateVolume implements the pinned supportability rules for +// one volume. Rules run in an explicit priority order; structural +// violations emit unsupported regardless of pending grace, while +// coverage gaps emit pending within grace and unsupported past +// it. +func evaluateVolume( + volumeID string, + expected VolumeExpected, + freshSlots []slotWithServer, + store storeSnapshot, +) volumeVerdict { + // If the volume is not in the accepted topology at all, it is + // unsupported — we cannot honestly build a VolumeTopologySnapshot + // for slot-expectations we do not have. + if expected.VolumeID == "" { + return volumeVerdict{ + state: SupportabilityUnsupported, + reasons: []string{ReasonUnknownReplicaClaim}, + note: "volume not in accepted topology", + } + } + + expectedReplicas := map[string]ExpectedSlot{} + for _, e := range expected.Slots { + expectedReplicas[e.ReplicaID] = e + } + + var reasons []string + var offenders []Observation + addReason := func(r string) { + for _, existing := range reasons { + if existing == r { + return + } + } + reasons = append(reasons, r) + } + addOffender := func(serverID string) { + if obs, ok := store.observations[serverID]; ok { + for _, prev := range offenders { + if prev.ServerID == serverID { + return + } + } + offenders = append(offenders, obs) + } + } + + // Rule §12a — duplicate-server topology across fresh slots of + // the same volume. Two fresh slots with different ReplicaIDs + // but the same ServerID violate the distinct-servers + // invariant. + seenServers := map[string]string{} // ServerID -> ReplicaID + for _, f := range freshSlots { + if prev, ok := seenServers[f.serverID]; ok && prev != f.slot.ReplicaID { + addReason(ReasonDuplicateServerTopology) + addOffender(f.serverID) + // Also flag the earlier contributor. + for _, g := range freshSlots { + if g.serverID == f.serverID && g.slot.ReplicaID == prev { + addOffender(g.serverID) + } + } + } else if !ok { + seenServers[f.serverID] = f.slot.ReplicaID + } + } + + // Rule §8 — conflicting primary claim. Two or more fresh + // slots claiming LocalRolePrimary for the same volume. The + // observation layer never picks a winner, regardless of + // epoch / timestamp / evidence score. + primaryClaimants := 0 + for _, f := range freshSlots { + if f.slot.LocalRoleClaim == LocalRolePrimary { + primaryClaimants++ + if primaryClaimants >= 2 { + addReason(ReasonConflictingPrimaryClaim) + addOffender(f.serverID) + } + } + } + if primaryClaimants >= 2 { + for _, f := range freshSlots { + if f.slot.LocalRoleClaim == LocalRolePrimary { + addOffender(f.serverID) + } + } + } + + // Rule §9 — unknown replica claim. A fresh slot fact refers + // to a ReplicaID not in the accepted topology for this + // volume. + for _, f := range freshSlots { + if _, ok := expectedReplicas[f.slot.ReplicaID]; !ok { + addReason(ReasonUnknownReplicaClaim) + addOffender(f.serverID) + } + } + + // Rule §12 — missing / stale per-slot server coverage, + // evaluated against the PRE-SNAPSHOT fresh server inventory + // (via store.freshnessFor), not against any synthesized + // ClusterSnapshot.Servers. Per expected slot, check if the + // assigned server is fresh, bootstrapping, missing, or + // expired. + coveredReplicas := map[string]bool{} + pending := false + for _, expectedSlot := range expected.Slots { + serverFresh := store.freshnessFor(expectedSlot.ServerID) + switch serverFresh { + case ServerFresh: + // Server is fresh. Does its observation include the + // expected ReplicaID? + found := false + for _, f := range freshSlots { + if f.serverID == expectedSlot.ServerID && f.slot.ReplicaID == expectedSlot.ReplicaID { + found = true + break + } + } + if found { + coveredReplicas[expectedSlot.ReplicaID] = true + } + // If not found: partial inventory on that server. + // Handled by the "coverage gap" pass below. + case ServerBootstrapping: + // Still within bootstrap grace; contributes to + // pending, not unsupported. + pending = true + case ServerMissing: + addReason(ReasonMissingServerObservation) + case ServerExpired: + addReason(ReasonStaleObservation) + addOffender(expectedSlot.ServerID) + } + } + + // Coverage gap: some expected ReplicaIDs are not covered by + // fresh slot facts. This is PartialInventory. Within bootstrap + // grace it is pending; past it, unsupported. + if len(coveredReplicas) < len(expected.Slots) { + // Check whether all uncovered expected slots are explained + // by a missing/stale/bootstrapping server reason we already + // recorded above. If some are covered by a fresh server + // whose observation just does not mention the expected + // ReplicaID, that is the "partial inventory on a fresh + // server" case. + for _, expectedSlot := range expected.Slots { + if coveredReplicas[expectedSlot.ReplicaID] { + continue + } + serverFresh := store.freshnessFor(expectedSlot.ServerID) + if serverFresh == ServerFresh { + if store.evaluatedAt.Sub(store.startedAt) < store.pendingGrace { + pending = true + } else { + addReason(ReasonPartialInventory) + } + } + } + } + + // Collapse: unsupported wins over pending. + if len(reasons) > 0 { + sort.Strings(reasons) + return volumeVerdict{ + state: SupportabilityUnsupported, + reasons: reasons, + offendingFacts: offenders, + note: fmt.Sprintf("%d reason(s); %d offending fact(s)", len(reasons), len(offenders)), + } + } + + // If no unsupported reason but some slot needed grace, the + // volume is pending. + if pending { + return volumeVerdict{ + state: SupportabilityPending, + reasons: []string{ReasonPartialInventory}, + note: "within bootstrap pending grace", + } + } + + // Otherwise, supported — assemble the VolumeTopologySnapshot. + return volumeVerdict{ + state: SupportabilitySupported, + topology: assembleVolumeTopology(volumeID, expected, freshSlots), + } +} + +// assembleVolumeTopology builds the VolumeTopologySnapshot for a +// supported volume. Slot order follows expected.Slots so the +// controller sees deterministic input. Each expected slot maps to +// a fresh SlotFact produced by the expected ServerID. +func assembleVolumeTopology( + volumeID string, + expected VolumeExpected, + freshSlots []slotWithServer, +) VolumeTopologySnapshot { + slots := make([]ReplicaCandidate, 0, len(expected.Slots)) + + byReplicaID := map[string]slotWithServer{} + for _, f := range freshSlots { + if _, ok := byReplicaID[f.slot.ReplicaID]; !ok { + byReplicaID[f.slot.ReplicaID] = f + } + } + + for _, e := range expected.Slots { + f, ok := byReplicaID[e.ReplicaID] + if !ok { + continue // supported means all covered; defensive + } + slots = append(slots, ReplicaCandidate{ + ReplicaID: f.slot.ReplicaID, + ServerID: e.ServerID, + DataAddr: f.slot.DataAddr, + CtrlAddr: f.slot.CtrlAddr, + Reachable: f.slot.Reachable, + ReadyForPrimary: f.slot.ReadyForPrimary, + Eligible: f.slot.Eligible, + Withdrawn: f.slot.Withdrawn, + EvidenceScore: f.slot.EvidenceScore, + }) + } + + // Authority is stamped by BuildSnapshot AFTER this function + // returns, using the read-only AuthorityBasisReader (publisher + // current line). Observation institution never mints authority + // here. The default zero value Authority.Assigned=false is + // correct for the initial-bind case (no publisher line yet). + return VolumeTopologySnapshot{ + VolumeID: volumeID, + Slots: slots, + } +} diff --git a/seaweed-block/core/authority/topology.go b/seaweed-block/core/authority/topology.go new file mode 100644 index 0000000000..0a6868f7ad --- /dev/null +++ b/seaweed-block/core/authority/topology.go @@ -0,0 +1,124 @@ +package authority + +import ( + "fmt" + "sort" + "time" +) + +// ServerObservation is one server's cluster-visible readiness for +// placement, failover, and rebalance. It is intentionally bounded: +// operator/API surfaces remain P15 work. +type ServerObservation struct { + ServerID string + Reachable bool + Eligible bool +} + +// ReplicaCandidate is one accepted replica slot in the richer P14 +// topology package. Unlike the first S3 slice, the multi-volume +// package carries an explicit evidence score so failover/rebalance +// can be evidence-backed rather than reachability-only. +type ReplicaCandidate struct { + ReplicaID string + ServerID string + DataAddr string + CtrlAddr string + Reachable bool + ReadyForPrimary bool + Eligible bool + Withdrawn bool + EvidenceScore uint64 +} + +// VolumeTopologySnapshot is the complete point-in-time topology and +// authority view for one volume in the accepted full P14 topology +// set: one current primary and exactly three candidate slots on +// distinct servers. +type VolumeTopologySnapshot struct { + VolumeID string + Authority AuthorityBasis + Slots []ReplicaCandidate +} + +// ClusterSnapshot is the cluster-scoped observation submitted to the +// multi-volume controller. Later snapshots supersede earlier ones. +type ClusterSnapshot struct { + CollectedRevision uint64 + CollectedAt time.Time + Servers []ServerObservation + Volumes []VolumeTopologySnapshot +} + +// TopologyControllerConfig pins the accepted richer topology set: +// multi-volume, three slots per volume, and bounded rebalance +// pressure when server load skew exceeds RebalanceSkew. +type TopologyControllerConfig struct { + ExpectedSlotsPerVolume int + RebalanceSkew int +} + +func (c TopologyControllerConfig) withDefaults() TopologyControllerConfig { + if c.ExpectedSlotsPerVolume == 0 { + c.ExpectedSlotsPerVolume = 3 + } + if c.RebalanceSkew == 0 { + c.RebalanceSkew = 1 + } + 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. +type DesiredAssignment struct { + Ask AssignmentAsk + Reason string + Revision uint64 + Observed bool +} + +func sortVolumeSnapshots(vols []VolumeTopologySnapshot) { + sort.Slice(vols, func(i, j int) bool { + return vols[i].VolumeID < vols[j].VolumeID + }) +} + +func indexServers(servers []ServerObservation) map[string]ServerObservation { + idx := make(map[string]ServerObservation, len(servers)) + for _, s := range servers { + idx[s.ServerID] = s + } + return idx +} + +func validateVolumeTopology(snap VolumeTopologySnapshot, expectedSlots int) error { + if snap.VolumeID == "" { + return fmt.Errorf("topology: volume snapshot missing VolumeID") + } + if len(snap.Slots) != expectedSlots { + return fmt.Errorf("topology: volume %s has %d slots, want %d", snap.VolumeID, len(snap.Slots), expectedSlots) + } + seenReplica := make(map[string]struct{}, len(snap.Slots)) + seenServer := make(map[string]struct{}, len(snap.Slots)) + for _, slot := range snap.Slots { + if slot.ReplicaID == "" { + return fmt.Errorf("topology: volume %s slot missing ReplicaID", snap.VolumeID) + } + if slot.ServerID == "" { + return fmt.Errorf("topology: volume %s slot %s missing ServerID", snap.VolumeID, slot.ReplicaID) + } + if slot.DataAddr == "" || slot.CtrlAddr == "" { + return fmt.Errorf("topology: volume %s slot %s missing addr", snap.VolumeID, slot.ReplicaID) + } + if _, ok := seenReplica[slot.ReplicaID]; ok { + return fmt.Errorf("topology: volume %s duplicate ReplicaID %s", snap.VolumeID, slot.ReplicaID) + } + if _, ok := seenServer[slot.ServerID]; ok { + return fmt.Errorf("topology: volume %s duplicate ServerID %s", snap.VolumeID, slot.ServerID) + } + seenReplica[slot.ReplicaID] = struct{}{} + seenServer[slot.ServerID] = struct{}{} + } + return nil +} diff --git a/seaweed-block/core/authority/unsupported_evidence.go b/seaweed-block/core/authority/unsupported_evidence.go new file mode 100644 index 0000000000..37d8e44a83 --- /dev/null +++ b/seaweed-block/core/authority/unsupported_evidence.go @@ -0,0 +1,72 @@ +package authority + +import "time" + +// ============================================================ +// P14 S4 — Observation-Institution Unsupported Evidence +// +// Per-volume latest-wins evidence shape. Kept separate from S3's +// policy-owner UnsupportedEvidence (which is owner-scoped, +// current-fact only). See sw-block/design/v3-phase-14-s4-sketch.md +// §9. +// +// Pending and Unsupported are VISIBLY DISTINCT collections on +// BuildResult. A volume that is within the pending grace is NOT +// in Unsupported — if those collapsed, 14A review of "pending vs +// unsupported" would be harder for no benefit. +// ============================================================ + +// VolumeUnsupportedEvidence records why one volume could not +// enter the synthesized ClusterSnapshot as supported. It is +// latest-wins per (VolumeID). +// +// OffendingFacts is retained raw — the observation layer does not +// rank or filter them. That keeps the evidence usable by humans +// and by 14A review. +type VolumeUnsupportedEvidence struct { + VolumeID string + SnapshotRevision uint64 + EvaluatedAt time.Time + Reasons []string + OffendingFacts []Observation + Note string +} + +// VolumePendingStatus records a volume that is within the +// pending grace. It is NOT an error — it is a transitional +// observation that has not yet earned unsupported evidence. +// Intentionally a different type from VolumeUnsupportedEvidence +// so consumers cannot accidentally blur the two. +type VolumePendingStatus struct { + VolumeID string + EvaluatedAt time.Time + PendingReasons []string + Note string +} + +// SupportabilityReport is the per-volume supportability +// breakdown for one build. Both maps are keyed by VolumeID. +// Volumes in Supported appear in the companion ClusterSnapshot; +// volumes in Pending / Unsupported do not. +type SupportabilityReport struct { + Pending map[string]VolumePendingStatus + Unsupported map[string]VolumeUnsupportedEvidence +} + +func newSupportabilityReport() *SupportabilityReport { + return &SupportabilityReport{ + Pending: map[string]VolumePendingStatus{}, + Unsupported: map[string]VolumeUnsupportedEvidence{}, + } +} + +// BuildResult is the full output of one snapshot build. The +// ClusterSnapshot is the OUTPUT; supportability decisions were +// made from store inputs, not from this value. (One-way pipeline, +// sketch §12 + §16a.) +type BuildResult struct { + Snapshot ClusterSnapshot + Report SupportabilityReport + BuiltAt time.Time + InputRev uint64 +}