From ad9ee63491d1ef1e8660a71f32963f3c2c86700b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:15:33 -0800 Subject: [PATCH 1/7] authority: a heartbeat that changes nothing wakes no observation rebuild The observation store wakes a rebuild only when an ingest changes what a snapshot build reads: a new server, a server's facts or freshness, a slot added, removed or changed but for its timestamps, a slot's expiry state, a volume two servers report, or a passed deadline. What changes with time is a deadline: each server's next expiry in a heap, the pending grace's end; the host wakes at the earliest. A published line wakes the build through the publisher's line-change hook. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/authority/authority.go | 17 ++ .../core/authority/observation_changes.go | 174 +++++++++++++ .../authority/observation_changes_test.go | 238 ++++++++++++++++++ .../core/authority/observation_host.go | 31 +++ .../core/authority/observation_store.go | 28 ++- seaweed-block/core/host/master/host.go | 3 + 6 files changed, 490 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/authority/observation_changes.go create mode 100644 seaweed-block/core/authority/observation_changes_test.go diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index 30cafb9342..1e9ba83378 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -124,6 +124,9 @@ type Publisher struct { // (SetIncarnationSource); its own lock, never taken under mu. incarnationMu sync.RWMutex incarnationOf func(volumeID, replicaID, dataAddr, ctrlAddr string) string + // lineChanged is told the volume of every published line (the + // observation build reads lines, and no heartbeat carries them). + lineChanged func(volumeID string) mu sync.Mutex state map[subKey]assignmentState @@ -480,6 +483,14 @@ func (p *Publisher) SetIncarnationSource(of func(volumeID, replicaID, dataAddr, p.incarnationMu.Unlock() } +// SetLineChangeHook registers fn, told the volume of every published line +// after the publication (outside the publisher's lock). nil removes it. +func (p *Publisher) SetLineChangeHook(fn func(volumeID string)) { + p.incarnationMu.Lock() + p.lineChanged = fn + p.incarnationMu.Unlock() +} + func (p *Publisher) apply(ask AssignmentAsk) error { if p.publicationAdmission != nil { return p.publicationAdmission(ask, func() error { return p.applyWithWorkspaceMove(ask, nil) }) @@ -751,6 +762,12 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr if p.observer != nil { safeInvokePublishObserver(p.observer, PublishEvent{Info: next, Ask: ask}) } + p.incarnationMu.RLock() + changed := p.lineChanged + p.incarnationMu.RUnlock() + if changed != nil { + changed(ask.VolumeID) + } return nil } diff --git a/seaweed-block/core/authority/observation_changes.go b/seaweed-block/core/authority/observation_changes.go new file mode 100644 index 0000000000..0c499335ee --- /dev/null +++ b/seaweed-block/core/authority/observation_changes.go @@ -0,0 +1,174 @@ +package authority + +import ( + "container/heap" + "reflect" + "time" +) + +// What a snapshot build reads changes only by a heartbeat that changes it, +// by time (a server's or a slot's expiry, the pending grace's end), by a +// published line, or by the topology. A heartbeat that refreshes only +// timestamps changes none of these, so it wakes no rebuild; the time each +// such fact changes is kept as a deadline, and the host wakes then. + +// buildReadsChangedLocked says whether storing next for its server (prev the +// observation it replaces) can change a snapshot build at now: a new server; +// a change of the server's facts or freshness; a slot added, removed, or +// changed in anything but its timestamps; a slot whose expiry state flips; +// or any slot of a volume that another server also reports (a build orders +// such slots by their timestamps, so a refresh can change it). s.mu held. +func (s *ObservationStore) buildReadsChangedLocked(prev Observation, hadPrev bool, next Observation, now time.Time) bool { + if !hadPrev || prev.Server != next.Server || now.After(prev.ExpiresAt) != now.After(next.ExpiresAt) || len(prev.Slots) != len(next.Slots) { + return true + } + before := make(map[string]SlotFact, len(prev.Slots)) + for _, sl := range prev.Slots { + before[slotKey(sl)] = sl + } + for _, sl := range next.Slots { + p, ok := before[slotKey(sl)] + if !ok || !sameSlotContent(p, sl) || slotExpired(p, prev, now) != slotExpired(sl, next, now) { + return true + } + if len(s.volServers[sl.VolumeID]) > 1 { + return true + } + } + return false +} + +// sameSlotContent compares two slot facts but for their timestamps. +func sameSlotContent(a, b SlotFact) bool { + a.ObservedAt, a.ExpiresAt, b.ObservedAt, b.ExpiresAt = time.Time{}, time.Time{}, time.Time{}, time.Time{} + return reflect.DeepEqual(a, b) +} + +// indexServerLocked records which volumes server id reports (prev's slots +// out, next's in). s.mu held. +func (s *ObservationStore) indexServerLocked(id string, prev []SlotFact, next []SlotFact) { + if s.volServers == nil { + s.volServers = map[string]map[string]struct{}{} + } + for _, sl := range prev { + if m := s.volServers[sl.VolumeID]; m != nil { + delete(m, id) + if len(m) == 0 { + delete(s.volServers, sl.VolumeID) + } + } + } + for _, sl := range next { + m := s.volServers[sl.VolumeID] + if m == nil { + m = map[string]struct{}{} + s.volServers[sl.VolumeID] = m + } + m[id] = struct{}{} + } +} + +// nextExpiry is the earliest expiry of obs (its own, or a slot's) not yet +// passed at now; zero when none is ahead. A fact expires once now is after +// its expiry (observation_store.go), so an expiry equal to now is still +// ahead. +func nextExpiry(obs Observation, now time.Time) time.Time { + var at time.Time + consider := func(t time.Time) { + if !t.IsZero() && !now.After(t) && (at.IsZero() || t.Before(at)) { + at = t + } + } + consider(obs.ExpiresAt) + for _, sl := range obs.Slots { + consider(sl.ExpiresAt) + } + return at +} + +// deadlineEntry is one server's next expiry; seq tells a current entry from +// one a later heartbeat replaced (lazy deletion). +type deadlineEntry struct { + at time.Time + server string + seq uint64 +} + +type deadlineHeap []deadlineEntry + +func (h deadlineHeap) Len() int { return len(h) } +func (h deadlineHeap) Less(i, j int) bool { return h[i].at.Before(h[j].at) } +func (h deadlineHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *deadlineHeap) Push(x any) { *h = append(*h, x.(deadlineEntry)) } +func (h *deadlineHeap) Pop() any { + old := *h + e := old[len(old)-1] + *h = old[:len(old)-1] + return e +} + +// scheduleLocked records server id's next expiry after now. s.mu held. +func (s *ObservationStore) scheduleLocked(id string, obs Observation, now time.Time) { + if s.deadlineSeq == nil { + s.deadlineSeq = map[string]uint64{} + } + s.deadlineSeq[id]++ + if at := nextExpiry(obs, now); !at.IsZero() { + heap.Push(&s.deadlines, deadlineEntry{at: at, server: id, seq: s.deadlineSeq[id]}) + } +} + +// NextDeadline is the earliest time a build's input changes with no +// heartbeat: a server's or slot's expiry, or the pending grace's end; zero +// when none is ahead. +func (s *ObservationStore) NextDeadline() time.Time { + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + for s.deadlines.Len() > 0 { + e := s.deadlines[0] + if e.seq == s.deadlineSeq[e.server] { + break + } + heap.Pop(&s.deadlines) // replaced by a later heartbeat + } + var at time.Time + if s.deadlines.Len() > 0 { + at = s.deadlines[0].at + } + if g := s.startedAt.Add(s.config.PendingGrace); g.After(now) && (at.IsZero() || g.Before(at)) { + at = g + } + return at +} + +// ExpireDue reports whether a deadline has passed since the last call (an +// expiry or the pending grace's end: a build's input changed), and moves +// each such server to its next deadline. +func (s *ObservationStore) ExpireDue() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.expireDueLocked(s.now()) +} + +// expireDueLocked is ExpireDue with s.mu held. +func (s *ObservationStore) expireDueLocked(now time.Time) bool { + due := false + for s.deadlines.Len() > 0 && now.After(s.deadlines[0].at) { + e := heap.Pop(&s.deadlines).(deadlineEntry) + if e.seq != s.deadlineSeq[e.server] { + continue + } + due = true + if obs, ok := s.observations[e.server]; ok { + s.scheduleLocked(e.server, obs, now) + } + } + if !s.graceSeen { + if g := s.startedAt.Add(s.config.PendingGrace); !g.After(now) { + s.graceSeen = true + due = true + } + } + return due +} diff --git a/seaweed-block/core/authority/observation_changes_test.go b/seaweed-block/core/authority/observation_changes_test.go new file mode 100644 index 0000000000..29e1b77dc0 --- /dev/null +++ b/seaweed-block/core/authority/observation_changes_test.go @@ -0,0 +1,238 @@ +package authority + +import ( + "context" + "fmt" + "math/rand" + "reflect" + "sync/atomic" + "testing" + "time" +) + +func countingStore(t *testing.T, clk *fakeClock, window time.Duration) (*ObservationStore, *atomic.Int64) { + t.Helper() + s := NewObservationStore(FreshnessConfig{FreshnessWindow: window}, clk.Now) + var wakes atomic.Int64 + s.SetOnMutation(func() { wakes.Add(1) }) + return s, &wakes +} + +func oneSlotObs(server string, at time.Time, slots ...SlotFact) Observation { + return Observation{ServerID: server, ObservedAt: at, Server: ServerFact{Reachable: true, Eligible: true}, Slots: slots} +} + +// A heartbeat that refreshes only timestamps (every volume process sends one +// every 2 s) wakes no rebuild; a changed slot, a new server, or a refresh of +// a volume two servers report does. On main every heartbeat woke a full +// rebuild. +func TestObservationStoreTimestampOnlyRefreshWakesNothing(t *testing.T) { + start := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + s, wakes := countingStore(t, clk, 30*time.Second) + const servers = 200 + for i := 0; i < servers; i++ { + if err := s.Ingest(oneSlotObs(fmt.Sprintf("s%03d", i), start, healthySlot(fmt.Sprintf("v%03d", i), "r1"))); err != nil { + t.Fatal(err) + } + } + if wakes.Load() != servers { + t.Fatalf("%d wakes for %d new servers", wakes.Load(), servers) + } + wakes.Store(0) + clk.Advance(2 * time.Second) + for round := 0; round < 3; round++ { + for i := 0; i < 100; i++ { + if err := s.Ingest(oneSlotObs(fmt.Sprintf("s%03d", i), clk.Now(), healthySlot(fmt.Sprintf("v%03d", i), "r1"))); err != nil { + t.Fatal(err) + } + } + clk.Advance(2 * time.Second) + } + if n := wakes.Load(); n != 0 { + t.Fatalf("300 timestamp-only heartbeats woke %d rebuilds, want 0", n) + } + changed := healthySlot("v007", "r1") + changed.ReadyForPrimary = false + if err := s.Ingest(oneSlotObs("s007", clk.Now(), changed)); err != nil { + t.Fatal(err) + } + if n := wakes.Load(); n != 1 { + t.Fatalf("a changed slot woke %d rebuilds, want 1", n) + } + // A volume two servers report: a refresh of either wakes. + if err := s.Ingest(oneSlotObs("s900", clk.Now(), healthySlot("v008", "r2"))); err != nil { + t.Fatal(err) + } + wakes.Store(0) + if err := s.Ingest(oneSlotObs("s008", clk.Now(), healthySlot("v008", "r1"))); err != nil { + t.Fatal(err) + } + if n := wakes.Load(); n != 1 { + t.Fatalf("a refresh of a volume two servers report woke %d rebuilds, want 1", n) + } +} + +// What changes with time wakes the host at its deadline, with no heartbeat: +// a server whose heartbeats stop is seen expired once its freshness window +// passes. +func TestObservationHostRebuildsAtAnExpiryWithNoHeartbeat(t *testing.T) { + start := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + host := NewObservationHost(ObservationHostConfig{ + Freshness: FreshnessConfig{FreshnessWindow: 100 * time.Millisecond}, + Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}}, + Now: clk.Now, + }) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + host.Start(ctx) + defer host.Stop() + _ = host.IngestHeartbeat(serverObs("s1", start, healthySlot("v1", "r1"))) + waitFor := func(what string, ok func(BuildResult) bool) { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + if b, have := host.LastBuild(); have && ok(b) { + return + } + time.Sleep(10 * time.Millisecond) + } + b, _ := host.LastBuild() + t.Fatalf("%s: last build at %v with %d servers", what, b.BuiltAt, len(b.Snapshot.Servers)) + } + waitFor("the heartbeat's build", func(b BuildResult) bool { return len(b.Snapshot.Servers) == 1 }) + clk.Advance(time.Second) // past s1's freshness; no heartbeat follows + waitFor("the expiry's build", func(b BuildResult) bool { return len(b.Snapshot.Servers) == 0 && b.BuiltAt.Equal(clk.Now()) }) +} + +// normalizedBuild is a build with its stamps cleared: when it was built, the +// store revision, and the timestamps the evidence carries. +func normalizedBuild(b BuildResult) BuildResult { + b.BuiltAt, b.InputRev = time.Time{}, 0 + b.Snapshot.CollectedAt, b.Snapshot.CollectedRevision = time.Time{}, 0 + vols := make([]VolumeTopologySnapshot, len(b.Snapshot.Volumes)) + for i, v := range b.Snapshot.Volumes { + v.Slots = append([]ReplicaCandidate(nil), v.Slots...) + for j := range v.Slots { + v.Slots[j].ObservedAt = time.Time{} + } + vols[i] = v + } + b.Snapshot.Volumes = vols + pend := map[string]VolumePendingStatus{} + for k, v := range b.Report.Pending { + v.EvaluatedAt = time.Time{} + pend[k] = v + } + b.Report.Pending = pend + uns := map[string]VolumeUnsupportedEvidence{} + for k, v := range b.Report.Unsupported { + v.EvaluatedAt, v.SnapshotRevision = time.Time{}, 0 + facts := make([]Observation, len(v.OffendingFacts)) + for i, o := range v.OffendingFacts { + o.ObservedAt, o.ExpiresAt = time.Time{}, time.Time{} + o.Slots = append([]SlotFact(nil), o.Slots...) + for j := range o.Slots { + o.Slots[j].ObservedAt, o.Slots[j].ExpiresAt = time.Time{}, time.Time{} + } + facts[i] = o + } + v.OffendingFacts = facts + uns[k] = v + } + b.Report.Unsupported = uns + return b +} + +// Whenever the store reports no change (no wake, no passed deadline), a +// build now equals the last build, but for its stamps: random heartbeats +// (new, changed, timestamp-only, of a shared volume), time steps past +// freshness windows and the pending grace, and GC. +func TestObservationStoreNoWakeMeansTheSameBuild(t *testing.T) { + topo := AcceptedTopology{Volumes: []VolumeExpected{ + {VolumeID: "va", Slots: []ExpectedSlot{{ReplicaID: "r1", ServerID: "s1"}}}, + {VolumeID: "vb", Slots: []ExpectedSlot{{ReplicaID: "r1", ServerID: "s2"}}}, + threeSlotVolume("vc"), + }} + for seed := int64(1); seed <= 300; seed++ { + rng := rand.New(rand.NewSource(seed)) + start := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + s := NewObservationStore(FreshnessConfig{FreshnessWindow: 5 * time.Second, PendingGrace: 7 * time.Second}, clk.Now) + var woke bool + s.SetOnMutation(func() { woke = true }) + last := BuildSnapshot(s.Snapshot(), topo, nil) + s.ExpireDue() + reports := map[string][]SlotFact{ + "s1": {healthySlot("va", "r1"), healthySlot("vc", "r1")}, + "s2": {healthySlot("vb", "r1"), healthySlot("vc", "r2")}, + "s3": {healthySlot("vc", "r3")}, + "s4": {healthySlot("vx", "r1")}, + } + names := []string{"s1", "s2", "s3", "s4"} + for step := 0; step < 300; step++ { + woke = false + switch rng.Intn(7) { + case 0, 1, 2: // a heartbeat, maybe with a change + srv := names[rng.Intn(len(names))] + slots := append([]SlotFact(nil), reports[srv]...) + if rng.Intn(4) == 0 { + i := rng.Intn(len(slots)) + slots[i].ReadyForPrimary = !slots[i].ReadyForPrimary + reports[srv] = slots + } + obs := oneSlotObs(srv, clk.Now(), slots...) + if rng.Intn(8) == 0 { + obs.Server.Eligible = false + } + _ = s.Ingest(obs) + case 3: // time passes + clk.Advance(time.Duration(rng.Intn(4000)) * time.Millisecond) + case 4: // the host's timer + if s.ExpireDue() { + woke = true + } + case 5: + s.GC(time.Duration(rng.Intn(20)) * time.Second) + case 6: // exactly at the next deadline, or just past it + if at := s.NextDeadline(); !at.IsZero() { + clk.Set(at.Add(time.Duration(rng.Intn(2)))) + } + } + if s.ExpireDue() { // a deadline passed: the host's timer would wake + woke = true + } + now := BuildSnapshot(s.Snapshot(), topo, nil) + if woke { + last = now + continue + } + if !reflect.DeepEqual(normalizedBuild(now), normalizedBuild(last)) { + t.Fatalf("seed %d step %d: the store reported no change, but the build changed:\nlast %+v\nnow %+v", seed, step, normalizedBuild(last), normalizedBuild(now)) + } + } + } +} + +// A published line wakes the observation build (no heartbeat carries it): +// the publisher tells its line-change hook the volume of every publication, +// and only of a publication. +func TestPublisherTellsItsLineChangeHook(t *testing.T) { + var told []string + pub := NewPublisher(NewStaticDirective(nil)) + pub.SetLineChangeHook(func(v string) { told = append(told, v) }) + ask := AssignmentAsk{VolumeID: "v1", ReplicaID: "r1", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind} + if err := pub.apply(ask); err != nil { + t.Fatal(err) + } + if len(told) != 1 || told[0] != "v1" { + t.Fatalf("hook told %v after one publication, want [v1]", told) + } + if err := pub.apply(ask); err == nil { + t.Fatal("a second bind was accepted") + } + if len(told) != 1 { + t.Fatalf("hook told %v after a refused ask", told) + } +} diff --git a/seaweed-block/core/authority/observation_host.go b/seaweed-block/core/authority/observation_host.go index 8748df39f0..1d1850f6df 100644 --- a/seaweed-block/core/authority/observation_host.go +++ b/seaweed-block/core/authority/observation_host.go @@ -116,6 +116,11 @@ func NewObservationHost(cfg ObservationHostConfig) *ObservationHost { return h } +// Wake asks for a rebuild: a change a build reads that no heartbeat +// carries (a published authority line, a topology change). Non-blocking; +// wakes coalesce. +func (h *ObservationHost) Wake() { h.signalRebuild() } + // Store returns the underlying store. Exposed for tests and for // downstream diagnosis; the host does not expect external code // to manipulate it beyond Ingest. @@ -221,14 +226,40 @@ func (h *ObservationHost) run(ctx context.Context) { h.rebuildOnce() for { + // A heartbeat that refreshes only timestamps wakes nothing; what + // changes with time (an expiry, the pending grace's end) wakes the + // loop at its deadline. + var deadlineC <-chan time.Time + var timer *time.Timer + if at := h.store.NextDeadline(); !at.IsZero() { + d := at.Sub(h.store.now()) + if d < 10*time.Millisecond { + d = 10 * time.Millisecond + } + timer = time.NewTimer(d) + deadlineC = timer.C + } + stopTimer := func() { + if timer != nil { + timer.Stop() + } + } select { case <-ctx.Done(): + stopTimer() return case <-h.stop: + stopTimer() return case <-h.wake: + stopTimer() h.rebuildOnce() + case <-deadlineC: + if h.store.ExpireDue() { + h.rebuildOnce() + } case <-gcC: + stopTimer() h.store.GC(h.gcRetain) // GC may have set the mutation flag; that is OK — the // next iteration will pick up the wake. diff --git a/seaweed-block/core/authority/observation_store.go b/seaweed-block/core/authority/observation_store.go index 4283ff4f82..12f26fb460 100644 --- a/seaweed-block/core/authority/observation_store.go +++ b/seaweed-block/core/authority/observation_store.go @@ -36,6 +36,15 @@ type ObservationStore struct { revision uint64 onMutation func() + // volServers: the servers reporting a slot of each volume (a volume + // two servers report is ordered by timestamps in a build). + volServers map[string]map[string]struct{} + // deadlines: each server's next expiry (lazily replaced: deadlineSeq); + // graceSeen: the pending grace's end was reported (observation_changes.go). + deadlines deadlineHeap + deadlineSeq map[string]uint64 + graceSeen bool + // 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 @@ -377,9 +386,22 @@ func (s *ObservationStore) ingest(obs Observation) ([]SlotHealthTransition, erro obs.ObservedAt, obs.ExpiresAt, obs.Server = prev.ObservedAt, prev.ExpiresAt, prev.Server } } + now := s.now() + // A deadline passed since the last build is a change too (the build a + // heartbeat wakes then sees the expiry, as before). + changed := s.expireDueLocked(now) + if s.buildReadsChangedLocked(prev, hadPrev, obs, now) { + changed = true + } + s.indexServerLocked(obs.ServerID, prev.Slots, obs.Slots) + s.scheduleLocked(obs.ServerID, obs, now) s.observations[obs.ServerID] = obs s.revision++ - fn = s.onMutation + if changed { + // A heartbeat that refreshes only timestamps wakes no rebuild: its + // expiry is a deadline (NextDeadline) the host wakes at. + fn = s.onMutation + } s.mu.Unlock() if fn != nil { @@ -561,6 +583,10 @@ func (s *ObservationStore) GC(retain time.Duration) int { for id, obs := range s.observations { if now.Sub(obs.ObservedAt) > retain { delete(s.observations, id) + s.indexServerLocked(id, obs.Slots, nil) + if s.deadlineSeq != nil { + s.deadlineSeq[id]++ // its pending deadline is void + } removed++ } } diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index ef00e39956..743de83b35 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -298,6 +298,9 @@ func New(cfg Config) (*Host, error) { Sink: sink, Reader: boot.Publisher, }) + // A published line changes what the observation build reads, and no + // heartbeat carries it: it wakes the build. + boot.Publisher.SetLineChangeHook(func(string) { obs.Wake() }) // An ask built outside the controller (a heal, a planned or workspace // move, an operator's request) is issued for the process its target // reports now. From 75bb94c46dc06bd53bf22557d012819d8c7606d0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:31:26 -0800 Subject: [PATCH 2/7] authority: the grace's end stays a deadline until consumed; the master's line wake is pinned NextDeadline keeps the pending grace's end until ExpireDue reports it, even once past, so a build taken just before it and submitted just after it is rebuilt with no heartbeat. The property test now fires the host's timer only at NextDeadline, so a dropped deadline shows. A master test pins the line-change wiring: a volume reported once is bound by the controller and the next build carries the line. Comments that promised a wake on every ingest now say what wakes. Co-Authored-By: Claude Opus 5.5 --- .../core/authority/observation_changes.go | 11 ++-- .../authority/observation_changes_test.go | 64 +++++++++++++++++-- .../core/authority/observation_host.go | 8 ++- .../core/authority/observation_store.go | 4 +- .../core/host/master/line_change_wake_test.go | 58 +++++++++++++++++ 5 files changed, 133 insertions(+), 12 deletions(-) create mode 100644 seaweed-block/core/host/master/line_change_wake_test.go diff --git a/seaweed-block/core/authority/observation_changes.go b/seaweed-block/core/authority/observation_changes.go index 0c499335ee..94e6f1a901 100644 --- a/seaweed-block/core/authority/observation_changes.go +++ b/seaweed-block/core/authority/observation_changes.go @@ -119,12 +119,12 @@ func (s *ObservationStore) scheduleLocked(id string, obs Observation, now time.T } // NextDeadline is the earliest time a build's input changes with no -// heartbeat: a server's or slot's expiry, or the pending grace's end; zero -// when none is ahead. +// heartbeat and ExpireDue has not reported yet: a server's or slot's expiry, +// or the pending grace's end (possibly already past); zero when none is +// left. func (s *ObservationStore) NextDeadline() time.Time { s.mu.Lock() defer s.mu.Unlock() - now := s.now() for s.deadlines.Len() > 0 { e := s.deadlines[0] if e.seq == s.deadlineSeq[e.server] { @@ -136,7 +136,10 @@ func (s *ObservationStore) NextDeadline() time.Time { if s.deadlines.Len() > 0 { at = s.deadlines[0].at } - if g := s.startedAt.Add(s.config.PendingGrace); g.After(now) && (at.IsZero() || g.Before(at)) { + // The grace's end stays a deadline until ExpireDue reports it, even once + // past: a build taken just before it, with the host's next look just + // after it, must still be rebuilt. + if g := s.startedAt.Add(s.config.PendingGrace); !s.graceSeen && (at.IsZero() || g.Before(at)) { at = g } return at diff --git a/seaweed-block/core/authority/observation_changes_test.go b/seaweed-block/core/authority/observation_changes_test.go index 29e1b77dc0..c48b97e55c 100644 --- a/seaweed-block/core/authority/observation_changes_test.go +++ b/seaweed-block/core/authority/observation_changes_test.go @@ -189,9 +189,9 @@ func TestObservationStoreNoWakeMeansTheSameBuild(t *testing.T) { _ = s.Ingest(obs) case 3: // time passes clk.Advance(time.Duration(rng.Intn(4000)) * time.Millisecond) - case 4: // the host's timer - if s.ExpireDue() { - woke = true + case 4: // time passes to the next deadline the host would wake at + if at := s.NextDeadline(); !at.IsZero() { + clk.Set(at.Add(time.Millisecond)) } case 5: s.GC(time.Duration(rng.Intn(20)) * time.Second) @@ -200,7 +200,9 @@ func TestObservationStoreNoWakeMeansTheSameBuild(t *testing.T) { clk.Set(at.Add(time.Duration(rng.Intn(2)))) } } - if s.ExpireDue() { // a deadline passed: the host's timer would wake + // The host's timer: it fires at NextDeadline (a deadline NextDeadline + // leaves out never fires). + if at := s.NextDeadline(); !at.IsZero() && !at.After(clk.Now()) && s.ExpireDue() { woke = true } now := BuildSnapshot(s.Snapshot(), topo, nil) @@ -236,3 +238,57 @@ func TestPublisherTellsItsLineChangeHook(t *testing.T) { t.Fatalf("hook told %v after a refused ask", told) } } + +// submitHook is a sink that runs a function at each submission (the +// submission is where a real build can cross a deadline). +type submitHook struct { + recordingSink + on func(n int) + n int +} + +func (s *submitHook) SubmitObservedState(snap ClusterSnapshot, report SupportabilityReport) error { + s.n++ + if s.on != nil { + s.on(s.n) + } + return s.recordingSink.SubmitObservedState(snap, report) +} + +// The pending grace's end is rebuilt even when a build taken just before it +// is submitted just after it, with no heartbeat ever arriving: the deadline +// stays until it is consumed. +func TestObservationHostRebuildsAfterTheGraceCrossedDuringASubmission(t *testing.T) { + start := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + grace := 100 * time.Millisecond + sink := &submitHook{} + sink.on = func(n int) { + if n == 1 { + clk.Set(start.Add(grace + time.Millisecond)) // the first build crosses the grace's end + } + } + host := NewObservationHost(ObservationHostConfig{ + Freshness: FreshnessConfig{FreshnessWindow: time.Hour, PendingGrace: grace}, + Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}}, + Sink: sink, + Now: clk.Now, + }) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + host.Start(ctx) + defer host.Stop() + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + if b, ok := host.LastBuild(); ok { + if _, pending := b.Report.Pending["v1"]; !pending { + if _, unsupported := b.Report.Unsupported["v1"]; unsupported { + return + } + } + } + time.Sleep(10 * time.Millisecond) + } + b, _ := host.LastBuild() + t.Fatalf("v1 is still pending past the grace with no heartbeat: pending %v, unsupported %v", b.Report.Pending, b.Report.Unsupported) +} diff --git a/seaweed-block/core/authority/observation_host.go b/seaweed-block/core/authority/observation_host.go index 1d1850f6df..3dbbc81085 100644 --- a/seaweed-block/core/authority/observation_host.go +++ b/seaweed-block/core/authority/observation_host.go @@ -16,9 +16,11 @@ import ( // 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 +// Default operation is build-on-change (sketch §11): an Ingest +// that changes what a build reads (observation_changes.go), a +// deadline passing (an expiry, the pending grace's end) or Wake (a +// published line) wakes the rebuild goroutine; a heartbeat that +// refreshes only timestamps does not. 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 diff --git a/seaweed-block/core/authority/observation_store.go b/seaweed-block/core/authority/observation_store.go index 12f26fb460..0081267ef4 100644 --- a/seaweed-block/core/authority/observation_store.go +++ b/seaweed-block/core/authority/observation_store.go @@ -246,7 +246,9 @@ func NewObservationStore(config FreshnessConfig, now func() time.Time) *Observat } // SetOnMutation registers a callback that fires whenever a -// successful ingest changes store contents. The callback must +// successful ingest changes what a snapshot build reads (not on a +// heartbeat that refreshes only timestamps; GC removing an entry fires it +// too). The callback must // NOT block; typical use is a non-blocking signal into the host's // rebuild goroutine. // diff --git a/seaweed-block/core/host/master/line_change_wake_test.go b/seaweed-block/core/host/master/line_change_wake_test.go new file mode 100644 index 0000000000..5929ddadfb --- /dev/null +++ b/seaweed-block/core/host/master/line_change_wake_test.go @@ -0,0 +1,58 @@ +package master + +import ( + "runtime" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" +) + +// A published line wakes the observation build, through the master's +// wiring of the publisher's line-change hook: a volume reported once (no +// heartbeat follows) is bound by the controller, and the next build carries +// that line. Timestamp-only heartbeats wake nothing, so without the wiring +// the build would keep the unbound basis until some unrelated change. +func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("the lifecycle stores need directory fsync") + } + h, err := New(Config{ + AuthorityStoreDir: t.TempDir(), + LifecycleStoreDir: t.TempDir(), + Listen: "127.0.0.1:0", + // No expiry and no GC wake within the test. + Freshness: authority.FreshnessConfig{FreshnessWindow: time.Hour}, + Topology: authority.AcceptedTopology{Volumes: []authority.VolumeExpected{{ + VolumeID: "v1", + Slots: []authority.ExpectedSlot{{ReplicaID: "r1", ServerID: "node-a"}}, + }}}, + }) + if err != nil { + t.Fatal(err) + } + h.Start() + defer closeTestMaster(t, h) + if err := h.obs.IngestHeartbeat(authority.HeartbeatMessage{ + ServerID: "node-a", SentAt: time.Now().UTC(), Reachable: true, Eligible: true, + Slots: []authority.HeartbeatSlot{{VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101", Reachable: true, ReadyForPrimary: true, Eligible: true}}, + }); err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + if line, ok := h.Publisher().VolumeAuthorityLine("v1"); ok && line.Assigned { + if b, have := h.obs.LastBuild(); have { + for _, v := range b.Snapshot.Volumes { + if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == line.Epoch { + return + } + } + } + } + time.Sleep(20 * time.Millisecond) + } + line, ok := h.Publisher().VolumeAuthorityLine("v1") + b, _ := h.obs.LastBuild() + t.Fatalf("published line %+v (%v), but the last build's volumes are %+v", line, ok, b.Snapshot.Volumes) +} From 1cb5e0e124fbcef3a3c6df84d691f1ec941983c7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:36:48 -0800 Subject: [PATCH 3/7] master: the line-wake test orders its builds so only the hook can wake the last The test now drains the initial build and the grace's rebuild before the one heartbeat, whose single wake is consumed by the build showing v1 supported; the controller binds after it, and with no heartbeat, expiry or GC tick left, the build carrying the line can only come from the hook. Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/line_change_wake_test.go | 64 +++++++++++++------ 1 file changed, 44 insertions(+), 20 deletions(-) diff --git a/seaweed-block/core/host/master/line_change_wake_test.go b/seaweed-block/core/host/master/line_change_wake_test.go index 5929ddadfb..6f07a6bb50 100644 --- a/seaweed-block/core/host/master/line_change_wake_test.go +++ b/seaweed-block/core/host/master/line_change_wake_test.go @@ -9,10 +9,16 @@ import ( ) // A published line wakes the observation build, through the master's -// wiring of the publisher's line-change hook: a volume reported once (no -// heartbeat follows) is bound by the controller, and the next build carries -// that line. Timestamp-only heartbeats wake nothing, so without the wiring -// the build would keep the unbound basis until some unrelated change. +// wiring of the publisher's line-change hook. The order is made +// deterministic so no other wake can stand in for the hook: +// - the master starts with nothing ingested; its initial build runs, and +// the 1 ms pending grace's deadline is consumed (its rebuild runs too); +// - after the builds drain, one heartbeat is ingested: its single wake is +// consumed by one build whose snapshot already holds it (the snapshot is +// taken after the wake is received), showing v1 supported and unbound; +// - the controller binds v1 after that build. No heartbeat follows, no +// expiry is due (a one-hour window), and there is no GC tick: a later +// build carrying the line can only come from the hook. func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("the lifecycle stores need directory fsync") @@ -21,8 +27,7 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", - // No expiry and no GC wake within the test. - Freshness: authority.FreshnessConfig{FreshnessWindow: time.Hour}, + Freshness: authority.FreshnessConfig{FreshnessWindow: time.Hour, PendingGrace: time.Millisecond}, Topology: authority.AcceptedTopology{Volumes: []authority.VolumeExpected{{ VolumeID: "v1", Slots: []authority.ExpectedSlot{{ReplicaID: "r1", ServerID: "node-a"}}, @@ -33,26 +38,45 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { } h.Start() defer closeTestMaster(t, h) + waitBuild := func(what string, ok func(authority.BuildResult) bool) authority.BuildResult { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + if b, have := h.obs.LastBuild(); have && ok(b) { + return b + } + time.Sleep(10 * time.Millisecond) + } + b, _ := h.obs.LastBuild() + t.Fatalf("%s: last build %+v", what, b.Snapshot.Volumes) + return authority.BuildResult{} + } + waitBuild("the initial build", func(authority.BuildResult) bool { return true }) + time.Sleep(300 * time.Millisecond) // the grace's deadline fires and its rebuild drains if err := h.obs.IngestHeartbeat(authority.HeartbeatMessage{ ServerID: "node-a", SentAt: time.Now().UTC(), Reachable: true, Eligible: true, Slots: []authority.HeartbeatSlot{{VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101", Reachable: true, ReadyForPrimary: true, Eligible: true}}, }); err != nil { t.Fatal(err) } - deadline := time.Now().Add(5 * time.Second) - for time.Now().Before(deadline) { - if line, ok := h.Publisher().VolumeAuthorityLine("v1"); ok && line.Assigned { - if b, have := h.obs.LastBuild(); have { - for _, v := range b.Snapshot.Volumes { - if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == line.Epoch { - return - } - } + waitBuild("the heartbeat's build (v1 supported)", func(b authority.BuildResult) bool { + for _, v := range b.Snapshot.Volumes { + if v.VolumeID == "v1" { + return true } } - time.Sleep(20 * time.Millisecond) - } - line, ok := h.Publisher().VolumeAuthorityLine("v1") - b, _ := h.obs.LastBuild() - t.Fatalf("published line %+v (%v), but the last build's volumes are %+v", line, ok, b.Snapshot.Volumes) + return false + }) + waitBuild("the build after the controller's publication", func(b authority.BuildResult) bool { + line, ok := h.Publisher().VolumeAuthorityLine("v1") + if !ok || !line.Assigned { + return false + } + for _, v := range b.Snapshot.Volumes { + if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == line.Epoch { + return true + } + } + return false + }) } From 2caed63f04d05b3b20927e0c19858e5d5ec01bea Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:41:47 -0800 Subject: [PATCH 4/7] master: the line-wake test waits on a settled observation host, not a sleep ObservationHost.BuildsForTest reports the builds completed and whether a wake is buffered or a build is running. The test settles the host before the heartbeat, requires the heartbeat's build to be a new one, settles again after the controller's publication, and then requires the line in a build after that point (or in the settled last build, which can only have come after the publication). Co-Authored-By: Claude Opus 5.5 --- .../core/authority/observation_host.go | 21 ++++++- .../core/host/master/line_change_wake_test.go | 61 +++++++++++++++---- 2 files changed, 68 insertions(+), 14 deletions(-) diff --git a/seaweed-block/core/authority/observation_host.go b/seaweed-block/core/authority/observation_host.go index 3dbbc81085..301a271be4 100644 --- a/seaweed-block/core/authority/observation_host.go +++ b/seaweed-block/core/authority/observation_host.go @@ -3,6 +3,7 @@ package authority import ( "context" "sync" + "sync/atomic" "time" ) @@ -57,8 +58,12 @@ type ObservationHost struct { sink ControllerSink reader AuthorityBasisReader - mu sync.Mutex - lastBuild *BuildResult + mu sync.Mutex + lastBuild *BuildResult + // builds counts completed rebuilds and building is set while one runs + // (BuildsForTest). + builds atomic.Uint64 + building atomic.Bool sinkErrors []error wake chan struct{} @@ -118,6 +123,13 @@ func NewObservationHost(cfg ObservationHostConfig) *ObservationHost { return h } +// BuildsForTest reports the rebuilds completed and whether the host is +// settled (no wake buffered, no rebuild running), so a test can order a +// change after every earlier build. Production code MUST NOT call this. +func (h *ObservationHost) BuildsForTest() (builds uint64, settled bool) { + return h.builds.Load(), len(h.wake) == 0 && !h.building.Load() +} + // Wake asks for a rebuild: a change a build reads that no heartbeat // carries (a published authority line, a topology change). Non-blocking; // wakes coalesce. @@ -281,6 +293,11 @@ func (h *ObservationHost) run(ctx context.Context) { // AND no report entries is a genuine no-op (e.g. start-up // before any ingest) and is skipped. func (h *ObservationHost) rebuildOnce() { + h.building.Store(true) + defer func() { + h.builds.Add(1) + h.building.Store(false) + }() snap := h.store.Snapshot() result := BuildSnapshot(snap, h.topology, h.reader) diff --git a/seaweed-block/core/host/master/line_change_wake_test.go b/seaweed-block/core/host/master/line_change_wake_test.go index 6f07a6bb50..347f75b417 100644 --- a/seaweed-block/core/host/master/line_change_wake_test.go +++ b/seaweed-block/core/host/master/line_change_wake_test.go @@ -38,28 +38,47 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { } h.Start() defer closeTestMaster(t, h) - waitBuild := func(what string, ok func(authority.BuildResult) bool) authority.BuildResult { + // settle waits until no wake is buffered and no rebuild runs, twice in a + // row with the same count (a deadline timer could fire in between), and + // returns the count. + settle := func(what string) uint64 { t.Helper() deadline := time.Now().Add(5 * time.Second) for time.Now().Before(deadline) { - if b, have := h.obs.LastBuild(); have && ok(b) { - return b + n1, ok1 := h.obs.BuildsForTest() + time.Sleep(50 * time.Millisecond) + n2, ok2 := h.obs.BuildsForTest() + if ok1 && ok2 && n1 == n2 && n1 > 0 { + return n2 + } + } + t.Fatalf("%s: the observation host did not settle", what) + return 0 + } + waitAfter := func(what string, after uint64, ok func(authority.BuildResult) bool) uint64 { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + n, _ := h.obs.BuildsForTest() + if b, have := h.obs.LastBuild(); have && n > after && ok(b) { + return n } time.Sleep(10 * time.Millisecond) } b, _ := h.obs.LastBuild() - t.Fatalf("%s: last build %+v", what, b.Snapshot.Volumes) - return authority.BuildResult{} + t.Fatalf("%s: no build after #%d satisfied it; last build %+v", what, after, b.Snapshot.Volumes) + return 0 } - waitBuild("the initial build", func(authority.BuildResult) bool { return true }) - time.Sleep(300 * time.Millisecond) // the grace's deadline fires and its rebuild drains + // The initial build and the 1 ms grace's rebuild, drained. + before := settle("startup") if err := h.obs.IngestHeartbeat(authority.HeartbeatMessage{ ServerID: "node-a", SentAt: time.Now().UTC(), Reachable: true, Eligible: true, Slots: []authority.HeartbeatSlot{{VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101", Reachable: true, ReadyForPrimary: true, Eligible: true}}, }); err != nil { t.Fatal(err) } - waitBuild("the heartbeat's build (v1 supported)", func(b authority.BuildResult) bool { + // The heartbeat's build: a new build, v1 supported. + waitAfter("the heartbeat's build", before, func(b authority.BuildResult) bool { for _, v := range b.Snapshot.Volumes { if v.VolumeID == "v1" { return true @@ -67,11 +86,29 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { } return false }) - waitBuild("the build after the controller's publication", func(b authority.BuildResult) bool { - line, ok := h.Publisher().VolumeAuthorityLine("v1") - if !ok || !line.Assigned { - return false + // The controller binds v1; its publication is the only wake left. + for wait := time.Now().Add(5 * time.Second); ; time.Sleep(10 * time.Millisecond) { + if line, ok := h.Publisher().VolumeAuthorityLine("v1"); ok && line.Assigned { + break } + if time.Now().After(wait) { + t.Fatal("the controller did not bind v1") + } + } + line, _ := h.Publisher().VolumeAuthorityLine("v1") + // Settled again: any build the heartbeat's wake caused has run. If the + // last build already carries the line, it came after the publication, + // so from the hook (the heartbeat's single wake was consumed by a build + // that saw no line); otherwise a later build must bring it. + settled := settle("after the publication") + if b, have := h.obs.LastBuild(); have { + for _, v := range b.Snapshot.Volumes { + if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == line.Epoch { + return + } + } + } + waitAfter("the build after the publication", settled, func(b authority.BuildResult) bool { for _, v := range b.Snapshot.Volumes { if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == line.Epoch { return true From db7f6530a3c43322e8451ef8d84218d68e6da960 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:48:58 -0800 Subject: [PATCH 5/7] authority: a counter handshake orders the master's line-wake test The observation host counts the rebuilds it takes (in the step that takes the wake) and the rebuilds it finishes, and records when its armed deadline timer fires, all under its lock; BuildsForTest returns them with whether a wake is buffered. The master test settles on started == done with no buffered wake and no timer due, records N, ingests one heartbeat (build N+1, v1 supported and unbound), and after the controller's publication requires build N+2 to carry the line: only the hook can take it. Co-Authored-By: Claude Opus 5.5 --- .../core/authority/observation_host.go | 49 +++++++++---- .../core/host/master/line_change_wake_test.go | 70 ++++++++----------- 2 files changed, 66 insertions(+), 53 deletions(-) diff --git a/seaweed-block/core/authority/observation_host.go b/seaweed-block/core/authority/observation_host.go index 301a271be4..d1d851bbe7 100644 --- a/seaweed-block/core/authority/observation_host.go +++ b/seaweed-block/core/authority/observation_host.go @@ -3,7 +3,6 @@ package authority import ( "context" "sync" - "sync/atomic" "time" ) @@ -60,11 +59,12 @@ type ObservationHost struct { mu sync.Mutex lastBuild *BuildResult - // builds counts completed rebuilds and building is set while one runs - // (BuildsForTest). - builds atomic.Uint64 - building atomic.Bool - sinkErrors []error + // buildsStarted counts rebuilds the loop took (in the step that takes + // their wake), buildsDone the rebuilds finished, timerAt when the armed deadline + // timer fires (zero: none); all under mu (BuildsForTest). + buildsStarted, buildsDone uint64 + timerAt time.Time + sinkErrors []error wake chan struct{} stop chan struct{} @@ -123,11 +123,22 @@ func NewObservationHost(cfg ObservationHostConfig) *ObservationHost { return h } -// BuildsForTest reports the rebuilds completed and whether the host is -// settled (no wake buffered, no rebuild running), so a test can order a -// change after every earlier build. Production code MUST NOT call this. -func (h *ObservationHost) BuildsForTest() (builds uint64, settled bool) { - return h.builds.Load(), len(h.wake) == 0 && !h.building.Load() +// BuildsForTest reports, under one lock, the rebuilds the loop took and +// finished, whether a wake is buffered, and when the armed deadline timer +// fires (zero: none), so a test can order a change after every earlier +// build. Production code MUST NOT call this. +func (h *ObservationHost) BuildsForTest() (started, done uint64, wakeBuffered bool, timerAt time.Time) { + h.mu.Lock() + defer h.mu.Unlock() + return h.buildsStarted, h.buildsDone, len(h.wake) > 0, h.timerAt +} + +// takeBuild counts a rebuild the loop takes, in the step that takes it. +func (h *ObservationHost) takeBuild() { + h.mu.Lock() + h.buildsStarted++ + h.timerAt = time.Time{} + h.mu.Unlock() } // Wake asks for a rebuild: a change a build reads that no heartbeat @@ -237,6 +248,7 @@ func (h *ObservationHost) run(ctx context.Context) { // First build on start — so consumers see an initial empty // snapshot rather than waiting for the first ingest. + h.takeBuild() h.rebuildOnce() for { @@ -252,6 +264,9 @@ func (h *ObservationHost) run(ctx context.Context) { } timer = time.NewTimer(d) deadlineC = timer.C + h.mu.Lock() + h.timerAt = time.Now().Add(d) + h.mu.Unlock() } stopTimer := func() { if timer != nil { @@ -267,10 +282,16 @@ func (h *ObservationHost) run(ctx context.Context) { return case <-h.wake: stopTimer() + h.takeBuild() h.rebuildOnce() case <-deadlineC: if h.store.ExpireDue() { + h.takeBuild() h.rebuildOnce() + } else { + h.mu.Lock() + h.timerAt = time.Time{} + h.mu.Unlock() } case <-gcC: stopTimer() @@ -293,10 +314,10 @@ func (h *ObservationHost) run(ctx context.Context) { // AND no report entries is a genuine no-op (e.g. start-up // before any ingest) and is skipped. func (h *ObservationHost) rebuildOnce() { - h.building.Store(true) defer func() { - h.builds.Add(1) - h.building.Store(false) + h.mu.Lock() + h.buildsDone++ + h.mu.Unlock() }() snap := h.store.Snapshot() result := BuildSnapshot(snap, h.topology, h.reader) diff --git a/seaweed-block/core/host/master/line_change_wake_test.go b/seaweed-block/core/host/master/line_change_wake_test.go index 347f75b417..3e9d47fef5 100644 --- a/seaweed-block/core/host/master/line_change_wake_test.go +++ b/seaweed-block/core/host/master/line_change_wake_test.go @@ -38,47 +38,57 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { } h.Start() defer closeTestMaster(t, h) - // settle waits until no wake is buffered and no rebuild runs, twice in a - // row with the same count (a deadline timer could fire in between), and - // returns the count. + // settle waits until every build the loop took has finished, no wake is + // buffered and no deadline timer fires within the test (the one-hour + // expiry timer stays armed), all read under the host's lock; it returns + // the builds done. settle := func(what string) uint64 { t.Helper() deadline := time.Now().Add(5 * time.Second) for time.Now().Before(deadline) { - n1, ok1 := h.obs.BuildsForTest() - time.Sleep(50 * time.Millisecond) - n2, ok2 := h.obs.BuildsForTest() - if ok1 && ok2 && n1 == n2 && n1 > 0 { - return n2 + started, done, buffered, timerAt := h.obs.BuildsForTest() + if started == done && done > 0 && !buffered && (timerAt.IsZero() || timerAt.After(time.Now().Add(time.Minute))) { + return done } + time.Sleep(10 * time.Millisecond) } t.Fatalf("%s: the observation host did not settle", what) return 0 } - waitAfter := func(what string, after uint64, ok func(authority.BuildResult) bool) uint64 { + waitDone := func(what string, n uint64, ok func(authority.BuildResult) bool) { t.Helper() deadline := time.Now().Add(5 * time.Second) for time.Now().Before(deadline) { - n, _ := h.obs.BuildsForTest() - if b, have := h.obs.LastBuild(); have && n > after && ok(b) { - return n + _, done, _, _ := h.obs.BuildsForTest() + if b, have := h.obs.LastBuild(); have && done >= n && ok(b) { + return } time.Sleep(10 * time.Millisecond) } b, _ := h.obs.LastBuild() - t.Fatalf("%s: no build after #%d satisfied it; last build %+v", what, after, b.Snapshot.Volumes) - return 0 + t.Fatalf("%s: no build #%d satisfied it; last build %+v", what, n, b.Snapshot.Volumes) } - // The initial build and the 1 ms grace's rebuild, drained. - before := settle("startup") + carriesLine := func(epoch uint64) func(authority.BuildResult) bool { + return func(b authority.BuildResult) bool { + for _, v := range b.Snapshot.Volumes { + if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == epoch { + return true + } + } + return false + } + } + // The initial build and the 1 ms grace's rebuild, finished. + n := settle("startup") if err := h.obs.IngestHeartbeat(authority.HeartbeatMessage{ ServerID: "node-a", SentAt: time.Now().UTC(), Reachable: true, Eligible: true, Slots: []authority.HeartbeatSlot{{VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101", Reachable: true, ReadyForPrimary: true, Eligible: true}}, }); err != nil { t.Fatal(err) } - // The heartbeat's build: a new build, v1 supported. - waitAfter("the heartbeat's build", before, func(b authority.BuildResult) bool { + // The heartbeat's one build (#n+1) shows v1 supported and unbound: the + // controller binds only after it. + waitDone("the heartbeat's build", n+1, func(b authority.BuildResult) bool { for _, v := range b.Snapshot.Volumes { if v.VolumeID == "v1" { return true @@ -86,7 +96,6 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { } return false }) - // The controller binds v1; its publication is the only wake left. for wait := time.Now().Add(5 * time.Second); ; time.Sleep(10 * time.Millisecond) { if line, ok := h.Publisher().VolumeAuthorityLine("v1"); ok && line.Assigned { break @@ -96,24 +105,7 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { } } line, _ := h.Publisher().VolumeAuthorityLine("v1") - // Settled again: any build the heartbeat's wake caused has run. If the - // last build already carries the line, it came after the publication, - // so from the hook (the heartbeat's single wake was consumed by a build - // that saw no line); otherwise a later build must bring it. - settled := settle("after the publication") - if b, have := h.obs.LastBuild(); have { - for _, v := range b.Snapshot.Volumes { - if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == line.Epoch { - return - } - } - } - waitAfter("the build after the publication", settled, func(b authority.BuildResult) bool { - for _, v := range b.Snapshot.Volumes { - if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == line.Epoch { - return true - } - } - return false - }) + // Every build after the heartbeat's was taken after the publication (no + // other wake was left): the hook's. One must come and carry the line. + waitDone("the hook's build", n+2, carriesLine(line.Epoch)) } From d17696d1ea4e45604a35d892ebb6e8a31b76a088 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:52:35 -0800 Subject: [PATCH 6/7] master: the line-wake test waits for the grace's rebuild (build 2) before the heartbeat Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/line_change_wake_test.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/host/master/line_change_wake_test.go b/seaweed-block/core/host/master/line_change_wake_test.go index 3e9d47fef5..44fbc9c9f4 100644 --- a/seaweed-block/core/host/master/line_change_wake_test.go +++ b/seaweed-block/core/host/master/line_change_wake_test.go @@ -42,12 +42,12 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { // buffered and no deadline timer fires within the test (the one-hour // expiry timer stays armed), all read under the host's lock; it returns // the builds done. - settle := func(what string) uint64 { + settle := func(what string, atLeast uint64) uint64 { t.Helper() deadline := time.Now().Add(5 * time.Second) for time.Now().Before(deadline) { started, done, buffered, timerAt := h.obs.BuildsForTest() - if started == done && done > 0 && !buffered && (timerAt.IsZero() || timerAt.After(time.Now().Add(time.Minute))) { + if started == done && done >= atLeast && !buffered && (timerAt.IsZero() || timerAt.After(time.Now().Add(time.Minute))) { return done } time.Sleep(10 * time.Millisecond) @@ -78,8 +78,10 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { return false } } - // The initial build and the 1 ms grace's rebuild, finished. - n := settle("startup") + // The initial build (#1) and the 1 ms grace's rebuild (#2, with nothing + // ingested yet) both finished: the grace's deadline is consumed, so no + // timer can arm after this point and see the heartbeat. + n := settle("startup", 2) if err := h.obs.IngestHeartbeat(authority.HeartbeatMessage{ ServerID: "node-a", SentAt: time.Now().UTC(), Reachable: true, Eligible: true, Slots: []authority.HeartbeatSlot{{VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101", Reachable: true, ReadyForPrimary: true, Eligible: true}}, From 9f823870477a73a2809069392ad659f29e975436 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 14:23:58 -0800 Subject: [PATCH 7/7] master: the line-wake test publishes by the product tick it runs itself The controller never bound a once-reported static volume on Linux, so the test now creates and places a volume through the lifecycle, ingests its holder's heartbeat, settles the observation host (started == done, no buffered wake, no timer due), runs the product tick (the master runs none by itself), which binds the volume, and requires a build after that point: only the line-change hook can take it. Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/line_change_wake_test.go | 133 ++++++++---------- 1 file changed, 58 insertions(+), 75 deletions(-) diff --git a/seaweed-block/core/host/master/line_change_wake_test.go b/seaweed-block/core/host/master/line_change_wake_test.go index 44fbc9c9f4..fb79d0c2b1 100644 --- a/seaweed-block/core/host/master/line_change_wake_test.go +++ b/seaweed-block/core/host/master/line_change_wake_test.go @@ -1,47 +1,61 @@ package master import ( + "context" "runtime" "testing" "time" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/lifecycle" ) // A published line wakes the observation build, through the master's -// wiring of the publisher's line-change hook. The order is made -// deterministic so no other wake can stand in for the hook: -// - the master starts with nothing ingested; its initial build runs, and -// the 1 ms pending grace's deadline is consumed (its rebuild runs too); -// - after the builds drain, one heartbeat is ingested: its single wake is -// consumed by one build whose snapshot already holds it (the snapshot is -// taken after the wake is received), showing v1 supported and unbound; -// - the controller binds v1 after that build. No heartbeat follows, no -// expiry is due (a one-hour window), and there is no GC tick: a later -// build carrying the line can only come from the hook. +// wiring of the publisher's line-change hook. The publication is the +// product tick's bind of a created and placed volume, run by the test (the +// master runs no tick by itself), and the order leaves nothing else to wake +// the build: +// - the master starts; its initial build (#1) and the 1 ms grace's +// rebuild (#2) finish; the volume is created and placed and its holder's +// heartbeat ingested; the observation host settles (every build taken +// has finished, no wake is buffered, no deadline is due within the test: +// a one-hour freshness window, no GC tick), all read under its lock: N +// builds done; +// - the test runs the product tick, which binds the volume; +// - a build N+1 must follow: nothing but the hook can take it. func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("the lifecycle stores need directory fsync") } h, err := New(Config{ - AuthorityStoreDir: t.TempDir(), - LifecycleStoreDir: t.TempDir(), - Listen: "127.0.0.1:0", - Freshness: authority.FreshnessConfig{FreshnessWindow: time.Hour, PendingGrace: time.Millisecond}, - Topology: authority.AcceptedTopology{Volumes: []authority.VolumeExpected{{ - VolumeID: "v1", - Slots: []authority.ExpectedSlot{{ReplicaID: "r1", ServerID: "node-a"}}, - }}}, + Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), + WorkspaceRPC: true, LifecycleProductLoop: true, LayoutCreateVolume: testLayoutCreateVolume, + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { + return authority.WorkspaceHead{}, nil + }, + Freshness: authority.FreshnessConfig{FreshnessWindow: time.Hour, PendingGrace: time.Millisecond}, }) if err != nil { t.Fatal(err) } h.Start() - defer closeTestMaster(t, h) - // settle waits until every build the loop took has finished, no wake is - // buffered and no deadline timer fires within the test (the one-hour - // expiry timer stays armed), all read under the host's lock; it returns - // the builds done. + t.Cleanup(func() { closeTestMaster(t, h) }) + c, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { c.Close() }) + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + t.Cleanup(cancel) + if _, err := h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-a", DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); err != nil { + t.Fatal(err) + } + // settle waits, under the host's lock, until every build taken has + // finished, no wake is buffered and no deadline timer fires within a + // minute, with at least atLeast builds done; it returns the builds done. settle := func(what string, atLeast uint64) uint64 { t.Helper() deadline := time.Now().Add(5 * time.Second) @@ -55,59 +69,28 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { t.Fatalf("%s: the observation host did not settle", what) return 0 } - waitDone := func(what string, n uint64, ok func(authority.BuildResult) bool) { - t.Helper() - deadline := time.Now().Add(5 * time.Second) - for time.Now().Before(deadline) { - _, done, _, _ := h.obs.BuildsForTest() - if b, have := h.obs.LastBuild(); have && done >= n && ok(b) { - return - } - time.Sleep(10 * time.Millisecond) - } - b, _ := h.obs.LastBuild() - t.Fatalf("%s: no build #%d satisfied it; last build %+v", what, n, b.Snapshot.Volumes) - } - carriesLine := func(epoch uint64) func(authority.BuildResult) bool { - return func(b authority.BuildResult) bool { - for _, v := range b.Snapshot.Volumes { - if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == epoch { - return true - } - } - return false - } - } - // The initial build (#1) and the 1 ms grace's rebuild (#2, with nothing - // ingested yet) both finished: the grace's deadline is consumed, so no - // timer can arm after this point and see the heartbeat. - n := settle("startup", 2) - if err := h.obs.IngestHeartbeat(authority.HeartbeatMessage{ - ServerID: "node-a", SentAt: time.Now().UTC(), Reachable: true, Eligible: true, - Slots: []authority.HeartbeatSlot{{VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101", Reachable: true, ReadyForPrimary: true, Eligible: true}}, - }); err != nil { + settle("startup", 2) + reviewCreate(t, c, ctx, "v1") + if _, err := h.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "v1", DesiredRF: 1, Candidates: []lifecycle.PlacementCandidate{{VolumeID: "v1", ServerID: "node-a", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil { t.Fatal(err) } - // The heartbeat's one build (#n+1) shows v1 supported and unbound: the - // controller binds only after it. - waitDone("the heartbeat's build", n+1, func(b authority.BuildResult) bool { - for _, v := range b.Snapshot.Volumes { - if v.VolumeID == "v1" { - return true - } - } - return false - }) - for wait := time.Now().Add(5 * time.Second); ; time.Sleep(10 * time.Millisecond) { - if line, ok := h.Publisher().VolumeAuthorityLine("v1"); ok && line.Assigned { - break - } - if time.Now().After(wait) { - t.Fatal("the controller did not bind v1") - } + reviewHeartbeat(t, c, ctx, "v1", "node-a", "127.0.0.1:10000", "127.0.0.1:10001") + n := settle("after the heartbeat", 3) + if _, ok := h.Publisher().VolumeAuthorityLine("v1"); ok { + t.Fatal("v1 was bound before the product tick: the publication under test is not the test's") } - line, _ := h.Publisher().VolumeAuthorityLine("v1") - // Every build after the heartbeat's was taken after the publication (no - // other wake was left): the hook's. One must come and carry the line. - waitDone("the hook's build", n+2, carriesLine(line.Epoch)) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + if line := waitAuthorityLine(t, h.Publisher(), "v1"); line.Epoch != 1 { + t.Fatalf("the product tick bound %+v", line) + } + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + if _, done, _, _ := h.obs.BuildsForTest(); done > n { + return + } + time.Sleep(10 * time.Millisecond) + } + t.Fatalf("no observation build followed the publication (still %d builds): the line-change hook did not wake it", n) }