From ee6a8471bd43cf26477344f743421442fae1bbe0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 08:53:36 -0800 Subject: [PATCH 1/4] fix: observe C3 recovery progress and graceful stop separately --- .../c3_graceful_stop_integration_test.go | 41 ++++++ .../c3_progress_wait_integration_test.go | 60 +++++++++ .../planned_handoff_integration_test.go | 48 ++++++- .../recovery_primary_wait_support_test.go | 77 ++++++++++++ .../blockvolume/recovery_primary_wait_test.go | 118 ++++++++++++++++++ ...snapshot_ladder_c3kill_integration_test.go | 2 +- .../core/host/volume/recovery_status_test.go | 68 ++++++++++ .../core/host/volume/recovery_watchdog.go | 62 +++++++-- .../core/host/volume/status_schema_test.go | 1 + .../core/host/volume/status_server.go | 20 +++ seaweed-block/core/storage/walstore.go | 22 ++++ seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/status-schema.md | 18 +++ 13 files changed, 525 insertions(+), 14 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/c3_graceful_stop_integration_test.go create mode 100644 seaweed-block/cmd/blockvolume/c3_progress_wait_integration_test.go create mode 100644 seaweed-block/cmd/blockvolume/recovery_primary_wait_support_test.go create mode 100644 seaweed-block/cmd/blockvolume/recovery_primary_wait_test.go create mode 100644 seaweed-block/core/host/volume/recovery_status_test.go diff --git a/seaweed-block/cmd/blockvolume/c3_graceful_stop_integration_test.go b/seaweed-block/cmd/blockvolume/c3_graceful_stop_integration_test.go new file mode 100644 index 0000000000..cfe964dc4e --- /dev/null +++ b/seaweed-block/cmd/blockvolume/c3_graceful_stop_integration_test.go @@ -0,0 +1,41 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "syscall" + "testing" + "time" +) + +// The graceful-stop procedure: the driver applies the same pre-create disk cap +// and measured neighbour as C3. No SIGKILL is sent until this cell has ended. +func TestC3GracefulStopWithReclaimPressure(t *testing.T) { + env := startHandoffEnvWith(t, 1, nil) + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + d := env.start(t, "blockvolume-graceful", "s1") + env.adopt(t, d, "s1") + var chunks []uint64 + for c := uint64(0); c < 32; c++ { + chunks = append(chunks, c) + } + env.writeImage(t, "s1", denseImage("graceful-pressure", chunks)) + began := time.Now() + t.Logf("GRACEFUL_BEGIN time=%s", began.UTC().Format(time.RFC3339Nano)) + if err := d.proc.Signal(syscall.SIGTERM); err != nil { + t.Fatal(err) + } + select { + case <-d.done: + keepFullLog(t, d) + t.Logf("GRACEFUL_PHASES log tail:\n%s", d.tail(80)) + t.Logf("GRACEFUL_END elapsed=%s err=%v", time.Since(began), d.err) + if d.err != nil { + t.Fatalf("graceful exit: %v", d.err) + } + case <-time.After(5 * time.Minute): + keepFullLog(t, d) + logTaskState(t, d, "graceful driver ceiling") + t.Skip("UNKNOWN: graceful driver ceiling expired; classify from phase/progress and kernel evidence, not elapsed time alone") + } +} diff --git a/seaweed-block/cmd/blockvolume/c3_progress_wait_integration_test.go b/seaweed-block/cmd/blockvolume/c3_progress_wait_integration_test.go new file mode 100644 index 0000000000..7e4e6a0b7e --- /dev/null +++ b/seaweed-block/cmd/blockvolume/c3_progress_wait_integration_test.go @@ -0,0 +1,60 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "encoding/json" + "fmt" + "github.com/seaweedfs/seaweed-block/core/host/volume" + "net/http" + "testing" + "time" +) + +func waitC3RecoveryPrimary(t *testing.T, d *daemon, addr, target string) { + t.Helper() + w := newRecoveryPrimaryWait(time.Now()) + client := &http.Client{Timeout: time.Second} + needle := fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at r1@", target) + for { + var s volume.RecoveryProgressStatus + resp, err := client.Get("http://" + addr + "/status/recovery-progress?volume=" + target) + if err == nil { + if resp.StatusCode != http.StatusOK { + err = fmt.Errorf("recovery observer HTTP %d", resp.StatusCode) + } else { + err = json.NewDecoder(resp.Body).Decode(&s) + } + resp.Body.Close() + if err == nil && s.ProcessID == "" { + err = fmt.Errorf("recovery observer lacks process identity") + } + } + now := time.Now() + if err == nil { + t.Logf("C3_RECOVERY volume=%s status=%+v", target, s) + } else { + t.Logf("C3_RECOVERY volume=%s unavailable=%v", target, err) + } + + state, waitErr := w.observe(now, s, d.line(needle) != "" && err == nil, err == nil) + if state == "unknown" { + if now.Sub(w.began) >= 15*time.Minute { + t.Skip("UNKNOWN: C3 recovery exceeded15min experiment ceiling") + } + t.Skipf("UNKNOWN: recovery observer unavailable for30s: %v", err) + } + if waitErr != nil { + t.Fatalf("%s: %v; log tail:\n%s", d.name, waitErr, d.tail(40)) + } + if state == "primary" { + return + } + select { + case <-d.done: + t.Fatalf("%s exited before PRIMARY: %v", d.name, d.err) + default: + } + time.Sleep(time.Second) + } +} diff --git a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go index 99e943d1ca..ddb6196c17 100644 --- a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go +++ b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go @@ -566,11 +566,13 @@ func (d *daemon) term(t *testing.T, timeout time.Duration) { // kill kills the child (no ACK is sent on a signal) and waits for it. func (d *daemon) kill(t *testing.T) { t.Helper() + began := time.Now() + defer func() { t.Logf("%s SIGKILL-to-reap=%s", d.name, time.Since(began)) }() d.cancel() select { case <-d.done: case <-time.After(10 * time.Second): - t.Fatalf("%s did not exit after kill", d.name) + d.waitForKilledReap(t) } } @@ -591,14 +593,16 @@ func (h *plannedHandoffHarness) start(t *testing.T, name, binary string, args .. d := &daemon{name: name, log: log.Name(), done: make(chan struct{}), cancel: cancel} started := false t.Cleanup(func() { + stopAt := time.Now() cancel() if started { select { case <-d.done: case <-time.After(10 * time.Second): - t.Errorf("%s did not exit after cancellation", name) + d.waitForKilledReap(t) } } + t.Logf("%s cancellation-to-reap=%s", name, time.Since(stopAt)) _ = log.Close() if t.Failed() { keepFullLog(t, d) @@ -912,3 +916,43 @@ func (c *nvmeInitiator) close() { } } } + +// A killed task can remain in uninterruptible filesystem I/O. The containing +// procedure owns its outer ceiling;10s alone is never a product-stop failure. +func (d *daemon) waitForKilledReap(t *testing.T) { + t.Helper() + began := time.Now() + ticker := time.NewTicker(5 * time.Second) + defer ticker.Stop() + ceiling := began.Add(15 * time.Minute) + if deadline, ok := t.Deadline(); ok && deadline.Add(-5*time.Second).Before(ceiling) { + ceiling = deadline.Add(-5 * time.Second) + } + timer := time.NewTimer(time.Until(ceiling)) + defer timer.Stop() + for { + logTaskState(t, d, "SIGKILL reap pending") + select { + case <-d.done: + t.Logf("environment: %s reaped after additional %s (SIGKILL; not graceful stop)", d.name, time.Since(began)) + return + case <-timer.C: + t.Skipf("UNKNOWN: environment reap observation ceiling reached; outstanding name=%s pid=%d, driver retains cleanup ownership", d.name, d.proc.Pid) + case <-ticker.C: + } + } +} +func logTaskState(t *testing.T, d *daemon, reason string) { + t.Helper() + if d.proc == nil { + return + } + dirs, err := filepath.Glob(fmt.Sprintf("/proc/%d/task/*", d.proc.Pid)) + t.Logf("environment: %s name=%s pid=%d at=%s tasks_error=%v", reason, d.name, d.proc.Pid, time.Now().UTC().Format(time.RFC3339Nano), err) + for _, dir := range dirs { + for _, field := range []string{"stat", "wchan", "stack", "io"} { + data, err := os.ReadFile(filepath.Join(dir, field)) + t.Logf("environment: task=%s %s=%q error=%v", filepath.Base(dir), field, data, err) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/recovery_primary_wait_support_test.go b/seaweed-block/cmd/blockvolume/recovery_primary_wait_support_test.go new file mode 100644 index 0000000000..7fa3a930c1 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/recovery_primary_wait_support_test.go @@ -0,0 +1,77 @@ +package main_test + +import ( + "fmt" + "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/storage" + "time" +) + +// The ceiling bounds the experiment, not product recovery. Reaching it is +// UNKNOWN even if a PRIMARY line arrives in the same observation. +type recoveryPrimaryWait struct { + began, last time.Time + lastAvailable time.Time + process string + phase storage.RecoveryPhase + completed uint64 + awaiting bool + fenceBytes, replayRecords uint64 + windowStarted bool +} + +func newRecoveryPrimaryWait(now time.Time) *recoveryPrimaryWait { + return &recoveryPrimaryWait{began: now, last: now, lastAvailable: now} +} +func (w *recoveryPrimaryWait) observe(now time.Time, s volume.RecoveryProgressStatus, adopted bool, available bool) (string, error) { + if now.Sub(w.began) >= 15*time.Minute { + return "unknown", nil + } + if !available { + if now.Sub(w.lastAvailable) >= 30*time.Second { + return "unknown", nil + } + return "waiting", nil + } + w.lastAvailable = now + if s.Stalled { + return "", fmt.Errorf("recovery_stalled at phase %d completed %d", s.Phase, s.Completed) + } + if s.ProcessID != "" { + if w.process != "" && w.process != s.ProcessID { + return "", fmt.Errorf("holder incarnation changed: %s -> %s", w.process, s.ProcessID) + } + w.process = s.ProcessID + } + if s.FenceBytes > w.fenceBytes || s.ReplayRecords > w.replayRecords { + completedAt := s.CounterProgressAt + if completedAt.IsZero() { + completedAt = now + } + if w.windowStarted && !w.awaiting && completedAt.Sub(w.last) >= 30*time.Second { + return "", fmt.Errorf("completed recovery gap reached30s before late work") + } + w.fenceBytes, w.replayRecords, w.last = s.FenceBytes, s.ReplayRecords, completedAt + w.windowStarted = true + } + if !w.windowStarted && (s.Phase == storage.RecoveryReplay || s.Phase == storage.RecoveryFence) { + w.windowStarted = true + w.last = now + } + w.phase, w.completed = s.Phase, s.Completed + + if w.windowStarted && s.AwaitingAuthority && !w.awaiting && !s.AuthorityWaitSince.IsZero() && s.AuthorityWaitSince.Sub(w.last) >= 30*time.Second { + return "", fmt.Errorf("silence reached30s before authority pause") + } + if s.AwaitingAuthority || w.awaiting { + w.last = now + } + w.awaiting = s.AwaitingAuthority + if !s.AwaitingAuthority && (s.Phase == storage.RecoveryReplay || s.Phase == storage.RecoveryFence) && now.Sub(w.last) >= 30*time.Second { + return "", fmt.Errorf("no completed recovery work for30s (phase %d completed %d)", w.phase, w.completed) + } + if adopted && s.ProcessID != "" { + return "primary", nil + } + return "waiting", nil +} diff --git a/seaweed-block/cmd/blockvolume/recovery_primary_wait_test.go b/seaweed-block/cmd/blockvolume/recovery_primary_wait_test.go new file mode 100644 index 0000000000..7395d6426e --- /dev/null +++ b/seaweed-block/cmd/blockvolume/recovery_primary_wait_test.go @@ -0,0 +1,118 @@ +package main_test + +import ( + "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/storage" + "testing" + "time" +) + +func TestRecoveryPrimaryWaitUsesProgressNotTotalTime(t *testing.T) { + start := time.Unix(1000, 0) + w := newRecoveryPrimaryWait(start) + for i := 1; i <= 6; i++ { + now := start.Add(time.Duration(i) * 20 * time.Second) + s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, Completed: uint64(i) * 4 << 20, FenceBytes: uint64(i) * 4 << 20} + if got, err := w.observe(now, s, false, true); got != "waiting" || err != nil { + t.Fatalf("progress %d: %s %v", i, got, err) + } + } + if got, err := w.observe(start.Add(121*time.Second), volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, Completed: 24 << 20}, true, true); got != "primary" || err != nil { + t.Fatalf("%s %v", got, err) + } +} + +func TestRecoveryPrimaryWaitRejectsRepeatedSamplesAndStall(t *testing.T) { + start := time.Unix(1000, 0) + w := newRecoveryPrimaryWait(start) + s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, Completed: 4 << 20, FenceBytes: 4 << 20} + w.observe(start, s, false, true) + if _, err := w.observe(start.Add(30*time.Second), s, false, true); err == nil { + t.Fatal("identical counter renewed") + } + w = newRecoveryPrimaryWait(start) + s.Stalled = true + if _, err := w.observe(start, s, true, true); err == nil { + t.Fatal("stalled sample passed as primary") + } +} + +func TestRecoveryPrimaryWaitAuthorityPauseAndCeilingUnknown(t *testing.T) { + start := time.Unix(1000, 0) + w := newRecoveryPrimaryWait(start) + s := volume.RecoveryProgressStatus{ProcessID: "p1", AwaitingAuthority: true} + if got, err := w.observe(start.Add(time.Minute), s, false, true); got != "waiting" || err != nil { + t.Fatalf("pause: %s %v", got, err) + } + s.AwaitingAuthority = false + if got, err := w.observe(start.Add(2*time.Minute), s, false, true); got != "waiting" || err != nil { + t.Fatalf("grant: %s %v", got, err) + } + if got, err := w.observe(start.Add(15*time.Minute), s, true, true); got != "unknown" || err != nil { + t.Fatalf("ceiling became pass: %s %v", got, err) + } +} + +func TestRecoveryPrimaryWaitLateProgressCannotHideSilence(t *testing.T) { + start := time.Unix(1000, 0) + for _, pause := range []bool{false, true} { + w := newRecoveryPrimaryWait(start) + first := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, Completed: 1, FenceBytes: 1, CounterProgressAt: start} + w.observe(start, first, false, true) + late := first + late.Completed = 2 + late.FenceBytes = 2 + late.CounterProgressAt = start.Add(31 * time.Second) + if pause { + late = first + late.AwaitingAuthority = true + late.AuthorityWaitSince = start.Add(31 * time.Second) + } + if _, err := w.observe(start.Add(31*time.Second), late, true, true); err == nil { + t.Fatalf("late pause=%t hid silence", pause) + } + } +} +func TestRecoveryPrimaryWaitUnavailableSamplePreservesPause(t *testing.T) { + start := time.Unix(1000, 0) + w := newRecoveryPrimaryWait(start) + s := volume.RecoveryProgressStatus{ProcessID: "p1", AwaitingAuthority: true, AuthorityWaitSince: start} + w.observe(start, s, false, true) + if state, err := w.observe(start.Add(29*time.Second), volume.RecoveryProgressStatus{}, false, false); state != "waiting" || err != nil { + t.Fatalf("missing: %s %v", state, err) + } + if !w.awaiting || w.process != "p1" { + t.Fatal("missing sample changed known state") + } + if state, err := w.observe(start.Add(30*time.Second), volume.RecoveryProgressStatus{}, true, false); state != "unknown" || err != nil { + t.Fatalf("missing observation passed: %s %v", state, err) + } +} + +func TestRecoveryPrimaryWaitPhaseChangeIsNotProgress(t *testing.T) { + start := time.Unix(1000, 0) + w := newRecoveryPrimaryWait(start) + s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryReplay, ReplayRecords: 7, Completed: 7, CounterProgressAt: start} + w.observe(start, s, false, true) + s.Phase = storage.RecoveryFence + s.Completed = 1 + s.CounterProgressAt = start.Add(29 * time.Second) + if _, err := w.observe(start.Add(30*time.Second), s, true, true); err == nil { + t.Fatal("phase-only change hid no-progress window") + } +} + +func TestRecoveryPrimaryWaitDoesNotCountPreReplayWork(t *testing.T) { + start := time.Unix(1000, 0) + w := newRecoveryPrimaryWait(start) + w.observe(start, volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryCreate}, false, true) + s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryReplay, ReplayRecords: 1, CounterProgressAt: start.Add(40 * time.Second)} + if got, err := w.observe(start.Add(40*time.Second), s, false, true); got != "waiting" || err != nil { + t.Fatalf("pre-replay time counted: %s %v", got, err) + } + s.Phase = storage.RecoveryFence + s.LastProgress = start.Add(69 * time.Second) + if _, err := w.observe(start.Add(70*time.Second), s, true, true); err == nil { + t.Fatal("phase-only timestamp hid counter silence") + } +} diff --git a/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go b/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go index 916f446a9b..5292143565 100644 --- a/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go +++ b/seaweed-block/cmd/blockvolume/snapshot_ladder_c3kill_integration_test.go @@ -89,7 +89,7 @@ func (env *handoffEnv) startTarget(t *testing.T, target, name string) *daemon { t.Helper() b := env.hosts["n-"+target] d := env.h.start(t, name, env.h.volume, env.volArgsFor(b)...) - d.waitLog(t, 60*time.Second, fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at r1@", target)) + waitC3RecoveryPrimary(t, d, b.status, target) poll(t, 60*time.Second, fmt.Sprintf("%s never reported its frontend ready", target), func() bool { return volumeFrontendReady(b.status, target) }) diff --git a/seaweed-block/core/host/volume/recovery_status_test.go b/seaweed-block/core/host/volume/recovery_status_test.go new file mode 100644 index 0000000000..0d5fd383a4 --- /dev/null +++ b/seaweed-block/core/host/volume/recovery_status_test.go @@ -0,0 +1,68 @@ +package volume + +import ( + "context" + "encoding/json" + "net/http" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestRecoveryStatusReportsOnlyCompletedFrontiers(t *testing.T) { + h, clk := watchdogHost(t, 30*time.Second) + h.applyFixtureFact(selfPrimaryFact(1)) + h.ReportRecoveryProgress(storage.RecoveryReplay, 7) + clk.advance(time.Second) + h.ReportRecoveryProgress(storage.RecoveryFence, 4<<20) + s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", h)) + addr, err := s.Start("127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer s.Close(context.Background()) + read := func() map[string]any { + t.Helper() + res, err := http.Get("http://" + addr + "/status/recovery-progress?volume=v1") + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + if res.StatusCode != 200 { + t.Fatalf("status %d", res.StatusCode) + } + var got map[string]any + if err := json.NewDecoder(res.Body).Decode(&got); err != nil { + t.Fatal(err) + } + return got + } + first := read() + if first["FenceBytes"] != float64(4<<20) || first["ReplayRecords"] != float64(7) || first["ProcessID"] == "" { + t.Fatalf("frontiers: %v", first) + } + clk.advance(10 * time.Second) + h.ReportRecoveryProgress(storage.RecoveryFence, 4<<20) + again := read() + if again["LastProgress"] != first["LastProgress"] { + t.Fatalf("repeat renewed: %v -> %v", first, again) + } + clk.advance(time.Second) + h.ReportRecoveryProgress(storage.RecoveryAttach, 1) + if read()["CounterProgressAt"] != first["CounterProgressAt"] { + t.Fatal("phase-only report changed counter timestamp") + } + h.ReportAuthorityWait(true) + if read()["AwaitingAuthority"] != true { + t.Fatal("missing authority pause") + } + h.ReportAuthorityWait(false) + clk.advance(31 * time.Second) + if h.UnhealthyReason() != UnhealthyRecoveryStalled { + t.Fatal("control did not stall") + } + if read()["Stalled"] != true { + t.Fatal("missing stalled latch") + } +} diff --git a/seaweed-block/core/host/volume/recovery_watchdog.go b/seaweed-block/core/host/volume/recovery_watchdog.go index 38440fb00a..0080fa466c 100644 --- a/seaweed-block/core/host/volume/recovery_watchdog.go +++ b/seaweed-block/core/host/volume/recovery_watchdog.go @@ -82,16 +82,20 @@ type recoveryWatchdog struct { timeout time.Duration now func() time.Time - primarySince time.Time // zero unless this replica holds the primary assignment - primaryEpoch uint64 - supportingSince time.Time // zero unless admitted as a supporting replica - supportingEpoch uint64 - timedOut bool // recovery_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 - lastProgress time.Time + primarySince time.Time // zero unless this replica holds the primary assignment + primaryEpoch uint64 + supportingSince time.Time // zero unless admitted as a supporting replica + supportingEpoch uint64 + timedOut bool // recovery_stalled latched until a ready fact + awaiting int // authority waits in progress: the window is paused while > 0 + authorityWaitSince time.Time + readySeen bool // promotion-ready once in this primary assignment: disarmed + progressPhase storage.RecoveryPhase + progressDone uint64 + fenceBytes uint64 + replayRecords uint64 + counterProgressAt time.Time + lastProgress time.Time } func newRecoveryWatchdog(timeout time.Duration) *recoveryWatchdog { @@ -123,6 +127,40 @@ func (h *Host) ReportRecoveryProgress(phase storage.RecoveryPhase, done uint64) w.timedOut = true } w.progressPhase, w.progressDone, w.lastProgress = phase, done, now + switch phase { + case storage.RecoveryFence: + w.fenceBytes = done + w.counterProgressAt = now + case storage.RecoveryReplay: + w.replayRecords = done + w.counterProgressAt = now + } +} + +// RecoveryProgressStatus is an observation of completed startup work in one +// process incarnation. Reading it does not renew the window or grant readiness. +type RecoveryProgressStatus struct { + ProcessID string // holder process incarnation; counters must not cross it + VolumeID string // served volume + Phase storage.RecoveryPhase // highest completed phase in fixed recovery order + Completed uint64 // cumulative completed work in Phase + FenceBytes uint64 // bytes whose fence sync completed + ReplayRecords uint64 // WAL records replayed, not bytes + CounterProgressAt time.Time // last completed replay record or synced fence slice; phase-only reports do not change it + LastProgress time.Time // last new completed frontier or authority-wait end + AuthorityWaitSince time.Time // start of the current master-owned pause + AwaitingAuthority bool // the master-owned authority wait pauses the window + Stalled bool // recovery_stalled latch; late work cannot clear it +} + +func (h *Host) recoveryProgressStatus() RecoveryProgressStatus { + w := h.wd + w.mu.Lock() + defer w.mu.Unlock() + return RecoveryProgressStatus{ProcessID: h.incarnation, VolumeID: h.cfg.VolumeID, + Phase: w.progressPhase, Completed: w.progressDone, FenceBytes: w.fenceBytes, + ReplayRecords: w.replayRecords, CounterProgressAt: w.counterProgressAt, LastProgress: w.lastProgress, + AwaitingAuthority: w.awaiting > 0, AuthorityWaitSince: w.authorityWaitSince, Stalled: w.timedOut} } // ReportAuthorityWait observes the chunk layer's wait for master @@ -158,6 +196,7 @@ func (w *recoveryWatchdog) authorityWaitEnds() { w.awaiting-- if w.awaiting == 0 { w.lastProgress = w.now() + w.authorityWaitSince = time.Time{} } } @@ -176,6 +215,9 @@ func (w *recoveryWatchdog) authorityWaitStarts() (fired bool) { w.timedOut, fired = true, true } } + if w.awaiting == 0 { + w.authorityWaitSince = w.now() + } w.awaiting++ return fired } diff --git a/seaweed-block/core/host/volume/status_schema_test.go b/seaweed-block/core/host/volume/status_schema_test.go index 815410cd39..7663c98456 100644 --- a/seaweed-block/core/host/volume/status_schema_test.go +++ b/seaweed-block/core/host/volume/status_schema_test.go @@ -27,6 +27,7 @@ var statusRoutes = []struct { typ reflect.Type }{ {"/status", "the volume's authority and health projection", reflect.TypeOf(StatusProjection{})}, + {"/status/recovery-progress", "completed recovery work in this holder process; reading never renews progress", reflect.TypeOf(RecoveryProgressStatus{})}, {"/status/peers", "replication peers of the served volume", reflect.TypeOf(peersStatusBody{})}, {"/status/durable", "durable store state of the served volume", reflect.TypeOf(durableStatusBody{})}, {"/status/wal-hold", "atomic WAL hold observations scoped to this process and store open", reflect.TypeOf(walHoldStatusBody{})}, diff --git a/seaweed-block/core/host/volume/status_server.go b/seaweed-block/core/host/volume/status_server.go index b356e42134..53dc1b224a 100644 --- a/seaweed-block/core/host/volume/status_server.go +++ b/seaweed-block/core/host/volume/status_server.go @@ -398,6 +398,7 @@ func (s *StatusServer) Start(addr string) (string, error) { mux := http.NewServeMux() registerLabHeapProfile(mux) mux.HandleFunc("/status", s.handleStatus) + mux.HandleFunc("/status/recovery-progress", s.handleRecoveryProgress) mux.HandleFunc("/metrics", s.handleWALHoldMetrics) mux.HandleFunc("/status/wal-hold", s.handleWALHoldStatus) mux.HandleFunc("/status/peers", s.handleStatusPeers) @@ -437,6 +438,25 @@ func (s *StatusServer) externalAccessAllowed() bool { return s.allowExternal } +func (s *StatusServer) handleRecoveryProgress(w http.ResponseWriter, r *http.Request) { + if !s.externalAccessAllowed() && !isLoopbackRemote(r.RemoteAddr) { + http.Error(w, "status endpoint restricted to loopback", http.StatusForbidden) + return + } + vol := r.URL.Query().Get("volume") + if vol == "" { + http.Error(w, "missing volume query param", http.StatusBadRequest) + return + } + h, ok := s.view.probe.(*Host) + if !ok || h == nil || h.wd == nil || vol != h.cfg.VolumeID { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(h.recoveryProgressStatus()) +} + // Close gracefully shuts the server down. Idempotent. func (s *StatusServer) Close(ctx context.Context) error { s.mu.Lock() diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 6844a2d0cc..a13bcc3187 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -1155,6 +1155,23 @@ func (s *WALStore) Close() (err error) { h := s.chunk.Load() s.captureMu.Unlock() defer func() { s.closeResult = err; close(s.closeComplete) }() + stopObservations := make(chan struct{}) + observationsDone := make(chan struct{}) + go func() { + defer close(observationsDone) + ticker := time.NewTicker(time.Second) + defer ticker.Stop() + for { + select { + case <-stopObservations: + return + case <-ticker.C: + p := s.ReclaimProgress() + fmt.Fprintf(os.Stderr, "storage: stop progress reclaimed=%d extent=%d phase=%s\n", p.ReclaimedBytes, p.ExtentBytes, p.Phase) + } + } + }() + defer func() { close(stopObservations); <-observationsDone }() phases := StoreStopPhases{} defer func() { phases.AtNs = time.Now().UnixNano() @@ -1163,6 +1180,7 @@ func (s *WALStore) Close() (err error) { phases.Error = err.Error() } s.lastStop.Store(&phases) + fmt.Fprintf(os.Stderr, "storage: stop phases=%+v\n", phases) }() if s.testCloseSnapshot != nil { @@ -1174,11 +1192,13 @@ func (s *WALStore) Close() (err error) { defer func() { err = errors.Join(err, closerErr) }() if h != nil { start := time.Now() + fmt.Fprintln(os.Stderr, "storage: stop phase=chunk_close") closerErr = h.closer() phases.ChunkCloseNs = time.Since(start).Nanoseconds() } lifecycleStart := time.Now() + fmt.Fprintln(os.Stderr, "storage: stop phase=lifecycle_wait") s.lifecycleMu.Lock() phases.LifecycleWaitNs = time.Since(lifecycleStart).Nanoseconds() defer s.lifecycleMu.Unlock() @@ -1199,11 +1219,13 @@ func (s *WALStore) Close() (err error) { var flushErr error if s.flusher != nil { start := time.Now() + fmt.Fprintln(os.Stderr, "storage: stop phase=flusher_stop") flushErr = s.flusher.Stop() phases.FlusherStopNs = time.Since(start).Nanoseconds() } if s.committer != nil { start := time.Now() + fmt.Fprintln(os.Stderr, "storage: stop phase=committer_stop") s.committer.Stop() phases.CommitterStopNs = time.Since(start).Nanoseconds() } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ca22eec784..bd1b21727b 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -623,7 +623,7 @@ 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-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`); observation: `TestRecoveryStatusReportsOnlyCompletedFrontiers` (`core/host/volume/recovery_status_test.go`); C3: `TestRecoveryPrimaryWaitUsesProgressNotTotalTime`, `TestRecoveryPrimaryWaitRejectsRepeatedSamplesAndStall`, `TestRecoveryPrimaryWaitAuthorityPauseAndCeilingUnknown`, `TestRecoveryPrimaryWaitLateProgressCannotHideSilence`, `TestRecoveryPrimaryWaitUnavailableSamplePreservesPause`, `TestRecoveryPrimaryWaitPhaseChangeIsNotProgress`, `TestRecoveryPrimaryWaitDoesNotCountPreReplayWork` (`cmd/blockvolume/recovery_primary_wait_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`, `TestCreateRecoveryReportsTheFenceThroughTheOptions` (`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`, `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 | diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 66c004c4aa..3ea485183a 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -49,6 +49,24 @@ The volume's authority and health projection. Go type `volume.StatusProjection`. | `MasterWait.SinceMs` | int64 | — | | `MasterWait.UntilMs` | int64 | — (omitted when empty) | +### `GET /status/recovery-progress` + +Completed recovery work in this holder process; reading never renews progress. Go type `volume.RecoveryProgressStatus`. + +| Field | Type | Meaning | +|---|---|---| +| `ProcessID` | string | holder process incarnation; counters must not cross it | +| `VolumeID` | string | served volume | +| `Phase` | RecoveryPhase (uint8) | highest completed phase in fixed recovery order | +| `Completed` | uint64 | cumulative completed work in Phase | +| `FenceBytes` | uint64 | bytes whose fence sync completed | +| `ReplayRecords` | uint64 | WAL records replayed, not bytes | +| `CounterProgressAt` | time (RFC 3339) | last completed replay record or synced fence slice; phase-only reports do not change it | +| `LastProgress` | time (RFC 3339) | last new completed frontier or authority-wait end | +| `AuthorityWaitSince` | time (RFC 3339) | start of the current master-owned pause | +| `AwaitingAuthority` | bool | the master-owned authority wait pauses the window | +| `Stalled` | bool | recovery_stalled latch; late work cannot clear it | + ### `GET /status/peers` Replication peers of the served volume. Go type `volume.peersStatusBody`. From 2b1129eba2d858fa01bbc34244a1c7fca539392e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 09:29:45 -0800 Subject: [PATCH 2/4] fix: require recovery exit evidence and keep Close off diagnostic output --- .../c3_progress_wait_integration_test.go | 2 +- .../recovery_primary_wait_support_test.go | 15 +++- .../blockvolume/recovery_primary_wait_test.go | 51 ++++++++++- .../core/storage/close_blocked_output_test.go | 89 +++++++++++++++++++ seaweed-block/core/storage/walstore.go | 22 ----- seaweed-block/docs/design/invariants.md | 2 +- 6 files changed, 154 insertions(+), 27 deletions(-) create mode 100644 seaweed-block/core/storage/close_blocked_output_test.go diff --git a/seaweed-block/cmd/blockvolume/c3_progress_wait_integration_test.go b/seaweed-block/cmd/blockvolume/c3_progress_wait_integration_test.go index 7e4e6a0b7e..b90c47ab6c 100644 --- a/seaweed-block/cmd/blockvolume/c3_progress_wait_integration_test.go +++ b/seaweed-block/cmd/blockvolume/c3_progress_wait_integration_test.go @@ -42,7 +42,7 @@ func waitC3RecoveryPrimary(t *testing.T, d *daemon, addr, target string) { if now.Sub(w.began) >= 15*time.Minute { t.Skip("UNKNOWN: C3 recovery exceeded15min experiment ceiling") } - t.Skipf("UNKNOWN: recovery observer unavailable for30s: %v", err) + t.Skipf("UNKNOWN: recovery observation lacks timely counter/exit evidence or was unavailable for30s: %v", err) } if waitErr != nil { t.Fatalf("%s: %v; log tail:\n%s", d.name, waitErr, d.tail(40)) diff --git a/seaweed-block/cmd/blockvolume/recovery_primary_wait_support_test.go b/seaweed-block/cmd/blockvolume/recovery_primary_wait_support_test.go index 7fa3a930c1..c47da0eafe 100644 --- a/seaweed-block/cmd/blockvolume/recovery_primary_wait_support_test.go +++ b/seaweed-block/cmd/blockvolume/recovery_primary_wait_support_test.go @@ -18,6 +18,7 @@ type recoveryPrimaryWait struct { awaiting bool fenceBytes, replayRecords uint64 windowStarted bool + workActive bool } func newRecoveryPrimaryWait(now time.Time) *recoveryPrimaryWait { @@ -46,16 +47,18 @@ func (w *recoveryPrimaryWait) observe(now time.Time, s volume.RecoveryProgressSt if s.FenceBytes > w.fenceBytes || s.ReplayRecords > w.replayRecords { completedAt := s.CounterProgressAt if completedAt.IsZero() { - completedAt = now + return "unknown", nil } if w.windowStarted && !w.awaiting && completedAt.Sub(w.last) >= 30*time.Second { return "", fmt.Errorf("completed recovery gap reached30s before late work") } w.fenceBytes, w.replayRecords, w.last = s.FenceBytes, s.ReplayRecords, completedAt w.windowStarted = true + w.workActive = true } if !w.windowStarted && (s.Phase == storage.RecoveryReplay || s.Phase == storage.RecoveryFence) { w.windowStarted = true + w.workActive = true w.last = now } w.phase, w.completed = s.Phase, s.Completed @@ -70,6 +73,16 @@ func (w *recoveryPrimaryWait) observe(now time.Time, s volume.RecoveryProgressSt if !s.AwaitingAuthority && (s.Phase == storage.RecoveryReplay || s.Phase == storage.RecoveryFence) && now.Sub(w.last) >= 30*time.Second { return "", fmt.Errorf("no completed recovery work for30s (phase %d completed %d)", w.phase, w.completed) } + // Phase-only completion is not a counter. Once replay/fence was seen, + // its exit must itself be observed inside the last completed-work window. + // A late attach sample cannot prove when that exit occurred, even when + // PRIMARY is already logged or a general LastProgress timestamp moved. + if w.workActive && s.Phase != storage.RecoveryReplay && s.Phase != storage.RecoveryFence { + if now.Sub(w.last) >= 30*time.Second { + return "unknown", nil + } + w.workActive = false + } if adopted && s.ProcessID != "" { return "primary", nil } diff --git a/seaweed-block/cmd/blockvolume/recovery_primary_wait_test.go b/seaweed-block/cmd/blockvolume/recovery_primary_wait_test.go index 7395d6426e..a49206b68f 100644 --- a/seaweed-block/cmd/blockvolume/recovery_primary_wait_test.go +++ b/seaweed-block/cmd/blockvolume/recovery_primary_wait_test.go @@ -1,6 +1,7 @@ package main_test import ( + "fmt" "github.com/seaweedfs/seaweed-block/core/host/volume" "github.com/seaweedfs/seaweed-block/core/storage" "testing" @@ -12,7 +13,7 @@ func TestRecoveryPrimaryWaitUsesProgressNotTotalTime(t *testing.T) { w := newRecoveryPrimaryWait(start) for i := 1; i <= 6; i++ { now := start.Add(time.Duration(i) * 20 * time.Second) - s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, Completed: uint64(i) * 4 << 20, FenceBytes: uint64(i) * 4 << 20} + s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, Completed: uint64(i) * 4 << 20, FenceBytes: uint64(i) * 4 << 20, CounterProgressAt: now} if got, err := w.observe(now, s, false, true); got != "waiting" || err != nil { t.Fatalf("progress %d: %s %v", i, got, err) } @@ -25,7 +26,7 @@ func TestRecoveryPrimaryWaitUsesProgressNotTotalTime(t *testing.T) { func TestRecoveryPrimaryWaitRejectsRepeatedSamplesAndStall(t *testing.T) { start := time.Unix(1000, 0) w := newRecoveryPrimaryWait(start) - s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, Completed: 4 << 20, FenceBytes: 4 << 20} + s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, Completed: 4 << 20, FenceBytes: 4 << 20, CounterProgressAt: start} w.observe(start, s, false, true) if _, err := w.observe(start.Add(30*time.Second), s, false, true); err == nil { t.Fatal("identical counter renewed") @@ -116,3 +117,49 @@ func TestRecoveryPrimaryWaitDoesNotCountPreReplayWork(t *testing.T) { t.Fatal("phase-only timestamp hid counter silence") } } + +func TestRecoveryPrimaryWaitExitNeedsTimelyWitness(t *testing.T) { + for _, phase := range []storage.RecoveryPhase{storage.RecoveryReplay, storage.RecoveryFence} { + for _, adopted := range []bool{false, true} { + t.Run(fmt.Sprintf("phase%d/primary%t", phase, adopted), func(t *testing.T) { + start := time.Unix(1000, 0) + w := newRecoveryPrimaryWait(start) + s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: phase, ReplayRecords: 1, CounterProgressAt: start} + if got, err := w.observe(start, s, false, true); got != "waiting" || err != nil { + t.Fatalf("setup: %s %v", got, err) + } + s.Phase = storage.RecoveryAttach + s.LastProgress = start.Add(31 * time.Second) + if got, err := w.observe(start.Add(31*time.Second), s, adopted, true); got != "unknown" || err != nil { + t.Fatalf("unproved exit became %s %v", got, err) + } + }) + } + } + // A witnessed timely exit ends only the replay/fence window; a later + // PRIMARY may follow other bounded work without inventing more counters. + t.Run("timely-exit", func(t *testing.T) { + start := time.Unix(1000, 0) + w := newRecoveryPrimaryWait(start) + s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, FenceBytes: 1, CounterProgressAt: start} + w.observe(start, s, false, true) + s.Phase = storage.RecoveryAttach + if got, err := w.observe(start.Add(29*time.Second), s, false, true); got != "waiting" || err != nil { + t.Fatalf("timely exit: %s %v", got, err) + } + if got, err := w.observe(start.Add(time.Minute), s, true, true); got != "primary" || err != nil { + t.Fatalf("witnessed exit: %s %v", got, err) + } + }) +} + +func TestRecoveryPrimaryWaitMissingCounterTimeIsUnknown(t *testing.T) { + start := time.Unix(1000, 0) + for _, adopted := range []bool{false, true} { + w := newRecoveryPrimaryWait(start) + s := volume.RecoveryProgressStatus{ProcessID: "p1", Phase: storage.RecoveryFence, FenceBytes: 1} + if got, err := w.observe(start.Add(31*time.Second), s, adopted, true); got != "unknown" || err != nil { + t.Fatalf("adopted=%t: missing timestamp became %s %v", adopted, got, err) + } + } +} diff --git a/seaweed-block/core/storage/close_blocked_output_test.go b/seaweed-block/core/storage/close_blocked_output_test.go new file mode 100644 index 0000000000..e6bcefc917 --- /dev/null +++ b/seaweed-block/core/storage/close_blocked_output_test.go @@ -0,0 +1,89 @@ +package storage + +import ( + "bytes" + "context" + "os" + "os/exec" + "testing" + "time" +) + +// A child bounds even a regressed Close/observer join. The sink is released +// and every child goroutine joined before reporting the assertion. +func TestWALStoreCloseDoesNotWaitForDiagnosticOutput(t *testing.T) { + if os.Getenv("SWBLOCK_CLOSE_BLOCKED_OUTPUT_CHILD") != "1" { + ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestWALStoreCloseDoesNotWaitForDiagnosticOutput$", "-test.timeout=10s") + cmd.Env = append(os.Environ(), "SWBLOCK_CLOSE_BLOCKED_OUTPUT_CHILD=1") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("bounded blocked-output child: %v\n%s", err, out) + } + return + } + s, _ := newMappedCheckpointStoreV3(t) + r, sink, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + old := os.Stderr + os.Stderr = sink + filled := make(chan struct{}) + go func() { defer close(filled); _, _ = sink.Write(bytes.Repeat([]byte{'x'}, 8<<20)) }() + select { + case <-filled: + os.Stderr = old + r.Close() + sink.Close() + t.Fatal("pipe did not provide a blocked sink") + case <-time.After(100 * time.Millisecond): + } + // Keep Close active long enough to exercise a periodic observer as well + // as its phase-entry and final diagnostics, if any are reintroduced. + s.testCloseSnapshot = func() { time.Sleep(1100 * time.Millisecond) } + results := make(chan error, 2) + go func() { results <- s.Close() }() + go func() { results <- s.Close() }() + completed := 0 + timer := time.NewTimer(3 * time.Second) + var closeErr error +wait: + for completed < 2 { + select { + case err := <-results: + completed++ + if err != nil { + closeErr = err + } + case <-timer.C: + break wait + } + } + timer.Stop() + beforeRelease := completed + // Release the blocked producer and any regressed Close logger; no writer + // is abandoned to make the success path appear bounded. + r.Close() + <-filled + for completed < 2 { + select { + case err := <-results: + completed++ + if err != nil { + closeErr = err + } + case <-time.After(2 * time.Second): + t.Fatal("Close did not join after releasing diagnostic sink") + } + } + os.Stderr = old + sink.Close() + if beforeRelease != 2 || closeErr != nil { + t.Fatalf("Close/closeComplete depended on diagnostic sink: completed=%d err=%v", beforeRelease, closeErr) + } + if stop := s.ChunkMapStatsV3().LastStop; stop == nil || stop.TotalNs <= 0 { + t.Fatalf("in-memory stop phases lost: %+v", stop) + } +} diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index a13bcc3187..6844a2d0cc 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -1155,23 +1155,6 @@ func (s *WALStore) Close() (err error) { h := s.chunk.Load() s.captureMu.Unlock() defer func() { s.closeResult = err; close(s.closeComplete) }() - stopObservations := make(chan struct{}) - observationsDone := make(chan struct{}) - go func() { - defer close(observationsDone) - ticker := time.NewTicker(time.Second) - defer ticker.Stop() - for { - select { - case <-stopObservations: - return - case <-ticker.C: - p := s.ReclaimProgress() - fmt.Fprintf(os.Stderr, "storage: stop progress reclaimed=%d extent=%d phase=%s\n", p.ReclaimedBytes, p.ExtentBytes, p.Phase) - } - } - }() - defer func() { close(stopObservations); <-observationsDone }() phases := StoreStopPhases{} defer func() { phases.AtNs = time.Now().UnixNano() @@ -1180,7 +1163,6 @@ func (s *WALStore) Close() (err error) { phases.Error = err.Error() } s.lastStop.Store(&phases) - fmt.Fprintf(os.Stderr, "storage: stop phases=%+v\n", phases) }() if s.testCloseSnapshot != nil { @@ -1192,13 +1174,11 @@ func (s *WALStore) Close() (err error) { defer func() { err = errors.Join(err, closerErr) }() if h != nil { start := time.Now() - fmt.Fprintln(os.Stderr, "storage: stop phase=chunk_close") closerErr = h.closer() phases.ChunkCloseNs = time.Since(start).Nanoseconds() } lifecycleStart := time.Now() - fmt.Fprintln(os.Stderr, "storage: stop phase=lifecycle_wait") s.lifecycleMu.Lock() phases.LifecycleWaitNs = time.Since(lifecycleStart).Nanoseconds() defer s.lifecycleMu.Unlock() @@ -1219,13 +1199,11 @@ func (s *WALStore) Close() (err error) { var flushErr error if s.flusher != nil { start := time.Now() - fmt.Fprintln(os.Stderr, "storage: stop phase=flusher_stop") flushErr = s.flusher.Stop() phases.FlusherStopNs = time.Since(start).Nanoseconds() } if s.committer != nil { start := time.Now() - fmt.Fprintln(os.Stderr, "storage: stop phase=committer_stop") s.committer.Stop() phases.CommitterStopNs = time.Since(start).Nanoseconds() } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index bd1b21727b..8c830fb39e 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -623,7 +623,7 @@ 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`); observation: `TestRecoveryStatusReportsOnlyCompletedFrontiers` (`core/host/volume/recovery_status_test.go`); C3: `TestRecoveryPrimaryWaitUsesProgressNotTotalTime`, `TestRecoveryPrimaryWaitRejectsRepeatedSamplesAndStall`, `TestRecoveryPrimaryWaitAuthorityPauseAndCeilingUnknown`, `TestRecoveryPrimaryWaitLateProgressCannotHideSilence`, `TestRecoveryPrimaryWaitUnavailableSamplePreservesPause`, `TestRecoveryPrimaryWaitPhaseChangeIsNotProgress`, `TestRecoveryPrimaryWaitDoesNotCountPreReplayWork` (`cmd/blockvolume/recovery_primary_wait_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`); observation: `TestRecoveryStatusReportsOnlyCompletedFrontiers` (`core/host/volume/recovery_status_test.go`); C3: `TestRecoveryPrimaryWaitUsesProgressNotTotalTime`, `TestRecoveryPrimaryWaitRejectsRepeatedSamplesAndStall`, `TestRecoveryPrimaryWaitAuthorityPauseAndCeilingUnknown`, `TestRecoveryPrimaryWaitLateProgressCannotHideSilence`, `TestRecoveryPrimaryWaitUnavailableSamplePreservesPause`, `TestRecoveryPrimaryWaitPhaseChangeIsNotProgress`, `TestRecoveryPrimaryWaitDoesNotCountPreReplayWork`, `TestRecoveryPrimaryWaitExitNeedsTimelyWitness`, `TestRecoveryPrimaryWaitMissingCounterTimeIsUnknown` (`cmd/blockvolume/recovery_primary_wait_test.go`); diagnostic shutdown isolation: `TestWALStoreCloseDoesNotWaitForDiagnosticOutput` (`core/storage/close_blocked_output_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`, `TestCreateRecoveryReportsTheFenceThroughTheOptions` (`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`, `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 | From 37fbb7ed045b5e9ea7ba04a944483b1cedb2ff2f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 11:18:22 -0800 Subject: [PATCH 3/4] ci: re-trigger From 116c0de507ce6a3e395c2967977369aded1363b0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 12:30:53 -0800 Subject: [PATCH 4/4] test(volume): review recovery snapshot watchdog lock site --- .../host/volume/recovery_lock_guard_test.go | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) 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 e29c5f1bd1..19b31a417a 100644 --- a/seaweed-block/core/host/volume/recovery_lock_guard_test.go +++ b/seaweed-block/core/host/volume/recovery_lock_guard_test.go @@ -22,6 +22,16 @@ func TestRecoveryWatchdogLockedMethodsNeverCallStorageOrWait(t *testing.T) { if err != nil { t.Fatal(err) } + // recoveryProgressStatus holds only w.mu while copying scalar fields and + // time.Time values. Its only calls are Lock/Unlock: no storage, helper, + // channel, I/O or wait is introduced by the read-only snapshot. + reviewed := map[string]bool{ + "ReportRecoveryProgress": true, "recoveryProgressStatus": true, + "authorityWaitEnds": true, "authorityWaitStarts": true, + "AwaitingAuthority": true, "primaryAssigned": true, "notPrimary": true, + "supportingAdmitted": true, "reason": true, "catchUpSince": true, + "epoch": true, + } locked := 0 for _, decl := range f.Decls { fn, ok := decl.(*ast.FuncDecl) @@ -34,12 +44,16 @@ func TestRecoveryWatchdogLockedMethodsNeverCallStorageOrWait(t *testing.T) { continue } locked++ + if !reviewed[fn.Name.Name] { + t.Errorf("unreviewed watchdog-locked method %s", fn.Name.Name) + } + delete(reviewed, fn.Name.Name) for _, violation := range watchdogBodyViolations(fset, fn.Body) { t.Errorf("watchdog-locked %s: %s", fn.Name.Name, violation) } } - if locked != 10 { - t.Fatalf("watchdog lock sites=%d, want 10 reviewed methods", locked) + if locked != 11 || len(reviewed) != 0 { + t.Fatalf("watchdog lock sites=%d, want 11 reviewed methods; missing=%v", locked, reviewed) } }