diff --git a/seaweed-block/core/authority/observation_store.go b/seaweed-block/core/authority/observation_store.go index f97fad32c4..563087904f 100644 --- a/seaweed-block/core/authority/observation_store.go +++ b/seaweed-block/core/authority/observation_store.go @@ -54,6 +54,66 @@ func (s *ObservationStore) SupersededCount() uint64 { return s.supersededCount } +// SlotFact returns the most-recently-observed SlotFact for a +// (volumeID, replicaID) pair across all reporting servers, or +// (zero, false) if no server has reported that slot. +// +// Used by master-side peer-set construction (G5-5A): supporting +// replicas don't have a published authority line (Publisher.apply +// only mints for the bound replica), so master falls back to the +// last-heartbeat-observed DataAddr/CtrlAddr to populate +// AssignmentFact.peers for primary fan-out. Topology membership is +// the allow-list — the caller must confirm the (volumeID, replicaID) +// is a declared slot before consulting this method. +// +// The returned SlotFact is the value reported by the LATEST +// observation across all servers — multiple servers may report the +// same (volumeID, replicaID) (e.g., during reassignment or topology +// confusion). The caller's authority/topology gates upstream of +// this method enforce the membership invariant; this method just +// answers "what addr did the cluster last hear about for this +// (volume, replica)?". +// +// Returns (zero, false) when: +// - no observation has reported any slot for this (volumeID, replicaID), OR +// - observations exist but the matching slot has empty DataAddr +// (caller-side fail-closed: skip the peer rather than synthesize +// a descriptor with an unusable addr) +// +// NOT authority input. Read-only; safe to call concurrently. +func (s *ObservationStore) SlotFact(volumeID, replicaID string) (SlotFact, bool) { + if volumeID == "" || replicaID == "" { + return SlotFact{}, false + } + s.mu.Lock() + defer s.mu.Unlock() + var ( + best SlotFact + bestObsAt time.Time + found bool + ) + for _, obs := range s.observations { + for _, slot := range obs.Slots { + if slot.VolumeID != volumeID || slot.ReplicaID != replicaID { + continue + } + if slot.DataAddr == "" { + // Fail-closed: an observation that names the slot but + // without a usable DataAddr is unusable for primary + // fan-out. Skip; let the caller's topology check + // surface as "no observation" if this is the only one. + continue + } + if !found || obs.ObservedAt.After(bestObsAt) { + best = slot + bestObsAt = obs.ObservedAt + found = true + } + } + } + return best, found +} + // SetNowForTest replaces the store's clock source. Tests use this // to drive expiry / freshness deterministically. Symmetric with // authority.TopologyController.SetNowForTest. Production code diff --git a/seaweed-block/core/authority/observation_store_slotfact_test.go b/seaweed-block/core/authority/observation_store_slotfact_test.go new file mode 100644 index 0000000000..5ebc5a7462 --- /dev/null +++ b/seaweed-block/core/authority/observation_store_slotfact_test.go @@ -0,0 +1,105 @@ +// G5-5A unit test for ObservationStore.SlotFact accessor. + +package authority + +import ( + "testing" + "time" +) + +func TestObservationStore_SlotFact_ReturnsLatestForReplica(t *testing.T) { + now := time.Date(2026, 4, 27, 10, 0, 0, 0, time.UTC) + clock := func() time.Time { return now } + s := NewObservationStore(FreshnessConfig{FreshnessWindow: 30 * time.Second}, clock) + + // One server reports a heartbeat for v1/r2 with a usable DataAddr. + if err := s.Ingest(Observation{ + ServerID: "m02-replica", + ObservedAt: now, + Slots: []SlotFact{ + {VolumeID: "v1", ReplicaID: "r2", DataAddr: "192.168.1.184:9221", CtrlAddr: "192.168.1.184:9211"}, + }, + }); err != nil { + t.Fatalf("Ingest: %v", err) + } + + got, ok := s.SlotFact("v1", "r2") + if !ok { + t.Fatal("SlotFact: ok=false; want true after ingest") + } + if got.DataAddr != "192.168.1.184:9221" || got.CtrlAddr != "192.168.1.184:9211" { + t.Errorf("SlotFact: got %+v", got) + } +} + +func TestObservationStore_SlotFact_NoObservation_ReturnsFalse(t *testing.T) { + s := NewObservationStore(FreshnessConfig{}, nil) + if _, ok := s.SlotFact("v1", "r2"); ok { + t.Fatal("SlotFact: ok=true on empty store; want false") + } +} + +func TestObservationStore_SlotFact_EmptyDataAddr_FailsClosed(t *testing.T) { + now := time.Date(2026, 4, 27, 10, 0, 0, 0, time.UTC) + s := NewObservationStore(FreshnessConfig{FreshnessWindow: 30 * time.Second}, func() time.Time { return now }) + // Heartbeat names the slot but reports empty DataAddr. + if err := s.Ingest(Observation{ + ServerID: "m02-replica", + ObservedAt: now, + Slots: []SlotFact{ + {VolumeID: "v1", ReplicaID: "r2", DataAddr: ""}, + }, + }); err != nil { + t.Fatalf("Ingest: %v", err) + } + if _, ok := s.SlotFact("v1", "r2"); ok { + t.Fatal("SlotFact: ok=true with empty DataAddr; want false (fail-closed)") + } +} + +func TestObservationStore_SlotFact_LatestObservationWins(t *testing.T) { + t0 := time.Date(2026, 4, 27, 10, 0, 0, 0, time.UTC) + now := t0 + s := NewObservationStore(FreshnessConfig{FreshnessWindow: 1 * time.Hour}, func() time.Time { return now }) + // Two reports for v1/r2 from different servers (rare but possible + // during reassignment / topology confusion). Latest ObservedAt wins. + _ = s.Ingest(Observation{ + ServerID: "src-a", + ObservedAt: t0, + Slots: []SlotFact{{VolumeID: "v1", ReplicaID: "r2", DataAddr: "OLD:1"}}, + }) + _ = s.Ingest(Observation{ + ServerID: "src-b", + ObservedAt: t0.Add(5 * time.Second), + Slots: []SlotFact{{VolumeID: "v1", ReplicaID: "r2", DataAddr: "NEW:1"}}, + }) + got, ok := s.SlotFact("v1", "r2") + if !ok { + t.Fatal("SlotFact: ok=false") + } + if got.DataAddr != "NEW:1" { + t.Errorf("DataAddr: got %q want NEW:1 (latest ObservedAt wins)", got.DataAddr) + } +} + +func TestObservationStore_SlotFact_VolumeOrReplicaMismatch_ReturnsFalse(t *testing.T) { + now := time.Date(2026, 4, 27, 10, 0, 0, 0, time.UTC) + s := NewObservationStore(FreshnessConfig{FreshnessWindow: 30 * time.Second}, func() time.Time { return now }) + _ = s.Ingest(Observation{ + ServerID: "src", + ObservedAt: now, + Slots: []SlotFact{{VolumeID: "v1", ReplicaID: "r2", DataAddr: "ADDR:1"}}, + }) + if _, ok := s.SlotFact("vOTHER", "r2"); ok { + t.Errorf("expected false for volume mismatch") + } + if _, ok := s.SlotFact("v1", "rOTHER"); ok { + t.Errorf("expected false for replica mismatch") + } + if _, ok := s.SlotFact("", "r2"); ok { + t.Errorf("expected false for empty volume") + } + if _, ok := s.SlotFact("v1", ""); ok { + t.Errorf("expected false for empty replica") + } +} diff --git a/seaweed-block/core/host/master/services.go b/seaweed-block/core/host/master/services.go index 47e9e4eef4..ff059a0cc5 100644 --- a/seaweed-block/core/host/master/services.go +++ b/seaweed-block/core/host/master/services.go @@ -211,7 +211,7 @@ func (s *services) SubscribeAssignments(req *control.SubscribeRequest, stream co // above guarantees each fits in uint32 so no aliasing. // Monotonic across process lifetimes because Epoch/EV are // durable authority facts preserved across master restart. - fact.Peers = s.collectPeers(req.VolumeId, info.ReplicaID) + fact.Peers = s.collectPeers(req.VolumeId, info) fact.PeerSetGeneration = (info.Epoch << 32) | info.EndpointVersion if err := stream.Send(fact); err != nil { return err @@ -309,42 +309,120 @@ func generationFitsUint32(epoch, endpointVersion uint64) (reason string, ok bool return "", true } -// collectPeers builds the AssignmentFact.peers list for a volume -// from the publisher's most-recent authoritative lines. Only -// replicas OTHER than self_replica are included — the primary -// does not ship to itself. Slots with no published line yet are -// skipped (they'll appear in later emissions once their line -// lands; cold-start is therefore benign, not erroneous). +// collectPeers builds the AssignmentFact.peers list for a volume. +// Topology membership is the allow-list — only declared slot +// members can appear in peers (option R rejected in T4a-5.0 +// discovery doc §9.5: never accumulate from arbitrary observed +// nodes). // -// This is the T4a-5 peer-set construction site. It is strictly -// a READ of publisher state — no caching, no derivation, no -// local accumulation (option R rejected in T4a-5.0 discovery -// doc §9.5). Peer membership comes from accepted topology -// (replicaSlotsFor) and per-peer line content comes from the -// publisher's durable LastPublished state — both are -// master-authoritative. -func (s *services) collectPeers(volumeID, selfReplicaID string) []*control.ReplicaDescriptor { +// Per-slot resolution (G5-5A architect ratification 2026-04-27): +// +// 1. PRIMARY path: for slots whose authority is published (the +// bound replica + any historically-bound replicas with retained +// records), use the publisher's `LastPublished` lineage — +// authoritative Epoch / EndpointVersion / DataAddr / CtrlAddr. +// +// 2. SUPPORTING path: for slots that ARE declared in topology +// but have NO published authority line (the common case for +// supporting replicas — Publisher.apply only mints for the +// bound replica), fall back to the observation store's last +// heartbeat-reported SlotFact for that (volumeID, replicaID). +// This is OBSERVATION TRUTH, not authority truth. The synthesized +// ReplicaDescriptor carries Epoch=0 + EndpointVersion=0 to mark +// it explicitly as observation-derived; only the addresses are +// load-bearing for primary fan-out. +// +// pub.state stays authority-only. Architect option (B) — minting +// "presence" records into pub.state — was REJECTED at round 54. +// +// Fail-closed cases (slot is skipped, NOT silently substituted): +// - slot is the self replica (primary doesn't ship to itself) +// - slot has no published line AND no observation store record +// - observation exists but reports empty DataAddr (unusable for dial) +// +// Without this fallback, a cross-host replicated write would hang at +// fsync barrier because primary's peers list is empty and nothing +// fans out. QA round 54 surfaced this as the headline G5-5 L3 gap. +func (s *services) collectPeers(volumeID string, selfInfo adapter.AssignmentInfo) []*control.ReplicaDescriptor { slots := s.host.replicaSlotsFor(volumeID) if len(slots) == 0 { return nil } - pub := s.host.boot.Publisher + var obsStore *authority.ObservationStore + if s.host.obs != nil { + obsStore = s.host.obs.Store() + } + return resolvePeers(slots, selfInfo, volumeID, s.host.boot.Publisher, obsStore) +} + +// peerLookup is the narrow read interface resolvePeers needs from +// the publisher. *authority.Publisher satisfies it; tests substitute +// a stub. +type peerLookup interface { + LastPublished(volumeID, replicaID string) (adapter.AssignmentInfo, bool) +} + +// peerObservation is the narrow read interface resolvePeers needs +// from the observation store. *authority.ObservationStore satisfies +// it; tests substitute a stub. nil is permitted (fail-closed: only +// path-1 published peers will resolve). +type peerObservation interface { + SlotFact(volumeID, replicaID string) (authority.SlotFact, bool) +} + +// resolvePeers implements the G5-5A peer-set construction policy +// (architect ratification 2026-04-27). Pure function; testable +// without constructing a full Host. +// +// Observation-derived peers (path 2) inherit the SUBSCRIBING +// primary's (Epoch, EndpointVersion). Rationale: in V3, supporting +// replicas have no authority line of their own; live-ship frames +// from primary→replica carry the PRIMARY's lineage, which is what +// the replica validates against. The peer descriptor's Epoch/EV +// fields are interpreted by the primary's ReplicaPeer constructor +// as "lineage to stamp on outgoing frames", so primary's own +// Epoch/EV is the architecturally-correct value. Stamping zero +// would correctly mark the descriptor as observation-derived but +// would break the downstream ReplicaPeer constructor's nonzero +// invariant (replication/peer.go:130). +func resolvePeers(slots []string, selfInfo adapter.AssignmentInfo, volumeID string, pub peerLookup, obsStore peerObservation) []*control.ReplicaDescriptor { peers := make([]*control.ReplicaDescriptor, 0, len(slots)) for _, rid := range slots { - if rid == selfReplicaID { + if rid == selfInfo.ReplicaID { continue } - info, ok := pub.LastPublished(volumeID, rid) - if !ok { + // Path 1: published authority line (bound replica or + // retained record after IntentReassign). + if info, ok := pub.LastPublished(volumeID, rid); ok { + peers = append(peers, &control.ReplicaDescriptor{ + ReplicaId: info.ReplicaID, + Epoch: info.Epoch, + EndpointVersion: info.EndpointVersion, + DataAddr: info.DataAddr, + CtrlAddr: info.CtrlAddr, + }) continue } - peers = append(peers, &control.ReplicaDescriptor{ - ReplicaId: info.ReplicaID, - Epoch: info.Epoch, - EndpointVersion: info.EndpointVersion, - DataAddr: info.DataAddr, - CtrlAddr: info.CtrlAddr, - }) + // Path 2: observation-only (supporting replica; topology + // membership confirmed by the slots loop above; addr from + // last heartbeat). Inherit subscriber's Epoch/EV so the + // downstream ReplicaPeer ships under primary's lineage. + if obsStore != nil { + if slot, ok := obsStore.SlotFact(volumeID, rid); ok { + peers = append(peers, &control.ReplicaDescriptor{ + ReplicaId: rid, + Epoch: selfInfo.Epoch, + EndpointVersion: selfInfo.EndpointVersion, + DataAddr: slot.DataAddr, + CtrlAddr: slot.CtrlAddr, + }) + continue + } + } + // Else: fail-closed skip. Slot is declared in topology but + // neither authority nor observation has a usable address yet + // (cold-start before heartbeat lands, or replica down). The + // next emission (after r2 heartbeats in) will include it. } return peers } diff --git a/seaweed-block/core/host/master/services_g5_5a_test.go b/seaweed-block/core/host/master/services_g5_5a_test.go new file mode 100644 index 0000000000..5a6957cf9d --- /dev/null +++ b/seaweed-block/core/host/master/services_g5_5a_test.go @@ -0,0 +1,147 @@ +// G5-5A — master peer-set construction must include topology slot +// members observed by heartbeat even when they don't have a bound +// authority publication. Architect ratification 2026-04-27 (round +// 54): Option A (observation fallback in collectPeers / resolvePeers). +// +// These tests pin the contract on `resolvePeers` (the pure helper +// extracted from `collectPeers`) so they exercise the full policy +// without constructing a real Host. + +package master + +import ( + "testing" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/authority" +) + +// stubPub satisfies the peerLookup interface. +type stubPub struct { + state map[[2]string]adapter.AssignmentInfo +} + +func (s *stubPub) LastPublished(volumeID, replicaID string) (adapter.AssignmentInfo, bool) { + info, ok := s.state[[2]string{volumeID, replicaID}] + return info, ok +} + +// stubObs satisfies the peerObservation interface. +type stubObs struct { + state map[[2]string]authority.SlotFact +} + +func (s *stubObs) SlotFact(volumeID, replicaID string) (authority.SlotFact, bool) { + slot, ok := s.state[[2]string{volumeID, replicaID}] + return slot, ok +} + +// TestResolvePeers_R1Bound_R2ObservedOnly_R2InPeersWithHeartbeatAddr +// is the headline G5-5A pin per architect binding 2026-04-27: +// "with r1 bound and r2 only heartbeat-observed as a supporting +// slot member, the assignment fact delivered to r1 includes r2 in +// peers with its heartbeat-reported DataAddr" +func TestResolvePeers_R1Bound_R2ObservedOnly_R2InPeersWithHeartbeatAddr(t *testing.T) { + pub := &stubPub{state: map[[2]string]adapter.AssignmentInfo{ + {"v1", "r1"}: {VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "10.0.0.1:9220", CtrlAddr: "10.0.0.1:9210"}, + }} + obs := &stubObs{state: map[[2]string]authority.SlotFact{ + {"v1", "r2"}: {VolumeID: "v1", ReplicaID: "r2", DataAddr: "10.0.0.2:9221", CtrlAddr: "10.0.0.2:9211"}, + }} + + peers := resolvePeers([]string{"r1", "r2"}, adapter.AssignmentInfo{ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}, "v1", pub, obs) + + if len(peers) != 1 { + t.Fatalf("expected exactly 1 peer (r2); got %d: %+v", len(peers), peers) + } + got := peers[0] + if got.ReplicaId != "r2" { + t.Errorf("ReplicaId: got %q want r2", got.ReplicaId) + } + if got.DataAddr != "10.0.0.2:9221" { + t.Errorf("DataAddr: got %q want 10.0.0.2:9221 (heartbeat-reported)", got.DataAddr) + } + if got.CtrlAddr != "10.0.0.2:9211" { + t.Errorf("CtrlAddr: got %q want 10.0.0.2:9211", got.CtrlAddr) + } + // Per architect ratification round 54: observation-derived peers + // inherit the SUBSCRIBING primary's (Epoch, EV) — not zero — + // because the live-ship lineage carries primary's authority, + // which is how the supporting replica validates incoming frames. + // Stubbed subscriber in this test is r1@1/EV=1. + if got.Epoch != 1 { + t.Errorf("Epoch: got %d want 1 (subscribing primary's epoch)", got.Epoch) + } + if got.EndpointVersion != 1 { + t.Errorf("EndpointVersion: got %d want 1 (subscribing primary's EV)", got.EndpointVersion) + } +} + +// TestResolvePeers_BothBound — both slots have published authority +// lines; both contribute via path 1 with their authoritative +// epoch/EV/addrs. Confirms path-1 still works (no regression). +func TestResolvePeers_BothBound(t *testing.T) { + pub := &stubPub{state: map[[2]string]adapter.AssignmentInfo{ + {"v1", "r1"}: {VolumeID: "v1", ReplicaID: "r1", Epoch: 5, EndpointVersion: 2, DataAddr: "10.0.0.1:9220"}, + {"v1", "r2"}: {VolumeID: "v1", ReplicaID: "r2", Epoch: 4, EndpointVersion: 1, DataAddr: "10.0.0.2:9221"}, + }} + obs := &stubObs{state: map[[2]string]authority.SlotFact{}} + peers := resolvePeers([]string{"r1", "r2"}, adapter.AssignmentInfo{ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}, "v1", pub, obs) + if len(peers) != 1 { + t.Fatalf("expected 1 peer (r2, self r1 excluded); got %d", len(peers)) + } + if peers[0].ReplicaId != "r2" || peers[0].Epoch != 4 || peers[0].EndpointVersion != 1 { + t.Errorf("path-1 record: got %+v want {r2, Epoch=4, EV=1}", peers[0]) + } +} + +// TestResolvePeers_NeitherBoundNorObserved — supporting replica that +// hasn't heartbeat in yet. Skipped fail-closed (caller never tries +// to dial an empty addr). +func TestResolvePeers_NeitherBoundNorObserved(t *testing.T) { + pub := &stubPub{state: map[[2]string]adapter.AssignmentInfo{ + {"v1", "r1"}: {VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}, + }} + obs := &stubObs{state: map[[2]string]authority.SlotFact{}} + peers := resolvePeers([]string{"r1", "r2"}, adapter.AssignmentInfo{ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}, "v1", pub, obs) + if len(peers) != 0 { + t.Fatalf("expected empty peers when r2 unbound + unobserved; got %+v", peers) + } +} + +// TestResolvePeers_NilObservationStore — observation store may be +// nil at construction time. Must fall back to path-1 only. +func TestResolvePeers_NilObservationStore(t *testing.T) { + pub := &stubPub{state: map[[2]string]adapter.AssignmentInfo{ + {"v1", "r1"}: {VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: "10.0.0.1:9220"}, + }} + peers := resolvePeers([]string{"r1", "r2"}, adapter.AssignmentInfo{ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}, "v1", pub, nil) + // Self r1 excluded; r2 path-2 fails (nil obs); peers empty. + if len(peers) != 0 { + t.Fatalf("expected empty peers with nil obs; got %+v", peers) + } +} + +// TestResolvePeers_PathOnePreferredOverPathTwo — when the same slot +// has BOTH a published line AND an observation, path-1 (authority) +// must win. The slot is the bound replica; observation is a stale +// heartbeat from before the bind. +func TestResolvePeers_PathOnePreferredOverPathTwo(t *testing.T) { + pub := &stubPub{state: map[[2]string]adapter.AssignmentInfo{ + {"v1", "r1"}: {VolumeID: "v1", ReplicaID: "r1", Epoch: 7, EndpointVersion: 3, DataAddr: "AUTH:1"}, + {"v1", "r2"}: {VolumeID: "v1", ReplicaID: "r2", Epoch: 7, EndpointVersion: 3, DataAddr: "AUTH:2"}, + }} + obs := &stubObs{state: map[[2]string]authority.SlotFact{ + {"v1", "r2"}: {VolumeID: "v1", ReplicaID: "r2", DataAddr: "OBS:2"}, + }} + peers := resolvePeers([]string{"r1", "r2"}, adapter.AssignmentInfo{ReplicaID: "r1", Epoch: 7, EndpointVersion: 3}, "v1", pub, obs) + if len(peers) != 1 { + t.Fatalf("expected 1 peer; got %d", len(peers)) + } + if peers[0].DataAddr != "AUTH:2" { + t.Errorf("DataAddr: got %q want AUTH:2 (path-1 must win over path-2)", peers[0].DataAddr) + } + if peers[0].Epoch != 7 { + t.Errorf("Epoch: got %d want 7 (authority value)", peers[0].Epoch) + } +}