From 2b1129eba2d858fa01bbc34244a1c7fca539392e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 09:29:45 -0800 Subject: [PATCH] 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 |