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 ff470eab69..5f6d1db5a7 100644 --- a/seaweed-block/core/host/volume/recovery_lock_guard_test.go +++ b/seaweed-block/core/host/volume/recovery_lock_guard_test.go @@ -2,10 +2,13 @@ package volume import ( "bytes" + "fmt" "go/ast" "go/format" "go/parser" "go/token" + "os" + "path/filepath" "strings" "testing" ) @@ -19,11 +22,6 @@ func TestRecoveryWatchdogLockedMethodsNeverCallStorageOrWait(t *testing.T) { if err != nil { t.Fatal(err) } - allowed := map[string]bool{ - "w.mu.Lock": true, "w.mu.Unlock": true, "w.now": true, - "w.primarySince.IsZero": true, "w.supportingSince.IsZero": true, - "w.lastProgress.After": true, "now.Sub": true, "w.now().Sub": true, - } locked := 0 for _, decl := range f.Decls { fn, ok := decl.(*ast.FuncDecl) @@ -36,20 +34,116 @@ func TestRecoveryWatchdogLockedMethodsNeverCallStorageOrWait(t *testing.T) { continue } locked++ - ast.Inspect(fn.Body, func(n ast.Node) bool { - call, ok := n.(*ast.CallExpr) - if !ok { - return true - } - var name bytes.Buffer - _ = format.Node(&name, fset, call.Fun) - if !allowed[name.String()] { - t.Errorf("watchdog-locked %s calls unreviewed %s", fn.Name.Name, name.String()) - } - return true - }) + for _, violation := range watchdogBodyViolations(fset, fn.Body) { + t.Errorf("watchdog-locked %s: %s", fn.Name.Name, violation) + } } if locked != 7 { t.Fatalf("watchdog lock sites=%d, want 7 reviewed methods", locked) } } + +func watchdogBodyViolations(fset *token.FileSet, body *ast.BlockStmt) []string { + allowed := map[string]bool{ + "w.mu.Lock": true, "w.mu.Unlock": true, "w.now": true, + "w.primarySince.IsZero": true, "w.supportingSince.IsZero": true, + "w.lastProgress.After": true, "now.Sub": true, "w.now().Sub": true, + } + var violations []string + ast.Inspect(body, func(n ast.Node) bool { + switch node := n.(type) { + case *ast.SendStmt, *ast.SelectStmt, *ast.RangeStmt, *ast.GoStmt: + violations = append(violations, fmt.Sprintf("unreviewed blocking/asynchronous construct %T", n)) + case *ast.UnaryExpr: + if node.Op == token.ARROW { + violations = append(violations, "channel receive") + } + case *ast.CallExpr: + var name bytes.Buffer + _ = format.Node(&name, fset, node.Fun) + if !allowed[name.String()] { + violations = append(violations, "unreviewed call "+name.String()) + } + } + return true + }) + return violations +} + +func TestRecoveryWatchdogLockGuardRejectsBlockingSyntax(t *testing.T) { + for _, statement := range []string{"ch <- value", "value = <-ch", "select { case <-ch: }", "for range ch {}", "go w.now()", "storage.Recover()"} { + t.Run(statement, func(t *testing.T) { + fset := token.NewFileSet() + f, err := parser.ParseFile(fset, "fixture.go", "package fixture; func bad() { "+statement+" }", 0) + if err != nil { + t.Fatal(err) + } + if len(watchdogBodyViolations(fset, f.Decls[0].(*ast.FuncDecl).Body)) == 0 { + t.Fatal("blocking mutation escaped") + } + }) + } +} + +// now may be replaced by tests, but production binds it only to time.Now. +// Pin the package-wide selector writes too: a blocking replacement elsewhere +// would bypass the locked-method call allow-list. +func TestRecoveryWatchdogClockBindingIsTimeNow(t *testing.T) { + files, err := filepath.Glob("*.go") + if err != nil { + t.Fatal(err) + } + bindings := 0 + for _, path := range files { + if strings.HasSuffix(path, "_test.go") { + continue + } + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + fset := token.NewFileSet() + f, err := parser.ParseFile(fset, path, data, 0) + if err != nil { + t.Fatal(err) + } + ast.Inspect(f, func(n ast.Node) bool { + if assignment, ok := n.(*ast.AssignStmt); ok { + for _, lhs := range assignment.Lhs { + if selector, ok := lhs.(*ast.SelectorExpr); ok && selector.Sel.Name == "now" { + t.Errorf("production clock selector assignment in %s needs review", path) + } + } + } + literal, ok := n.(*ast.CompositeLit) + if !ok { + return true + } + typ, ok := literal.Type.(*ast.Ident) + if !ok || typ.Name != "recoveryWatchdog" { + return true + } + for _, item := range literal.Elts { + kv, ok := item.(*ast.KeyValueExpr) + if !ok { + t.Errorf("unkeyed watchdog in %s", path) + continue + } + key, ok := kv.Key.(*ast.Ident) + if !ok || key.Name != "now" { + continue + } + bindings++ + var value bytes.Buffer + _ = format.Node(&value, fset, kv.Value) + if value.String() != "time.Now" { + t.Errorf("watchdog clock=%s", value.String()) + } + } + return true + }) + } + if bindings != 1 { + t.Fatalf("clock bindings=%d, want one reviewed time.Now", bindings) + } +} diff --git a/seaweed-block/core/storage/chunk_map_publication_v3.go b/seaweed-block/core/storage/chunk_map_publication_v3.go index 8fc67568d7..b93c51d090 100644 --- a/seaweed-block/core/storage/chunk_map_publication_v3.go +++ b/seaweed-block/core/storage/chunk_map_publication_v3.go @@ -83,6 +83,10 @@ func sameMapTupleV3(d descriptorV3, c *chunkMapCandidateV3) bool { // snapshot before installing the open proof domain. A fallback remains a root // even when none of its pages belong to the selected generation. func (p *descriptorPublisherV3) bindMapV3(c *chunkMapCandidateV3, d *mapProofEpochV3) error { + return p.bindMapV3Progress(c, d, nil) +} + +func (p *descriptorPublisherV3) bindMapV3Progress(c *chunkMapCandidateV3, d *mapProofEpochV3, progress *recoveryReporter) error { if c == nil || c.owner == nil || d == nil { return mapCoverageRefusal("map_binding_missing") } @@ -92,14 +96,14 @@ func (p *descriptorPublisherV3) bindMapV3(c *chunkMapCandidateV3, d *mapProofEpo if !sameMapTupleV3(current, c) { return mapCoverageRefusal("map_tuple_changed") } - if _, _, e := readChunkLSNMapV3(c.owner.fd, current, c.owner.chunkBlocks); e != nil { + if _, _, e := readChunkLSNMapV3Progress(c.owner.fd, current, c.owner.chunkBlocks, progress); e != nil { return e } if otherValid { if other.UUID != current.UUID || other.MapLineage != current.MapLineage || !sameGeometryV3(other, current) { return ErrMapInvalid } - if _, _, e := readChunkLSNMapV3(c.owner.fd, other, c.owner.chunkBlocks); e != nil { + if _, _, e := readChunkLSNMapV3Progress(c.owner.fd, other, c.owner.chunkBlocks, progress); e != nil { return e } } diff --git a/seaweed-block/core/storage/recovery_progress.go b/seaweed-block/core/storage/recovery_progress.go index dc56a5c4a1..00acaf4ba6 100644 --- a/seaweed-block/core/storage/recovery_progress.go +++ b/seaweed-block/core/storage/recovery_progress.go @@ -13,12 +13,20 @@ const ( RecoveryOpenMap RecoveryPhase = iota + 1 RecoveryOpenCopy RecoveryScan + RecoveryScanSpans + RecoveryScanSort + RecoveryScanFrontier + RecoveryProject + RecoveryDecide + RecoveryInstall RecoveryMap RecoveryReplay + RecoveryReclaim RecoveryAttach ) type recoveryProgressKey struct{} +type recoveryClockKey struct{} // WithRecoveryProgress carries a synchronous observer, not a deadline or an // admission grant. done is cumulative within phase, including across retries. @@ -50,10 +58,18 @@ type recoveryReporter struct { } func newRecoveryReporter(ctx context.Context, phase RecoveryPhase) *recoveryReporter { - return &recoveryReporter{ctx: ctx, phase: phase, now: time.Now} + now := time.Now + // Package-local clock seam exercises the real loops without sleeping. + if clock, ok := ctx.Value(recoveryClockKey{}).(func(RecoveryPhase) time.Time); ok { + now = func() time.Time { return clock(phase) } + } + return &recoveryReporter{ctx: ctx, phase: phase, now: now} } func (r *recoveryReporter) advance(n uint64) { + if r == nil { + return + } r.done += n now := r.now() if r.done-r.lastDone >= 256 || r.lastAt.IsZero() || now.Sub(r.lastAt) >= time.Second { @@ -68,23 +84,32 @@ func (r *recoveryReporter) flushAt(now time.Time) { } } -func (r *recoveryReporter) finish() { r.flushAt(r.now()) } +func (r *recoveryReporter) finish() { + if r != nil { + r.flushAt(r.now()) + } +} func copyRecoveryMap(ctx context.Context, dst, src []chunkLSNEntryV3) ([]chunkLSNEntryV3, error) { return copyRecoveryMapPhase(ctx, RecoveryMap, dst, src) } func copyRecoveryMapPhase(ctx context.Context, phase RecoveryPhase, dst, src []chunkLSNEntryV3) ([]chunkLSNEntryV3, error) { - dst = dst[:0] + // A canceled copy must not change the live map, including its backing + // array. Publish this private candidate only after every entry was copied. + candidate := make([]chunkLSNEntryV3, 0, len(src)) progress := newRecoveryReporter(ctx, phase) for start := 0; start < len(src); start += 256 { if err := ctx.Err(); err != nil { return dst, err } end := min(start+256, len(src)) - dst = append(dst, src[start:end]...) + candidate = append(candidate, src[start:end]...) progress.advance(uint64(end - start)) } progress.finish() - return dst, nil + if err := ctx.Err(); err != nil { + return dst, err + } + return candidate, nil } diff --git a/seaweed-block/core/storage/recovery_progress_test.go b/seaweed-block/core/storage/recovery_progress_test.go index e2ca5df442..3e1b572406 100644 --- a/seaweed-block/core/storage/recovery_progress_test.go +++ b/seaweed-block/core/storage/recovery_progress_test.go @@ -1,12 +1,51 @@ package storage import ( + "bytes" "context" + "errors" + "path/filepath" "reflect" "testing" "time" ) +func TestRecoveryCancellationKeepsLiveGeometryAndCanRetry(t *testing.T) { + s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), 2048, 4096, v3TestWAL, WModeStrict, 1) + if err != nil { + t.Fatal(err) + } + defer s.Close() + writeSynced(t, s, 1500, 1500) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + ctx = WithRecoveryProgress(ctx, func(phase RecoveryPhase, done uint64) { + if phase == RecoveryMap && done == 256 { + cancel() + } + }) + if _, err := s.RecoverContext(ctx); !errors.Is(err, context.Canceled) { + t.Fatalf("cancel: %v", err) + } + if len(s.v3.mapEntries) != 2048 { + t.Fatalf("interrupted recovery published %d entries, want 2048", len(s.v3.mapEntries)) + } + got, err := s.Read(1500) + if err != nil || !bytes.Equal(got, blk(byte(1500%256))) { + t.Fatalf("canceled recovery lost live data: %v", err) + } + writeSynced(t, s, 1800, 1800) + if _, err := s.Recover(); err != nil { + t.Fatalf("retry: %v", err) + } + for _, lba := range []uint32{1500, 1800} { + got, err := s.Read(lba) + if err != nil || !bytes.Equal(got, blk(byte(lba))) { + t.Fatalf("retry LBA %d: %v", lba, err) + } + } +} + func TestRecoveryMapCountsOneTiBEntriesWithoutATotalDeadline(t *testing.T) { src := make([]chunkLSNEntryV3, 262144) var high uint64 @@ -60,7 +99,9 @@ func TestWALStoreOpenReportsValidatedMapAndCopyBeforeReplay(t *testing.T) { t.Fatal(err) } defer r.Close() - if seen[RecoveryOpenMap] == 0 || seen[RecoveryOpenCopy] != 16 { + // Open validates the selected and fallback roots, then binding validates + // both again. All four reads belong to one cumulative open-map frontier. + if seen[RecoveryOpenMap] != 64 || seen[RecoveryOpenCopy] != 16 { t.Fatalf("unobserved open work: %v", seen) } } @@ -87,3 +128,129 @@ func TestRecoveryReporterSlowReplayReportsBeforeTheEntryBatch(t *testing.T) { t.Fatalf("completed entries=%d", high) } } + +func TestRecoveryProgressRealLoopsOutliveAWindow(t *testing.T) { + s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), 2048, 4096, 4<<20, WModeStrict, 1) + if err != nil { + t.Fatal(err) + } + defer s.Close() + for lba := uint32(0); lba < 512; lba++ { + if _, err := s.Write(lba, blk(byte(lba))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + times := map[RecoveryPhase]time.Time{} + last := map[RecoveryPhase]time.Time{} + seen := map[RecoveryPhase]uint64{} + phase := RecoveryPhase(0) + base := time.Unix(1000, 0) + ctx := context.WithValue(context.Background(), recoveryClockKey{}, func(p RecoveryPhase) time.Time { + now := times[p] + if now.IsZero() { + now = base + } + now = now.Add(500 * time.Millisecond) + times[p] = now + return now + }) + ctx = WithRecoveryProgress(ctx, func(p RecoveryPhase, done uint64) { + if p < phase || done <= seen[p] { + t.Fatalf("non-monotone actual work %d/%d after %d", p, done, phase) + } + if previous := last[p]; !previous.IsZero() && times[p].Sub(previous) > time.Second { + t.Fatalf("actual phase %d exceeded inactivity window between reports: %s", p, times[p].Sub(previous)) + } + phase, seen[p], last[p] = p, done, times[p] + }) + if _, err := s.RecoverContext(ctx); err != nil { + t.Fatal(err) + } + for _, p := range []RecoveryPhase{RecoveryScan, RecoveryScanSpans, RecoveryScanSort, RecoveryScanFrontier, RecoveryProject, RecoveryDecide, RecoveryMap, RecoveryReplay, RecoveryReclaim} { + if seen[p] == 0 { + t.Errorf("unobserved actual phase %d", p) + } + if p != RecoveryScanSort && times[p].Sub(base) <= 2*time.Second { + t.Errorf("control phase %d did not span multiple windows", p) + } + } +} + +func TestRecoveryProgressBindingReadsOutliveAWindow(t *testing.T) { + s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), 2048, 4096, v3TestWAL, WModeStrict, 1) + if err != nil { + t.Fatal(err) + } + defer s.Close() + now := time.Unix(1000, 0) + start, last := now, now + var seen uint64 + ctx := WithRecoveryProgress(context.Background(), func(p RecoveryPhase, done uint64) { + if p != RecoveryOpenMap || done <= seen || now.Sub(last) > time.Second { + t.Fatalf("binding progress %d/%d gap %s", p, done, now.Sub(last)) + } + seen, last = done, now + }) + r := newRecoveryReporter(ctx, RecoveryOpenMap) + r.now = func() time.Time { now = now.Add(500 * time.Millisecond); return now } + if err := s.v3.pub.bindMapV3Progress(s.v3.pub.mapCurrent, s.v3.mapProof, r); err != nil { + t.Fatal(err) + } + r.finish() + if seen != 4096 || now.Sub(start) <= 2*time.Second { + t.Fatalf("binding omitted pages: done=%d elapsed=%s", seen, now.Sub(start)) + } +} + +func TestRecoveryProgressInstallingLoopsOutliveAWindow(t *testing.T) { + for _, reopen := range []bool{false, true} { + t.Run(map[bool]string{false: "live_install_replay", true: "reopen_retention"}[reopen], func(t *testing.T) { + path := filepath.Join(t.TempDir(), "volume") + s, err := createMappedWALStoreV3ForTest(path, 2048, 4096, 4<<20, WModeStrict, 1) + if err != nil { + t.Fatal(err) + } + h := beginV3(t, s, 0, idA) + for lba := uint32(0); lba < 512; lba++ { + if err := h.ApplyInstallEntry(lba, blk(byte(lba)), uint64(lba)+1); err != nil { + t.Fatal(err) + } + } + if reopen { + crashRecoveryHardeningStore(t, s) + s, err = OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + } + defer s.Close() + now := time.Unix(1000, 0) + start, last := now, now + var seen uint64 + ctx := context.WithValue(context.Background(), recoveryClockKey{}, func(p RecoveryPhase) time.Time { + if p == RecoveryInstall { + now = now.Add(500 * time.Millisecond) + } + return now + }) + ctx = WithRecoveryProgress(ctx, func(p RecoveryPhase, done uint64) { + if p != RecoveryInstall { + return + } + if done <= seen || now.Sub(last) > time.Second { + t.Fatalf("install progress=%d gap=%s", done, now.Sub(last)) + } + seen, last = done, now + }) + if _, err := s.RecoverContext(ctx); !errors.Is(err, ErrBaseIncomplete) { + t.Fatalf("install outcome: %v", err) + } + if seen != 512 || now.Sub(start) <= 2*time.Second { + t.Fatalf("install work=%d elapsed=%s", seen, now.Sub(start)) + } + }) + } +} diff --git a/seaweed-block/core/storage/recovery_v3.go b/seaweed-block/core/storage/recovery_v3.go index e4b203e3a1..a84bab840b 100644 --- a/seaweed-block/core/storage/recovery_v3.go +++ b/seaweed-block/core/storage/recovery_v3.go @@ -59,6 +59,11 @@ type trustedRecordV3 struct { // in a trusted chain only increase; a decrease is a contradiction and is // refused. func contiguousPrefixV3(start, F uint64, recs []trustedRecordV3) (R, E uint64, err error) { + return contiguousPrefixV3Progress(start, F, recs, nil) +} + +func contiguousPrefixV3Progress(start, F uint64, recs []trustedRecordV3, progress *recoveryReporter) (R, E uint64, err error) { + defer progress.finish() R, E = F, start var prev uint64 for _, r := range recs { @@ -66,6 +71,7 @@ func contiguousPrefixV3(start, F uint64, recs []trustedRecordV3) (R, E uint64, e // The loop returns at the first gap, so any padding seen here // lies inside the kept run: E moves past it. E = r.End + progress.advance(1) continue } if r.FirstLSN == 0 || r.LastLSN < r.FirstLSN { @@ -83,6 +89,7 @@ func contiguousPrefixV3(start, F uint64, recs []trustedRecordV3) (R, E uint64, e default: return R, E, nil // a gap: everything from here on is dropped } + progress.advance(1) } return R, E, nil } @@ -104,8 +111,12 @@ type recoveryOutcomeV3 struct { // installing outcomes are reported in the result, damaged or not, and the // caller wraps them in ErrBaseIncomplete. func decideRecoveryV3(d descriptorV3, recs []trustedRecordV3, maxDurable uint64) (recoveryOutcomeV3, error) { + return decideRecoveryV3Progress(d, recs, maxDurable, nil) +} + +func decideRecoveryV3Progress(d descriptorV3, recs []trustedRecordV3, maxDurable uint64, progress *recoveryReporter) (recoveryOutcomeV3, error) { o := recoveryOutcomeV3{Start: scanStartV3(d), F: replayFloorV3(d)} - R, E, err := contiguousPrefixV3(o.Start, o.F, recs) + R, E, err := contiguousPrefixV3Progress(o.Start, o.F, recs, progress) if err != nil { ierr := NewWALIntegrityFailure(err, err.Error()) if d.BaseState == BaseInstalling { diff --git a/seaweed-block/core/storage/wal_io_v3.go b/seaweed-block/core/storage/wal_io_v3.go index d4b1f3c92d..ae608fcbdc 100644 --- a/seaweed-block/core/storage/wal_io_v3.go +++ b/seaweed-block/core/storage/wal_io_v3.go @@ -215,6 +215,10 @@ func (w *walWriterV3) advanceHeadV3(p uint64) error { // the owner must complete the durable drop fence and descriptor publication // before another append. No ring/nonce reset or floor waiver occurs here. func (w *walWriterV3) restoreScanV3(r walScanResultV3) error { + return w.restoreScanV3Progress(r, nil) +} + +func (w *walWriterV3) restoreScanV3Progress(r walScanResultV3, progress *recoveryReporter) error { d, floor, ok := w.pub.walSnapshotV3() w.mu.Lock() defer w.mu.Unlock() @@ -231,7 +235,7 @@ func (w *walWriterV3) restoreScanV3(r walScanResultV3) error { // The owner fences any dropped suffix first. Its raw HighestLSN must not // pin the allocator after that suffix has been discarded. w.highestLSN = r.Frontier - w.indexReclaimScanLockedV3(r) + w.indexReclaimScanLockedV3Progress(r, progress) return nil } @@ -239,16 +243,25 @@ func (w *walWriterV3) restoreScanV3(r walScanResultV3) error { // NOT restore or rewind the writer position/LSN, including on an // installing reopen whose suffix cannot be admitted until resume. func (w *walWriterV3) rememberReclaimScanV3(r walScanResultV3) error { + return w.rememberReclaimScanV3Progress(r, nil) +} + +func (w *walWriterV3) rememberReclaimScanV3Progress(r walScanResultV3, progress *recoveryReporter) error { w.mu.Lock() defer w.mu.Unlock() if r.Nonce != w.nonce { return errWALBindingV3 } - w.indexReclaimScanLockedV3(r) + w.indexReclaimScanLockedV3Progress(r, progress) return nil } func (w *walWriterV3) indexReclaimScanLockedV3(r walScanResultV3) { + w.indexReclaimScanLockedV3Progress(r, nil) +} + +func (w *walWriterV3) indexReclaimScanLockedV3Progress(r walScanResultV3, progress *recoveryReporter) { + defer progress.finish() w.reclaim = w.reclaim[:0] for _, rec := range r.Records { if rec.End > r.End { @@ -264,6 +277,7 @@ func (w *walWriterV3) indexReclaimScanLockedV3(r walScanResultV3) { if rec.Entry.Type == walEntryWrite || rec.Entry.Type == walEntryWriteBatch { w.reclaim = append(w.reclaim, walReclaimPointV3{last, rec.End}) } + progress.advance(1) } } @@ -405,6 +419,8 @@ func scanWALV3AcceptedProgress(ctx context.Context, fd *os.File, d descriptorV3, // LSN interval union, not an expansion proportional to an untrusted LSN gap // or batch count. Record geometry and endpoints have already been validated. type interval struct{ first, last uint64 } + progress.finish() + spansProgress := newRecoveryReporter(ctx, RecoveryScanSpans) spans := make([]interval, 0, len(r.Records)) for _, record := range r.Records { e := record.Entry @@ -413,13 +429,32 @@ func scanWALV3AcceptedProgress(ctx context.Context, fd *os.File, d descriptorV3, last += e.BatchCount - 1 } spans = append(spans, interval{e.LSN, last}) + spansProgress.advance(1) } - sort.Slice(spans, func(i, j int) bool { return spans[i].first < spans[j].first }) + spansProgress.finish() + sortProgress := newRecoveryReporter(ctx, RecoveryScanSort) + // Each comparison and the bounded swaps between comparisons are constant + // work. Check the clock every 256 completed comparisons, not once after + // the entire O(n log n) sort. The same input repeats the same frontier. + var comparisons uint64 + sort.Slice(spans, func(i, j int) bool { + less := spans[i].first < spans[j].first + comparisons++ + if comparisons%256 == 0 { + sortProgress.advance(256) + } + return less + }) + sortProgress.advance(comparisons % 256) + sortProgress.finish() + frontierProgress := newRecoveryReporter(ctx, RecoveryScanFrontier) for _, span := range spans { if r.Frontier == counterMaxV3 || span.first > r.Frontier+1 { break } r.Frontier = max(r.Frontier, span.last) + frontierProgress.advance(1) } + frontierProgress.finish() return r, nil } diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index b8aa6f77f8..d559e4c061 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -385,12 +385,11 @@ func openWALStoreV3File(path string, f *os.File, requireMap bool, opts WALStoreO } var ownedMap *chunkLSNMapV3 var mapCurrent *chunkMapCandidateV3 + openProgress := newRecoveryReporter(progressCtx, RecoveryOpenMap) // Earlier dark row5 fixtures have no map tuple. A real immutable root is // never optional: missing metadata is not a clean map. if requireMap || d.MapRootHash != [32]byte{} { - progress := newRecoveryReporter(progressCtx, RecoveryOpenMap) - ownedMap, mapCurrent, err = openDescriptorMapV3Progress(path+".chunkmap", d, other, progress) - progress.finish() + ownedMap, mapCurrent, err = openDescriptorMapV3Progress(path+".chunkmap", d, other, openProgress) if err != nil { _ = f.Close() return nil, err @@ -452,9 +451,10 @@ func openWALStoreV3File(path string, f *os.File, requireMap bool, opts WALStoreO v.wack.Store(d.W) if ownedMap != nil { v.mapProof = newMapProofEpochV3() - if err := v.pub.bindMapV3(mapCurrent, v.mapProof); err != nil { + if err := v.pub.bindMapV3Progress(mapCurrent, v.mapProof, openProgress); err != nil { return err } + openProgress.finish() v.ownedMap = ownedMap v.mapEntries, err = copyRecoveryMapPhase(progressCtx, RecoveryOpenCopy, nil, mapCurrent.entries) if err != nil { @@ -485,7 +485,6 @@ func (s *WALStore) recoverV3(ctx context.Context) (uint64, error) { h() } d := v.pub.current() - s.dm.clear() scan, err := scanWALV3AcceptedProgress(ctx, s.fd, d, v.pub.accept) if err != nil { if d.BaseState == BaseInstalling { @@ -496,18 +495,25 @@ func (s *WALStore) recoverV3(ctx context.Context) (uint64, error) { return 0, err } recs := make([]trustedRecordV3, 0, len(scan.Records)) + projectProgress := newRecoveryReporter(ctx, RecoveryProject) for _, r := range scan.Records { last := r.Entry.LSN if r.Entry.Type == walEntryWriteBatch { last += r.Entry.BatchCount - 1 } recs = append(recs, trustedRecordV3{FirstLSN: r.Entry.LSN, LastLSN: last, End: r.End}) + projectProgress.advance(1) } - o, err := decideRecoveryV3(d, recs, scan.MaxDurableLSN) + projectProgress.finish() + o, err := decideRecoveryV3Progress(d, recs, scan.MaxDurableLSN, newRecoveryReporter(ctx, RecoveryDecide)) if err != nil { return 0, err // R < W*: fail closed (wal_corrupt) } if o.Installing { + if err := ctx.Err(); err != nil { + return 0, err + } + s.dm.clear() // The recovered bounds of an installing reopen (DESIGN 8.3), kept for // a covering supersession: E, R and whether the suffix is damaged. // Nothing is fenced, published or admitted here; the allocator @@ -521,6 +527,7 @@ func (s *WALStore) recoverV3(ctx context.Context) (uint64, error) { // resume or a fenced supersession then refuses before any I/O; the // live install continues. if d.BaseInstallID != v.liveInstallID { + installProgress := newRecoveryReporter(ctx, RecoveryInstall) ro := &installReopenV3{id: d.BaseInstallID, E: o.E, R: o.R, damaged: o.Damaged, walSize: d.WALSize} for _, r := range scan.Records { if r.Entry.LSN > o.R { @@ -529,12 +536,14 @@ func (s *WALStore) recoverV3(ctx context.Context) (uint64, error) { if r.Entry.Type == walEntryWrite || r.Entry.Type == walEntryWriteBatch { ro.records = append(ro.records, r) } + installProgress.advance(1) } + installProgress.finish() v.installReopen = ro if v.w != nil { kept := scan kept.End, kept.Frontier = o.E, o.R - if err := v.w.rememberReclaimScanV3(kept); err != nil { + if err := v.w.rememberReclaimScanV3Progress(kept, newRecoveryReporter(ctx, RecoveryReclaim)); err != nil { return 0, err } } @@ -550,12 +559,15 @@ func (s *WALStore) recoverV3(ctx context.Context) (uint64, error) { // cleared, so the completed image serves them and not older BASE // bytes; the volatile map coverage (the BASE writes' UNKNOWN) is // kept as it is. + installProgress := newRecoveryReporter(ctx, RecoveryInstall) for _, r := range scan.Records { if r.Entry.LSN > o.R { break } s.replayRecordV3(r, d.WALSize, d.BlockSize) + installProgress.advance(1) } + installProgress.finish() } v.appended.Store(max(v.appended.Load(), o.R)) s.nextLSN = max(s.nextLSN, o.R+1) @@ -574,13 +586,14 @@ func (s *WALStore) recoverV3(ctx context.Context) (uint64, error) { return 0, err } } + // Cancellation is accepted only before replacing the live maps. Once + // replay begins, finish the existing fence/publication/admission sequence; + // returning halfway would expose a partial dirty map to direct callers. + s.dm.clear() // Replay the records <= R into the dirty map (last writer wins); the // rest are dropped and fenced below. progress := newRecoveryReporter(ctx, RecoveryReplay) for _, r := range scan.Records { - if err := ctx.Err(); err != nil { - return 0, err - } e := r.Entry if e.LSN > o.R { break @@ -632,7 +645,7 @@ func (s *WALStore) recoverV3(ctx context.Context) (uint64, error) { } restore := scan restore.End = o.E - if err := v.w.restoreScanV3(restore); err != nil { + if err := v.w.restoreScanV3Progress(restore, newRecoveryReporter(ctx, RecoveryReclaim)); err != nil { s.dm.clear() return 0, err } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d140f180d9..d039bf95d6 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -65,8 +65,7 @@ stateDiagram-v2 | — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001`, `INV-WAL-V3-ACTIVATION-001`, `INV-WAL-V3-DESCRIPTOR-001`, `INV-WAL-V3-MAP-PUBLISH-001` | | — | CreateRefused | a new volume needs the durable root's free space >= its size + WAL, 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` | -| Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `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`) | pending shared-start progress review; C.L | STUB | -| `INV-WAL-OPGATE-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` | | 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-MAP-PUBLISH-001`, `INV-FE-PRIMARY-READY-OPERATIONAL-001`, `INV-WS-SERVE-LEASE-HELD-001`, `INV-PRIMARY-ACK-PROFILE-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` | | Serving | Serving | each `Read`, `Write`, `Sync` passes the operational, chunk-fence and lineage checks; write admission samples the active writer's native pressure before waiting; a write is durable only when a covering `Sync` returns | `core/frontend/durable/storage_adapter.go` `gate`; `core/storage/walstore.go` `WALStore.Sync` | `INV-FE-LINEAGE-GATE-001`, `INV-WAL-SYNC-FRONTIER-001`, `INV-FE-FUA-SYNC-001`, `INV-FE-FLUSH-SYNC-001`, `INV-WAL-V3-ADMISSION-001`, `INV-WAL-V3-W-001` | @@ -1267,11 +1266,14 @@ Storage recovery barriers precede the promotion watchdog mutex. The synchronous completed-work observer may take that mutex under capture, lifecycle, sync, store and descriptor locks; watchdog-locked methods may call no storage, wait, or unreviewed callback. `TestRecoveryWatchdogLockedMethodsNeverCallStorageOrWait` -pins the seven locked methods and their calls. Time affects only an unhealthy +pins the seven locked methods, their calls and blocking syntax; +`TestRecoveryWatchdogClockBindingIsTimeNow` pins the production clock binding. Time affects only an unhealthy readiness observation: the observer authorizes no Serving, lease or HEAD write. -The recovery clock consumes a fixed-order `(phase, done)` frontier: validated open-map entries, initial map copy, scan, map -copy, retained replay, attach. Counts are cumulative within each phase across +The recovery clock consumes a fixed-order `(phase, done)` frontier: validated open-map entries (including binding revalidation), initial map copy, +scan, span construction, sort comparisons, frontier calculation, trusted-record +projection, recovery decision, install replay/retention, map copy, retained +replay, reclaim indexing, attach. Counts are cumulative within each phase across same-process retries; a repeated or earlier frontier is not progress. Late progress cannot clear an already elapsed inactivity window. The existing same-epoch promotion-ready fact alone clears the timeout latch. C.L's start