Merge pull request #134 from seaweedfs/feat/recovery-watchdog

volume, master: recovery watchdog reports an explicit unhealthy fact
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-15 14:08:02 -08:00
commit fd7da7a760
17 files changed
+1402 -246

No files matched your search

+4
View File
@@ -44,6 +44,8 @@ type flags struct {
ctrlAddr string
hbInterval time.Duration
workspaceLease bool
// recoverTimeout: #128 rule 6 recovery watchdog.
recoverTimeout time.Duration
// printReadyLine: test-only flag — emits one structured JSON
// line to stdout on the FIRST received assignment with
// Epoch > 0. L2 subprocess smoke uses this to assert route
@@ -150,6 +152,7 @@ func parseFlags(args []string) (flags, error) {
fs.StringVar(&f.dataAddr, "data-addr", "", "data-path address (required)")
fs.StringVar(&f.ctrlAddr, "ctrl-addr", "", "control-path address (required)")
fs.DurationVar(&f.hbInterval, "heartbeat-interval", 2*time.Second, "heartbeat send interval")
fs.DurationVar(&f.recoverTimeout, "recover-timeout", volume.DefaultRecoverTimeout, "how long a primary-assigned replica may stay not promotion-ready before it reports itself unhealthy (recovery_timeout) so the master can fail over")
fs.BoolVar(&f.workspaceLease, "workspace-lease", false, "walstore-chunk workspace: require host-owned master lease; fail closed when unavailable")
fs.BoolVar(&f.printReadyLine, "t0-print-ready", false, "internal test-only: emit one structured JSON line on stdout on first assignment")
fs.BoolVar(&f.enableT1Readiness, "t1-readiness", false, "enable readiness bridge (HealthyPathExecutor) so adapter projection reaches Healthy")
@@ -494,6 +497,7 @@ func run(f flags) int {
DataAddr: f.dataAddr,
CtrlAddr: f.ctrlAddr,
HeartbeatInterval: f.hbInterval,
RecoverTimeout: f.recoverTimeout,
ReadyMarker: readyCh,
EnableT1Readiness: f.enableT1Readiness,
WorkspaceLease: f.workspaceLease,
@@ -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.
@@ -220,11 +220,46 @@ 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
}
// One fact per volume/replica slot: a report that names a slot twice
// is refused before any mutation, so storage and health transitions
// can never disagree about which entry is the slot (#134).
seen := make(map[string]struct{}, len(obs.Slots))
for _, slot := range obs.Slots {
k := slotKey(slot)
if _, dup := seen[k]; dup {
return nil, ErrInvalidObservation
}
seen[k] = struct{}{}
}
// Always compute ExpiresAt from store config — do not trust
@@ -237,8 +272,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 +288,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 +320,7 @@ func (s *ObservationStore) Ingest(obs Observation) error {
if fn != nil {
fn()
}
return nil
return transitions, nil
}
func mergeServerSlots(prev []SlotFact, next []SlotFact) []SlotFact {
@@ -0,0 +1,73 @@
package authority
import (
"errors"
"testing"
"time"
)
// Review of #134 r2: an observation carrying the same volume/replica
// slot twice is refused before any mutation, so a duplicate can never
// fabricate a health transition that does not describe the stored slot.
func dupStore(t *testing.T) (*ObservationStore, time.Time) {
t.Helper()
base := time.Unix(1000, 0)
return NewObservationStore(FreshnessConfig{FreshnessWindow: time.Hour}, func() time.Time { return base.Add(time.Minute) }), base
}
func slotWith(reason string) SlotFact {
return SlotFact{VolumeID: "v1", ReplicaID: "r1", DataAddr: "d", CtrlAddr: "c", Reachable: true, Eligible: reason == "", UnhealthyReason: reason}
}
func TestObservationStore_DuplicateSlotKeysRefused(t *testing.T) {
for _, tc := range []struct {
name string
slots []SlotFact
}{
{"conflicting", []SlotFact{slotWith(""), slotWith("recovery_timeout")}},
{"identical", []SlotFact{slotWith("recovery_timeout"), slotWith("recovery_timeout")}},
} {
t.Run(tc.name, func(t *testing.T) {
s, base := dupStore(t)
if _, err := s.IngestWithHealthTransitions(Observation{ServerID: "s1", ObservedAt: base, Slots: []SlotFact{slotWith("recovery_timeout")}}); err != nil {
t.Fatal(err)
}
rev := s.Snapshot().revision
tr, err := s.IngestWithHealthTransitions(Observation{ServerID: "s1", ObservedAt: base.Add(time.Second), Slots: tc.slots})
if !errors.Is(err, ErrInvalidObservation) {
t.Fatalf("duplicate slot keys: err=%v; want ErrInvalidObservation", err)
}
if len(tr) != 0 {
t.Fatalf("refused observation produced transitions %+v", tr)
}
if got := s.Snapshot().revision; got != rev {
t.Fatalf("refused observation mutated the store: revision %d -> %d", rev, got)
}
if f, ok := s.SlotFact("v1", "r1"); !ok || f.UnhealthyReason != "recovery_timeout" {
t.Fatalf("stored slot after refusal: %+v %t; want the earlier recovery_timeout fact", f, ok)
}
})
}
}
// Positive: distinct slots in one observation are accepted, and each
// changed slot yields its own transition.
func TestObservationStore_UniqueMultiSlotTransitions(t *testing.T) {
s, base := dupStore(t)
a := SlotFact{VolumeID: "v1", ReplicaID: "r1", DataAddr: "d", CtrlAddr: "c", Reachable: true, Eligible: true}
b := SlotFact{VolumeID: "v2", ReplicaID: "r1", DataAddr: "d2", CtrlAddr: "c2", Reachable: true, Eligible: true}
if _, err := s.IngestWithHealthTransitions(Observation{ServerID: "s1", ObservedAt: base, Slots: []SlotFact{a, b}}); err != nil {
t.Fatal(err)
}
a2, b2 := a, b
a2.Eligible, a2.UnhealthyReason = false, "recovery_timeout"
b2.Eligible, b2.UnhealthyReason = false, "role_admission_failed"
tr, err := s.IngestWithHealthTransitions(Observation{ServerID: "s1", ObservedAt: base.Add(time.Second), Slots: []SlotFact{a2, b2}})
if err != nil {
t.Fatal(err)
}
if len(tr) != 2 || tr[0].VolumeID != "v1" || tr[0].New != "recovery_timeout" || tr[1].VolumeID != "v2" || tr[1].New != "role_admission_failed" {
t.Fatalf("transitions %+v; want v1 -> recovery_timeout and v2 -> role_admission_failed", tr)
}
}
@@ -57,6 +57,9 @@ type SlotFact struct {
// Incarnation identifies the reporting volume process (new on
// every process start); raw fact, empty from older binaries.
Incarnation string
// UnhealthyReason is the slot's explicit unhealthy report (reported
// with Eligible=false); raw fact, empty when healthy.
UnhealthyReason string
// ObservedAt/ExpiresAt are store-owned per-slot freshness
// markers. They let one Kubernetes node run multiple
// blockvolume processes that each report a different slot
@@ -57,6 +57,7 @@ type HeartbeatSlot struct {
Withdrawn bool
EvidenceScore uint64
Incarnation string
UnhealthyReason string
// LocalRoleClaim is the V2 "I think I am" role flag, mapped
// one-to-one into the V3 Observation shape without
// reinterpretation. Two servers each sending LocalRolePrimary
@@ -95,6 +96,7 @@ func HeartbeatToObservation(msg HeartbeatMessage) (Observation, error) {
Withdrawn: s.Withdrawn,
EvidenceScore: s.EvidenceScore,
Incarnation: s.Incarnation,
UnhealthyReason: s.UnhealthyReason,
LocalRoleClaim: s.LocalRoleClaim,
})
}
@@ -66,8 +66,10 @@ func TestStatusFrontendsForAssignedVolume_ReturnsObservedFrontendFactsForAllSlot
func TestStatusFrontendsForAssignedVolume_DedupesRepeatedFacts(t *testing.T) {
obs := authority.NewObservationHost(authority.ObservationHostConfig{})
// The repeated replica IDs below are what this pins. A heartbeat
// naming the same slot twice is refused at ingest (#134), so the
// fact is ingested once.
hb := frontendHeartbeat("node-a", "v1", "r1", "127.0.0.1:3260")
hb.Slots = append(hb.Slots, hb.Slots[0])
if err := obs.IngestHeartbeat(hb); err != nil {
t.Fatalf("ingest heartbeat: %v", err)
}
+1
View File
@@ -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
@@ -0,0 +1,293 @@
package master
import (
"context"
"sync"
"sync/atomic"
"testing"
"time"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/seaweedfs/seaweed-block/core/authority"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
)
// #128 rule 6 on the master: an explicit unhealthy slot (Eligible=false
// plus a reason) fails over at once to a qualified peer, promotes nobody
// without one, and surfaces the reason in volume status and as events.
// Heartbeats go through the real ReportHeartbeat wire path.
type wireSlot struct {
incarnation string
ready bool
unhealthy string // non-empty: Eligible=false with this reason
}
func reportRF3(t *testing.T, svc *services, r1, r2, r3 wireSlot) {
t.Helper()
for i, s := range []struct {
server, replica string
slot wireSlot
}{
{"node-a", "r1", r1}, {"node-b", "r2", r2}, {"node-c", "r3", r3},
} {
_, err := svc.ReportHeartbeat(context.Background(), &control.HeartbeatReport{
ServerId: s.server, SentAt: timestamppb.Now(), Reachable: true, Eligible: true,
Slots: []*control.HeartbeatSlot{{
VolumeId: "vol-rf3",
ReplicaId: s.replica,
DataAddr: "127.0.0.1:19" + string(rune('1'+i)) + "01",
CtrlAddr: "127.0.0.1:19" + string(rune('1'+i)) + "02",
Reachable: true,
ReadyForPrimary: s.slot.ready,
Eligible: s.slot.unhealthy == "",
EvidenceScore: uint64(30 - i),
Incarnation: s.slot.incarnation,
UnhealthyReason: s.slot.unhealthy,
}},
})
if err != nil {
t.Fatalf("ReportHeartbeat %s: %v", s.server, err)
}
}
}
func watchdogMaster(t *testing.T) (*Host, *services) {
t.Helper()
h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{
ExpectedSlotsPerVolume: 3, PrimaryBootGrace: time.Minute,
})
seedRF3PlacementForServersWithAddrs(t, h, "vol-rf3", "node-a", "node-b", "node-c")
svc := newServices(h)
reportRF3(t, svc, wireSlot{"r1-a", true, ""}, wireSlot{"r2-a", true, ""}, wireSlot{"r3-a", true, ""})
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatalf("initial product tick: %v", err)
}
if line := waitAuthorityLine(t, h.Publisher(), "vol-rf3"); line.ReplicaID != "r1" {
t.Fatalf("initial line=%+v want r1", line)
}
return h, svc
}
func unhealthyReplicas(t *testing.T, svc *services) map[string]string {
t.Helper()
resp, err := svc.QueryVolumeStatus(context.Background(), &control.StatusRequest{VolumeId: "vol-rf3"})
if err != nil {
t.Fatalf("QueryVolumeStatus: %v", err)
}
out := map[string]string{}
for _, u := range resp.GetUnhealthyReplicas() {
out[u.GetReplicaId()] = u.GetReason()
}
return out
}
func timelineEvents(t *testing.T, svc *services) []*control.ClusterEvent {
t.Helper()
tl, err := svc.GetVolumeTimeline(context.Background(), &control.GetVolumeTimelineRequest{VolumeId: "vol-rf3"})
if err != nil {
t.Fatalf("timeline: %v", err)
}
return tl.GetEvents()
}
// No qualified peer: nobody is promoted; the reason is in volume status
// and the timeline; a later ready report clears both.
func TestRecoveryWatchdog_MasterNoQualifiedPeerPromotesNobody(t *testing.T) {
h, svc := watchdogMaster(t)
defer closeTestMaster(t, h)
reportRF3(t, svc, wireSlot{"r1-b", false, "recovery_timeout"}, wireSlot{"r2-a", false, ""}, wireSlot{"r3-a", false, ""})
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatalf("product tick: %v", err)
}
time.Sleep(150 * time.Millisecond)
if line, _ := h.Publisher().VolumeAuthorityLine("vol-rf3"); line.ReplicaID != "r1" || line.Epoch != 1 {
t.Fatalf("no qualified peer: line=%+v want r1@1 unchanged", line)
}
if got := unhealthyReplicas(t, svc); got["r1"] != "recovery_timeout" || len(got) != 1 {
t.Fatalf("volume status unhealthy replicas=%v; want r1=recovery_timeout", got)
}
if !timelineHasEvent(timelineEvents(t, svc), "replica_unhealthy", "recovery_timeout") {
t.Fatalf("timeline has no replica_unhealthy/recovery_timeout event")
}
reportRF3(t, svc, wireSlot{"r1-b", true, ""}, wireSlot{"r2-a", false, ""}, wireSlot{"r3-a", false, ""})
if got := unhealthyReplicas(t, svc); len(got) != 0 {
t.Fatalf("after a ready report: unhealthy replicas=%v; want none", got)
}
cleared := false
for _, e := range timelineEvents(t, svc) {
if e.GetEventType() == "replica_unhealthy_cleared" && e.GetReplicaId() == "r1" && e.GetOldValue() == "recovery_timeout" {
cleared = true
}
}
if !cleared {
t.Fatalf("timeline has no replica_unhealthy_cleared event for r1")
}
}
// A qualified peer exists: the unhealthy primary fails over at once, even
// though it is a restarted incarnation that would otherwise be in its
// boot grace.
func TestRecoveryWatchdog_MasterUnhealthyFailsOverToQualifiedPeer(t *testing.T) {
h, svc := watchdogMaster(t)
defer closeTestMaster(t, h)
h.SetPromotionEvidenceProvider(&switchProbe{}) // r1 not ready, r2 ready with evidence
reportRF3(t, svc, wireSlot{"r1-b", false, "recovery_timeout"}, wireSlot{"r2-a", true, ""}, wireSlot{"r3-a", false, ""})
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatalf("product tick: %v", err)
}
if line := waitAuthorityReplica(t, h.Publisher(), "vol-rf3", "r2"); line.Epoch != 2 {
t.Fatalf("unhealthy primary with a qualified peer: line=%+v want r2@2", line)
}
}
// A running primary that was ready and later reports not ready on the
// same incarnation (no unhealthy reason) follows the normal failover
// rules: no boot grace for that incarnation, so it fails over to the
// qualified peer, and nothing is listed as unhealthy (claude05, 21:24Z).
func TestRecoveryWatchdog_MasterLaterDegradationFollowsNormalRules(t *testing.T) {
h, svc := watchdogMaster(t)
defer closeTestMaster(t, h)
h.SetPromotionEvidenceProvider(&switchProbe{}) // r1 not ready, r2 ready with evidence
reportRF3(t, svc, wireSlot{"r1-a", false, ""}, wireSlot{"r2-a", true, ""}, wireSlot{"r3-a", false, ""})
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatalf("product tick: %v", err)
}
if line := waitAuthorityReplica(t, h.Publisher(), "vol-rf3", "r2"); line.Epoch != 2 {
t.Fatalf("degraded running primary with a qualified peer: line=%+v want r2@2", line)
}
if got := unhealthyReplicas(t, svc); len(got) != 0 {
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)
}
}
// Review of #134 r2: a heartbeat carrying the same slot twice is
// refused at the RPC; volume status and the timeline stay unchanged.
func TestRecoveryWatchdog_MasterDuplicateSlotHeartbeatRefused(t *testing.T) {
h, svc := watchdogMaster(t)
defer closeTestMaster(t, h)
t0 := time.Now()
reportR1(t, svc, wireSlot{"r1-b", false, "recovery_timeout"}, t0)
before := r1HealthEvents(t, svc)
slot := func(reason string) *control.HeartbeatSlot {
return &control.HeartbeatSlot{
VolumeId: "vol-rf3", ReplicaId: "r1", DataAddr: "127.0.0.1:19101", CtrlAddr: "127.0.0.1:19102",
Reachable: true, Eligible: reason == "", Incarnation: "r1-b", UnhealthyReason: reason,
}
}
for i, slots := range [][]*control.HeartbeatSlot{
{slot(""), slot("recovery_timeout")}, // conflicting
{slot("recovery_timeout"), slot("recovery_timeout")}, // identical
} {
_, err := svc.ReportHeartbeat(context.Background(), &control.HeartbeatReport{
ServerId: "node-a", SentAt: timestamppb.New(t0.Add(time.Duration(i+1) * time.Millisecond)),
Reachable: true, Eligible: true, Slots: slots,
})
if err == nil {
t.Fatalf("duplicate-slot heartbeat %d accepted", i)
}
}
if got := r1HealthEvents(t, svc); len(got) != len(before) {
t.Fatalf("health events changed by refused heartbeats: %v -> %v", before, got)
}
if got := unhealthyReplicas(t, svc); got["r1"] != "recovery_timeout" {
t.Fatalf("volume status after refusal: %v; want r1=recovery_timeout", got)
}
}
+57 -1
View File
@@ -10,6 +10,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
"github.com/seaweedfs/seaweed-block/core/ops"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
@@ -130,7 +131,7 @@ func (s *services) ReportHeartbeat(ctx context.Context, r *control.HeartbeatRepo
return nil, err
}
msg := heartbeatFromWire(r)
if err := s.host.obs.IngestHeartbeat(msg); err != nil {
if err := s.host.ingestHeartbeatRecordingHealth(msg); err != nil {
return nil, fmt.Errorf("ingest: %w", err)
}
return &control.HeartbeatAck{
@@ -345,6 +346,7 @@ func (s *services) QueryVolumeStatus(ctx context.Context, req *control.StatusReq
}
replicaIDs = primaryFirstReplicaIDs(replicaIDs, line.ReplicaID)
resp.Frontends = statusFrontendsForAssignedVolume(s.host.obs, req.VolumeId, replicaIDs, line.Assigned)
resp.UnhealthyReplicas = statusUnhealthyReplicas(s.host.obs, req.VolumeId, replicaIDs)
}
if ev, ok := ctrl.LastUnsupported(req.VolumeId); ok {
resp.LastUnsupportedReason = ev.Reason
@@ -453,6 +455,7 @@ func validateHeartbeat(r *control.HeartbeatReport) error {
if r.SentAt == nil || !r.SentAt.IsValid() {
return errors.New("heartbeat: invalid SentAt")
}
seen := make(map[string]int, len(r.Slots))
for i, s := range r.Slots {
if s == nil {
return fmt.Errorf("heartbeat: slot[%d] is nil", i)
@@ -460,6 +463,11 @@ func validateHeartbeat(r *control.HeartbeatReport) error {
if s.VolumeId == "" || s.ReplicaId == "" {
return fmt.Errorf("heartbeat: slot[%d] missing VolumeID or ReplicaID", i)
}
key := s.VolumeId + "/" + s.ReplicaId
if j, dup := seen[key]; dup {
return fmt.Errorf("heartbeat: slot[%d] repeats slot[%d] (%s)", i, j, key)
}
seen[key] = i
if s.DataAddr == "" || s.CtrlAddr == "" {
return fmt.Errorf("heartbeat: slot[%d] (%s/%s) missing DataAddr or CtrlAddr", i, s.VolumeId, s.ReplicaId)
}
@@ -660,6 +668,7 @@ func heartbeatFromWire(r *control.HeartbeatReport) authority.HeartbeatMessage {
Withdrawn: s.Withdrawn,
EvidenceScore: s.EvidenceScore,
Incarnation: s.Incarnation,
UnhealthyReason: s.UnhealthyReason,
LocalRoleClaim: authority.LocalRoleClaim(s.LocalRoleClaim),
})
}
@@ -712,3 +721,50 @@ func frontendTargetsToWire(in []authority.FrontendTargetFact) []*control.Fronten
}
return out
}
// statusUnhealthyReplicas lists the replicas whose fresh slot fact
// carries an explicit unhealthy reason (#128 rule 6).
func statusUnhealthyReplicas(obs *authority.ObservationHost, volumeID string, replicaIDs []string) []*control.ReplicaUnhealthy {
if obs == nil {
return nil
}
var out []*control.ReplicaUnhealthy
for _, replicaID := range replicaIDs {
if slot, ok := obs.Store().SlotFact(volumeID, replicaID); ok && slot.UnhealthyReason != "" {
out = append(out, &control.ReplicaUnhealthy{ReplicaId: replicaID, Reason: slot.UnhealthyReason})
}
}
return out
}
// ingestHeartbeatRecordingHealth ingests a heartbeat and records a
// replica_unhealthy / replica_unhealthy_cleared event for every slot
// whose unhealthy reason the accepted report changed (#128 rule 6). The
// transitions come from the accepted store mutation itself, so a refused
// report records nothing and expiry never fabricates a clear. healthMu
// keeps the events in accepted order across concurrent heartbeats.
func (h *Host) ingestHeartbeatRecordingHealth(msg authority.HeartbeatMessage) error {
h.healthMu.Lock()
defer h.healthMu.Unlock()
transitions, err := h.obs.IngestHeartbeatWithHealthTransitions(msg)
if err != nil {
return err
}
for _, tr := range transitions {
if tr.New == "" {
h.events.append(ops.ClusterEvent{
VolumeID: tr.VolumeID, ReplicaID: tr.ReplicaID,
Type: "replica_unhealthy_cleared", Severity: "info",
Message: "replica reported healthy again", OldValue: tr.Old,
})
continue
}
h.events.append(ops.ClusterEvent{
VolumeID: tr.VolumeID, ReplicaID: tr.ReplicaID,
Type: "replica_unhealthy", Severity: "warning",
Message: "replica reported an explicit unhealthy fact: " + tr.New,
Reason: tr.New, OldValue: tr.Old, NewValue: tr.New,
})
}
return nil
}
+30 -5
View File
@@ -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"
@@ -41,6 +42,11 @@ type Config struct {
// Zero picks the default (2s).
HeartbeatInterval time.Duration
// RecoverTimeout bounds how long a primary-assigned replica may stay
// not promotion-ready before it reports an explicit unhealthy fact
// (#128 rule 6). Zero picks DefaultRecoverTimeout.
RecoverTimeout time.Duration
// Logger receives structured startup + loop-event logs.
// Nil falls through to the default log package logger.
Logger *log.Logger
@@ -96,6 +102,8 @@ type Host struct {
// incarnation is new on every process start and reported in every
// heartbeat, so the master can tell a restart from a long silence.
incarnation string
// wd is the recovery watchdog (#128 rule 6).
wd *recoveryWatchdog
cfg Config
log *log.Logger
@@ -255,6 +263,8 @@ func New(cfg Config) (*Host, error) {
asnCli: control.NewAssignmentServiceClient(conn),
}
h.incarnation = newIncarnation()
h.wd = newRecoveryWatchdog(cfg.RecoverTimeout)
h.log.Printf("blockvolume: volume %s recovery watchdog: a primary assignment must become promotion-ready within %s", cfg.VolumeID, h.wd.timeout)
if cfg.ReplicationVolume != nil {
h.setReplicationLocked(cfg.ReplicationVolume)
}
@@ -583,6 +593,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 {
fact, ready := h.promotionReady()
unhealthy := h.unhealthyReason(fact, ready)
return &control.HeartbeatReport{
ServerId: h.cfg.ServerID,
SentAt: timestamppb.Now(),
@@ -596,9 +608,10 @@ func (h *Host) buildReport() *control.HeartbeatReport {
CtrlAddr: h.cfg.CtrlAddr,
Frontends: h.frontendTargetsSnapshot(),
Reachable: true,
ReadyForPrimary: h.readyForPrimaryFact(),
Eligible: true,
ReadyForPrimary: ready,
Eligible: unhealthy == "", // an explicit unhealthy slot is ineligible
Incarnation: h.incarnation,
UnhealthyReason: unhealthy,
},
},
}
@@ -621,14 +634,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
@@ -734,6 +754,7 @@ func (h *Host) streamOnce(ctx context.Context) error {
// installed, admitting local-only writes with zero fan-out.
func (h *Host) applyFact(fact *control.AssignmentFact) {
if fact.ReplicaId != h.cfg.ReplicaID {
h.wd.notPrimary()
// Another replica is authoritative for this volume line. Record that
// line first so AdapterProjectionView can keep this replica frontend-
// unhealthy even if its local engine is otherwise caught up.
@@ -753,6 +774,7 @@ func (h *Host) applyFact(fact *control.AssignmentFact) {
return
}
h.adpt.OnAssignment(info)
h.wd.supportingAdmitted(info.Epoch)
h.log.Printf("blockvolume: volume %s admitted as SUPPORTING replica %s at epoch=%d EV=%d behind primary %s; frontend remains gated",
h.cfg.VolumeID, info.ReplicaID, info.Epoch, info.EndpointVersion, fact.ReplicaId)
// Supporting replicas need durable lineage latching for promotion-readiness,
@@ -766,6 +788,9 @@ func (h *Host) applyFact(fact *control.AssignmentFact) {
return
}
// The recovery watchdog runs from the primary assignment, before any
// admission step can fail (#128 rule 6).
h.wd.primaryAssigned(fact.Epoch)
if blocked, reason := h.localReadinessBlock(); blocked {
h.storeLocalReadinessReplayFact(fact)
h.log.Printf("blockvolume: volume %s local readiness blocked (%s); NOT applying primary assignment %s@%d to adapter",
@@ -1,6 +1,8 @@
package volume
import (
"time"
"github.com/seaweedfs/seaweed-block/core/engine"
"github.com/seaweedfs/seaweed-block/core/frontend"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
@@ -164,6 +166,30 @@ func (v *AdapterProjectionView) roleAdmissionReason() string {
return ""
}
// unhealthyReason is the host's explicit unhealthy report (#128 rule 6),
// or "" when the probe does not provide one.
func (v *AdapterProjectionView) unhealthyReason() string {
if v == nil || v.probe == nil {
return ""
}
if p, ok := v.probe.(interface{ UnhealthyReason() string }); ok {
return p.UnhealthyReason()
}
return ""
}
// catchUpSince is when the host was admitted as a supporting replica at
// its current epoch; zero when not supporting or not provided.
func (v *AdapterProjectionView) catchUpSince() time.Time {
if v == nil || v.probe == nil {
return time.Time{}
}
if p, ok := v.probe.(interface{ CatchUpSince() time.Time }); ok {
return p.CatchUpSince()
}
return time.Time{}
}
func (v *AdapterProjectionView) isSupersededLine(epoch, endpointVersion uint64) bool {
return v != nil &&
v.probe != nil &&
@@ -0,0 +1,192 @@
package volume
import (
"sync"
"time"
"github.com/seaweedfs/seaweed-block/core/engine"
)
// Recovery watchdog (#128 rule 6).
//
// A replica that holds the PRIMARY assignment but whose local recovery
// has not produced the engine's promotion-ready fact within the recover
// timeout reports an explicit unhealthy fact (Eligible=false plus a typed
// reason) instead of staying silently not-ready, so the master fails over
// at once to a peer that passes the promotion evidence gate, or, with no
// qualifying peer, promotes nobody and surfaces the reason.
//
// - Scope: only a primary-assigned replica is flagged. A supporting
// replica in a long catch-up is not; its catch-up state (elapsed,
// lag) is visible in /status instead.
// - The timeout runs from the primary assignment in this incarnation
// (a new primary epoch restarts it).
// - recovery_timeout latches until a fresh promotion-ready fact clears
// it (Eligible=true, reason empty). An epoch that already moved
// stays moved: the master decides that, not the volume.
// - It watches recovery after a primary assignment only: once the
// replica has been promotion-ready in that assignment, the watchdog
// is disarmed until the next primary epoch or a new process
// incarnation (its state is per process). A running primary that
// 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, 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.
const (
UnhealthyRecoveryTimeout = "recovery_timeout"
UnhealthyRoleAdmission = "role_admission_failed"
// DefaultRecoverTimeout matches blockmaster's default freshness
// window.
DefaultRecoverTimeout = 30 * time.Second
)
// A nil *recoveryWatchdog (a Host built without New, as some tests do)
// is inert: no reason is ever reported.
type recoveryWatchdog struct {
mu sync.Mutex
timeout time.Duration
now func() time.Time
primarySince time.Time // zero unless this replica holds the primary assignment
primaryEpoch uint64
supportingSince time.Time // zero unless admitted as a supporting replica
supportingEpoch uint64
timedOut bool // recovery_timeout latched until a ready fact
readySeen bool // promotion-ready once in this primary assignment: disarmed
}
func newRecoveryWatchdog(timeout time.Duration) *recoveryWatchdog {
if timeout <= 0 {
timeout = DefaultRecoverTimeout
}
return &recoveryWatchdog{timeout: timeout, now: time.Now}
}
// primaryAssigned records a primary assignment for this replica. A new
// epoch restarts the timeout.
func (w *recoveryWatchdog) primaryAssigned(epoch uint64) {
if w == nil {
return
}
w.mu.Lock()
defer w.mu.Unlock()
if w.primarySince.IsZero() || epoch != w.primaryEpoch {
w.primarySince, w.primaryEpoch, w.timedOut, w.readySeen = w.now(), epoch, false, false
}
w.supportingSince, w.supportingEpoch = time.Time{}, 0
}
// notPrimary records that another replica holds the primary assignment.
func (w *recoveryWatchdog) notPrimary() {
if w == nil {
return
}
w.mu.Lock()
defer w.mu.Unlock()
w.primarySince, w.primaryEpoch, w.timedOut, w.readySeen = time.Time{}, 0, false, false
}
// supportingAdmitted records this replica's admission as a supporting
// replica at epoch; a new epoch restarts its catch-up clock.
func (w *recoveryWatchdog) supportingAdmitted(epoch uint64) {
if w == nil {
return
}
w.mu.Lock()
defer w.mu.Unlock()
w.primarySince, w.primaryEpoch, w.timedOut, w.readySeen = time.Time{}, 0, false, false
if w.supportingSince.IsZero() || epoch != w.supportingEpoch {
w.supportingSince, w.supportingEpoch = w.now(), epoch
}
}
// reason returns the slot's explicit unhealthy reason given whether it
// 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
}
w.mu.Lock()
defer w.mu.Unlock()
if w.primarySince.IsZero() {
return "", false
}
if roleAdmissionFailed {
return UnhealthyRoleAdmission, false
}
if ready && readyEpoch == w.primaryEpoch {
w.timedOut, w.readySeen = false, true
return "", false
}
if w.readySeen {
return "", false
}
if !w.timedOut && w.now().Sub(w.primarySince) >= w.timeout {
w.timedOut, fired = true, true
}
if w.timedOut {
return UnhealthyRecoveryTimeout, fired
}
return "", false
}
// catchUpSince is when this replica was admitted as a supporting replica
// at its current epoch; zero when it is not supporting.
func (w *recoveryWatchdog) catchUpSince() time.Time {
if w == nil {
return time.Time{}
}
w.mu.Lock()
defer w.mu.Unlock()
return w.supportingSince
}
// 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 {
fact, ready := h.promotionReady()
return h.unhealthyReason(fact, ready)
}
// 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, 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)
}
return reason
}
func (w *recoveryWatchdog) epoch() uint64 {
w.mu.Lock()
defer w.mu.Unlock()
return w.primaryEpoch
}
// CatchUpSince is when this replica was admitted as a supporting replica
// at its current epoch; zero when it is not supporting.
func (h *Host) CatchUpSince() time.Time {
if h == nil || h.wd == nil {
return time.Time{}
}
return h.wd.catchUpSince()
}
@@ -0,0 +1,267 @@
package volume
import (
"errors"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/engine"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
)
// #128 rule 6: a primary-assigned replica that is not promotion-ready
// within its recover timeout reports an explicit unhealthy fact.
type fakeClock struct{ t time.Time }
func (c *fakeClock) now() time.Time { return c.t }
func (c *fakeClock) advance(d time.Duration) { c.t = c.t.Add(d) }
func watchdogHost(t *testing.T, timeout time.Duration) (*Host, *fakeClock) {
t.Helper()
h := newTestVolumeHost(t)
clk := &fakeClock{t: time.Unix(1000, 0)}
h.wd = newRecoveryWatchdog(timeout)
h.wd.now = clk.now
return h, clk
}
func selfPrimaryFact(epoch uint64) *control.AssignmentFact {
return &control.AssignmentFact{
VolumeId: "v1", ReplicaId: "r1", Epoch: epoch, EndpointVersion: 1,
DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101",
}
}
func reportSlot(t *testing.T, h *Host) *control.HeartbeatSlot {
t.Helper()
rep := h.buildReport()
if len(rep.Slots) != 1 {
t.Fatalf("report slots: %d", len(rep.Slots))
}
return rep.Slots[0]
}
// The heartbeat of a primary-assigned, not-ready replica turns explicit
// unhealthy (Eligible=false, recovery_timeout) once the timeout elapses.
func TestRecoveryWatchdog_PrimaryNotReadyPastTimeoutReportsUnhealthy(t *testing.T) {
h, clk := watchdogHost(t, 30*time.Second)
h.applyFact(selfPrimaryFact(1))
clk.advance(29 * time.Second)
if s := reportSlot(t, h); !s.Eligible || s.UnhealthyReason != "" || s.ReadyForPrimary {
t.Fatalf("inside the recover timeout: %+v; want eligible, no reason, not ready", s)
}
clk.advance(2 * time.Second)
if s := reportSlot(t, h); s.Eligible || s.UnhealthyReason != UnhealthyRecoveryTimeout {
t.Fatalf("past the recover timeout: eligible=%t reason=%q; want ineligible, %s", s.Eligible, s.UnhealthyReason, UnhealthyRecoveryTimeout)
}
if got := h.UnhealthyReason(); got != UnhealthyRecoveryTimeout {
t.Fatalf("UnhealthyReason()=%q", got)
}
}
// A supporting replica in a long catch-up is never flagged.
func TestRecoveryWatchdog_SupportingReplicaNotFlagged(t *testing.T) {
h, clk := watchdogHost(t, 30*time.Second)
h.applyFact(selfPrimaryFact(1))
h.applyFact(&control.AssignmentFact{ // another replica is now primary
VolumeId: "v1", ReplicaId: "r2", Epoch: 2, EndpointVersion: 1,
DataAddr: "127.0.0.1:9301", CtrlAddr: "127.0.0.1:9302",
})
h.wd.supportingAdmitted(2)
clk.advance(time.Hour)
if s := reportSlot(t, h); !s.Eligible || s.UnhealthyReason != "" {
t.Fatalf("supporting replica after an hour: %+v; want eligible, no reason", s)
}
}
// recovery_timeout latches until a fresh ready fact clears it; once
// ready in this assignment the watchdog is disarmed; a new primary epoch
// re-arms it with a fresh clock.
func TestRecoveryWatchdog_ReadyClearsAndDisarmsNewEpochRearms(t *testing.T) {
w := newRecoveryWatchdog(10 * time.Second)
clk := &fakeClock{t: time.Unix(1000, 0)}
w.now = clk.now
w.primaryAssigned(1)
clk.advance(11 * time.Second)
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, 0, false); r != UnhealthyRecoveryTimeout || fired {
t.Fatalf("latched: %q fired=%t; want the reason, fired only once", r, fired)
}
if r, _ := w.reason(true, 1, false); r != "" {
t.Fatalf("ready: %q; want cleared", 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, 0, false); r != "" {
t.Fatalf("new epoch inside timeout: %q", r)
}
clk.advance(2 * time.Second)
if r, _ := w.reason(false, 0, false); r != UnhealthyRecoveryTimeout {
t.Fatalf("new epoch past timeout: %q", r)
}
}
// The G1 role-admission latch of a primary-assigned replica is reported
// 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, 0, true); r != "" {
t.Fatalf("not primary-assigned: %q", r)
}
w.primaryAssigned(1)
if r, _ := w.reason(false, 0, true); r != UnhealthyRoleAdmission {
t.Fatalf("primary-assigned with the G1 latch: %q; want %s", r, UnhealthyRoleAdmission)
}
}
// /status carries the unhealthy reason, and a supporting replica's
// catch-up state.
func TestRecoveryWatchdog_StatusShowsReasonAndCatchUp(t *testing.T) {
h, clk := watchdogHost(t, time.Second)
h.applyFact(selfPrimaryFact(1))
clk.advance(2 * time.Second)
s := NewStatusServer(h.view)
if got := s.statusProjection().UnhealthyReason; got != UnhealthyRecoveryTimeout {
t.Fatalf("/status UnhealthyReason=%q; want %s", got, UnhealthyRecoveryTimeout)
}
h2 := newTestVolumeHost(t)
h2.wd.supportingAdmitted(3)
time.Sleep(20 * time.Millisecond)
st := NewStatusServer(h2.view).statusProjection()
if st.UnhealthyReason != "" || st.CatchUp == nil || st.CatchUp.ElapsedMs < 20 {
t.Fatalf("supporting replica /status: reason=%q catchUp=%+v; want no reason and catch-up elapsed >= 20ms", st.UnhealthyReason, st.CatchUp)
}
}
// Once ready in this assignment, a later not-ready on the same
// incarnation is a running primary degrading, not a boot-recovery stall:
// no recovery_timeout, however long it lasts (claude05, 21:24Z).
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(readyAt(1), true); r != "" {
t.Fatalf("ready: %q", r)
}
clk.advance(time.Hour)
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(readyAt(1), false); r != "" {
t.Fatalf("same assignment replayed: %q; want still disarmed", r)
}
}
// A new process incarnation re-arms the watchdog: its state is per
// process, so a restarted primary that stays not-ready past the timeout
// reports recovery_timeout even for the same primary epoch.
func TestRecoveryWatchdog_NewIncarnationRearms(t *testing.T) {
old, clk := watchdogHost(t, 10*time.Second)
old.applyFact(selfPrimaryFact(1))
if r := old.unhealthyReason(readyAt(1), true); r != "" {
t.Fatalf("old process ready: %q", r)
}
restarted, clk2 := watchdogHost(t, 10*time.Second) // new process, same replica
if restarted.incarnation == old.incarnation {
t.Fatalf("restarted process kept incarnation %q", old.incarnation)
}
restarted.applyFact(selfPrimaryFact(1)) // same primary epoch
clk2.advance(11 * time.Second)
if s := reportSlot(t, restarted); s.Eligible || s.UnhealthyReason != UnhealthyRecoveryTimeout {
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(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)
}
}
@@ -163,6 +163,22 @@ type StatusProjection struct {
// RoleAdmissionFailure (G1) explains a not-Healthy projection caused
// by a failed role call on the replica listener; empty otherwise.
RoleAdmissionFailure string `json:",omitempty"`
// UnhealthyReason is the slot's explicit unhealthy report (#128 rule
// 6), the value its heartbeat carries; empty when healthy.
UnhealthyReason string `json:",omitempty"`
// CatchUp shows a supporting replica's catch-up progress while it is
// not yet replica_ready; it is visible without being an alert.
CatchUp *CatchUpStatus `json:",omitempty"`
}
// CatchUpStatus is a supporting replica's catch-up state.
type CatchUpStatus struct {
// ElapsedMs is the time since this replica was admitted as a
// supporting replica at its current epoch.
ElapsedMs int64
// LagLSN is the engine's H-R (primary head minus this replica's
// durable frontier) as last observed; 0 when unknown or caught up.
LagLSN uint64
}
// NewStatusServer wires a server to one volume host's view.
@@ -413,13 +429,22 @@ func (s *StatusServer) statusProjection() StatusProjection {
case ep.Mode == engine.ModeDegraded || ep.Mode == engine.ModeIdle:
replicationRole = ReplicationRoleNotReady
}
return StatusProjection{
out := StatusProjection{
Projection: p,
FrontendPrimaryReady: p.Healthy && !superseded && !supportingReady,
AuthorityRole: authorityRole,
ReplicationRole: replicationRole,
RoleAdmissionFailure: s.view.roleAdmissionReason(),
UnhealthyReason: s.view.unhealthyReason(),
}
if since := s.view.catchUpSince(); !since.IsZero() && replicationRole != ReplicationRoleReady {
cu := &CatchUpStatus{ElapsedMs: time.Since(since).Milliseconds()}
if ep.H > ep.R {
cu.LagLSN = ep.H - ep.R
}
out.CatchUp = cu
}
return out
}
func (s *StatusServer) supportingReplicaReady(selfEpoch, selfEV uint64) bool {
File diff suppressed because it is too large. Load diff
@@ -126,6 +126,12 @@ message HeartbeatSlot {
// every process start. Raw observation fact: the controller uses it
// only to bound a restarted primary's boot grace.
string incarnation = 12;
// unhealthy_reason is an explicit unhealthy report for this slot
// (#128 rule 6): recovery_timeout when a primary-assigned replica did
// not become promotion-ready within its recover timeout, or
// role_admission_failed for the G1 latch. Set together with
// eligible=false; empty when healthy.
string unhealthy_reason = 13;
}
// FrontendTarget — read-only frontend publication fact reported by
@@ -225,6 +231,14 @@ message StatusResponse {
string last_unsupported_reason = 6;
string last_convergence_stuck_at = 7;
repeated FrontendTarget frontends = 8;
// unhealthy_replicas lists the volume's replicas whose fresh
// heartbeat carries an explicit unhealthy reason (#128 rule 6).
repeated ReplicaUnhealthy unhealthy_replicas = 9;
}
message ReplicaUnhealthy {
string replica_id = 1;
string reason = 2;
}
message GetClusterStatusRequest {