From 6bf0445fcdec38174c6c7c19ed2888937827c591 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 01:04:57 -0800 Subject: [PATCH 1/5] host: recovery_stalled counts every synced startup slice and pauses for the master's authority wait The startup inactivity window renewed only on replay, scan, map and attach work. A new store's prezero and the WAL fence wrote and synced whole regions with no report, so on a slow disk the window could end inside one silent step; and the chunk layer's wait for master authority, a wait the master bounds, ran out the same window. - storage: phases RecoveryCreate and RecoveryFence; syncedSlices runs a sized step 4 MiB at a time and reports a slice only after its sync; prezeroNewStore uses it, and recovery reports the fence's synced bytes. - durable: create passes RecoveryProgress; AuthorityWait tells the host when the authority wait starts and ends; Chunk.AuthorityGap names the projection fields that withhold authority. - host: recovery_timeout becomes recovery_stalled; waits are counted, the window pauses while any runs and restarts when the last ends, a stall latched before stays latched; /status RecoveryWait=awaiting_authority. Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/durable_startup.go | 2 +- seaweed-block/cmd/blockvolume/main.go | 3 +- .../observation_store_duplicate_slot_test.go | 16 +- .../durable/authority_wait_hook_test.go | 57 +++++++ .../core/frontend/durable/provider.go | 13 +- .../core/frontend/durable/provider_chunk.go | 6 + .../master/recovery_watchdog_master_test.go | 34 ++-- .../core/host/volume/projection_bridge.go | 12 ++ .../volume/recovery_authority_wait_test.go | 124 ++++++++++++++ .../host/volume/recovery_lock_guard_test.go | 4 +- .../host/volume/recovery_progress_test.go | 8 +- .../host/volume/recovery_typed_reason_test.go | 6 +- .../core/host/volume/recovery_watchdog.go | 80 +++++++-- .../host/volume/recovery_watchdog_test.go | 34 ++-- .../core/host/volume/status_server.go | 5 + seaweed-block/core/rpc/control/control.pb.go | 4 +- seaweed-block/core/rpc/proto/control.proto | 4 +- seaweed-block/core/storage/data_sync.go | 31 ++-- .../storage/recovery_create_progress_test.go | 156 ++++++++++++++++++ .../core/storage/recovery_progress.go | 22 ++- seaweed-block/core/storage/walstore_v3.go | 11 +- seaweed-block/deploy/config/blockvolume.env | 5 +- seaweed-block/docs/design/block-design.md | 2 +- seaweed-block/docs/design/invariants.md | 6 +- .../docs/design/kubernetes-block-design.md | 4 +- seaweed-block/docs/standalone-deployment.md | 2 +- seaweed-block/docs/status-schema.md | 2 + seaweed-block/docs/volume-lifecycle.md | 9 +- 28 files changed, 561 insertions(+), 101 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/authority_wait_hook_test.go create mode 100644 seaweed-block/core/host/volume/recovery_authority_wait_test.go create mode 100644 seaweed-block/core/storage/recovery_create_progress_test.go diff --git a/seaweed-block/cmd/blockvolume/durable_startup.go b/seaweed-block/cmd/blockvolume/durable_startup.go index 8ab0bc73a9..5aad1df110 100644 --- a/seaweed-block/cmd/blockvolume/durable_startup.go +++ b/seaweed-block/cmd/blockvolume/durable_startup.go @@ -39,7 +39,7 @@ const ( // durableStartupFaulted: the process stays up fail-closed, with frontend // I/O refused, and a primary assignment reports the reason at once. A // replay failure that cannot be classified is faulted too, as before, and -// is covered by the recovery_timeout fallback. An open failure that +// is covered by the recovery_stalled fallback. An open failure that // cannot be classified returns durableStartupFatal, keeping the earlier // exit. func openAndRecoverDurable(dp durableStartup, h localRecoveryHost, volumeID string, _ time.Duration) (durableStartupOutcome, string, error) { diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index dbfa2c89bc..fb725ce54d 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -206,7 +206,7 @@ func parseFlagsWithCgroup(args []string, readFile func(string) ([]byte, 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, "maximum inactivity without new completed recovery or attach work for a primary-assigned replica before it reports unhealthy (recovery_timeout); not a total startup deadline") + fs.DurationVar(&f.recoverTimeout, "recover-timeout", volume.DefaultRecoverTimeout, "maximum inactivity without new completed recovery or attach work for a primary-assigned replica before it reports unhealthy (recovery_stalled); a wait for master authority pauses it; not a total startup deadline") fs.BoolVar(&f.workspaceLease, "workspace-lease", false, "required for walstore-chunk: 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") @@ -735,6 +735,7 @@ func runVolume(f flags, exits *processExit) int { var dp *durable.DurableProvider cfg := durable.ProviderConfig{ RecoveryProgress: h.ReportRecoveryProgress, + AuthorityWait: h.ReportAuthorityWait, Impl: durable.ImplName(f.durableImpl), StorageRoot: f.durableRoot, BlockSize: blockSize, diff --git a/seaweed-block/core/authority/observation_store_duplicate_slot_test.go b/seaweed-block/core/authority/observation_store_duplicate_slot_test.go index 5fb4578206..f955891d89 100644 --- a/seaweed-block/core/authority/observation_store_duplicate_slot_test.go +++ b/seaweed-block/core/authority/observation_store_duplicate_slot_test.go @@ -25,12 +25,12 @@ func TestObservationStore_DuplicateSlotKeysRefused(t *testing.T) { name string slots []SlotFact }{ - {"conflicting", []SlotFact{slotWith(""), slotWith("recovery_timeout")}}, - {"identical", []SlotFact{slotWith("recovery_timeout"), slotWith("recovery_timeout")}}, + {"conflicting", []SlotFact{slotWith(""), slotWith("recovery_stalled")}}, + {"identical", []SlotFact{slotWith("recovery_stalled"), slotWith("recovery_stalled")}}, } { 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 { + if _, err := s.IngestWithHealthTransitions(Observation{ServerID: "s1", ObservedAt: base, Slots: []SlotFact{slotWith("recovery_stalled")}}); err != nil { t.Fatal(err) } rev := s.Snapshot().revision @@ -44,8 +44,8 @@ func TestObservationStore_DuplicateSlotKeysRefused(t *testing.T) { 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) + if f, ok := s.SlotFact("v1", "r1"); !ok || f.UnhealthyReason != "recovery_stalled" { + t.Fatalf("stored slot after refusal: %+v %t; want the earlier recovery_stalled fact", f, ok) } }) } @@ -61,13 +61,13 @@ func TestObservationStore_UniqueMultiSlotTransitions(t *testing.T) { t.Fatal(err) } a2, b2 := a, b - a2.Eligible, a2.UnhealthyReason = false, "recovery_timeout" + a2.Eligible, a2.UnhealthyReason = false, "recovery_stalled" 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) + if len(tr) != 2 || tr[0].VolumeID != "v1" || tr[0].New != "recovery_stalled" || tr[1].VolumeID != "v2" || tr[1].New != "role_admission_failed" { + t.Fatalf("transitions %+v; want v1 -> recovery_stalled and v2 -> role_admission_failed", tr) } } diff --git a/seaweed-block/core/frontend/durable/authority_wait_hook_test.go b/seaweed-block/core/frontend/durable/authority_wait_hook_test.go new file mode 100644 index 0000000000..fa61a53517 --- /dev/null +++ b/seaweed-block/core/frontend/durable/authority_wait_hook_test.go @@ -0,0 +1,57 @@ +package durable_test + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" +) + +// The chunk layer's wait for master authority is visible to the host +// (AuthorityWait true, then false when the layer attaches) and in the +// durable status, with the projection fields that withhold authority. +func TestAuthorityWaitIsReportedAndShowsItsGap(t *testing.T) { + var mu sync.Mutex + var seen []bool + view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) + cfg := durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, + BlockSize: 4096, ChunkBlocks: 4, + AuthorityWait: func(waiting bool) { + mu.Lock() + seen = append(seen, waiting) + mu.Unlock() + }, + } + testutil.NewLayoutFixture(t, "v1", 64, 4).Configure(&cfg) + p, err := durable.NewDurableProvider(cfg, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + waitFor(t, 20*time.Second, "the wait reported and shown", func() bool { + st := p.DurableStatuses() + mu.Lock() + defer mu.Unlock() + return len(seen) == 1 && seen[0] && len(st) == 1 && st[0].Chunk != nil && + st[0].Chunk.AwaitingAuthority && st[0].Chunk.AuthorityGap != "" + }) + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 2})) + waitFor(t, 20*time.Second, "the wait's end reported after attach", func() bool { + st := p.DurableStatuses() + mu.Lock() + defer mu.Unlock() + return len(seen) == 2 && !seen[1] && len(st) == 1 && st[0].Chunk != nil && + st[0].Chunk.Attached && !st[0].Chunk.AwaitingAuthority && st[0].Chunk.AuthorityGap == "" + }) +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 56038228d9..ddc8988576 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -121,8 +121,13 @@ var ErrDetachOutcomeUnknown = errors.New("durable: detach outcome unknown; I/O s // ProviderConfig configures a DurableProvider. type ProviderConfig struct { - // RecoveryProgress observes completed local-open work before RecoverVolume. + // RecoveryProgress observes completed local-create and local-open work + // before RecoverVolume. RecoveryProgress func(storage.RecoveryPhase, uint64) + // AuthorityWait observes the chunk layer's wait for master authority: + // true when a recovered volume starts waiting, false when the wait ends. + // The wait is bounded by the master, not by local recovery progress. + AuthorityWait func(waiting bool) // Impl selects which LogicalStorage implementation to open or // create. Zero value (ImplAuto): an existing volume opens with its // on-disk implementation, and a new volume is created as walstore. @@ -430,6 +435,7 @@ type ChunkStatus struct { Maintenance *MaintenanceStatus `json:",omitempty"` // the holder maintenance loop; absent when disabled Attached bool // the chunk layer is attached to the remote AwaitingAuthority bool // recovered; the layer waits for master authority to attach + AuthorityGap string `json:",omitempty"` // while awaiting: the projection fields that withhold authority Fenced bool // a newer holder fenced this layer: it publishes nothing RemoteLSN uint64 // the LSN of the remote HEAD (what the remote holds durably) Stats storage.ChunkLayerStats // the layer's cut counters; zero until attached @@ -840,6 +846,9 @@ func (p *DurableProvider) DurableStatuses() []VolumeStatus { st := h.backend.durableStatus(volumeID, h.path, string(h.impl)) if cv, ok := chunks[volumeID]; ok { cs := &ChunkStatus{AwaitingAuthority: cv.awaiting} + if cv.awaiting { + cs.AuthorityGap = chunkAuthorityGap(p.view.Projection(), volumeID) + } if counts, ok := cv.head.(interface { HeadWriteOutcomes() (map[layout.HeadWriteCause]uint64, map[layout.HeadWriteCause]uint64) }); ok { @@ -1079,7 +1088,7 @@ func (p *DurableProvider) createFresh(volumeID, path string, impl ImplName) (*vo if p.testWALStoreFactory != nil { ws, err = p.testWALStoreFactory(path, true) } else { - ws, err = storage.CreateWALStoreWithOptions(path, p.cfg.NumBlocks, p.cfg.BlockSize, storage.WALStoreOptions{ChunkBlocks: p.cfg.ChunkBlocks}) + ws, err = storage.CreateWALStoreWithOptions(path, p.cfg.NumBlocks, p.cfg.BlockSize, storage.WALStoreOptions{ChunkBlocks: p.cfg.ChunkBlocks, RecoveryProgress: p.cfg.RecoveryProgress}) } if err != nil { return nil, fmt.Errorf("durable: CreateWALStore %s: %w", path, err) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index d58be97bca..f9547f70e0 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -184,6 +184,12 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen } log.Printf("durable: chunk layer for volume=%s waits for master authority (%s): projection lacks %s", volumeID, bound, chunkAuthorityGap(p.view.Projection(), volumeID)) + // The wait's bound is the master's: the startup stall window pauses + // for it and restarts when it ends. + if aw := p.cfg.AuthorityWait; aw != nil { + aw(true) + defer aw(false) + } ended := "superseded by a later recovery" defer func() { log.Printf("durable: chunk authority wait for volume=%s ended after %s: %s", volumeID, time.Since(start), ended) 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 d0964a72ac..c45fd98e20 100644 --- a/seaweed-block/core/host/master/recovery_watchdog_master_test.go +++ b/seaweed-block/core/host/master/recovery_watchdog_master_test.go @@ -100,7 +100,7 @@ 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, ""}) + reportRF3(t, svc, wireSlot{"r1-b", false, "recovery_stalled"}, wireSlot{"r2-a", false, ""}, wireSlot{"r3-a", false, ""}) if _, err := h.RunLifecycleProductTick(); err != nil { t.Fatalf("product tick: %v", err) } @@ -108,11 +108,11 @@ func TestRecoveryWatchdog_MasterNoQualifiedPeerPromotesNobody(t *testing.T) { 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 got := unhealthyReplicas(t, svc); got["r1"] != "recovery_stalled" || len(got) != 1 { + t.Fatalf("volume status unhealthy replicas=%v; want r1=recovery_stalled", got) } - if !timelineHasEvent(timelineEvents(t, svc), "replica_unhealthy", "recovery_timeout") { - t.Fatalf("timeline has no replica_unhealthy/recovery_timeout event") + if !timelineHasEvent(timelineEvents(t, svc), "replica_unhealthy", "recovery_stalled") { + t.Fatalf("timeline has no replica_unhealthy/recovery_stalled event") } reportRF3(t, svc, wireSlot{"r1-b", true, ""}, wireSlot{"r2-a", false, ""}, wireSlot{"r3-a", false, ""}) @@ -121,7 +121,7 @@ func TestRecoveryWatchdog_MasterNoQualifiedPeerPromotesNobody(t *testing.T) { } cleared := false for _, e := range timelineEvents(t, svc) { - if e.GetEventType() == "replica_unhealthy_cleared" && e.GetReplicaId() == "r1" && e.GetOldValue() == "recovery_timeout" { + if e.GetEventType() == "replica_unhealthy_cleared" && e.GetReplicaId() == "r1" && e.GetOldValue() == "recovery_stalled" { cleared = true } } @@ -138,7 +138,7 @@ func TestRecoveryWatchdog_MasterUnhealthyFailsOverToQualifiedPeer(t *testing.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, ""}) + reportRF3(t, svc, wireSlot{"r1-b", false, "recovery_stalled"}, wireSlot{"r2-a", true, ""}, wireSlot{"r3-a", false, ""}) if _, err := h.RunLifecycleProductTick(); err != nil { t.Fatalf("product tick: %v", err) } @@ -155,7 +155,7 @@ func TestRecoveryWatchdog_MasterWaitsWhenALaggingReplicaHoldsTheHighestEnd(t *te defer closeTestMaster(t, h) h.SetPromotionEvidenceProvider(&switchProbe{r3End: 80}) - reportRF3(t, svc, wireSlot{"r1-b", false, "recovery_timeout"}, wireSlot{"r2-a", true, ""}, wireSlot{"r3-a", false, ""}) + reportRF3(t, svc, wireSlot{"r1-b", false, "recovery_stalled"}, wireSlot{"r2-a", true, ""}, wireSlot{"r3-a", false, ""}) if _, err := h.RunLifecycleProductTick(); err != nil { t.Fatalf("product tick: %v", err) } @@ -241,7 +241,7 @@ func TestRecoveryWatchdog_MasterConcurrentHeartbeatsKeepBothTransitions(t *testi case <-time.After(300 * time.Millisecond): } }) - reportR1(t, svc, wireSlot{"r1-b", false, "recovery_timeout"}, t0) // unhealthy + reportR1(t, svc, wireSlot{"r1-b", false, "recovery_stalled"}, t0) // unhealthy <-done got := r1HealthEvents(t, svc) if len(got) != 2 || got[0] != "replica_unhealthy" || got[1] != "replica_unhealthy_cleared" { @@ -258,9 +258,9 @@ func TestRecoveryWatchdog_MasterExpiryFabricatesNoClear(t *testing.T) { 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) + reportR1(t, svc, wireSlot{"r1-b", false, "recovery_stalled"}, 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)) + reportR1(t, svc, wireSlot{"r1-b", false, "recovery_stalled"}, 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)) @@ -273,7 +273,7 @@ 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", false, "recovery_stalled"}, 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) @@ -286,7 +286,7 @@ 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) + reportR1(t, svc, wireSlot{"r1-b", false, "recovery_stalled"}, t0) before := r1HealthEvents(t, svc) slot := func(reason string) *control.HeartbeatSlot { @@ -296,8 +296,8 @@ func TestRecoveryWatchdog_MasterDuplicateSlotHeartbeatRefused(t *testing.T) { } } for i, slots := range [][]*control.HeartbeatSlot{ - {slot(""), slot("recovery_timeout")}, // conflicting - {slot("recovery_timeout"), slot("recovery_timeout")}, // identical + {slot(""), slot("recovery_stalled")}, // conflicting + {slot("recovery_stalled"), slot("recovery_stalled")}, // identical } { _, err := svc.ReportHeartbeat(auth.DevCall(context.Background()), &control.HeartbeatReport{ ServerId: "node-a", SentAt: timestamppb.New(t0.Add(time.Duration(i+1) * time.Millisecond)), @@ -310,7 +310,7 @@ func TestRecoveryWatchdog_MasterDuplicateSlotHeartbeatRefused(t *testing.T) { 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) + if got := unhealthyReplicas(t, svc); got["r1"] != "recovery_stalled" { + t.Fatalf("volume status after refusal: %v; want r1=recovery_stalled", got) } } diff --git a/seaweed-block/core/host/volume/projection_bridge.go b/seaweed-block/core/host/volume/projection_bridge.go index d63b29de93..a54d23e8dd 100644 --- a/seaweed-block/core/host/volume/projection_bridge.go +++ b/seaweed-block/core/host/volume/projection_bridge.go @@ -230,6 +230,18 @@ func (v *AdapterProjectionView) unhealthyReason() string { return "" } +// recoveryWait is RecoveryAwaitingAuthority while the host's recovery +// window is paused for the master's authority wait, else "". +func (v *AdapterProjectionView) recoveryWait() string { + if v == nil || v.probe == nil { + return "" + } + if p, ok := v.probe.(interface{ AwaitingAuthority() bool }); ok && p.AwaitingAuthority() { + return RecoveryAwaitingAuthority + } + 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 { diff --git a/seaweed-block/core/host/volume/recovery_authority_wait_test.go b/seaweed-block/core/host/volume/recovery_authority_wait_test.go new file mode 100644 index 0000000000..e794fc9b42 --- /dev/null +++ b/seaweed-block/core/host/volume/recovery_authority_wait_test.go @@ -0,0 +1,124 @@ +package volume + +import ( + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// A recovery followed by the chunk layer's full wait for master authority +// (30 s of answered contact, then attach) reports no recovery_stalled: the +// window pauses for the wait and restarts when it ends. +func TestRecoveryStalled_FullAuthorityWaitDoesNotStall(t *testing.T) { + h, clk := watchdogHost(t, 30*time.Second) + h.applyFixtureFact(selfPrimaryFact(1)) + for slice := uint64(1); slice <= 16; slice++ { // a 64 MiB fence on a slow disk + clk.advance(time.Second) + h.ReportRecoveryProgress(storage.RecoveryFence, slice*4<<20) + } + clk.advance(20 * time.Second) // publication before the wait: inside the window + h.ReportAuthorityWait(true) + if got := NewStatusServer(h.view).statusProjection().RecoveryWait; got != RecoveryAwaitingAuthority { + t.Fatalf("/status RecoveryWait=%q during the wait; want %s", got, RecoveryAwaitingAuthority) + } + clk.advance(45 * time.Second) // the master's wait, longer than the window + if got := h.UnhealthyReason(); got != "" { + t.Fatalf("stalled during the authority wait: %q", got) + } + h.ReportRecoveryProgress(storage.RecoveryAttach, 1) + h.ReportAuthorityWait(false) + if got := NewStatusServer(h.view).statusProjection().RecoveryWait; got != "" { + t.Fatalf("/status RecoveryWait=%q after the wait", got) + } + clk.advance(29 * time.Second) + if got := h.UnhealthyReason(); got != "" { + t.Fatalf("stalled inside the window restarted by the wait's end: %q", got) + } + if r := h.unhealthyReason(readyAt(1), true); r != "" { + t.Fatalf("adoption after the wait: %q", r) + } + clk.advance(time.Hour) + if r := h.unhealthyReason(readyAt(1), false); r != "" { + t.Fatalf("adopted once, then not ready: %q", r) + } +} + +// A silent step beyond the window is still caught: fence slices renew the +// window, the silence after them does not, and a later authority wait does +// not hide a stall already latched. +func TestRecoveryStalled_SilentStepBeyondTheWindowIsCaught(t *testing.T) { + h, clk := watchdogHost(t, 30*time.Second) + h.applyFixtureFact(selfPrimaryFact(1)) + for slice := uint64(1); slice <= 4; slice++ { + clk.advance(time.Second) + h.ReportRecoveryProgress(storage.RecoveryFence, slice*4<<20) + } + clk.advance(31 * time.Second) + if got := h.UnhealthyReason(); got != UnhealthyRecoveryStalled { + t.Fatalf("a silent fence slice past the window: %q", got) + } + h.ReportAuthorityWait(true) + clk.advance(time.Minute) + if got := h.UnhealthyReason(); got != UnhealthyRecoveryStalled { + t.Fatalf("the authority wait hid a latched stall: %q", got) + } +} + +// Create comes first in the fixed order: its slices renew the window, and +// a later phase after it is still new progress. +func TestRecoveryStalled_CreateSlicesRenewTheWindow(t *testing.T) { + h, clk := watchdogHost(t, 30*time.Second) + h.applyFixtureFact(selfPrimaryFact(1)) + for slice := uint64(1); slice <= 40; slice++ { // 160 MiB prezero at 4 MiB/s + clk.advance(time.Second) + h.ReportRecoveryProgress(storage.RecoveryCreate, slice*4<<20) + if got := h.UnhealthyReason(); got != "" { + t.Fatalf("create slice %d: %q", slice, got) + } + } + clk.advance(25 * time.Second) + h.ReportRecoveryProgress(storage.RecoveryOpenMap, 1) + clk.advance(25 * time.Second) + if got := h.UnhealthyReason(); got != "" { + t.Fatalf("open after create: %q", got) + } +} + +// Waits are counted: a superseded recovery's wait that ends after a newer +// wait started does not resume the window, and an unmatched end is ignored. +func TestRecoveryStalled_StaleWaitEndDoesNotResume(t *testing.T) { + h, clk := watchdogHost(t, 30*time.Second) + h.applyFixtureFact(selfPrimaryFact(1)) + h.ReportAuthorityWait(true) // recovery 1's wait + h.ReportAuthorityWait(true) // recovery 2's wait + h.ReportAuthorityWait(false) // recovery 1's wait ends late + clk.advance(time.Minute) + if got := h.UnhealthyReason(); got != "" || !h.AwaitingAuthority() { + t.Fatalf("a stale wait end resumed the window: reason %q awaiting %t", got, h.AwaitingAuthority()) + } + h.ReportAuthorityWait(false) // recovery 2's wait ends + h.ReportAuthorityWait(false) // unmatched + if h.AwaitingAuthority() { + t.Fatal("still paused after every wait ended") + } + clk.advance(31 * time.Second) + if got := h.UnhealthyReason(); got != UnhealthyRecoveryStalled { + t.Fatalf("window after the waits: %q", got) + } +} + +// Late synced progress after a genuine stall does not clear it. +func TestRecoveryStalled_LateSyncedSliceKeepsTheStall(t *testing.T) { + h, clk := watchdogHost(t, 30*time.Second) + h.applyFixtureFact(selfPrimaryFact(1)) + h.ReportRecoveryProgress(storage.RecoveryFence, 4<<20) + clk.advance(31 * time.Second) + if got := h.UnhealthyReason(); got != UnhealthyRecoveryStalled { + t.Fatalf("held sync past the window: %q", got) + } + h.ReportRecoveryProgress(storage.RecoveryFence, 8<<20) // the held sync returns + if got := h.UnhealthyReason(); got != UnhealthyRecoveryStalled { + t.Fatalf("a late slice cleared a reported stall: %q", got) + } +} diff --git a/seaweed-block/core/host/volume/recovery_lock_guard_test.go b/seaweed-block/core/host/volume/recovery_lock_guard_test.go index 5f6d1db5a7..e6007f45fb 100644 --- a/seaweed-block/core/host/volume/recovery_lock_guard_test.go +++ b/seaweed-block/core/host/volume/recovery_lock_guard_test.go @@ -38,8 +38,8 @@ func TestRecoveryWatchdogLockedMethodsNeverCallStorageOrWait(t *testing.T) { t.Errorf("watchdog-locked %s: %s", fn.Name.Name, violation) } } - if locked != 7 { - t.Fatalf("watchdog lock sites=%d, want 7 reviewed methods", locked) + if locked != 9 { + t.Fatalf("watchdog lock sites=%d, want 9 reviewed methods", locked) } } diff --git a/seaweed-block/core/host/volume/recovery_progress_test.go b/seaweed-block/core/host/volume/recovery_progress_test.go index 6bcb43d462..066db4bd5c 100644 --- a/seaweed-block/core/host/volume/recovery_progress_test.go +++ b/seaweed-block/core/host/volume/recovery_progress_test.go @@ -18,7 +18,7 @@ func TestRecoveryProgress_CountingEntriesOutliveTheTotalWindow(t *testing.T) { } } clk.advance(30 * time.Second) - if got := h.UnhealthyReason(); got != UnhealthyRecoveryTimeout { + if got := h.UnhealthyReason(); got != UnhealthyRecoveryStalled { t.Fatalf("no entries for the window: %q", got) } } @@ -34,12 +34,12 @@ func TestRecoveryProgress_RepeatedAttachPreparationDoesNotRenew(t *testing.T) { h.ReportRecoveryProgress(storage.RecoveryAttach, 0) h.ReportRecoveryProgress(storage.RecoveryAttach, 262144) } - if got := h.UnhealthyReason(); got != UnhealthyRecoveryTimeout { + if got := h.UnhealthyReason(); got != UnhealthyRecoveryStalled { t.Fatalf("retried preparation kept failed attach alive: %q", got) } // Late progress must not undo a timeout's already reported outcome. h.ReportRecoveryProgress(storage.RecoveryAttach, 262145) - if got := h.UnhealthyReason(); got != UnhealthyRecoveryTimeout { + if got := h.UnhealthyReason(); got != UnhealthyRecoveryStalled { t.Fatalf("late progress cleared timeout: %q", got) } } @@ -49,7 +49,7 @@ func TestRecoveryProgress_LateEntryCannotHideAnUnobservedStall(t *testing.T) { h.applyFixtureFact(selfPrimaryFact(1)) clk.advance(31 * time.Second) h.ReportRecoveryProgress(storage.RecoveryScan, 1) - if got := h.UnhealthyReason(); got != UnhealthyRecoveryTimeout { + if got := h.UnhealthyReason(); got != UnhealthyRecoveryStalled { t.Fatalf("late entry hid stall: %q", got) } } diff --git a/seaweed-block/core/host/volume/recovery_typed_reason_test.go b/seaweed-block/core/host/volume/recovery_typed_reason_test.go index 94d1caeeb1..7e83addb3f 100644 --- a/seaweed-block/core/host/volume/recovery_typed_reason_test.go +++ b/seaweed-block/core/host/volume/recovery_typed_reason_test.go @@ -124,7 +124,7 @@ func TestLocalRecoveryFailure_CorruptWALReportsWALCorruptAtOnce(t *testing.T) { // Scope and fallback: a replica that is not primary-assigned is not // flagged by a local failure; an unclassified failure reports nothing -// early and recovery_timeout still covers it. +// early and recovery_stalled still covers it. func TestLocalRecoveryFailure_ScopeAndUnclassifiedFallback(t *testing.T) { h, clk := watchdogHost(t, 10*time.Second) h.ReportLocalRecoveryFailure(storage.NewSubstrateIOFailure(errors.New("read"), "replay")) @@ -143,8 +143,8 @@ func TestLocalRecoveryFailure_ScopeAndUnclassifiedFallback(t *testing.T) { t.Fatalf("unclassified failure inside the timeout: reason=%q; want none yet", s.UnhealthyReason) } clk2.advance(11 * time.Second) - if s := reportSlot(t, h2); s.UnhealthyReason != UnhealthyRecoveryTimeout { - t.Fatalf("unclassified failure past the timeout: reason=%q; want %s", s.UnhealthyReason, UnhealthyRecoveryTimeout) + if s := reportSlot(t, h2); s.UnhealthyReason != UnhealthyRecoveryStalled { + t.Fatalf("unclassified failure past the timeout: reason=%q; want %s", s.UnhealthyReason, UnhealthyRecoveryStalled) } _ = clk } diff --git a/seaweed-block/core/host/volume/recovery_watchdog.go b/seaweed-block/core/host/volume/recovery_watchdog.go index e58708851a..ee787e8ba5 100644 --- a/seaweed-block/core/host/volume/recovery_watchdog.go +++ b/seaweed-block/core/host/volume/recovery_watchdog.go @@ -15,9 +15,10 @@ import ( // 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 -// inactivity window reports an explicit unhealthy fact (Eligible=false plus a typed -// reason) instead of staying silently not-ready, so the master fails over +// has completed no new work within the recover inactivity window, before +// it produced the engine's promotion-ready fact, 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. // @@ -27,7 +28,12 @@ import ( // - The window starts at the primary assignment in this incarnation and // advances only on a new (phase, cumulative completed work) high-water mark. // A new primary epoch restarts the window, not the process's work frontier. -// - recovery_timeout latches until a fresh promotion-ready fact clears +// Sized steps (create, fence) report each synced slice, so their cost on +// a slow disk is progress, not silence. +// - The window pauses while the recovered volume awaits master authority +// (awaiting_authority): that wait is bounded by the master, which sees +// the volume, not by local progress. It restarts when the wait ends. +// - recovery_stalled 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 @@ -47,10 +53,15 @@ import ( // with a classifiable error (LocalRecoveryHealthReason), a // primary-assigned replica reports that typed reason at once instead // of waiting out the timeout. An unclassified failure reports nothing -// early; recovery_timeout still covers it. +// early; recovery_stalled still covers it. const ( - UnhealthyRecoveryTimeout = "recovery_timeout" + // UnhealthyRecoveryStalled: no completed recovery, fence, create or + // attach work for the window. + UnhealthyRecoveryStalled = "recovery_stalled" + // RecoveryAwaitingAuthority: the recovered volume waits for master + // authority; the recovery_stalled window is paused (status RecoveryWait). + RecoveryAwaitingAuthority = "awaiting_authority" UnhealthyRoleAdmission = "role_admission_failed" UnhealthyWALCorrupt = "wal_corrupt" UnhealthyIOError = "io_error" @@ -75,7 +86,8 @@ type recoveryWatchdog struct { primaryEpoch uint64 supportingSince time.Time // zero unless admitted as a supporting replica supportingEpoch uint64 - timedOut bool // recovery_timeout latched until a ready fact + timedOut bool // recovery_stalled latched until a ready fact + awaiting int // authority waits in progress: the window is paused while > 0 readySeen bool // promotion-ready once in this primary assignment: disarmed progressPhase storage.RecoveryPhase progressDone uint64 @@ -91,7 +103,7 @@ func newRecoveryWatchdog(timeout time.Duration) *recoveryWatchdog { // ReportRecoveryProgress observes completed startup work; it grants no readiness. func (h *Host) ReportRecoveryProgress(phase storage.RecoveryPhase, done uint64) { - if h == nil || h.wd == nil || phase < storage.RecoveryOpenMap || phase > storage.RecoveryAttach || done == 0 { + if h == nil || h.wd == nil || phase < storage.RecoveryCreate || phase > storage.RecoveryAttach || done == 0 { return } w := h.wd @@ -107,12 +119,50 @@ func (h *Host) ReportRecoveryProgress(phase storage.RecoveryPhase, done uint64) if w.lastProgress.After(since) { since = w.lastProgress } - if !w.primarySince.IsZero() && !w.readySeen && now.Sub(since) >= w.timeout { + if !w.primarySince.IsZero() && !w.readySeen && w.awaiting == 0 && now.Sub(since) >= w.timeout { w.timedOut = true } w.progressPhase, w.progressDone, w.lastProgress = phase, done, now } +// ReportAuthorityWait observes the chunk layer's wait for master +// authority: true when a wait starts, false when that wait ends. Waits are +// counted, so a superseded recovery's wait ending late cannot resume the +// window while a newer wait still runs. While any wait lasts the stall +// window is paused; when the last one ends the window restarts. A stall +// latched before the wait stays latched. +func (h *Host) ReportAuthorityWait(waiting bool) { + if h == nil || h.wd == nil { + return + } + w := h.wd + w.mu.Lock() + defer w.mu.Unlock() + if waiting { + w.awaiting++ + return + } + if w.awaiting == 0 { + return // an end without its start: nothing to resume + } + w.awaiting-- + if w.awaiting == 0 { + w.lastProgress = w.now() + } +} + +// AwaitingAuthority reports whether the stall window is paused for the +// chunk layer's wait for master authority. +func (h *Host) AwaitingAuthority() bool { + if h == nil || h.wd == nil { + return false + } + w := h.wd + w.mu.Lock() + defer w.mu.Unlock() + return w.awaiting > 0 +} + // primaryAssigned records a primary assignment for this replica. A new // epoch restarts the timeout. func (w *recoveryWatchdog) primaryAssigned(epoch uint64) { @@ -156,7 +206,7 @@ func (w *recoveryWatchdog) supportingAdmitted(epoch uint64) { // 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. +// latched recovery_stalled. func (w *recoveryWatchdog) reason(ready bool, readyEpoch uint64, roleAdmissionFailed bool, localFailure string) (reason string, fired bool) { if w == nil { return "", false @@ -183,11 +233,11 @@ func (w *recoveryWatchdog) reason(ready bool, readyEpoch uint64, roleAdmissionFa if w.lastProgress.After(since) { since = w.lastProgress } - if !w.timedOut && w.now().Sub(since) >= w.timeout { + if !w.timedOut && w.awaiting == 0 && w.now().Sub(since) >= w.timeout { w.timedOut, fired = true, true } if w.timedOut { - return UnhealthyRecoveryTimeout, fired + return UnhealthyRecoveryStalled, fired } return "", false } @@ -226,8 +276,8 @@ func (h *Host) unhealthyReason(fact engine.PromotionReadyFact, ready bool) strin local, _ := h.localRecoveryReason.Load().(string) reason, fired := h.wd.reason(ready, fact.Epoch, failed, local) if fired { - h.log.Printf("blockvolume: volume %s primary assignment epoch=%d has no new recovery/attach work for %s: reporting unhealthy (%s)", - h.cfg.VolumeID, h.wd.epoch(), h.wd.timeout, UnhealthyRecoveryTimeout) + h.log.Printf("blockvolume: volume %s primary assignment epoch=%d completed no recovery work for %s: reporting unhealthy (%s)", + h.cfg.VolumeID, h.wd.epoch(), h.wd.timeout, UnhealthyRecoveryStalled) } return reason } @@ -249,7 +299,7 @@ func (h *Host) CatchUpSince() time.Time { // LocalRecoveryHealthReason classifies a local durable open or replay // failure into a typed unhealthy reason (#133). It returns "" for an -// error it cannot classify (the watchdog's timeout still covers that). +// error it cannot classify (recovery_stalled still covers that). // // - wal_corrupt: the substrate found a WAL/extent integrity fault // (storage.RecoveryFailure kind WALIntegrity, or ErrWALIntegrityFault). diff --git a/seaweed-block/core/host/volume/recovery_watchdog_test.go b/seaweed-block/core/host/volume/recovery_watchdog_test.go index 5ec6552fb2..a048c134f5 100644 --- a/seaweed-block/core/host/volume/recovery_watchdog_test.go +++ b/seaweed-block/core/host/volume/recovery_watchdog_test.go @@ -43,7 +43,7 @@ func reportSlot(t *testing.T, h *Host) *control.HeartbeatSlot { } // The heartbeat of a primary-assigned, not-ready replica turns explicit -// unhealthy (Eligible=false, recovery_timeout) once the timeout elapses. +// unhealthy (Eligible=false, recovery_stalled) once the timeout elapses. func TestRecoveryWatchdog_PrimaryNotReadyPastTimeoutReportsUnhealthy(t *testing.T) { h, clk := watchdogHost(t, 30*time.Second) h.applyFixtureFact(selfPrimaryFact(1)) @@ -53,10 +53,10 @@ func TestRecoveryWatchdog_PrimaryNotReadyPastTimeoutReportsUnhealthy(t *testing. 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 s := reportSlot(t, h); s.Eligible || s.UnhealthyReason != UnhealthyRecoveryStalled { + t.Fatalf("past the recover timeout: eligible=%t reason=%q; want ineligible, %s", s.Eligible, s.UnhealthyReason, UnhealthyRecoveryStalled) } - if got := h.UnhealthyReason(); got != UnhealthyRecoveryTimeout { + if got := h.UnhealthyReason(); got != UnhealthyRecoveryStalled { t.Fatalf("UnhealthyReason()=%q", got) } } @@ -76,7 +76,7 @@ func TestRecoveryWatchdog_SupportingReplicaNotFlagged(t *testing.T) { } } -// recovery_timeout latches until a fresh ready fact clears it; once +// recovery_stalled 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) { @@ -86,10 +86,10 @@ func TestRecoveryWatchdog_ReadyClearsAndDisarmsNewEpochRearms(t *testing.T) { w.primaryAssigned(1) clk.advance(11 * time.Second) - if r, fired := w.reason(false, 0, false, ""); r != UnhealthyRecoveryTimeout || !fired { + if r, fired := w.reason(false, 0, false, ""); r != UnhealthyRecoveryStalled || !fired { t.Fatalf("past timeout: %q fired=%t", r, fired) } - if r, fired := w.reason(false, 0, false, ""); r != UnhealthyRecoveryTimeout || fired { + if r, fired := w.reason(false, 0, false, ""); r != UnhealthyRecoveryStalled || fired { t.Fatalf("latched: %q fired=%t; want the reason, fired only once", r, fired) } if r, _ := w.reason(true, 1, false, ""); r != "" { @@ -105,7 +105,7 @@ func TestRecoveryWatchdog_ReadyClearsAndDisarmsNewEpochRearms(t *testing.T) { t.Fatalf("new epoch inside timeout: %q", r) } clk.advance(2 * time.Second) - if r, _ := w.reason(false, 0, false, ""); r != UnhealthyRecoveryTimeout { + if r, _ := w.reason(false, 0, false, ""); r != UnhealthyRecoveryStalled { t.Fatalf("new epoch past timeout: %q", r) } } @@ -130,8 +130,8 @@ func TestRecoveryWatchdog_StatusShowsReasonAndCatchUp(t *testing.T) { h.applyFixtureFact(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) + if got := s.statusProjection().UnhealthyReason; got != UnhealthyRecoveryStalled { + t.Fatalf("/status UnhealthyReason=%q; want %s", got, UnhealthyRecoveryStalled) } h2 := newTestVolumeHost(t) @@ -145,7 +145,7 @@ func TestRecoveryWatchdog_StatusShowsReasonAndCatchUp(t *testing.T) { // 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. +// no recovery_stalled, however long it lasts. func TestRecoveryWatchdog_ReadyThenLaterNotReadyReportsNoTimeout(t *testing.T) { h, clk := watchdogHost(t, 10*time.Second) h.applyFixtureFact(selfPrimaryFact(1)) @@ -155,7 +155,7 @@ func TestRecoveryWatchdog_ReadyThenLaterNotReadyReportsNoTimeout(t *testing.T) { } 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) + t.Fatalf("not ready an hour after being ready, same incarnation: %q; want no recovery_stalled", r) } h.applyFixtureFact(selfPrimaryFact(1)) // the same assignment replayed: still disarmed clk.advance(time.Hour) @@ -166,7 +166,7 @@ func TestRecoveryWatchdog_ReadyThenLaterNotReadyReportsNoTimeout(t *testing.T) { // 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. +// reports recovery_stalled even for the same primary epoch. func TestRecoveryWatchdog_NewIncarnationRearms(t *testing.T) { old, clk := watchdogHost(t, 10*time.Second) old.applyFixtureFact(selfPrimaryFact(1)) @@ -180,8 +180,8 @@ func TestRecoveryWatchdog_NewIncarnationRearms(t *testing.T) { } restarted.applyFixtureFact(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) + if s := reportSlot(t, restarted); s.Eligible || s.UnhealthyReason != UnhealthyRecoveryStalled { + t.Fatalf("restarted process past timeout: eligible=%t reason=%q; want ineligible, %s", s.Eligible, s.UnhealthyReason, UnhealthyRecoveryStalled) } clk.advance(time.Hour) if r := old.unhealthyReason(readyAt(1), false); r != "" { @@ -224,8 +224,8 @@ func TestRecoveryWatchdog_OldEpochReadyDoesNotDisarmNewAssignment(t *testing.T) 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) + if s := reportSlot(t, h); s.Eligible || s.UnhealthyReason != UnhealthyRecoveryStalled { + t.Fatalf("epoch 3 never admitted, engine ready only at epoch 2: eligible=%t reason=%q; want %s", s.Eligible, s.UnhealthyReason, UnhealthyRecoveryStalled) } *ready = engine.PromotionReadyFact{Ready: true, Epoch: 3, EndpointVersion: 1, ReplicaID: "rB"} diff --git a/seaweed-block/core/host/volume/status_server.go b/seaweed-block/core/host/volume/status_server.go index 4dd71e8ff0..633ff396f0 100644 --- a/seaweed-block/core/host/volume/status_server.go +++ b/seaweed-block/core/host/volume/status_server.go @@ -217,6 +217,10 @@ type StatusProjection struct { // UnhealthyReason is the slot's explicit unhealthy report (#128 rule // 6), the value its heartbeat carries; empty when healthy. UnhealthyReason string `json:",omitempty"` + // RecoveryWait names a wait that pauses the recovery_stalled window: + // awaiting_authority while the recovered volume waits for master + // authority (the master bounds it); empty otherwise. + RecoveryWait 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"` @@ -687,6 +691,7 @@ func (s *StatusServer) authorityProjection() StatusProjection { ReplicationRole: replicationRole, RoleAdmissionFailure: s.view.roleAdmissionReason(), UnhealthyReason: s.view.unhealthyReason(), + RecoveryWait: s.view.recoveryWait(), } if warning := s.view.assignmentEndpointWarning(); warning != "" { out.Warnings = append(out.Warnings, warning) diff --git a/seaweed-block/core/rpc/control/control.pb.go b/seaweed-block/core/rpc/control/control.pb.go index 4bb6895e17..bc7d6a584a 100644 --- a/seaweed-block/core/rpc/control/control.pb.go +++ b/seaweed-block/core/rpc/control/control.pb.go @@ -596,8 +596,8 @@ type HeartbeatSlot struct { // only to bound a restarted primary's boot grace. Incarnation string `protobuf:"bytes,12,opt,name=incarnation,proto3" json:"incarnation,omitempty"` // 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 + // (#128 rule 6): recovery_stalled when a primary-assigned replica + // completed no recovery work within its recover window, or // role_admission_failed for the G1 latch. Set together with // eligible=false; empty when healthy. UnhealthyReason string `protobuf:"bytes,13,opt,name=unhealthy_reason,json=unhealthyReason,proto3" json:"unhealthy_reason,omitempty"` diff --git a/seaweed-block/core/rpc/proto/control.proto b/seaweed-block/core/rpc/proto/control.proto index 3f1eebcca7..63c3671e23 100644 --- a/seaweed-block/core/rpc/proto/control.proto +++ b/seaweed-block/core/rpc/proto/control.proto @@ -234,8 +234,8 @@ message HeartbeatSlot { // 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 + // (#128 rule 6): recovery_stalled when a primary-assigned replica + // completed no recovery work within its recover window, or // role_admission_failed for the G1 latch. Set together with // eligible=false; empty when healthy. string unhealthy_reason = 13; diff --git a/seaweed-block/core/storage/data_sync.go b/seaweed-block/core/storage/data_sync.go index d9c09de74e..b0e715b98c 100644 --- a/seaweed-block/core/storage/data_sync.go +++ b/seaweed-block/core/storage/data_sync.go @@ -96,7 +96,8 @@ func configuredAllocationMode() (string, error) { } // Only newly-created files reach this hook; existing bytes are never rewritten. -func prezeroNewStore(f *os.File, size int64) error { +// Each synced slice is reported to progress (nil: not reported). +func prezeroNewStore(f *os.File, size int64, progress *recoveryReporter) error { mode, err := configuredAllocationMode() if err != nil { return err @@ -105,19 +106,23 @@ func prezeroNewStore(f *os.File, size int64) error { return nil } zero := make([]byte, 1<<20) - for off := int64(0); off < size; { - b := zero[:min(int64(len(zero)), size-off)] - n, err := f.WriteAt(b, off) - if err != nil { - return fmt.Errorf("storage: prezero: %w", err) + // Allocation/size/extent metadata must be fully durable before the check: + // every slice is synced, the last one included. + err = syncedSlices(uint64(size), func(base, n uint64) error { + for off := uint64(0); off < n; { + b := zero[:min(uint64(len(zero)), n-off)] + w, err := f.WriteAt(b, int64(base+off)) + if err != nil { + return fmt.Errorf("storage: prezero: %w", err) + } + if w != len(b) { + return io.ErrShortWrite + } + off += uint64(w) } - if n != len(b) { - return io.ErrShortWrite - } - off += int64(n) - } - // Allocation/size/extent metadata must be fully durable before the check. - if err := f.Sync(); err != nil { + return f.Sync() + }, progress) + if err != nil { return err } if err := verifyInitializedFile(f); err != nil { diff --git a/seaweed-block/core/storage/recovery_create_progress_test.go b/seaweed-block/core/storage/recovery_create_progress_test.go new file mode 100644 index 0000000000..45a1e6398c --- /dev/null +++ b/seaweed-block/core/storage/recovery_create_progress_test.go @@ -0,0 +1,156 @@ +package storage + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" + "time" +) + +// A sized step counts each slice only after its sync: a failed step reports +// the slices before it and never the bytes written but not synced. +func TestSyncedSlicesCountOnlySyncedSlices(t *testing.T) { + var reports []uint64 + ctx := WithRecoveryProgress(context.Background(), func(phase RecoveryPhase, done uint64) { + if phase != RecoveryCreate { + t.Fatalf("phase %d", phase) + } + reports = append(reports, done) + }) + injected := errors.New("injected sync failure") + calls := 0 + err := syncedSlices(5*fenceSliceBytes, func(off, n uint64) error { + calls++ + if calls == 3 { + return injected // the write of slice 3 happened, its sync did not + } + return nil + }, newRecoveryReporter(ctx, RecoveryCreate)) + if !errors.Is(err, injected) { + t.Fatalf("err = %v", err) + } + if len(reports) != 2 || reports[1] != 2*fenceSliceBytes { + t.Fatalf("reports %v; want the two synced slices, 8 MiB", reports) + } +} + +// A new store's prezero reports each synced slice as RecoveryCreate, up to +// the file's whole size, through the options production passes on create. +func TestPrezeroReportsEachSyncedSlice(t *testing.T) { + t.Setenv("SWBLOCK_ALLOCATION", "prezero") + if _, err := configuredAllocationMode(); err != nil { + t.Skipf("prezero unavailable here: %v", err) + } + var reports []uint64 + path := filepath.Join(t.TempDir(), "volume") + s, err := CreateWALStoreWithOptions(path, 4096, 4096, WALStoreOptions{RecoveryProgress: func(phase RecoveryPhase, done uint64) { + if phase != RecoveryCreate { + return + } + if len(reports) > 0 && done <= reports[len(reports)-1] { + t.Fatalf("non-monotone create progress %v then %d", reports, done) + } + reports = append(reports, done) + }}) + if err != nil { + t.Fatal(err) + } + defer s.Close() + fi, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + want := uint64(fi.Size()) + slices := (want + fenceSliceBytes - 1) / fenceSliceBytes + if len(reports) == 0 || reports[len(reports)-1] != want || uint64(len(reports)) != slices { + t.Fatalf("create reports %v; want %d slices ending at the file size %d", reports, slices, want) + } +} + +// Recovery reports the fence's bytes as RecoveryFence once they are synced: +// a reopened store's recovery fences its whole unused WAL region. +func TestRecoveryReportsTheSyncedFence(t *testing.T) { + const wal = 1 << 20 + path := filepath.Join(t.TempDir(), "volume") + created, err := createWALStoreV3ForTest(path, 256, 4096, wal, WModeStrict) + if err != nil { + t.Fatal(err) + } + if err := created.Close(); err != nil { + t.Fatal(err) + } + s, err := openUnmappedWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + defer s.Close() + var fenced uint64 + ctx := WithRecoveryProgress(context.Background(), func(phase RecoveryPhase, done uint64) { + if phase == RecoveryFence { + fenced = done + } + }) + if _, err := s.RecoverContext(ctx); err != nil { + t.Fatal(err) + } + if fenced != wal { + t.Fatalf("fence progress %d; want the whole WAL region %d", fenced, wal) + } +} + +// A fence slice held in its fsync reports nothing until the sync returns; +// once released, recovery finishes (the caller joins it) and every slice +// has been reported. +func TestRecoveryFenceHeldSyncReportsAfterRelease(t *testing.T) { + const wal = 3 * fenceSliceBytes + path := filepath.Join(t.TempDir(), "volume") + created, err := createWALStoreV3ForTest(path, 256, 4096, wal, WModeStrict) + if err != nil { + t.Fatal(err) + } + if err := created.Close(); err != nil { + t.Fatal(err) + } + s, err := openUnmappedWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + defer s.Close() + held, release := make(chan struct{}), make(chan struct{}) + first := true + s.testAfterFenceFsync = func() { + if first { + first = false + close(held) + <-release + } + } + reports := make(chan uint64, 8) + ctx := WithRecoveryProgress(context.Background(), func(phase RecoveryPhase, done uint64) { + if phase == RecoveryFence { + reports <- done + } + }) + done := make(chan error, 1) + go func() { _, err := s.RecoverContext(ctx); done <- err }() + <-held + select { + case n := <-reports: + t.Fatalf("a held slice reported %d bytes before its sync returned", n) + case <-time.After(100 * time.Millisecond): + } + close(release) + if err := <-done; err != nil { + t.Fatalf("recovery after the held sync: %v", err) + } + close(reports) + var got []uint64 + for n := range reports { + got = append(got, n) + } + if len(got) != 3 || got[2] != wal { + t.Fatalf("fence reports %v; want 3 slices ending at %d", got, uint64(wal)) + } +} diff --git a/seaweed-block/core/storage/recovery_progress.go b/seaweed-block/core/storage/recovery_progress.go index d7c7189fc5..2731a9f621 100644 --- a/seaweed-block/core/storage/recovery_progress.go +++ b/seaweed-block/core/storage/recovery_progress.go @@ -10,7 +10,9 @@ import ( type RecoveryPhase uint8 const ( - RecoveryOpenMap RecoveryPhase = iota + 1 + // RecoveryCreate: bytes of a new store's prezero, each slice synced. + RecoveryCreate RecoveryPhase = iota + 1 + RecoveryOpenMap RecoveryOpenCopy RecoveryScan RecoveryScanSpans @@ -21,6 +23,8 @@ const ( RecoveryInstall RecoveryMap RecoveryReplay + // RecoveryFence: bytes of the drop fence, each slice synced. + RecoveryFence RecoveryReclaim RecoveryAttach ) @@ -103,6 +107,22 @@ func (r *recoveryReporter) finish() { } } +// syncedSlices runs a step over [0, total) one slice at a time. step must +// write and sync its slice; only a slice whose step returned nil is +// reported, so bytes written but not synced never count. +func syncedSlices(total uint64, step func(off, n uint64) error, progress *recoveryReporter) error { + for off := uint64(0); off < total; { + n := min(total-off, fenceSliceBytes) + if err := step(off, n); err != nil { + return err + } + off += n + progress.advance(n) + } + progress.finish() + return nil +} + func copyRecoveryMap(ctx context.Context, dst, src []chunkLSNEntryV3) ([]chunkLSNEntryV3, error) { return copyRecoveryMapPhase(ctx, RecoveryMap, dst, src) } diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 4f2332e8a8..2107de3a37 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -296,7 +296,7 @@ func createWALStoreV3Configured(path string, numBlocks, blockSize uint32, walSiz } err = fd.Truncate(totalSize) if err == nil { - err = prezeroNewStore(fd, totalSize) + err = prezeroNewStore(fd, totalSize, newRecoveryReporter(WithRecoveryProgress(context.Background(), opts.RecoveryProgress), RecoveryCreate)) } if err == nil && chunkBlocks != 0 { var m *chunkLSNMapV3 @@ -743,7 +743,14 @@ func (s *WALStore) recoverV3(ctx context.Context) (uint64, error) { } // The drop fence, then the recovered head, then the writer and admission. floor, sameNonce := v.pub.reuseFloor() - if err := s.fenceV3(o.E, floor, d.WALSize, sameNonce, d.WALOffset); err != nil { + // Each synced fence slice is recovery progress. The hook runs under the + // store lock and only records a frontier (the watchdog's leaf lock). + fence := newRecoveryReporter(ctx, RecoveryFence) + v.fenceSliceHook = fence.advance + err = s.fenceV3(o.E, floor, d.WALSize, sameNonce, d.WALOffset) + v.fenceSliceHook = nil + fence.finish() + if err != nil { s.dm.clear() return 0, err } diff --git a/seaweed-block/deploy/config/blockvolume.env b/seaweed-block/deploy/config/blockvolume.env index 66e5475a80..573a9e214f 100644 --- a/seaweed-block/deploy/config/blockvolume.env +++ b/seaweed-block/deploy/config/blockvolume.env @@ -31,8 +31,9 @@ SWB_CTRL_ADDR=127.0.0.1:9202 SWB_STATUS_ADDR=127.0.0.1:9203 # --heartbeat-interval (default 2s). Heartbeat send interval. SWB_HEARTBEAT_INTERVAL=2s -# --recover-timeout (default 30s). How long a primary-assigned replica may stay -# not promotion-ready before it reports itself unhealthy (recovery_timeout). +# --recover-timeout (default 30s). How long a primary-assigned replica may go +# without completed recovery work before it reports itself unhealthy +# (recovery_stalled). A wait for master authority pauses it. SWB_RECOVER_TIMEOUT=30s # --durable-root (default empty: in-memory, NOT durable). Directory for the diff --git a/seaweed-block/docs/design/block-design.md b/seaweed-block/docs/design/block-design.md index eb8450ff61..172ab87568 100644 --- a/seaweed-block/docs/design/block-design.md +++ b/seaweed-block/docs/design/block-design.md @@ -316,7 +316,7 @@ While invalid the volume reports no last data epoch: it reconciles as diverged, When local recovery fails, blockvolume reports a typed reason at once instead of waiting for a timeout (`cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason`): - `wal_corrupt`: a WAL integrity failure (bad bounds, a damaged committed record); - `io_error`: an I/O error from the substrate; -- `recovery_timeout`: anything unclassified, from the watchdog. +- `recovery_stalled`: anything unclassified, from the watchdog: no completed recovery work for the window. The reason is an unhealthy, not-eligible fact; blockmaster does not promote or serve from it. Recovery warnings such as `wal_hole_suspected` appear in status without changing health. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index a62c4e5a59..1380e0d2cf 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -78,7 +78,7 @@ stateDiagram-v2 | — | CreateRefused | a new volume needs the durable root's free space >= its size + WAL (a lab build, tag `swblock_lab_bigvol`, only warns), checked before the store, its WAL or its fresh marker is created (the replica floor, written when the assignment arrives, precedes the check and stays); the refusal ends the process with status 1; an existing volume opens and warns when its remaining data growth + WAL exceed the free space | `core/frontend/durable/headroom.go`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-LOCAL-HEADROOM-001` | | — | CreateRefused | a chunk volume in create mode (no local store yet): before the provider is built, the geometry flags are compared with the volume record; they disagree, or the record is there but does not decode: exit 78; the filer failed the read: exit 75; nothing is created; an absent record keeps the create path; an existing store is never rechecked against the flags | `cmd/blockvolume/main.go` (create-mode check); `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal` | `INV-VOL-GEOMETRY-FLAGS-RECORD-001` | | — | OpenRefused | the file's header carries a removed experimental engine's magic (smartwal, parallel-walstore): refused typed under every selector, read-only, never modified | `core/frontend/durable/provider.go` `verifyImplOnDisk` | `INV-OPEN-REMOVED-ENGINE-REFUSED-001` | -| Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001`, `INV-RECOVERY-PROGRESS-WINDOW-001` | +| Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001`, `INV-RECOVERY-PROGRESS-WINDOW-001`, `INV-RECOVERY-SIZED-STEP-SLICES-001`, `INV-RECOVERY-AUTHORITY-WAIT-PAUSE-001` | | Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end; the frontend targets start, and `FrontendPrimaryReady` is reported, only once the backend admits I/O (a chunk volume: after its storage claim; attach-pending or fenced reports not ready with the reason); a workspace primary claims HEAD, listens and reports ready only while its lease guard permits now (`WorkspaceLeaseGuard.Held`; without a grant: `NotReadyReason=lease_not_held`, exit 75 after the start-time wait); a primary of a replicated line serves only when its own `--replication-ack` is the profile its assignment names (otherwise not Healthy, `NotReadyReason` naming both profiles, ahead of the backend's own refusal) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `core/host/volume/status_server.go` `statusProjection`; `core/host/volume/workspace_lease.go` `Held`; `core/host/volume/workspace_startup.go` `noteAckProfile` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001`, `INV-WAL-V3-W-RECOVERY-001`, `INV-WAL-V3-FENCE-001`, `INV-WAL-V3-FENCE-SLICE-001`, `INV-WAL-V3-MAP-PUBLISH-001`, `INV-FE-PRIMARY-READY-OPERATIONAL-001`, `INV-WS-SERVE-LEASE-HELD-001`, `INV-PRIMARY-ACK-PROFILE-001`, `INV-ATTACH-ASSIGNMENT-BOUND-001`, `INV-LAYOUT-REMOTE-CAPABILITIES-001` | | Recovering | Serving (v1.1 upgrade, clean-stop seed) | the chunk layer attaches an unmarked store on the draft v1.1 format (lab builds only), after Recover and the storage claim: each whole local chunk is written Rebuilt all → U, Hash → HU, Commit → HP with HEAD's hash (a chunk HEAD does not name: the zero chunk's) only when all hold: a clean-stop proof (the HEAD the claim was built on was a committed, idle detach, `DetachedBy`), its claim id is the store's layout claim id, and its position is the store's synced position the pages are valid through; otherwise each whole local chunk is U (left to the compare pass); partial and absent chunks are classified alike in both; a marked store never seeds | `core/frontend/chunkstore/layout/start.go` `Start` (`ReportCleanStop`); `core/frontend/durable/provider_layout.go` `startLayoutRoot`; `core/storage/chunk_record_upgrade.go` `upgradeChunkRecordSeeded`, `seedsLineage`, `cleanStopHashes` | `INV-CHUNK-RECORD-SEED-001`, `INV-CHUNK-RECORD-UPGRADE-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001`, `INV-WAL-V3-W-RECOVERY-001` | @@ -610,7 +610,9 @@ The "Machine / transition" column refers to Part A. Notes under a table record w |---|---|---|---|---|---|---| | `INV-REBUILD-SNAPSHOT-COMPLETE-001` | A rebuild snapshot returns all readable nonzero blocks or an error, never a partial success. The sender propagates snapshot failure before shipping blocks or RebuildDone. | M3 NeedsRebuild (base enumeration) | `core/storage/logical_storage.go` `AllBlocks`; storage implementations; `core/transport/rebuild_sender.go` `doRebuild` | `TestChunkHydration_SnapshotFailsOnReadError`, `TestRebuildSnapshotErrorNeverShipsPartialImage` | Existing fail-closed recovery contract; error propagation only | ACTIVE | | `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `TestNativeReplacementTornWrapKeepsAcknowledgedSuffix` (`core/storage/legacy_replacement_v3_test.go`) | `WALRecovery` `I1` | ACTIVE | -| `INV-RECOVERY-PROGRESS-WINDOW-001` | Startup reports recovery_timeout only after a window without a new fixed-order phase/count frontier; repeated preparation cannot renew it. Progress never grants readiness or ownership. | M1 Recovering | `core/host/volume/recovery_watchdog.go`; `cmd/blockvolume/durable_startup.go`; `core/storage/recovery_progress.go` | `TestDurableStartup_LocalRecoveryWorkIsOutsideFixedDeadline` (`cmd/blockvolume/durable_startup_budget_test.go`); `TestRecoveryProgress_CountingEntriesOutliveTheTotalWindow`, `TestRecoveryProgress_RepeatedAttachPreparationDoesNotRenew` (`core/host/volume/recovery_progress_test.go`); attach: `TestAttachReportsItsVolumeSizedLocalWork`, `TestAttachReportsTheCreatedThisStartScan`, `TestAttachProgressFlushesSlowWorkAboutEverySecond` (`core/storage/chunk_attach_progress_test.go`), `TestAttachProgressCountsEachAttemptFromZero`, `TestAttachRemoteCallsCarryTheirOwnBound`, `TestAttachManifestReadCarriesThePerFetchRule` (`core/frontend/durable/attach_progress_test.go`), `TestAttachManifestReadBoundsEachFetch` (`core/frontend/chunkstore/layout_attach_fetch_test.go`) | — (joint recovery+attach Linux qualification: 7495 PASS, 0 FAIL, race x5 including the attach tests); C.L | ACTIVE | +| `INV-RECOVERY-PROGRESS-WINDOW-001` | Startup reports recovery_stalled only after a window without a new fixed-order phase/count frontier; repeated preparation cannot renew it. Progress never grants readiness or ownership. | M1 Recovering | `core/host/volume/recovery_watchdog.go`; `cmd/blockvolume/durable_startup.go`; `core/storage/recovery_progress.go` | `TestDurableStartup_LocalRecoveryWorkIsOutsideFixedDeadline` (`cmd/blockvolume/durable_startup_budget_test.go`); `TestRecoveryProgress_CountingEntriesOutliveTheTotalWindow`, `TestRecoveryProgress_RepeatedAttachPreparationDoesNotRenew` (`core/host/volume/recovery_progress_test.go`); attach: `TestAttachReportsItsVolumeSizedLocalWork`, `TestAttachReportsTheCreatedThisStartScan`, `TestAttachProgressFlushesSlowWorkAboutEverySecond` (`core/storage/chunk_attach_progress_test.go`), `TestAttachProgressCountsEachAttemptFromZero`, `TestAttachRemoteCallsCarryTheirOwnBound`, `TestAttachManifestReadCarriesThePerFetchRule` (`core/frontend/durable/attach_progress_test.go`), `TestAttachManifestReadBoundsEachFetch` (`core/frontend/chunkstore/layout_attach_fetch_test.go`) | — (joint recovery+attach Linux qualification: 7495 PASS, 0 FAIL, race x5 including the attach tests); C.L | ACTIVE | +| `INV-RECOVERY-SIZED-STEP-SLICES-001` | A sized startup step (a new store's prezero, the WAL fence) reports its bytes as recovery progress only after their sync, prezero one 4 MiB slice at a time. | M1 Recovering | `core/storage/recovery_progress.go` `syncedSlices`; `core/storage/data_sync.go` `prezeroNewStore`; `core/storage/walstore_v3.go` `fenceV3` | `TestSyncedSlicesCountOnlySyncedSlices`, `TestPrezeroReportsEachSyncedSlice`, `TestRecoveryReportsTheSyncedFence`, `TestRecoveryFenceHeldSyncReportsAfterRelease` (`core/storage/recovery_create_progress_test.go`); `TestRecoveryStalled_CreateSlicesRenewTheWindow` (`core/host/volume/recovery_authority_wait_test.go`) | — | ACTIVE | +| `INV-RECOVERY-AUTHORITY-WAIT-PAUSE-001` | The recovery_stalled window pauses while a recovered volume awaits master authority and restarts when that wait ends; a stall latched before the wait stays latched. The wait is bounded by the master. | M1 Recovering | `core/host/volume/recovery_watchdog.go` `ReportAuthorityWait`; `core/frontend/durable/provider_chunk.go` `chunkAuthorityWait` | `TestRecoveryStalled_FullAuthorityWaitDoesNotStall`, `TestRecoveryStalled_SilentStepBeyondTheWindowIsCaught` (`core/host/volume/recovery_authority_wait_test.go`); `TestAuthorityWaitIsReportedAndShowsItsGap` (`core/frontend/durable/authority_wait_hook_test.go`) | — | ACTIVE | | `INV-OPEN-REMOVED-ENGINE-REFUSED-001` | A volume whose header carries a removed experimental engine's magic (smartwal `SWAW`; parallel-walstore `SWPW` at offset 0 or 4096) is refused typed (copy the data to a walstore volume with v1.0.x first) under every selector, read-only and never modified. | M1 [*] → OpenRefused | `core/frontend/durable/provider.go` `verifyImplOnDisk` | `TestDurableProvider_RefusesRemovedEngineVolumes` (byte-identical file after each refusal; `core/frontend/durable/provider_auto_impl_test.go`); `TestWALStoreChunk_SelectorRules` (`core/frontend/durable/provider_chunk_test.go`) | — | ACTIVE | | `INV-OPEN-REMOVED-ENGINE-NAME-REFUSED-001` | A selector naming a removed experimental engine (`smartwal`, `parallel-walstore`) is refused typed, with the same advice, by blockvolume, the provider and the Kubernetes launcher before any volume is touched. | M1 [*] → OpenRefused | `core/frontend/durable/provider.go` `RemovedEngineName`, `NewDurableProvider`; `cmd/blockvolume/main.go` `parseFlags`; `core/launcher/k8s_renderer.go` | `TestDurableProvider_RefusesRemovedEngineNames` (`core/frontend/durable/provider_auto_impl_test.go`); `TestBlockvolumeRefusesRemovedEngineNames` (`cmd/blockvolume/durable_impl_default_test.go`); `TestK8sRendererRefusesRemovedEngines` (`core/launcher/k8s_renderer_test.go`) | — | ACTIVE | | `INV-WAL-OPGATE-001` | A durable backend refuses `Read`, `Write` and `Sync` until `RecoverVolume` succeeds; a failed recovery leaves it refused. | M1 Opened → Serving; Recovering → RecoveryFailed | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/durable/provider.go` `RecoverVolume` | `TestT3b_DurableProvider_Open_StartsNotOperational` (`core/frontend/durable/provider_test.go`); `TestT3b_Recovery_CleanRecover_FlipsOperational` (`core/frontend/durable/recovery_test.go`); `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/design/kubernetes-block-design.md b/seaweed-block/docs/design/kubernetes-block-design.md index 20ea776aa3..26800b1d45 100644 --- a/seaweed-block/docs/design/kubernetes-block-design.md +++ b/seaweed-block/docs/design/kubernetes-block-design.md @@ -138,7 +138,7 @@ Key values: `blockNodes[]`; `ports.iscsiBase`, `ports.nvmeBase`, `ports.statusBa **Detection.** - blockvolume heartbeats every 2 s (`--heartbeat-interval`; `core/host/volume/host.go` `buildReport`). Each slot carries reachable, `ready_for_primary`, eligible, withdrawn, incarnation, `unhealthy_reason` and its frontends. - blockmaster expires an observation after `--freshness-window` (30 s). -- The volume reports `recovery_timeout` after `--recover-timeout` (30 s) and `wal_corrupt`, `io_error` or `role_admission_failed` at once (`core/host/volume/recovery_watchdog.go`; [core §1.7](block-design.md#17-recovery-and-typed-fail-closed-reasons)). +- The volume reports `recovery_stalled` after `--recover-timeout` (30 s) without completed recovery work and `wal_corrupt`, `io_error` or `role_admission_failed` at once (`core/host/volume/recovery_watchdog.go`; [core §1.7](block-design.md#17-recovery-and-typed-fail-closed-reasons)). - A restarted primary keeps its authority for one boot-grace period per incarnation, but not after 3 restarts in 10 minutes or an explicit unhealthy report (`core/authority/primary_boot_grace.go`; `topology.go` `PrimaryBootFlapRestarts`, `PrimaryBootFlapWindow`). **Who decides.** blockmaster's product loop (`core/host/master/product_loop.go` `RunLifecycleProductTick`) builds a snapshot and submits it to the topology controller. @@ -232,7 +232,7 @@ stateDiagram-v2 ## 7. Readiness -**blockvolume process readiness.** At start, blockvolume blocks local readiness ("awaiting durable recovery") and opens and recovers its store (`cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`). Three outcomes: ready (the block clears), faulted (the process stays up and reports a typed reason: `wal_corrupt`, `io_error`, or `recovery_timeout` from the watchdog) or fatal (the process exits). While blocked, `applyFact` admits nothing, primary or supporting, and stores the assignment to replay once readiness clears. The status server (`core/host/volume/status_server.go`) exposes `/status`, `/status/peers`, `/status/durable`, `/status/nvme`, `/status/frontend-capabilities`; its projection carries `Healthy`, `FrontendPrimaryReady`, `AuthorityRole` (primary, superseded, unknown), `ReplicationRole` (none, recovering, not_ready, replica_ready, unknown), `UnhealthyReason` and catch-up lag. +**blockvolume process readiness.** At start, blockvolume blocks local readiness ("awaiting durable recovery") and opens and recovers its store (`cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`). Three outcomes: ready (the block clears), faulted (the process stays up and reports a typed reason: `wal_corrupt`, `io_error`, or `recovery_stalled` from the watchdog) or fatal (the process exits). While blocked, `applyFact` admits nothing, primary or supporting, and stores the assignment to replay once readiness clears. The status server (`core/host/volume/status_server.go`) exposes `/status`, `/status/peers`, `/status/durable`, `/status/nvme`, `/status/frontend-capabilities`; its projection carries `Healthy`, `FrontendPrimaryReady`, `AuthorityRole` (primary, superseded, unknown), `ReplicationRole` (none, recovering, not_ready, replica_ready, unknown), `UnhealthyReason` and catch-up lag. **Managed volume readiness** (`core/ops/managed_volume_model.go` `classifyManagedVolume`): one status per volume (invalid, unsafe, blocked, recovering, recovered, degraded, ready, unknown) over sub-states for Kubernetes, authority, CSI, host path, recovery and workload. Known blockers win before staleness, and stale evidence is never ready: diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index db608cdbf0..6d71b8fd37 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -405,7 +405,7 @@ volume or prove frontend readiness. | `SWB_DATA_ADDR`, `SWB_CTRL_ADDR` | `--data-addr`, `--ctrl-addr` | required | Data-path and control-path addresses | | `SWB_STATUS_ADDR` | `--status-addr` | empty (off) | Status HTTP endpoint; loopback only, unauthenticated | | `SWB_HEARTBEAT_INTERVAL` | `--heartbeat-interval` | `2s` | Heartbeat interval | -| `SWB_RECOVER_TIMEOUT` | `--recover-timeout` | `30s` | Time to become promotion-ready before reporting `recovery_timeout` | +| `SWB_RECOVER_TIMEOUT` | `--recover-timeout` | `30s` | Time without completed recovery work before reporting `recovery_stalled` (paused while awaiting master authority) | | `SWB_DURABLE_ROOT` | `--durable-root` | empty (in memory, not durable) | Storage directory; writable by the service user | | `SWB_DURABLE_IMPL` | `--durable-impl` | empty (auto) | Auto creates new volumes as `walstore`, opens existing ones with their on-disk format, and refuses a `walstore-chunk` root; so does every explicit value other than `walstore-chunk` (a chunk root holds data that may live only in the remote HEAD: open it with `--durable-impl=walstore-chunk` and its remote configuration). Explicit: `walstore`, `walstore-chunk` (workspace, proof of concept). The removed experimental engines (`smartwal`, `parallel-walstore`) are refused. The examples set `walstore`. | | `SWB_DURABLE_BLOCKS` | `--durable-blocks` | `2048` | Blocks on first create | diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 3638511c7c..54efd05c1b 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -36,6 +36,7 @@ The volume's authority and health projection. Go type `volume.StatusProjection`. | `ReplicationRole` | string | ReplicationRole is none (a primary), recovering, not_ready, replica_ready or unknown. | | `RoleAdmissionFailure` | string | RoleAdmissionFailure (G1) explains a not-Healthy projection caused by a failed role call on the replica listener; empty otherwise. (omitted when empty) | | `UnhealthyReason` | string | UnhealthyReason is the slot's explicit unhealthy report (#128 rule 6), the value its heartbeat carries; empty when healthy. (omitted when empty) | +| `RecoveryWait` | string | RecoveryWait names a wait that pauses the recovery_stalled window: awaiting_authority while the recovered volume waits for master authority (the master bounds it); empty otherwise. (omitted when empty) | | `CatchUp` | object | CatchUp shows a supporting replica's catch-up progress while it is not yet replica_ready; it is visible without being an alert. (omitted when empty) | | `CatchUp.ElapsedMs` | int64 | ElapsedMs is the time since this replica was admitted as a supporting replica at its current epoch. | | `CatchUp.LagLSN` | uint64 | LagLSN is the engine's H-R (primary head minus this replica's durable frontier) as last observed; 0 when unknown or caught up. | @@ -253,6 +254,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Maintenance.lastPass.headGen` | uint64 | observed cleaning HEAD generation; diagnostic only | | `Volumes[].Chunk.Attached` | bool | the chunk layer is attached to the remote | | `Volumes[].Chunk.AwaitingAuthority` | bool | recovered; the layer waits for master authority to attach | +| `Volumes[].Chunk.AuthorityGap` | string | while awaiting: the projection fields that withhold authority (omitted when empty) | | `Volumes[].Chunk.Fenced` | bool | a newer holder fenced this layer: it publishes nothing | | `Volumes[].Chunk.RemoteLSN` | uint64 | the LSN of the remote HEAD (what the remote holds durably) | | `Volumes[].Chunk.Stats` | object | the layer's cut counters; zero until attached | diff --git a/seaweed-block/docs/volume-lifecycle.md b/seaweed-block/docs/volume-lifecycle.md index 5eee3761ed..2978ef200e 100644 --- a/seaweed-block/docs/volume-lifecycle.md +++ b/seaweed-block/docs/volume-lifecycle.md @@ -340,9 +340,12 @@ without the move does not serve: a sealed HEAD stays sealed for its own epoch. At startup, `--recover-timeout` (default `30s`) is an inactivity window shared by local recovery and attachment, not a total startup deadline. Newly completed -WAL records and chunk-map entries advance its progress frontier. Repeating the -same preparation during a retry does not renew it. A full window without new -work reports `recovery_timeout` in status and heartbeats and keeps I/O refused; +WAL records and chunk-map entries advance its progress frontier, and so does +each synced 4 MiB slice of a WAL fence or a new store's prezero. Repeating the +same preparation during a retry does not renew it. The window pauses while the +recovered volume waits for master authority (`AwaitingAuthority` and +`AuthorityGap` in the durable status): the master bounds that wait. A full window without new +work reports `recovery_stalled` in status and heartbeats and keeps I/O refused; it never grants a lease or moves a single-copy volume. Recovery corruption and I/O failures still report their typed errors immediately. After a physical restart, recovery reads authoritative local disk again. From 009e9bb1885592c45675fee8be8d0c3c784a73df Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 01:36:24 -0800 Subject: [PATCH 2/5] storage: recovery's fence progress keeps a fence hook already set Recovery replaced any fenceSliceHook for the fence and then cleared it, so a hook set by its caller saw nothing. It now calls that hook first and restores it afterwards. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/walstore_v3.go | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 2107de3a37..e6b81b88a4 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -744,11 +744,18 @@ func (s *WALStore) recoverV3(ctx context.Context) (uint64, error) { // The drop fence, then the recovered head, then the writer and admission. floor, sameNonce := v.pub.reuseFloor() // Each synced fence slice is recovery progress. The hook runs under the - // store lock and only records a frontier (the watchdog's leaf lock). + // store lock and only records a frontier (the watchdog's leaf lock); a + // hook already set keeps being called and is restored afterwards. fence := newRecoveryReporter(ctx, RecoveryFence) - v.fenceSliceHook = fence.advance + prevHook := v.fenceSliceHook + v.fenceSliceHook = func(n uint64) { + if prevHook != nil { + prevHook(n) + } + fence.advance(n) + } err = s.fenceV3(o.E, floor, d.WALSize, sameNonce, d.WALOffset) - v.fenceSliceHook = nil + v.fenceSliceHook = prevHook fence.finish() if err != nil { s.dm.clear() From cb542b3c21cdc306be560687221c3f934d7cf790 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 03:05:09 -0800 Subject: [PATCH 3/5] host, durable: the authority pause ends at the grant and latches silence before it Review fixes. The provider ends the stall window's pause when authority is granted, before the local attach, so a stuck attach is a stall again; the first authority wait latches silence that already filled the window, so the pause cannot hide it and its end cannot erase it. The held-sync and held-attach tests release their holds before Close on every exit, and the real prezero gets a sync seam with an order and a failed-sync control. Co-Authored-By: Claude Opus 5.5 --- .../durable/authority_wait_hook_test.go | 46 +++++++++++++++ .../core/frontend/durable/provider_chunk.go | 14 ++++- .../frontend/durable/provider_chunk_test.go | 5 +- .../volume/recovery_authority_wait_test.go | 36 ++++++++++++ .../host/volume/recovery_lock_guard_test.go | 4 +- .../core/host/volume/recovery_watchdog.go | 57 ++++++++++++++----- seaweed-block/core/storage/data_sync.go | 5 +- .../storage/recovery_create_progress_test.go | 55 +++++++++++++++++- seaweed-block/docs/design/invariants.md | 4 +- 9 files changed, 203 insertions(+), 23 deletions(-) diff --git a/seaweed-block/core/frontend/durable/authority_wait_hook_test.go b/seaweed-block/core/frontend/durable/authority_wait_hook_test.go index fa61a53517..cbfcb8509d 100644 --- a/seaweed-block/core/frontend/durable/authority_wait_hook_test.go +++ b/seaweed-block/core/frontend/durable/authority_wait_hook_test.go @@ -9,6 +9,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil" + "github.com/seaweedfs/seaweed-block/core/storage" ) // The chunk layer's wait for master authority is visible to the host @@ -55,3 +56,48 @@ func TestAuthorityWaitIsReportedAndShowsItsGap(t *testing.T) { st[0].Chunk.Attached && !st[0].Chunk.AwaitingAuthority && st[0].Chunk.AuthorityGap == "" }) } + +// The pause ends at the grant, before the local attach: while the granted +// attach is held (its HEAD read blocked) the host has already been told the +// wait ended, so a stuck attach counts against the stall window. +func TestAuthorityWaitEndsAtTheGrantBeforeTheAttach(t *testing.T) { + var mu sync.Mutex + var seen []bool + g := newGated(storage.NewMemChunkRemote()) + g.holdGetHead = make(chan struct{}) + view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) + p := chunkProvider(t, t.TempDir(), g, view, 0, func(cfg *durable.ProviderConfig) { + cfg.AuthorityWait = func(waiting bool) { + mu.Lock() + seen = append(seen, waiting) + mu.Unlock() + } + }) + // Registered after the provider's Close, so it runs first: a failing + // test never leaves the attach held while Close waits for it. + t.Cleanup(g.release) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 2})) + waitEntered(t, g, "gethead") // the granted attach is held reading HEAD + mu.Lock() + got := append([]bool(nil), seen...) + mu.Unlock() + if len(got) != 2 || !got[0] || got[1] { + t.Fatalf("authority wait reports while the granted attach is held: %v, want [true false]", got) + } + g.release() + waitFor(t, 20*time.Second, "the attach completes", func() bool { + st := p.DurableStatuses() + return len(st) == 1 && st[0].Chunk != nil && st[0].Chunk.Attached + }) + mu.Lock() + defer mu.Unlock() + if len(seen) != 2 { + t.Fatalf("authority wait reports after the attach: %v, want exactly one start and one end", seen) + } +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index f9547f70e0..f067d5e9b6 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -185,10 +185,19 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen log.Printf("durable: chunk layer for volume=%s waits for master authority (%s): projection lacks %s", volumeID, bound, chunkAuthorityGap(p.view.Projection(), volumeID)) // The wait's bound is the master's: the startup stall window pauses - // for it and restarts when it ends. + // while authority is missing and restarts at the grant, before any local + // attach work, so a stuck attach is still a stall. + endPause := func() {} if aw := p.cfg.AuthorityWait; aw != nil { aw(true) - defer aw(false) + paused := true + endPause = func() { + if paused { + paused = false + aw(false) + } + } + defer endPause() } ended := "superseded by a later recovery" defer func() { @@ -269,6 +278,7 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen expired, ended = true, "assignment allowance ended before attach retry" return } + endPause() // granted: the attach below is local work again if attempts++; attempts == 1 { log.Printf("durable: chunk layer for volume=%s: master authority after %s (replica=%q epoch=%d endpoint=%d); first attach attempt", volumeID, time.Since(start), proj.ReplicaID, proj.Epoch, proj.EndpointVersion) diff --git a/seaweed-block/core/frontend/durable/provider_chunk_test.go b/seaweed-block/core/frontend/durable/provider_chunk_test.go index 3fb0549583..07749f7800 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_test.go @@ -28,7 +28,7 @@ const ( pcChunkBlocks = 16 ) -func chunkProvider(t *testing.T, root string, remote storage.ChunkRemote, view *stubView, interval time.Duration) *durable.DurableProvider { +func chunkProvider(t *testing.T, root string, remote storage.ChunkRemote, view *stubView, interval time.Duration, mods ...func(*durable.ProviderConfig)) *durable.DurableProvider { t.Helper() fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks) if gated, ok := remote.(*gatedRemote); ok { @@ -49,6 +49,9 @@ func chunkProvider(t *testing.T, root string, remote storage.ChunkRemote, view * gated.ChunkRemote = inner return gated, nil } + for _, mod := range mods { + mod(&cfg) + } p, err := durable.NewDurableProvider(cfg, view) if err != nil { t.Fatal(err) diff --git a/seaweed-block/core/host/volume/recovery_authority_wait_test.go b/seaweed-block/core/host/volume/recovery_authority_wait_test.go index e794fc9b42..801b4ebbec 100644 --- a/seaweed-block/core/host/volume/recovery_authority_wait_test.go +++ b/seaweed-block/core/host/volume/recovery_authority_wait_test.go @@ -122,3 +122,39 @@ func TestRecoveryStalled_LateSyncedSliceKeepsTheStall(t *testing.T) { t.Fatalf("a late slice cleared a reported stall: %q", got) } } + +// Silence that already filled the window when the authority wait starts is +// a stall, though nothing sampled the health in between: the pause does not +// hide it, and the wait's end does not erase it. +func TestRecoveryStalled_SilenceBeforeTheWaitIsLatchedAtItsStart(t *testing.T) { + h, clk := watchdogHost(t, 30*time.Second) + h.applyFixtureFact(selfPrimaryFact(1)) + clk.advance(31 * time.Second) // no progress and no health sample + h.ReportAuthorityWait(true) + if got := h.UnhealthyReason(); got != UnhealthyRecoveryStalled { + t.Fatalf("31 s of silence before the wait, read during it: %q", got) + } + h.ReportAuthorityWait(false) + if got := h.UnhealthyReason(); got != UnhealthyRecoveryStalled { + t.Fatalf("after the wait ended: %q", got) + } +} + +// After the grant ends the pause, a held attach that completes no work is a +// stall once the window passes. +func TestRecoveryStalled_HeldAttachAfterTheGrantStalls(t *testing.T) { + h, clk := watchdogHost(t, 30*time.Second) + h.applyFixtureFact(selfPrimaryFact(1)) + h.ReportRecoveryProgress(storage.RecoveryFence, 4<<20) + h.ReportAuthorityWait(true) + clk.advance(time.Minute) // the master's wait + h.ReportAuthorityWait(false) // the grant: the attach starts and is held + clk.advance(29 * time.Second) + if got := h.UnhealthyReason(); got != "" { + t.Fatalf("inside the window after the grant: %q", got) + } + clk.advance(2 * time.Second) + if got := h.UnhealthyReason(); got != UnhealthyRecoveryStalled { + t.Fatalf("a held attach past the window: %q", got) + } +} diff --git a/seaweed-block/core/host/volume/recovery_lock_guard_test.go b/seaweed-block/core/host/volume/recovery_lock_guard_test.go index e6007f45fb..e29c5f1bd1 100644 --- a/seaweed-block/core/host/volume/recovery_lock_guard_test.go +++ b/seaweed-block/core/host/volume/recovery_lock_guard_test.go @@ -38,8 +38,8 @@ func TestRecoveryWatchdogLockedMethodsNeverCallStorageOrWait(t *testing.T) { t.Errorf("watchdog-locked %s: %s", fn.Name.Name, violation) } } - if locked != 9 { - t.Fatalf("watchdog lock sites=%d, want 9 reviewed methods", locked) + if locked != 10 { + t.Fatalf("watchdog lock sites=%d, want 10 reviewed methods", locked) } } diff --git a/seaweed-block/core/host/volume/recovery_watchdog.go b/seaweed-block/core/host/volume/recovery_watchdog.go index ee787e8ba5..38440fb00a 100644 --- a/seaweed-block/core/host/volume/recovery_watchdog.go +++ b/seaweed-block/core/host/volume/recovery_watchdog.go @@ -62,9 +62,9 @@ const ( // RecoveryAwaitingAuthority: the recovered volume waits for master // authority; the recovery_stalled window is paused (status RecoveryWait). RecoveryAwaitingAuthority = "awaiting_authority" - UnhealthyRoleAdmission = "role_admission_failed" - UnhealthyWALCorrupt = "wal_corrupt" - UnhealthyIOError = "io_error" + UnhealthyRoleAdmission = "role_admission_failed" + UnhealthyWALCorrupt = "wal_corrupt" + UnhealthyIOError = "io_error" // UnhealthyRebuildRetainedBase: this replica's rebuild is refused // because its store still holds an installed BASE (removed and added // back with its older store: a v1 limit). Wipe the replica's data @@ -126,24 +126,34 @@ func (h *Host) ReportRecoveryProgress(phase storage.RecoveryPhase, done uint64) } // ReportAuthorityWait observes the chunk layer's wait for master -// authority: true when a wait starts, false when that wait ends. Waits are -// counted, so a superseded recovery's wait ending late cannot resume the -// window while a newer wait still runs. While any wait lasts the stall -// window is paused; when the last one ends the window restarts. A stall -// latched before the wait stays latched. +// authority: true when a wait starts, false when it ends (at the grant, +// before local attach work). Waits are counted, so a superseded recovery's +// wait ending late cannot resume the window while a newer wait still runs. +// While any wait lasts the stall window is paused; when the last one ends +// the window restarts. Silence that already filled the window when the +// first wait starts is latched as a stall first, and a latched stall stays. func (h *Host) ReportAuthorityWait(waiting bool) { if h == nil || h.wd == nil { return } - w := h.wd - w.mu.Lock() - defer w.mu.Unlock() - if waiting { - w.awaiting++ + if !waiting { + h.wd.authorityWaitEnds() return } + // The log line is written after the watchdog lock is released. + if h.wd.authorityWaitStarts() { + h.log.Printf("blockvolume: volume %s primary assignment epoch=%d completed no recovery work for %s before its authority wait: reporting unhealthy (%s)", + h.cfg.VolumeID, h.wd.epoch(), h.wd.timeout, UnhealthyRecoveryStalled) + } +} + +// authorityWaitEnds counts an ending authority wait; when the last one +// ends the window restarts. An end without its start is ignored. +func (w *recoveryWatchdog) authorityWaitEnds() { + w.mu.Lock() + defer w.mu.Unlock() if w.awaiting == 0 { - return // an end without its start: nothing to resume + return } w.awaiting-- if w.awaiting == 0 { @@ -151,6 +161,25 @@ func (h *Host) ReportAuthorityWait(waiting bool) { } } +// authorityWaitStarts counts a starting authority wait. When it is the +// first, silence that already filled the window is latched as a stall +// before the pause hides it; fired reports that latch. +func (w *recoveryWatchdog) authorityWaitStarts() (fired bool) { + w.mu.Lock() + defer w.mu.Unlock() + if w.awaiting == 0 && !w.primarySince.IsZero() && !w.readySeen && !w.timedOut { + since := w.primarySince + if w.lastProgress.After(since) { + since = w.lastProgress + } + if w.now().Sub(since) >= w.timeout { + w.timedOut, fired = true, true + } + } + w.awaiting++ + return fired +} + // AwaitingAuthority reports whether the stall window is paused for the // chunk layer's wait for master authority. func (h *Host) AwaitingAuthority() bool { diff --git a/seaweed-block/core/storage/data_sync.go b/seaweed-block/core/storage/data_sync.go index b0e715b98c..85add85e88 100644 --- a/seaweed-block/core/storage/data_sync.go +++ b/seaweed-block/core/storage/data_sync.go @@ -95,6 +95,9 @@ func configuredAllocationMode() (string, error) { } } +// prezeroSync syncs one prezero slice; tests replace it to order or fail it. +var prezeroSync = func(f *os.File) error { return f.Sync() } + // Only newly-created files reach this hook; existing bytes are never rewritten. // Each synced slice is reported to progress (nil: not reported). func prezeroNewStore(f *os.File, size int64, progress *recoveryReporter) error { @@ -120,7 +123,7 @@ func prezeroNewStore(f *os.File, size int64, progress *recoveryReporter) error { } off += uint64(w) } - return f.Sync() + return prezeroSync(f) }, progress) if err != nil { return err diff --git a/seaweed-block/core/storage/recovery_create_progress_test.go b/seaweed-block/core/storage/recovery_create_progress_test.go index 45a1e6398c..ce958373b4 100644 --- a/seaweed-block/core/storage/recovery_create_progress_test.go +++ b/seaweed-block/core/storage/recovery_create_progress_test.go @@ -5,6 +5,8 @@ import ( "errors" "os" "path/filepath" + "strings" + "sync" "testing" "time" ) @@ -119,6 +121,10 @@ func TestRecoveryFenceHeldSyncReportsAfterRelease(t *testing.T) { } defer s.Close() held, release := make(chan struct{}), make(chan struct{}) + var releaseOnce sync.Once + // Deferred after Close, so it runs first: a failing test never leaves + // the recovery held while Close waits for it. + defer releaseOnce.Do(func() { close(release) }) first := true s.testAfterFenceFsync = func() { if first { @@ -141,7 +147,7 @@ func TestRecoveryFenceHeldSyncReportsAfterRelease(t *testing.T) { t.Fatalf("a held slice reported %d bytes before its sync returned", n) case <-time.After(100 * time.Millisecond): } - close(release) + releaseOnce.Do(func() { close(release) }) if err := <-done; err != nil { t.Fatalf("recovery after the held sync: %v", err) } @@ -154,3 +160,50 @@ func TestRecoveryFenceHeldSyncReportsAfterRelease(t *testing.T) { t.Fatalf("fence reports %v; want 3 slices ending at %d", got, uint64(wal)) } } + +// The real prezero reports a slice only after that slice's sync returned, +// and a failed sync stops it with only the earlier slices reported. +func TestPrezeroReportsAfterEachSyncAndStopsAtAFailedOne(t *testing.T) { + t.Setenv("SWBLOCK_ALLOCATION", "prezero") + if _, err := configuredAllocationMode(); err != nil { + t.Skipf("prezero unavailable here: %v", err) + } + saved := prezeroSync + t.Cleanup(func() { prezeroSync = saved }) + var events []string + syncs := 0 + failAt := 0 // 0: never + prezeroSync = func(f *os.File) error { + syncs++ + events = append(events, "sync") + if syncs == failAt { + return errors.New("injected prezero sync failure") + } + return f.Sync() + } + observe := func(phase RecoveryPhase, done uint64) { + if phase == RecoveryCreate { + events = append(events, "report") + } + } + s, err := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "ordered"), 4096, 4096, WALStoreOptions{RecoveryProgress: observe}) + if err != nil { + t.Fatal(err) + } + _ = s.Close() + if len(events) < 4 { + t.Fatalf("events %v: want at least two slices", events) + } + for i, e := range events { + if want := map[bool]string{true: "sync", false: "report"}[i%2 == 0]; e != want { + t.Fatalf("events %v: position %d is %q, want %q (each report follows its slice's sync)", events, i, e, want) + } + } + events, syncs, failAt = nil, 0, 2 + if _, err := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "failed"), 4096, 4096, WALStoreOptions{RecoveryProgress: observe}); err == nil { + t.Fatal("a prezero whose second sync failed created the store") + } + if want := []string{"sync", "report", "sync"}; strings.Join(events, ",") != strings.Join(want, ",") { + t.Fatalf("events %v, want %v: only the first slice reported", events, want) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 1380e0d2cf..3e05f9c8cf 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -611,8 +611,8 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-REBUILD-SNAPSHOT-COMPLETE-001` | A rebuild snapshot returns all readable nonzero blocks or an error, never a partial success. The sender propagates snapshot failure before shipping blocks or RebuildDone. | M3 NeedsRebuild (base enumeration) | `core/storage/logical_storage.go` `AllBlocks`; storage implementations; `core/transport/rebuild_sender.go` `doRebuild` | `TestChunkHydration_SnapshotFailsOnReadError`, `TestRebuildSnapshotErrorNeverShipsPartialImage` | Existing fail-closed recovery contract; error propagation only | ACTIVE | | `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `TestNativeReplacementTornWrapKeepsAcknowledgedSuffix` (`core/storage/legacy_replacement_v3_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-RECOVERY-PROGRESS-WINDOW-001` | Startup reports recovery_stalled only after a window without a new fixed-order phase/count frontier; repeated preparation cannot renew it. Progress never grants readiness or ownership. | M1 Recovering | `core/host/volume/recovery_watchdog.go`; `cmd/blockvolume/durable_startup.go`; `core/storage/recovery_progress.go` | `TestDurableStartup_LocalRecoveryWorkIsOutsideFixedDeadline` (`cmd/blockvolume/durable_startup_budget_test.go`); `TestRecoveryProgress_CountingEntriesOutliveTheTotalWindow`, `TestRecoveryProgress_RepeatedAttachPreparationDoesNotRenew` (`core/host/volume/recovery_progress_test.go`); attach: `TestAttachReportsItsVolumeSizedLocalWork`, `TestAttachReportsTheCreatedThisStartScan`, `TestAttachProgressFlushesSlowWorkAboutEverySecond` (`core/storage/chunk_attach_progress_test.go`), `TestAttachProgressCountsEachAttemptFromZero`, `TestAttachRemoteCallsCarryTheirOwnBound`, `TestAttachManifestReadCarriesThePerFetchRule` (`core/frontend/durable/attach_progress_test.go`), `TestAttachManifestReadBoundsEachFetch` (`core/frontend/chunkstore/layout_attach_fetch_test.go`) | — (joint recovery+attach Linux qualification: 7495 PASS, 0 FAIL, race x5 including the attach tests); C.L | ACTIVE | -| `INV-RECOVERY-SIZED-STEP-SLICES-001` | A sized startup step (a new store's prezero, the WAL fence) reports its bytes as recovery progress only after their sync, prezero one 4 MiB slice at a time. | M1 Recovering | `core/storage/recovery_progress.go` `syncedSlices`; `core/storage/data_sync.go` `prezeroNewStore`; `core/storage/walstore_v3.go` `fenceV3` | `TestSyncedSlicesCountOnlySyncedSlices`, `TestPrezeroReportsEachSyncedSlice`, `TestRecoveryReportsTheSyncedFence`, `TestRecoveryFenceHeldSyncReportsAfterRelease` (`core/storage/recovery_create_progress_test.go`); `TestRecoveryStalled_CreateSlicesRenewTheWindow` (`core/host/volume/recovery_authority_wait_test.go`) | — | ACTIVE | -| `INV-RECOVERY-AUTHORITY-WAIT-PAUSE-001` | The recovery_stalled window pauses while a recovered volume awaits master authority and restarts when that wait ends; a stall latched before the wait stays latched. The wait is bounded by the master. | M1 Recovering | `core/host/volume/recovery_watchdog.go` `ReportAuthorityWait`; `core/frontend/durable/provider_chunk.go` `chunkAuthorityWait` | `TestRecoveryStalled_FullAuthorityWaitDoesNotStall`, `TestRecoveryStalled_SilentStepBeyondTheWindowIsCaught` (`core/host/volume/recovery_authority_wait_test.go`); `TestAuthorityWaitIsReportedAndShowsItsGap` (`core/frontend/durable/authority_wait_hook_test.go`) | — | ACTIVE | +| `INV-RECOVERY-SIZED-STEP-SLICES-001` | A sized startup step (a new store's prezero, the WAL fence) reports its bytes as recovery progress only after their sync, prezero one 4 MiB slice at a time. | M1 Recovering | `core/storage/recovery_progress.go` `syncedSlices`; `core/storage/data_sync.go` `prezeroNewStore`; `core/storage/walstore_v3.go` `fenceV3` | `TestSyncedSlicesCountOnlySyncedSlices`, `TestPrezeroReportsEachSyncedSlice`, `TestRecoveryReportsTheSyncedFence`, `TestRecoveryFenceHeldSyncReportsAfterRelease`, `TestPrezeroReportsAfterEachSyncAndStopsAtAFailedOne` (`core/storage/recovery_create_progress_test.go`); `TestRecoveryStalled_CreateSlicesRenewTheWindow` (`core/host/volume/recovery_authority_wait_test.go`) | — | ACTIVE | +| `INV-RECOVERY-AUTHORITY-WAIT-PAUSE-001` | The recovery_stalled window pauses while a recovered volume awaits master authority and restarts at the grant, before local attach work; silence that filled the window before the wait is latched at its start. The master bounds the wait. | M1 Recovering | `core/host/volume/recovery_watchdog.go` `ReportAuthorityWait`; `core/frontend/durable/provider_chunk.go` `chunkAuthorityWait` | `TestRecoveryStalled_FullAuthorityWaitDoesNotStall`, `TestRecoveryStalled_SilentStepBeyondTheWindowIsCaught`, `TestRecoveryStalled_SilenceBeforeTheWaitIsLatchedAtItsStart`, `TestRecoveryStalled_HeldAttachAfterTheGrantStalls` (`core/host/volume/recovery_authority_wait_test.go`); `TestAuthorityWaitIsReportedAndShowsItsGap`, `TestAuthorityWaitEndsAtTheGrantBeforeTheAttach` (`core/frontend/durable/authority_wait_hook_test.go`) | — | ACTIVE | | `INV-OPEN-REMOVED-ENGINE-REFUSED-001` | A volume whose header carries a removed experimental engine's magic (smartwal `SWAW`; parallel-walstore `SWPW` at offset 0 or 4096) is refused typed (copy the data to a walstore volume with v1.0.x first) under every selector, read-only and never modified. | M1 [*] → OpenRefused | `core/frontend/durable/provider.go` `verifyImplOnDisk` | `TestDurableProvider_RefusesRemovedEngineVolumes` (byte-identical file after each refusal; `core/frontend/durable/provider_auto_impl_test.go`); `TestWALStoreChunk_SelectorRules` (`core/frontend/durable/provider_chunk_test.go`) | — | ACTIVE | | `INV-OPEN-REMOVED-ENGINE-NAME-REFUSED-001` | A selector naming a removed experimental engine (`smartwal`, `parallel-walstore`) is refused typed, with the same advice, by blockvolume, the provider and the Kubernetes launcher before any volume is touched. | M1 [*] → OpenRefused | `core/frontend/durable/provider.go` `RemovedEngineName`, `NewDurableProvider`; `cmd/blockvolume/main.go` `parseFlags`; `core/launcher/k8s_renderer.go` | `TestDurableProvider_RefusesRemovedEngineNames` (`core/frontend/durable/provider_auto_impl_test.go`); `TestBlockvolumeRefusesRemovedEngineNames` (`cmd/blockvolume/durable_impl_default_test.go`); `TestK8sRendererRefusesRemovedEngines` (`core/launcher/k8s_renderer_test.go`) | — | ACTIVE | | `INV-WAL-OPGATE-001` | A durable backend refuses `Read`, `Write` and `Sync` until `RecoverVolume` succeeds; a failed recovery leaves it refused. | M1 Opened → Serving; Recovering → RecoveryFailed | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/durable/provider.go` `RecoverVolume` | `TestT3b_DurableProvider_Open_StartsNotOperational` (`core/frontend/durable/provider_test.go`); `TestT3b_Recovery_CleanRecover_FlipsOperational` (`core/frontend/durable/recovery_test.go`); `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | From 49ca6baf558a7b07dfb033022b37560e442234bd Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 03:30:23 -0800 Subject: [PATCH 4/5] durable: the authority pause follows every transition, not only the first grant A grant whose attach failed and whose authority was then lost returned to the wait without a new pause, so the master's resumed wait could read as a stall. The pause now starts whenever authority is missing and ends at each grant, before the local attach. Co-Authored-By: Claude Opus 5.5 --- .../durable/authority_wait_hook_test.go | 54 +++++++++++++++++++ .../core/frontend/durable/provider_chunk.go | 24 +++++---- seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 68 insertions(+), 12 deletions(-) diff --git a/seaweed-block/core/frontend/durable/authority_wait_hook_test.go b/seaweed-block/core/frontend/durable/authority_wait_hook_test.go index cbfcb8509d..c7300b6d6d 100644 --- a/seaweed-block/core/frontend/durable/authority_wait_hook_test.go +++ b/seaweed-block/core/frontend/durable/authority_wait_hook_test.go @@ -101,3 +101,57 @@ func TestAuthorityWaitEndsAtTheGrantBeforeTheAttach(t *testing.T) { t.Fatalf("authority wait reports after the attach: %v, want exactly one start and one end", seen) } } + +// Authority granted, its attach failed, then authority lost before the +// retry: the retry returns to the wait, which pauses the stall window +// again; the next grant ends that pause and the volume attaches. +func TestAuthorityLostAfterAGrantPausesAgain(t *testing.T) { + var mu sync.Mutex + var seen []bool + snapshot := func() []bool { + mu.Lock() + defer mu.Unlock() + return append([]bool(nil), seen...) + } + g := newGated(storage.NewMemChunkRemote()) + g.failGetHead = 1 // the first granted attach fails; its retry waits a second + view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) + p := chunkProvider(t, t.TempDir(), g, view, 0, func(cfg *durable.ProviderConfig) { + cfg.AuthorityWait = func(waiting bool) { + mu.Lock() + seen = append(seen, waiting) + mu.Unlock() + } + }) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + granted := healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 2}) + view.set(granted) + waitFor(t, 20*time.Second, "the grant ends the pause", func() bool { + got := snapshot() + return len(got) == 2 && got[0] && !got[1] + }) + view.set(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) // lost before the retry + waitFor(t, 20*time.Second, "the resumed wait pauses again", func() bool { + got := snapshot() + return len(got) >= 3 && got[2] + }) + view.set(granted) + waitFor(t, 20*time.Second, "the attach after the second grant", func() bool { + st := p.DurableStatuses() + return len(st) == 1 && st[0].Chunk != nil && st[0].Chunk.Attached + }) + got := snapshot() + if len(got)%2 != 0 { + t.Fatalf("pause reports %v: every pause must end", got) + } + for i, w := range got { + if w != (i%2 == 0) { + t.Fatalf("pause reports %v: starts and ends must alternate", got) + } + } +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index f067d5e9b6..7fbd0e654b 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -185,19 +185,20 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen log.Printf("durable: chunk layer for volume=%s waits for master authority (%s): projection lacks %s", volumeID, bound, chunkAuthorityGap(p.view.Projection(), volumeID)) // The wait's bound is the master's: the startup stall window pauses - // while authority is missing and restarts at the grant, before any local - // attach work, so a stuck attach is still a stall. - endPause := func() {} + // while authority is missing and restarts at each grant, before any local + // attach work, so a stuck attach is still a stall; authority lost again + // before an attach pauses it again. + setPaused := func(bool) {} if aw := p.cfg.AuthorityWait; aw != nil { - aw(true) - paused := true - endPause = func() { - if paused { - paused = false - aw(false) + paused := false + setPaused = func(want bool) { + if want != paused { + paused = want + aw(want) } } - defer endPause() + setPaused(true) + defer setPaused(false) } ended := "superseded by a later recovery" defer func() { @@ -264,6 +265,7 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen } proj := p.view.Projection() if !chunkAuthority(proj, volumeID) { + setPaused(true) // missing (again): the master's wait // Authority first: a grant that arrives on the same tick as the // bound attaches instead of giving up. if gaveUp() { @@ -278,7 +280,7 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen expired, ended = true, "assignment allowance ended before attach retry" return } - endPause() // granted: the attach below is local work again + setPaused(false) // granted: the attach below is local work again if attempts++; attempts == 1 { log.Printf("durable: chunk layer for volume=%s: master authority after %s (replica=%q epoch=%d endpoint=%d); first attach attempt", volumeID, time.Since(start), proj.ReplicaID, proj.Epoch, proj.EndpointVersion) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 3e05f9c8cf..0142485654 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -612,7 +612,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `TestNativeReplacementTornWrapKeepsAcknowledgedSuffix` (`core/storage/legacy_replacement_v3_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-RECOVERY-PROGRESS-WINDOW-001` | Startup reports recovery_stalled only after a window without a new fixed-order phase/count frontier; repeated preparation cannot renew it. Progress never grants readiness or ownership. | M1 Recovering | `core/host/volume/recovery_watchdog.go`; `cmd/blockvolume/durable_startup.go`; `core/storage/recovery_progress.go` | `TestDurableStartup_LocalRecoveryWorkIsOutsideFixedDeadline` (`cmd/blockvolume/durable_startup_budget_test.go`); `TestRecoveryProgress_CountingEntriesOutliveTheTotalWindow`, `TestRecoveryProgress_RepeatedAttachPreparationDoesNotRenew` (`core/host/volume/recovery_progress_test.go`); attach: `TestAttachReportsItsVolumeSizedLocalWork`, `TestAttachReportsTheCreatedThisStartScan`, `TestAttachProgressFlushesSlowWorkAboutEverySecond` (`core/storage/chunk_attach_progress_test.go`), `TestAttachProgressCountsEachAttemptFromZero`, `TestAttachRemoteCallsCarryTheirOwnBound`, `TestAttachManifestReadCarriesThePerFetchRule` (`core/frontend/durable/attach_progress_test.go`), `TestAttachManifestReadBoundsEachFetch` (`core/frontend/chunkstore/layout_attach_fetch_test.go`) | — (joint recovery+attach Linux qualification: 7495 PASS, 0 FAIL, race x5 including the attach tests); C.L | ACTIVE | | `INV-RECOVERY-SIZED-STEP-SLICES-001` | A sized startup step (a new store's prezero, the WAL fence) reports its bytes as recovery progress only after their sync, prezero one 4 MiB slice at a time. | M1 Recovering | `core/storage/recovery_progress.go` `syncedSlices`; `core/storage/data_sync.go` `prezeroNewStore`; `core/storage/walstore_v3.go` `fenceV3` | `TestSyncedSlicesCountOnlySyncedSlices`, `TestPrezeroReportsEachSyncedSlice`, `TestRecoveryReportsTheSyncedFence`, `TestRecoveryFenceHeldSyncReportsAfterRelease`, `TestPrezeroReportsAfterEachSyncAndStopsAtAFailedOne` (`core/storage/recovery_create_progress_test.go`); `TestRecoveryStalled_CreateSlicesRenewTheWindow` (`core/host/volume/recovery_authority_wait_test.go`) | — | ACTIVE | -| `INV-RECOVERY-AUTHORITY-WAIT-PAUSE-001` | The recovery_stalled window pauses while a recovered volume awaits master authority and restarts at the grant, before local attach work; silence that filled the window before the wait is latched at its start. The master bounds the wait. | M1 Recovering | `core/host/volume/recovery_watchdog.go` `ReportAuthorityWait`; `core/frontend/durable/provider_chunk.go` `chunkAuthorityWait` | `TestRecoveryStalled_FullAuthorityWaitDoesNotStall`, `TestRecoveryStalled_SilentStepBeyondTheWindowIsCaught`, `TestRecoveryStalled_SilenceBeforeTheWaitIsLatchedAtItsStart`, `TestRecoveryStalled_HeldAttachAfterTheGrantStalls` (`core/host/volume/recovery_authority_wait_test.go`); `TestAuthorityWaitIsReportedAndShowsItsGap`, `TestAuthorityWaitEndsAtTheGrantBeforeTheAttach` (`core/frontend/durable/authority_wait_hook_test.go`) | — | ACTIVE | +| `INV-RECOVERY-AUTHORITY-WAIT-PAUSE-001` | The recovery_stalled window pauses while a recovered volume awaits master authority and restarts at the grant, before local attach work; silence that filled the window before the wait is latched at its start. The master bounds the wait. | M1 Recovering | `core/host/volume/recovery_watchdog.go` `ReportAuthorityWait`; `core/frontend/durable/provider_chunk.go` `chunkAuthorityWait` | `TestRecoveryStalled_FullAuthorityWaitDoesNotStall`, `TestRecoveryStalled_SilentStepBeyondTheWindowIsCaught`, `TestRecoveryStalled_SilenceBeforeTheWaitIsLatchedAtItsStart`, `TestRecoveryStalled_HeldAttachAfterTheGrantStalls` (`core/host/volume/recovery_authority_wait_test.go`); `TestAuthorityWaitIsReportedAndShowsItsGap`, `TestAuthorityWaitEndsAtTheGrantBeforeTheAttach`, `TestAuthorityLostAfterAGrantPausesAgain` (`core/frontend/durable/authority_wait_hook_test.go`) | — | ACTIVE | | `INV-OPEN-REMOVED-ENGINE-REFUSED-001` | A volume whose header carries a removed experimental engine's magic (smartwal `SWAW`; parallel-walstore `SWPW` at offset 0 or 4096) is refused typed (copy the data to a walstore volume with v1.0.x first) under every selector, read-only and never modified. | M1 [*] → OpenRefused | `core/frontend/durable/provider.go` `verifyImplOnDisk` | `TestDurableProvider_RefusesRemovedEngineVolumes` (byte-identical file after each refusal; `core/frontend/durable/provider_auto_impl_test.go`); `TestWALStoreChunk_SelectorRules` (`core/frontend/durable/provider_chunk_test.go`) | — | ACTIVE | | `INV-OPEN-REMOVED-ENGINE-NAME-REFUSED-001` | A selector naming a removed experimental engine (`smartwal`, `parallel-walstore`) is refused typed, with the same advice, by blockvolume, the provider and the Kubernetes launcher before any volume is touched. | M1 [*] → OpenRefused | `core/frontend/durable/provider.go` `RemovedEngineName`, `NewDurableProvider`; `cmd/blockvolume/main.go` `parseFlags`; `core/launcher/k8s_renderer.go` | `TestDurableProvider_RefusesRemovedEngineNames` (`core/frontend/durable/provider_auto_impl_test.go`); `TestBlockvolumeRefusesRemovedEngineNames` (`cmd/blockvolume/durable_impl_default_test.go`); `TestK8sRendererRefusesRemovedEngines` (`core/launcher/k8s_renderer_test.go`) | — | ACTIVE | | `INV-WAL-OPGATE-001` | A durable backend refuses `Read`, `Write` and `Sync` until `RecoverVolume` succeeds; a failed recovery leaves it refused. | M1 Opened → Serving; Recovering → RecoveryFailed | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/durable/provider.go` `RecoverVolume` | `TestT3b_DurableProvider_Open_StartsNotOperational` (`core/frontend/durable/provider_test.go`); `TestT3b_Recovery_CleanRecover_FlipsOperational` (`core/frontend/durable/recovery_test.go`); `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | From 9b6114bfe3414bb1c8a2634c7c265706daf74d46 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 03:36:38 -0800 Subject: [PATCH 5/5] storage: the held-sync control bounds every wait and owns its worker Waiting for the held slice and for the recovery's return is bounded, and on every exit the test releases the hold, joins its recovery worker (bounded) and only then closes the store, so a regression fails the test instead of hanging it. Co-Authored-By: Claude Opus 5.5 --- .../storage/recovery_create_progress_test.go | 46 +++++++++++++++---- 1 file changed, 38 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/storage/recovery_create_progress_test.go b/seaweed-block/core/storage/recovery_create_progress_test.go index ce958373b4..8dc8e42cb6 100644 --- a/seaweed-block/core/storage/recovery_create_progress_test.go +++ b/seaweed-block/core/storage/recovery_create_progress_test.go @@ -107,6 +107,7 @@ func TestRecoveryReportsTheSyncedFence(t *testing.T) { // has been reported. func TestRecoveryFenceHeldSyncReportsAfterRelease(t *testing.T) { const wal = 3 * fenceSliceBytes + const bound = 10 * time.Second // every wait in this test is bounded path := filepath.Join(t.TempDir(), "volume") created, err := createWALStoreV3ForTest(path, 256, 4096, wal, WModeStrict) if err != nil { @@ -119,12 +120,9 @@ func TestRecoveryFenceHeldSyncReportsAfterRelease(t *testing.T) { if err != nil { t.Fatal(err) } - defer s.Close() held, release := make(chan struct{}), make(chan struct{}) var releaseOnce sync.Once - // Deferred after Close, so it runs first: a failing test never leaves - // the recovery held while Close waits for it. - defer releaseOnce.Do(func() { close(release) }) + releaseHold := func() { releaseOnce.Do(func() { close(release) }) } first := true s.testAfterFenceFsync = func() { if first { @@ -139,17 +137,49 @@ func TestRecoveryFenceHeldSyncReportsAfterRelease(t *testing.T) { reports <- done } }) + // The test owns its recovery worker: on every exit it releases the hold, + // joins the worker (bounded), and only then closes the store; a worker + // that does not return is reported and the store is left open rather + // than closed under it. done := make(chan error, 1) + var recoverErr error + joined := false + join := func() bool { + if joined { + return true + } + select { + case recoverErr = <-done: + joined = true + case <-time.After(bound): + } + return joined + } go func() { _, err := s.RecoverContext(ctx); done <- err }() - <-held + defer func() { + releaseHold() + if !join() { + t.Errorf("recovery did not return within %s of its release; the store is not closed", bound) + return + } + _ = s.Close() + }() + select { + case <-held: + case <-time.After(bound): + t.Fatalf("no fence slice reached its fsync within %s", bound) + } select { case n := <-reports: t.Fatalf("a held slice reported %d bytes before its sync returned", n) case <-time.After(100 * time.Millisecond): } - releaseOnce.Do(func() { close(release) }) - if err := <-done; err != nil { - t.Fatalf("recovery after the held sync: %v", err) + releaseHold() + if !join() { + t.Fatalf("recovery did not return within %s of its release", bound) + } + if recoverErr != nil { + t.Fatalf("recovery after the held sync: %v", recoverErr) } close(reports) var got []uint64