Merge branch 'pr453' into HEAD

This commit is contained in:
pingqiu committed 2026-11-22 20:47:21 -08:00
commit 7fb4e251c7
4 files changed
+250 -34

No files matched your search

@@ -2,6 +2,7 @@ package authority
import (
"errors"
"log"
"sort"
"sync"
"time"
@@ -10,7 +11,7 @@ import (
// ============================================================
// P14 S4 — Observation Store
//
// Push-ingested latest-wins observation store per ServerID. The
// Push-ingested latest-wins observation store per replica slot. 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
@@ -35,18 +36,19 @@ type ObservationStore struct {
revision uint64
onMutation func()
// supersededCount counts heartbeat ingests that were dropped
// because a newer ObservedAt was already stored for the same
// ServerID. Diagnostic only — PCDD-DELAYED-HB-001 evidence
// supersededCount counts slot reports that were dropped because a
// newer ObservedAt was stored for that server/volume/replica slot.
// Diagnostic only — PCDD-DELAYED-HB-001 evidence
// surface. Not an authority input; publisher / controller /
// evidence minting paths MUST NOT read it. Exposed via
// SupersededCount().
supersededCount uint64
supersededSlots map[[3]string]uint64
}
// SupersededCount returns the total number of ingests that were
// dropped because a newer observation from the same server was
// already stored. Diagnostic surface for PCDD-DELAYED-HB-001.
// SupersededCount returns the total number of slot reports dropped
// because a newer report of that same server/volume/replica was stored.
// Diagnostic surface for PCDD-DELAYED-HB-001.
// NOT authority input. Monotonic across the lifetime of the store.
func (s *ObservationStore) SupersededCount() uint64 {
s.mu.Lock()
@@ -54,6 +56,14 @@ func (s *ObservationStore) SupersededCount() uint64 {
return s.supersededCount
}
// SupersededSlotCount is the diagnostic count for one reporting slot.
// Like SupersededCount, it is not an authority input.
func (s *ObservationStore) SupersededSlotCount(serverID, volumeID, replicaID string) uint64 {
s.mu.Lock()
defer s.mu.Unlock()
return s.supersededSlots[[3]string{serverID, volumeID, replicaID}]
}
// 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.
@@ -201,10 +211,11 @@ func NewObservationStore(config FreshnessConfig, now func() time.Time) *Observat
}
cfg := config.withDefaults()
return &ObservationStore{
config: cfg,
now: now,
startedAt: now(),
observations: map[string]Observation{},
config: cfg,
now: now,
startedAt: now(),
observations: map[string]Observation{},
supersededSlots: make(map[[3]string]uint64),
}
}
@@ -231,11 +242,10 @@ var ErrInvalidObservation = errors.New("observation_store: invalid observation")
// 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.
// Latest-wins per (ServerID, volume, replica). A slot report strictly
// older than that slot's stored fact is ignored; other slots in the
// observation are accepted independently. No error is returned for
// superseded reports.
func (s *ObservationStore) Ingest(obs Observation) error {
_, err := s.ingest(obs)
return err
@@ -290,44 +300,65 @@ func (s *ObservationStore) ingest(obs Observation) ([]SlotHealthTransition, erro
var fn func()
var transitions []SlotHealthTransition
type supersededReport struct {
volume, replica string
sentAt, newest time.Time
total uint64
}
var dropped []supersededReport
// Both the all-superseded and mixed-report paths release mu before
// returning. Logging never runs under the store lock.
defer func() {
for _, d := range dropped {
log.Printf("heartbeat superseded server=%s volume=%s replica=%s sent_at=%s newest=%s total=%d",
obs.ServerID, d.volume, d.replica, d.sentAt.UTC().Format(time.RFC3339Nano), d.newest.UTC().Format(time.RFC3339Nano), d.total)
}
}()
s.mu.Lock()
prev, hadPrev := s.observations[obs.ServerID]
if hadPrev {
if prev.ObservedAt.After(obs.ObservedAt) {
// Out-of-order ingest: keep the newer one already
// stored. No mutation fired.
//
// Diagnostic counter for PCDD-DELAYED-HB-001. Not an
// authority input. Must never be read by publisher /
// controller / evidence minting path — it exists so
// tests and operators can see that a superseded
// heartbeat was observed and recorded-as-superseded,
// distinct from "silently dropped".
s.supersededCount++
s.mu.Unlock()
return nil, nil
}
}
// Health transitions, from this accepted report against the same
// server's previously stored fact for each slot it carries.
// slot's stored fact. INV-OBS-SLOT-ORDER-001 / V1-SPEC r2.53:
// timestamps order one sender's
// slot only; a later report from another slot cannot supersede it.
accepted := make([]SlotFact, 0, len(obs.Slots))
for _, slot := range obs.Slots {
old := ""
var newest time.Time
if hadPrev {
for _, p := range prev.Slots {
if slotKey(p) == slotKey(slot) {
old = p.UnhealthyReason
newest = slotObservedAt(p, prev)
break
}
}
}
if newest.After(slot.ObservedAt) {
s.supersededCount++
key := [3]string{obs.ServerID, slot.VolumeID, slot.ReplicaID}
s.supersededSlots[key]++
dropped = append(dropped, supersededReport{slot.VolumeID, slot.ReplicaID, slot.ObservedAt, newest, s.supersededSlots[key]})
continue
}
accepted = append(accepted, slot)
if old != slot.UnhealthyReason {
transitions = append(transitions, SlotHealthTransition{
VolumeID: slot.VolumeID, ReplicaID: slot.ReplicaID, Old: old, New: slot.UnhealthyReason,
})
}
}
if len(obs.Slots) > 0 && len(accepted) == 0 {
s.mu.Unlock()
return nil, nil
}
obs.Slots = accepted
if hadPrev {
obs.Slots = mergeServerSlots(prev.Slots, obs.Slots)
if prev.ObservedAt.After(obs.ObservedAt) {
// Preserve the newest server metadata without lending its
// timestamp or freshness to another process's slot.
obs.ObservedAt, obs.ExpiresAt, obs.Server = prev.ObservedAt, prev.ExpiresAt, prev.Server
}
}
s.observations[obs.ServerID] = obs
s.revision++
@@ -0,0 +1,153 @@
package authority
import (
"bytes"
"fmt"
"log"
"strings"
"testing"
"time"
)
type unlockedHeartbeatLog struct {
bytes.Buffer
store *ObservationStore
locked bool
}
func (w *unlockedHeartbeatLog) Write(p []byte) (int, error) {
if w.store.mu.TryLock() {
w.store.mu.Unlock()
} else {
w.locked = true
}
return w.Buffer.Write(p)
}
func TestObservationStore_SupersededSlotLogsAfterUnlock(t *testing.T) {
base := time.Unix(1000, 0)
s := NewObservationStore(FreshnessConfig{}, func() time.Time { return base })
w := &unlockedHeartbeatLog{store: s}
old := log.Writer()
log.SetOutput(w)
t.Cleanup(func() { log.SetOutput(old) })
for _, server := range []string{"one-host", "other-host"} {
for _, volume := range []string{"a", "b"} {
slot := healthySlot(volume, "r1")
if err := s.Ingest(Observation{ServerID: server, ObservedAt: base, Slots: []SlotFact{slot}}); err != nil {
t.Fatal(err)
}
}
}
for _, tc := range []struct{ server, volume string }{{"one-host", "a"}, {"one-host", "a"}, {"one-host", "b"}, {"other-host", "a"}} {
if err := s.Ingest(Observation{ServerID: tc.server, ObservedAt: base.Add(-time.Second), Slots: []SlotFact{healthySlot(tc.volume, "r1")}}); err != nil {
t.Fatal(err)
}
}
if w.locked {
t.Fatal("superseded diagnostic was emitted while the store lock was held")
}
lines := strings.Split(strings.TrimSpace(w.String()), "\n")
if len(lines) != 4 {
t.Fatalf("diagnostics=%q; want one line per dropped slot", w.String())
}
for i, want := range []string{
"server=one-host volume=a replica=r1 sent_at=1970-01-01T00:16:39Z newest=1970-01-01T00:16:40Z total=1",
"server=one-host volume=a replica=r1 sent_at=1970-01-01T00:16:39Z newest=1970-01-01T00:16:40Z total=2",
"server=one-host volume=b replica=r1 sent_at=1970-01-01T00:16:39Z newest=1970-01-01T00:16:40Z total=1",
"server=other-host volume=a replica=r1 sent_at=1970-01-01T00:16:39Z newest=1970-01-01T00:16:40Z total=1",
} {
if !strings.Contains(lines[i], "heartbeat superseded "+want) {
t.Errorf("diagnostic %d=%q; want %q", i, lines[i], want)
}
}
if s.SupersededSlotCount("one-host", "a", "r1") != 2 ||
s.SupersededSlotCount("one-host", "b", "r1") != 1 ||
s.SupersededSlotCount("other-host", "a", "r1") != 1 ||
s.SupersededSlotCount("other-host", "b", "r1") != 0 || s.SupersededCount() != 4 {
t.Fatal("per-slot diagnostics disagree with emitted totals or aggregate count")
}
}
// INV-OBS-SLOT-ORDER-001 / V1-SPEC r2.53: processes on one server order only their
// own (volume, replica) reports; another slot's later timestamp is irrelevant.
func TestObservationStore_InterleavedSendersOrderPerSlot(t *testing.T) {
for _, n := range []int{10, 100} {
t.Run(fmt.Sprintf("%d slots", n), func(t *testing.T) {
base := time.Unix(1000, 0)
now := base.Add(3 * time.Second)
s := NewObservationStore(FreshnessConfig{FreshnessWindow: 10 * time.Second}, func() time.Time { return now })
for round := 0; round < 2; round++ {
for i := n - 1; i >= 0; i-- {
slot := healthySlot(fmt.Sprintf("v%d", i/2), fmt.Sprintf("r%d", i%2+1))
slot.DataAddr = fmt.Sprintf("round-%d-slot-%d", round, i)
at := base.Add(time.Duration(round)*time.Second + time.Duration(i)*time.Millisecond)
obs, err := HeartbeatToObservation(serverObs("one-host", at, slot))
if err != nil {
t.Fatal(err)
}
if err := s.Ingest(obs); err != nil {
t.Fatal(err)
}
}
}
for i := 0; i < n; i++ {
got, ok := s.SlotFactOnServer("one-host", fmt.Sprintf("v%d", i/2), fmt.Sprintf("r%d", i%2+1))
if !ok || got.DataAddr != fmt.Sprintf("round-1-slot-%d", i) {
t.Errorf("slot %d lost an independent sender's heartbeat: fact=%+v present=%v", i, got, ok)
}
}
if got := s.SupersededCount(); got != 0 {
t.Fatalf("other senders superseded %d slot reports", got)
}
})
}
}
func TestObservationStore_MixedSlotReportKeepsOnlyNewerFacts(t *testing.T) {
base := time.Unix(1000, 0)
now := base.Add(4 * time.Second)
s := NewObservationStore(FreshnessConfig{FreshnessWindow: 10 * time.Second}, func() time.Time { return now })
report := func(at time.Duration, slots ...SlotFact) []SlotHealthTransition {
t.Helper()
tr, err := s.IngestWithHealthTransitions(Observation{ServerID: "one-host", ObservedAt: base.Add(at), Slots: slots})
if err != nil {
t.Fatal(err)
}
return tr
}
a, b, c := healthySlot("a", "r1"), healthySlot("b", "r1"), healthySlot("c", "r1")
report(3*time.Second, a)
report(time.Second, b)
a.UnhealthyReason, b.UnhealthyReason, c.UnhealthyReason = "stale", "new-b", "new-c"
mutations := 0
s.SetOnMutation(func() { mutations++ })
tr := report(2*time.Second, a, b, c)
if len(tr) != 2 || tr[0].VolumeID != "b" || tr[0].New != "new-b" || tr[1].VolumeID != "c" || tr[1].New != "new-c" {
t.Fatalf("mixed report transitions=%+v; want only b and c", tr)
}
if got, ok := s.SlotFactOnServer("one-host", "a", "r1"); !ok || got.UnhealthyReason != "" {
t.Fatalf("stale a replaced its newer fact: %+v, %v", got, ok)
}
if s.SupersededCount() != 1 || mutations != 1 {
t.Fatalf("mixed report: superseded=%d mutations=%d; want 1/1", s.SupersededCount(), mutations)
}
rev := s.Snapshot().revision
if tr := report(time.Second, a, b, c); len(tr) != 0 {
t.Fatalf("all-stale report emitted transitions: %+v", tr)
}
if s.SupersededCount() != 4 || mutations != 1 || s.Snapshot().revision != rev {
t.Fatalf("all-stale report: superseded=%d mutations=%d revision=%d; want 4/1/%d", s.SupersededCount(), mutations, s.Snapshot().revision, rev)
}
// The server's timestamp stays at its newest report; each accepted slot
// keeps its own expiry, including after a delayed mixed report.
now = base.Add(12500 * time.Millisecond)
if _, ok := s.SlotFactOnServer("one-host", "a", "r1"); !ok {
t.Fatal("a lost its later expiry to another slot's older report")
}
for _, volume := range []string{"b", "c"} {
if _, ok := s.SlotFactOnServer("one-host", volume, "r1"); ok {
t.Fatalf("%s inherited a's later freshness", volume)
}
}
}
+28 -1
View File
@@ -81,6 +81,32 @@ Recovery warnings such as `wal_hole_suspected` are recorded in Serving without c
blockmaster's publisher is the only component that mints epochs. Diagrams: the assignment lifecycle in [core §1.5](block-design.md#15-authority-blockmaster-assignments-epochs-leases), and the workspace lease and move in [agent workspace §7](agent-workspace-design.md#7-lease-takeover-and-host-moves).
**Heartbeat observations, per server/volume/replica slot.**
`ObservationStore.ingest` compares each reported slot only with that slot's
stored timestamp (`slotObservedAt`). An older slot is dropped and counted;
an equal or newer slot is accepted. A mixed report merges accepted slots and
retains every other stored slot. An all-superseded nonempty report changes no
observation or health transition. Accepted slots keep their own freshness;
server metadata keeps its newest timestamp without lending it to another slot.
```mermaid
flowchart LR
Report[Receive heartbeat report] --> Compare{Each slot: stored timestamp newer?}
Compare -->|yes| Drop[Drop and count only that slot]
Compare -->|no| Accept[Accept that slot and its health transition]
Drop --> Mixed{Any accepted slots or an empty report?}
Accept --> Mixed
Mixed -->|yes| Merge[Merge accepted slots; retain other slots and newest server metadata]
Mixed -->|no| Keep[Keep stored observations unchanged]
```
| From | To | Event and guard | Enforced in | Protects |
|---|---|---|---|---|
| Stored observations | Stored observations (slot refused) | stored timestamp for this server/volume/replica is strictly newer than the report; drop and count only this slot | `core/authority/observation_store.go` `ingest`, `slotObservedAt` | `INV-OBS-SLOT-ORDER-001` |
| Stored observations | Stored observations (mixed report merged) | accept equal/newer slots against their own stored timestamp; merge only accepted slots, preserving other slots and independent freshness | `core/authority/observation_store.go` `ingest`, `mergeServerSlots` | `INV-OBS-SLOT-ORDER-001` |
| Stored observations | Stored observations (no mutation) | a nonempty report has no accepted slot; publish no observation mutation or health transition | `core/authority/observation_store.go` `ingest` | `INV-OBS-SLOT-ORDER-001` |
**Assignment line, per volume.**
| From | To | Event and guard | Enforced in | Protects |
@@ -467,7 +493,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO
## Part B. Invariant ledger
315 rows: 244 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 300 new.
316 rows: 245 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 301 new.
The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger.
@@ -930,6 +956,7 @@ Notes:
| `INV-CSI-CONSUMES-AUTHORITY-001` | CSI never imports authority code or builds assignment facts; it takes the publish target from blockmaster and refreshes it before a stage, and blockmaster mints the IDs of the events CSI reports. | M2 (read side) | `core/csi/master_backend.go` `LookupPublishTarget`; `core/csi/node.go` `refreshPublishContext`; `core/host/master/observation_service.go` `ReportClusterEvent` | `TestG15a_CSI_DoesNotImportAuthorityOrConstructAssignmentFacts` (`core/csi/boundary_guard_test.go`); `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestObservationService_ReportClusterEventAppearsInVolumeTimeline` (`core/host/master/observation_service_test.go`) | — | ACTIVE |
| `INV-K8S-NONLOOPBACK-001` | Generated multi-node Helm values enable external iSCSI, external status and loopback rejection; with rejection enabled CSI never publishes a loopback target and fails closed when only loopback targets exist. | M2 (read side) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`; `core/csi/master_backend.go` `rejectFrontendAddr` | `TestOpsGenerateHelmValuesMultiNodeExternalISCSI` (`cmd/sw-block/main_test.go`); `TestNodeLoss_ControlStatusLookup_RejectsLoopbackPublishTargetsWhenEnabled`, `TestNodeLoss_ControlStatusLookup_FailClosedWhenOnlyLoopbackTargets` (`core/csi/master_backend_test.go`) | — | ACTIVE |
| `INV-OBS-PRODUCT-EVENTS-001` | blockmaster records placement-verified, promotion-candidate-evaluation and authority-published events, and the CSI node reports `csi_reattach_observed` after a successful stage. | M3 promotion decision (observation) | `core/host/master/product_loop.go` `recordPlacementVerifiedEvents`, `recordPromotionEvaluationEvents`, `recordAuthorityPublishedEvent` | `TestMasterTimeline_RecordsPlacementVerified`, `TestMasterTimeline_RecordsPromotionCandidateEvaluation`, `TestMasterTimeline_RecordsAuthorityPublishedAfterMint` (`core/host/master/event_ring_test.go`); `TestNodeStage_ReportsCSIReattachObservedAfterSuccessfulStage` (`core/csi/node_test.go`) | — | ACTIVE |
| `INV-OBS-SLOT-ORDER-001` | A heartbeat slot (server, volume, replica) is ordered only against that slot's own previous heartbeat: a later-stamped heartbeat of another slot of the same server never supersedes it. | M2 heartbeat observations: per-slot refusal / mixed merge / all-superseded no mutation (V1-SPEC r2.53) | `core/authority/observation_store.go` `ingest` (per-slot comparison), `slotObservedAt`; `SupersededSlotCount` (diagnostic only) | `TestObservationStore_InterleavedSendersOrderPerSlot`, `TestObservationStore_MixedSlotReportKeepsOnlyNewerFacts`, `TestObservationStore_SupersededSlotLogsAfterUnlock` (`core/authority/observation_store_slot_order_test.go`) | 1.0 limit: a backward wall-clock step longer than the freshness window expires that host's slots; 1.0.1: per-process sequence. | ACTIVE |
| `INV-OBS-SLOT-FROM-EXPECTED-SERVER-001` | A replica's slot in the assembled topology takes addresses and health only from a fresh fact reported by the server its expected slot names; another server's fact for the same replica is never used, so with none from that server the slot is a placeholder. | AUTHORITY/ORDER: observation to assignment line | `core/authority/snapshot_builder.go` `assembleVolumeTopology` | `TestAssembleVolumeTopology_SlotFactOnlyFromTheExpectedServer` (`core/authority/snapshot_slot_server_test.go`) | — (pure assembly; the unit test is the proof form) | ACTIVE |
| `INV-HELM-RF-NODECOUNT-001` | Generated Helm values fail closed when the requested replication factor exceeds the selected Ready schedulable node count. | M3 (configuration) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`, `selectHelmValuesNodes` | `TestOpsGenerateHelmValuesRejectsRFAboveSelectedNodes` (`cmd/sw-block/main_test.go`) | — | ACTIVE |
| `INV-HOSTPATH-TRANSPARENT-001` | The read model reports transparent host-path recovery only with a multipathed, Active/Optimized, stale-fenced path, writer and reader checks, and the same pod UID. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume`, `deriveManagedVolumeStates` | `TestManagedVolumeProjection_TransparentISCSIALUARecovered`, `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE |
+5
View File
@@ -54,6 +54,11 @@ one live blockvolume per volume ([one process per volume](releases/one-process-p
- **SeaweedFS space:** every cut and snapshot stores the chunks that changed since the previous one. Space comes
back only by GC and then a SeaweedFS vacuum (below).
Each volume process reports its own heartbeat slot (server, volume and replica).
The master orders each slot against that slot's previous report. In version 1.0,
a backward host-clock step longer than the freshness window (30 seconds by
default) can expire the host's slots; keep host clocks synchronized.
## Recovery point and sync policy
- **A stopped volume** keeps everything it acknowledged, on its host.