diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index 79056bafe3..375e22e527 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 @@ -479,6 +482,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) }) @@ -750,6 +761,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..94e6f1a901 --- /dev/null +++ b/seaweed-block/core/authority/observation_changes.go @@ -0,0 +1,177 @@ +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 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() + 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 + } + // 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 +} + +// 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..c48b97e55c --- /dev/null +++ b/seaweed-block/core/authority/observation_changes_test.go @@ -0,0 +1,294 @@ +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: // 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) + 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)))) + } + } + // 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) + 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) + } +} + +// 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 8748df39f0..d1d851bbe7 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 @@ -55,9 +57,14 @@ type ObservationHost struct { sink ControllerSink reader AuthorityBasisReader - mu sync.Mutex - lastBuild *BuildResult - sinkErrors []error + mu sync.Mutex + lastBuild *BuildResult + // 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{} @@ -116,6 +123,29 @@ func NewObservationHost(cfg ObservationHostConfig) *ObservationHost { return h } +// 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 +// 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. @@ -218,17 +248,53 @@ 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 { + // 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 + h.mu.Lock() + h.timerAt = time.Now().Add(d) + h.mu.Unlock() + } + stopTimer := func() { + if timer != nil { + timer.Stop() + } + } select { case <-ctx.Done(): + stopTimer() return case <-h.stop: + stopTimer() 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() h.store.GC(h.gcRetain) // GC may have set the mutation flag; that is OK — the // next iteration will pick up the wake. @@ -248,6 +314,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() { + defer func() { + 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/authority/observation_store.go b/seaweed-block/core/authority/observation_store.go index 4283ff4f82..0081267ef4 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 @@ -237,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. // @@ -377,9 +388,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 +585,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 a96e23ca2a..f97a6097da 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -309,6 +309,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. 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..fb79d0c2b1 --- /dev/null +++ b/seaweed-block/core/host/master/line_change_wake_test.go @@ -0,0 +1,96 @@ +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 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{ + 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() + 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) + for time.Now().Before(deadline) { + started, done, buffered, timerAt := h.obs.BuildsForTest() + if started == done && done >= atLeast && !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 + } + 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) + } + 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") + } + 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) +}