diff --git a/seaweed-block/core/authority/observation_host.go b/seaweed-block/core/authority/observation_host.go index c65e63a4b5..8748df39f0 100644 --- a/seaweed-block/core/authority/observation_host.go +++ b/seaweed-block/core/authority/observation_host.go @@ -153,6 +153,17 @@ func (h *ObservationHost) IngestHeartbeat(msg HeartbeatMessage) error { return h.Ingest(obs) } +// IngestHeartbeatWithHealthTransitions is IngestHeartbeat returning the +// accepted slot health transitions (ObservationStore +// .IngestWithHealthTransitions). +func (h *ObservationHost) IngestHeartbeatWithHealthTransitions(msg HeartbeatMessage) ([]SlotHealthTransition, error) { + obs, err := HeartbeatToObservation(msg) + if err != nil { + return nil, err + } + return h.store.IngestWithHealthTransitions(obs) +} + // LastBuild returns the most recent BuildResult produced by the // rebuild loop, if any. Safe for concurrent readers; returns a // value copy. diff --git a/seaweed-block/core/authority/observation_store.go b/seaweed-block/core/authority/observation_store.go index 67d995246d..96fb5320f4 100644 --- a/seaweed-block/core/authority/observation_store.go +++ b/seaweed-block/core/authority/observation_store.go @@ -220,11 +220,35 @@ var ErrInvalidObservation = errors.New("observation_store: invalid observation") // stale ingest). No error is returned for that case; it's a // routine ordering event, not a bug. func (s *ObservationStore) Ingest(obs Observation) error { + _, err := s.ingest(obs) + return err +} + +// SlotHealthTransition is a slot whose explicit unhealthy reason changed +// with an accepted observation: Old is the reason in the same server's +// previously stored fact for that slot (whether or not it had expired; +// "" when there was none), New the reason just stored. +type SlotHealthTransition struct { + VolumeID string + ReplicaID string + Old string + New string +} + +// IngestWithHealthTransitions ingests like Ingest and returns, derived +// from the accepted mutation itself under the store lock, every slot +// whose unhealthy reason changed. A refused (older) observation returns +// none, and expiry never produces one: only an accepted report does. +func (s *ObservationStore) IngestWithHealthTransitions(obs Observation) ([]SlotHealthTransition, error) { + return s.ingest(obs) +} + +func (s *ObservationStore) ingest(obs Observation) ([]SlotHealthTransition, error) { if obs.ServerID == "" { - return ErrInvalidObservation + return nil, ErrInvalidObservation } if obs.ObservedAt.IsZero() { - return ErrInvalidObservation + return nil, ErrInvalidObservation } // Always compute ExpiresAt from store config — do not trust @@ -237,8 +261,10 @@ func (s *ObservationStore) Ingest(obs Observation) error { } var fn func() + var transitions []SlotHealthTransition s.mu.Lock() - if prev, ok := s.observations[obs.ServerID]; ok { + prev, hadPrev := s.observations[obs.ServerID] + if hadPrev { if prev.ObservedAt.After(obs.ObservedAt) { // Out-of-order ingest: keep the newer one already // stored. No mutation fired. @@ -251,8 +277,28 @@ func (s *ObservationStore) Ingest(obs Observation) error { // distinct from "silently dropped". s.supersededCount++ s.mu.Unlock() - return nil + return nil, nil } + } + // Health transitions, from this accepted report against the same + // server's previously stored fact for each slot it carries. + for _, slot := range obs.Slots { + old := "" + if hadPrev { + for _, p := range prev.Slots { + if slotKey(p) == slotKey(slot) { + old = p.UnhealthyReason + break + } + } + } + if old != slot.UnhealthyReason { + transitions = append(transitions, SlotHealthTransition{ + VolumeID: slot.VolumeID, ReplicaID: slot.ReplicaID, Old: old, New: slot.UnhealthyReason, + }) + } + } + if hadPrev { obs.Slots = mergeServerSlots(prev.Slots, obs.Slots) } s.observations[obs.ServerID] = obs @@ -263,7 +309,7 @@ func (s *ObservationStore) Ingest(obs Observation) error { if fn != nil { fn() } - return nil + return transitions, nil } func mergeServerSlots(prev []SlotFact, next []SlotFact) []SlotFact { diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index 06a2cc816d..47e670b187 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -94,6 +94,7 @@ type LifecycleStores struct { // is: New -> Start -> (serve requests) -> Close. type Host struct { cfg Config + healthMu sync.Mutex // orders replica health events with their accepted heartbeats (#128 rule 6) log *log.Logger boot *bootstrap.DurableAuthorityBootstrap ctrl *authority.TopologyController diff --git a/seaweed-block/core/host/master/recovery_watchdog_master_test.go b/seaweed-block/core/host/master/recovery_watchdog_master_test.go index da6b623b28..f22265d797 100644 --- a/seaweed-block/core/host/master/recovery_watchdog_master_test.go +++ b/seaweed-block/core/host/master/recovery_watchdog_master_test.go @@ -2,6 +2,8 @@ package master import ( "context" + "sync" + "sync/atomic" "testing" "time" @@ -163,3 +165,94 @@ func TestRecoveryWatchdog_MasterLaterDegradationFollowsNormalRules(t *testing.T) t.Fatalf("unhealthy replicas=%v; want none (no explicit unhealthy fact)", got) } } + +func reportR1(t *testing.T, svc *services, slot wireSlot, sentAt time.Time) { + t.Helper() + _, err := svc.ReportHeartbeat(context.Background(), &control.HeartbeatReport{ + ServerId: "node-a", SentAt: timestamppb.New(sentAt), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{ + VolumeId: "vol-rf3", ReplicaId: "r1", DataAddr: "127.0.0.1:19101", CtrlAddr: "127.0.0.1:19102", + Reachable: true, ReadyForPrimary: slot.ready, Eligible: slot.unhealthy == "", + EvidenceScore: 30, Incarnation: slot.incarnation, UnhealthyReason: slot.unhealthy, + }}, + }) + if err != nil { + t.Errorf("ReportHeartbeat r1: %v", err) + } +} + +func r1HealthEvents(t *testing.T, svc *services) []string { + t.Helper() + var out []string + for _, e := range timelineEvents(t, svc) { + if e.GetReplicaId() == "r1" && (e.GetEventType() == "replica_unhealthy" || e.GetEventType() == "replica_unhealthy_cleared") { + out = append(out, e.GetEventType()) + } + } + return out +} + +// onFirstMutation runs fn once, right after the next accepted store +// mutation (inside that ingest, after the store lock is released). +func onFirstMutation(h *Host, fn func()) { + var once sync.Once + h.ObservationHost().Store().SetOnMutation(func() { once.Do(fn) }) +} + +// Review of #134 (P2 3): a second heartbeat lands between the first +// one's ingest and its event bookkeeping. Both transitions must be +// recorded, in accepted order: unhealthy, then cleared. +func TestRecoveryWatchdog_MasterConcurrentHeartbeatsKeepBothTransitions(t *testing.T) { + h, svc := watchdogMaster(t) + defer closeTestMaster(t, h) + + t0 := time.Now() + done := make(chan struct{}) + onFirstMutation(h, func() { + go func() { + reportR1(t, svc, wireSlot{"r1-b", true, ""}, t0.Add(time.Millisecond)) // healthy, newer + close(done) + }() + select { // let it run now if nothing blocks it + case <-done: + case <-time.After(300 * time.Millisecond): + } + }) + reportR1(t, svc, wireSlot{"r1-b", false, "recovery_timeout"}, t0) // unhealthy + <-done + got := r1HealthEvents(t, svc) + if len(got) != 2 || got[0] != "replica_unhealthy" || got[1] != "replica_unhealthy_cleared" { + t.Fatalf("r1 health events=%v; want [replica_unhealthy replica_unhealthy_cleared]", got) + } +} + +// Review of #134 (P2 3): the stored unhealthy fact expires during an +// ingest that reports unhealthy again. No clear may be fabricated. +func TestRecoveryWatchdog_MasterExpiryFabricatesNoClear(t *testing.T) { + h, svc := watchdogMaster(t) + defer closeTestMaster(t, h) + var offset atomic.Int64 + h.ObservationHost().SetNowForTest(func() time.Time { return time.Now().Add(time.Duration(offset.Load())) }) + + t0 := time.Now() + reportR1(t, svc, wireSlot{"r1-b", false, "recovery_timeout"}, t0) + onFirstMutation(h, func() { offset.Store(int64(time.Hour)) }) // everything expires mid-ingest + reportR1(t, svc, wireSlot{"r1-b", false, "recovery_timeout"}, t0.Add(time.Millisecond)) + for _, ev := range r1HealthEvents(t, svc) { + if ev == "replica_unhealthy_cleared" { + t.Fatalf("r1 health events=%v: a clear was fabricated by expiry", r1HealthEvents(t, svc)) + } + } +} + +// Control: an older heartbeat the store refuses records nothing. +func TestRecoveryWatchdog_MasterRejectedHeartbeatRecordsNothing(t *testing.T) { + h, svc := watchdogMaster(t) + defer closeTestMaster(t, h) + t0 := time.Now() + reportR1(t, svc, wireSlot{"r1-b", false, "recovery_timeout"}, t0) + reportR1(t, svc, wireSlot{"r1-b", true, ""}, t0.Add(-time.Second)) // older: refused + if got := r1HealthEvents(t, svc); len(got) != 1 || got[0] != "replica_unhealthy" { + t.Fatalf("r1 health events=%v; want only [replica_unhealthy]", got) + } +} diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 27bdaa3f13..b4fe87ade3 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -12,6 +12,7 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/engine" "github.com/seaweedfs/seaweed-block/core/replication" control "github.com/seaweedfs/seaweed-block/core/rpc/control" "google.golang.org/grpc" @@ -584,8 +585,8 @@ func (h *Host) runHeartbeat(ctx context.Context) { // buildReport collects local slot facts into a wire HeartbeatReport. // T0 single-volume-per-process simplicity: one replica slot. func (h *Host) buildReport() *control.HeartbeatReport { - ready := h.readyForPrimaryFact() - unhealthy := h.unhealthyReason(ready) + fact, ready := h.promotionReady() + unhealthy := h.unhealthyReason(fact, ready) return &control.HeartbeatReport{ ServerId: h.cfg.ServerID, SentAt: timestamppb.Now(), @@ -625,14 +626,21 @@ func newIncarnation() string { // a valid candidate fact even though it remains frontend-unhealthy until // authority moves. func (h *Host) readyForPrimaryFact() bool { + _, ready := h.promotionReady() + return ready +} + +// promotionReady returns the engine's promotion fact and whether it +// counts as ready (ready, and its line not superseded). +func (h *Host) promotionReady() (engine.PromotionReadyFact, bool) { if h == nil || h.view == nil { - return false + return engine.PromotionReadyFact{}, false } fact := h.view.PromotionReadyFact() if !fact.Ready { - return false + return fact, false } - return !h.view.isSupersededLine(fact.Epoch, fact.EndpointVersion) + return fact, !h.view.isSupersededLine(fact.Epoch, fact.EndpointVersion) } // runSubscribe maintains a SubscribeAssignments stream. Reconnects diff --git a/seaweed-block/core/host/volume/recovery_watchdog.go b/seaweed-block/core/host/volume/recovery_watchdog.go index 88118d2511..a19b7e2a80 100644 --- a/seaweed-block/core/host/volume/recovery_watchdog.go +++ b/seaweed-block/core/host/volume/recovery_watchdog.go @@ -3,6 +3,8 @@ package volume import ( "sync" "time" + + "github.com/seaweedfs/seaweed-block/core/engine" ) // Recovery watchdog (#128 rule 6). @@ -29,7 +31,11 @@ import ( // later degrades is not a boot-recovery stall: it goes through the // normal controller/gate failover. // - role_admission_failed reports the G1 role-admission latch of a -// primary-assigned replica, for as long as the latch holds. +// primary-assigned replica, for as long as the latch holds, whatever +// an older engine-ready fact says. +// - Only a ready fact for the watched primary epoch clears or disarms: +// an engine still ready at an older epoch (its new assignment not +// admitted) does not. // // wal_corrupt and io_error need typed failures out of the durable // recovery path; they are a tracked follow-up. @@ -104,9 +110,12 @@ func (w *recoveryWatchdog) supportingAdmitted(epoch uint64) { } // reason returns the slot's explicit unhealthy reason given whether it -// is promotion-ready now and whether the G1 latch holds. fired is true -// on the call that latched recovery_timeout. -func (w *recoveryWatchdog) reason(ready, roleAdmissionFailed bool) (reason string, fired bool) { +// is promotion-ready now, at which epoch that readiness is, and whether +// the G1 latch holds. Readiness counts only for the watched primary +// epoch, compared under the lock, so an assignment that advanced while +// the fact was read is not cleared by it. fired is true on the call that +// latched recovery_timeout. +func (w *recoveryWatchdog) reason(ready bool, readyEpoch uint64, roleAdmissionFailed bool) (reason string, fired bool) { if w == nil { return "", false } @@ -115,7 +124,7 @@ func (w *recoveryWatchdog) reason(ready, roleAdmissionFailed bool) (reason strin if w.primarySince.IsZero() { return "", false } - if ready { + if ready { // RED: old order, epoch ignored w.timedOut, w.readySeen = false, true return "", false } @@ -148,15 +157,18 @@ func (w *recoveryWatchdog) catchUpSince() time.Time { // UnhealthyReason is the slot's explicit unhealthy reason now (#128 // rule 6), the same value its heartbeat reports; empty when healthy. func (h *Host) UnhealthyReason() string { - return h.unhealthyReason(h.readyForPrimaryFact()) + fact, ready := h.promotionReady() + return h.unhealthyReason(fact, ready) } -func (h *Host) unhealthyReason(ready bool) string { +// unhealthyReason evaluates the watchdog with the promotion fact (its +// epoch binds readiness to the watched assignment) and the G1 latch. +func (h *Host) unhealthyReason(fact engine.PromotionReadyFact, ready bool) string { if h == nil || h.wd == nil { return "" } failed, _ := h.RoleAdmissionFailure() - reason, fired := h.wd.reason(ready, failed) + reason, fired := h.wd.reason(ready, fact.Epoch, failed) if fired { h.log.Printf("blockvolume: volume %s primary assignment epoch=%d not promotion-ready after %s: reporting unhealthy (%s)", h.cfg.VolumeID, h.wd.epoch(), h.wd.timeout, UnhealthyRecoveryTimeout) diff --git a/seaweed-block/core/host/volume/recovery_watchdog_test.go b/seaweed-block/core/host/volume/recovery_watchdog_test.go index a86f8ae553..02a580b2c8 100644 --- a/seaweed-block/core/host/volume/recovery_watchdog_test.go +++ b/seaweed-block/core/host/volume/recovery_watchdog_test.go @@ -1,9 +1,11 @@ package volume import ( + "errors" "testing" "time" + "github.com/seaweedfs/seaweed-block/core/engine" control "github.com/seaweedfs/seaweed-block/core/rpc/control" ) @@ -84,26 +86,26 @@ func TestRecoveryWatchdog_ReadyClearsAndDisarmsNewEpochRearms(t *testing.T) { w.primaryAssigned(1) clk.advance(11 * time.Second) - if r, fired := w.reason(false, false); r != UnhealthyRecoveryTimeout || !fired { + if r, fired := w.reason(false, 0, false); r != UnhealthyRecoveryTimeout || !fired { t.Fatalf("past timeout: %q fired=%t", r, fired) } - if r, fired := w.reason(false, false); r != UnhealthyRecoveryTimeout || fired { + if r, fired := w.reason(false, 0, false); r != UnhealthyRecoveryTimeout || fired { t.Fatalf("latched: %q fired=%t; want the reason, fired only once", r, fired) } - if r, _ := w.reason(true, false); r != "" { + if r, _ := w.reason(true, 1, false); r != "" { t.Fatalf("ready: %q; want cleared", r) } - if r, _ := w.reason(false, false); r != "" { + if r, _ := w.reason(false, 0, false); r != "" { t.Fatalf("unready again in the same assignment: %q; want disarmed", r) } w.primaryAssigned(2) // new primary epoch: fresh clock clk.advance(9 * time.Second) - if r, _ := w.reason(false, false); r != "" { + if r, _ := w.reason(false, 0, false); r != "" { t.Fatalf("new epoch inside timeout: %q", r) } clk.advance(2 * time.Second) - if r, _ := w.reason(false, false); r != UnhealthyRecoveryTimeout { + if r, _ := w.reason(false, 0, false); r != UnhealthyRecoveryTimeout { t.Fatalf("new epoch past timeout: %q", r) } } @@ -112,11 +114,11 @@ func TestRecoveryWatchdog_ReadyClearsAndDisarmsNewEpochRearms(t *testing.T) { // at once; it never applies to a replica without the primary assignment. func TestRecoveryWatchdog_RoleAdmissionFailure(t *testing.T) { w := newRecoveryWatchdog(time.Hour) - if r, _ := w.reason(false, true); r != "" { + if r, _ := w.reason(false, 0, true); r != "" { t.Fatalf("not primary-assigned: %q", r) } w.primaryAssigned(1) - if r, _ := w.reason(false, true); r != UnhealthyRoleAdmission { + if r, _ := w.reason(false, 0, true); r != UnhealthyRoleAdmission { t.Fatalf("primary-assigned with the G1 latch: %q; want %s", r, UnhealthyRoleAdmission) } } @@ -148,16 +150,16 @@ func TestRecoveryWatchdog_ReadyThenLaterNotReadyReportsNoTimeout(t *testing.T) { h, clk := watchdogHost(t, 10*time.Second) h.applyFact(selfPrimaryFact(1)) clk.advance(time.Second) - if r := h.unhealthyReason(true); r != "" { + if r := h.unhealthyReason(readyAt(1), true); r != "" { t.Fatalf("ready: %q", r) } clk.advance(time.Hour) - if r := h.unhealthyReason(false); r != "" { + if r := h.unhealthyReason(readyAt(1), false); r != "" { t.Fatalf("not ready an hour after being ready, same incarnation: %q; want no recovery_timeout", r) } h.applyFact(selfPrimaryFact(1)) // the same assignment replayed: still disarmed clk.advance(time.Hour) - if r := h.unhealthyReason(false); r != "" { + if r := h.unhealthyReason(readyAt(1), false); r != "" { t.Fatalf("same assignment replayed: %q; want still disarmed", r) } } @@ -168,7 +170,7 @@ func TestRecoveryWatchdog_ReadyThenLaterNotReadyReportsNoTimeout(t *testing.T) { func TestRecoveryWatchdog_NewIncarnationRearms(t *testing.T) { old, clk := watchdogHost(t, 10*time.Second) old.applyFact(selfPrimaryFact(1)) - if r := old.unhealthyReason(true); r != "" { + if r := old.unhealthyReason(readyAt(1), true); r != "" { t.Fatalf("old process ready: %q", r) } @@ -182,7 +184,84 @@ func TestRecoveryWatchdog_NewIncarnationRearms(t *testing.T) { t.Fatalf("restarted process past timeout: eligible=%t reason=%q; want ineligible, %s", s.Eligible, s.UnhealthyReason, UnhealthyRecoveryTimeout) } clk.advance(time.Hour) - if r := old.unhealthyReason(false); r != "" { + if r := old.unhealthyReason(readyAt(1), false); r != "" { t.Fatalf("old process stays disarmed: %q", r) } } + +func readyAt(epoch uint64) engine.PromotionReadyFact { + return engine.PromotionReadyFact{Ready: true, Epoch: epoch, EndpointVersion: 1} +} + +// readyView makes the host's promotion fact controllable through *ready. +func readyView(h *Host, volumeID, replicaID string, ready *engine.PromotionReadyFact) { + h.view = NewAdapterProjectionView(stubProjector{ + p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: ready.Epoch, EndpointVersion: 1}, + ready: ready, + }, volumeID, replicaID, h) +} + +// Review of #134 (P2 1), real host: ready at epoch 2, then the epoch-3 +// primary assignment is refused at admission (peer-set install fails), +// so the engine is still ready at epoch 2 only. That must not disarm the +// epoch-3 watchdog: it times out; a genuine epoch-3 ready fact clears it. +func TestRecoveryWatchdog_OldEpochReadyDoesNotDisarmNewAssignment(t *testing.T) { + h, a, repl := newStubbedHost(t, "vol1", "rB", &orderingRecorder{}) + clk := &fakeClock{t: time.Unix(1000, 0)} + h.wd = newRecoveryWatchdog(10 * time.Second) + h.wd.now = clk.now + ready := &engine.PromotionReadyFact{Ready: true, Epoch: 2, EndpointVersion: 1, ReplicaID: "rB"} + readyView(h, "vol1", "rB", ready) + + h.applyFact(selfFact(2)) + if s := reportSlot(t, h); !s.Eligible || s.UnhealthyReason != "" { + t.Fatalf("ready primary at epoch 2: %+v", s) + } + + repl.returnErr = errors.New("injected: peer set install failed") + h.applyFact(selfFact(3)) // refused: the adapter stays at epoch 2 + if a.callCount.Load() != 1 { + t.Fatal("fixture: the epoch-3 assignment was adopted") + } + clk.advance(11 * time.Second) + if s := reportSlot(t, h); s.Eligible || s.UnhealthyReason != UnhealthyRecoveryTimeout { + t.Fatalf("epoch 3 never admitted, engine ready only at epoch 2: eligible=%t reason=%q; want %s", s.Eligible, s.UnhealthyReason, UnhealthyRecoveryTimeout) + } + + *ready = engine.PromotionReadyFact{Ready: true, Epoch: 3, EndpointVersion: 1, ReplicaID: "rB"} + if s := reportSlot(t, h); !s.Eligible || s.UnhealthyReason != "" { + t.Fatalf("genuine epoch-3 ready fact: eligible=%t reason=%q; want cleared", s.Eligible, s.UnhealthyReason) + } +} + +// Review of #134 (P2 2), real host: a previously ready primary whose +// epoch-3 role call fails (G1 latch) reports role_admission_failed even +// though its engine is still ready at epoch 2; redelivery with a working +// role call clears the latch. +func TestRecoveryWatchdog_G1LatchWinsOverOldReady(t *testing.T) { + h, _, _ := newStubbedHost(t, "vol1", "rB", &orderingRecorder{}) + h.wd = newRecoveryWatchdog(time.Hour) + ready := &engine.PromotionReadyFact{Ready: true, Epoch: 2, EndpointVersion: 1, ReplicaID: "rB"} + readyView(h, "vol1", "rB", ready) + fencer := &switchFencer{} + if err := h.SetSelfFence(fencer); err != nil { + t.Fatal(err) + } + h.applyFact(selfFact(2)) + if s := reportSlot(t, h); !s.Eligible || s.UnhealthyReason != "" { + t.Fatalf("ready primary at epoch 2: %+v", s) + } + + fencer.fail.Store(true) + h.applyFact(selfFact(3)) // role call fails: G1 latch + if s := reportSlot(t, h); s.Eligible || s.UnhealthyReason != UnhealthyRoleAdmission { + t.Fatalf("G1 latch with an old ready fact: eligible=%t reason=%q; want %s", s.Eligible, s.UnhealthyReason, UnhealthyRoleAdmission) + } + + fencer.fail.Store(false) + h.applyFact(selfFact(3)) // redelivery succeeds + *ready = engine.PromotionReadyFact{Ready: true, Epoch: 3, EndpointVersion: 1, ReplicaID: "rB"} + if s := reportSlot(t, h); !s.Eligible || s.UnhealthyReason != "" { + t.Fatalf("after successful redelivery and an epoch-3 ready fact: eligible=%t reason=%q; want cleared", s.Eligible, s.UnhealthyReason) + } +}