mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 02:27:26 +01:00
P14 S4: observation institution + multi-volume topology controller
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) <noreply@anthropic.com>
This commit is contained in:
1 parent
0fc367f3a3
commit
60c5ff5db4
13 files changed
+4159
No files matched your search
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
Reference in new issue
Block a user