diff --git a/seaweed-block/cmd/blockvolume/durable_startup.go b/seaweed-block/cmd/blockvolume/durable_startup.go index f25e8790e3..8ab0bc73a9 100644 --- a/seaweed-block/cmd/blockvolume/durable_startup.go +++ b/seaweed-block/cmd/blockvolume/durable_startup.go @@ -42,7 +42,7 @@ const ( // is covered by the recovery_timeout fallback. An open failure that // cannot be classified returns durableStartupFatal, keeping the earlier // exit. -func openAndRecoverDurable(dp durableStartup, h localRecoveryHost, volumeID string, recoverTimeout time.Duration) (durableStartupOutcome, string, error) { +func openAndRecoverDurable(dp durableStartup, h localRecoveryHost, volumeID string, _ time.Duration) (durableStartupOutcome, string, error) { if _, err := dp.EnsureStorage(volumeID); err != nil { if volume.LocalRecoveryHealthReason(err) == "" { return durableStartupFatal, "", err @@ -52,8 +52,14 @@ func openAndRecoverDurable(dp durableStartup, h localRecoveryHost, volumeID stri h.ReportLocalRecoveryFailure(err) return durableStartupFaulted, evidence, err } - ctx, cancel := context.WithTimeout(context.Background(), recoverTimeout) - defer cancel() + // The host owns the shared inactivity clock. Volume-sized local replay + // must not consume an attach operation's fixed deadline. + ctx := context.Background() + if progress, ok := h.(interface { + ReportRecoveryProgress(storage.RecoveryPhase, uint64) + }); ok { + ctx = storage.WithRecoveryProgress(ctx, progress.ReportRecoveryProgress) + } report, err := dp.RecoverVolume(ctx, volumeID) if err != nil { h.BlockLocalReadiness(report.Evidence) diff --git a/seaweed-block/cmd/blockvolume/durable_startup_budget_test.go b/seaweed-block/cmd/blockvolume/durable_startup_budget_test.go new file mode 100644 index 0000000000..b5f9886f15 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/durable_startup_budget_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// This counting provider represents local map replay without disk throughput or +// wall-clock sleeps. It probes the production startup boundary, not a widened +// deadline: a per-volume walk must not inherit the attach operation's timer. +type countingLocalRecovery struct { + entries int + visited int + underDeadline int +} + +func (p *countingLocalRecovery) EnsureStorage(string) (storage.LogicalStorage, error) { + return nil, nil +} +func (p *countingLocalRecovery) RecoverVolume(ctx context.Context, id string) (durable.RecoveryReport, error) { + for i := 0; i < p.entries; i++ { + p.visited++ + if _, timed := ctx.Deadline(); timed { + p.underDeadline++ + } + } + return durable.RecoveryReport{VolumeID: id, Evidence: "local replay completed"}, nil +} + +func TestDurableStartup_LocalRecoveryWorkIsOutsideFixedDeadline(t *testing.T) { + for _, entries := range []int{1, 262144} { + t.Run(map[int]string{1: "one", 262144: "one_tib_chunk_count"}[entries], func(t *testing.T) { + p := &countingLocalRecovery{entries: entries} + outcome, _, err := openAndRecoverDurable(p, &spyHost{}, "v1", 10*time.Second) + if err != nil || outcome != durableStartupReady || p.visited != entries { + t.Fatalf("startup=%v err=%v visited=%d want=%d", outcome, err, p.visited, entries) + } + if p.underDeadline != 0 { + t.Fatalf("volume-sized local recovery visited %d/%d entries under a fixed deadline; growing replay must precede the bounded attach operation", p.underDeadline, entries) + } + }) + } +} diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index ef6e45f552..8b55eea573 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -197,7 +197,7 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.dataAddr, "data-addr", "", "data-path address (required)") fs.StringVar(&f.ctrlAddr, "ctrl-addr", "", "control-path address (required)") fs.DurationVar(&f.hbInterval, "heartbeat-interval", 2*time.Second, "heartbeat send interval") - fs.DurationVar(&f.recoverTimeout, "recover-timeout", volume.DefaultRecoverTimeout, "how long a primary-assigned replica may stay not promotion-ready before it reports itself unhealthy (recovery_timeout) so the master can fail over") + fs.DurationVar(&f.recoverTimeout, "recover-timeout", volume.DefaultRecoverTimeout, "maximum inactivity without new completed recovery or attach work for a primary-assigned replica before it reports unhealthy (recovery_timeout); not a total startup deadline") fs.BoolVar(&f.workspaceLease, "workspace-lease", false, "walstore-chunk workspace: require host-owned master lease; fail closed when unavailable") fs.BoolVar(&f.printReadyLine, "t0-print-ready", false, "internal test-only: emit one structured JSON line on stdout on first assignment") fs.BoolVar(&f.enableT1Readiness, "t1-readiness", false, "enable readiness bridge (HealthyPathExecutor) so adapter projection reaches Healthy") @@ -713,6 +713,7 @@ func runVolume(f flags, exits *processExit) int { blocks, blockSize, geometryErr := durableCreateGeometry(f) var dp *durable.DurableProvider cfg := durable.ProviderConfig{ + RecoveryProgress: h.ReportRecoveryProgress, Impl: durable.ImplName(f.durableImpl), StorageRoot: f.durableRoot, BlockSize: blockSize, diff --git a/seaweed-block/core/frontend/chunkstore/layout_attach_fetch_test.go b/seaweed-block/core/frontend/chunkstore/layout_attach_fetch_test.go new file mode 100644 index 0000000000..3f8e8e7097 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_attach_fetch_test.go @@ -0,0 +1,145 @@ +package chunkstore + +import ( + "context" + "errors" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// slowObjects serves a manifest's root and segments, each fetch taking +// delay (stall for the one path containing stallOn), and counts fetches. +type slowObjects struct { + objs map[string][]byte // by path relative to the volume + delay time.Duration + stallOn string + mu sync.Mutex + fetches int +} + +func (s *slowObjects) fetch(ctx context.Context, p string) ([]byte, bool, error) { + s.mu.Lock() + s.fetches++ + s.mu.Unlock() + d := s.delay + if s.stallOn != "" && strings.Contains(p, s.stallOn) { + d = time.Hour + } + select { + case <-ctx.Done(): + return nil, false, ctx.Err() + case <-time.After(d): + } + for rel, b := range s.objs { + if strings.HasSuffix(p, "/"+rel) { + return b, true, nil + } + } + return nil, false, nil +} + +// manifestOfShards builds a manifest with one chunk in each of n shards +// (n segments), and the objects a reader of it fetches. +func manifestOfShards(t *testing.T, v VolumeRef, n int) (layout.RootName, map[string][]byte, []string) { + t.Helper() + m := map[uint64]layout.Ref{} + for i := 0; i < n; i++ { + idx := uint64(i) * layout.ShardSize + m[idx] = layout.Ref{Owner: v.Name, OwnerID: v.ID, Chunk: layout.NameChunk(idx, []byte{byte(i)})} + } + root, segs, err := layout.Build(m) + if err != nil { + t.Fatal(err) + } + rn, rb, err := layout.NameRoot(root) + if err != nil { + t.Fatal(err) + } + objs := map[string][]byte{rn.Path(): rb} + var segPaths []string + for sn, b := range segs { + objs[sn.Path()] = b + segPaths = append(segPaths, sn.Path()) + } + return rn, objs, segPaths +} + +// A whole-manifest read within an attach is a root fetch and one fetch per +// segment, each under its own bound, never one bound around the read: 27 +// segments (1 TiB) each just under the bound complete although the read +// takes far longer than the bound, reporting every segment as it lands; +// one segment that stalls past its bound fails the read. +func TestAttachManifestReadBoundsEachFetch(t *testing.T) { + v := VolumeRef{Name: "v", ID: layout.VolumeID{7}} + rn, objs, segPaths := manifestOfShards(t, v, 27) + const bound = 60 * time.Millisecond + src := &slowObjects{objs: objs, delay: 40 * time.Millisecond} + r, err := layout.NewReader("/blocks", v.Dir(), src.fetch) + if err != nil { + t.Fatal(err) + } + var reports []uint64 + start := time.Now() + m, err := boundedManifest(context.Background(), r, rn, storage.AttachFetch{Bound: bound, Done: func(n uint64) { reports = append(reports, n) }}) + took := time.Since(start) + if err != nil { + t.Fatalf("a read of 27 segments each within its bound failed after %s: %v", took, err) + } + if len(m) != 27 || len(reports) != 27 || took < 10*bound { + t.Fatalf("entries %d, segment reports %d, took %s (want 27, 27, well over the %s bound)", len(m), len(reports), took, bound) + } + for _, n := range reports { + if n != 1 { + t.Fatalf("segment reports %v: each segment holds one entry here", reports) + } + } + + // An outer deadline of its own, far above the expected run: without the + // per-fetch bound (the regression) the read ends here, not at the suite's. + outer, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + src2 := &slowObjects{objs: objs, delay: time.Millisecond, stallOn: segPaths[13]} + r2, _ := layout.NewReader("/blocks", v.Dir(), src2.fetch) + var got int + start = time.Now() + _, err = boundedManifest(outer, r2, rn, storage.AttachFetch{Bound: bound, Done: func(uint64) { got++ }}) + if time.Since(start) > 10*time.Second { + t.Fatalf("a stalled segment fetch held the read %s: no per-fetch bound", time.Since(start)) + } + if err == nil || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("a stalled segment fetch: %v (want its own deadline)", err) + } + if got >= 27 { + t.Fatalf("a stalled read reported every segment (%d)", got) + } +} + +// stallHeadStore is a layout store whose HEAD read never answers. +type stallHeadStore struct{ sessionStore } + +func (stallHeadStore) ReadHead(ctx context.Context) (layout.Head, bool, error) { + <-ctx.Done() + return layout.Head{}, false, ctx.Err() +} + +// The real GetHead reads HEAD (and rolls back a crashed session) before the +// manifest: within an attach that object call is bounded on its own too, so +// a stalled HEAD read fails the attempt instead of holding it. +func TestAttachGetHeadBoundsTheHeadRead(t *testing.T) { + l := &LayoutRemote{st: stallHeadStore{}, vol: VolumeRef{Name: "v", ID: layout.VolumeID{7}}, me: layout.HolderID{Epoch: 1, Holder: "h", ClaimID: "k"}} + outer, cancel := context.WithTimeout(context.Background(), 20*time.Second) // independent of the bound under test + defer cancel() + start := time.Now() + _, err := l.GetHead(storage.WithAttachFetch(outer, storage.AttachFetch{Bound: 50 * time.Millisecond})) + if took := time.Since(start); took > 10*time.Second { + t.Fatalf("a stalled HEAD read held GetHead %s: no bound on it", took) + } + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("a stalled HEAD read: %v (want its own deadline)", err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote.go b/seaweed-block/core/frontend/chunkstore/layout_remote.go index 5a1386db67..cfc80ca47e 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_remote.go +++ b/seaweed-block/core/frontend/chunkstore/layout_remote.go @@ -222,7 +222,11 @@ func (l *LayoutRemote) openSessionLocked(ctx context.Context) error { // but this process does not hold (it died with the process), and returns // HEAD. func (l *LayoutRemote) rollBackLocked(ctx context.Context) (layout.Head, error) { - h, found, err := l.st.ReadHead(ctx) + // Within an attach every object call here (the HEAD read, a rollback's + // writes) carries its own bound, as each manifest fetch does. + rctx, cancel := attachFetchBound(ctx) + h, found, err := l.st.ReadHead(rctx) + cancel() if err != nil { return layout.Head{}, err } @@ -233,12 +237,18 @@ func (l *LayoutRemote) rollBackLocked(ctx context.Context) (layout.Head, error) mine := h.Epoch == l.me.Epoch && h.Holder == l.me.Holder && h.ClaimID == l.me.ClaimID switch { case mine && h.Activity.Kind == layout.ActSnap && h.Activity.Session != l.session: - if h, err = layout.RunAbort(ctx, l.st, l.me, h.Activity.Session, layout.CauseSessionRollback); err != nil { + actx, cancel := attachFetchBound(ctx) + h, err = layout.RunAbort(actx, l.st, l.me, h.Activity.Session, layout.CauseSessionRollback) + cancel() + if err != nil { return layout.Head{}, layoutRemoteErr(err) } l.ownGen = h.Gen case mine && h.Activity.Kind == layout.ActClean && h.Activity.Session != l.cleaning: - if h, err = layout.RunEndClean(ctx, l.st, l.me, h.Activity.Session, layout.CauseSessionRollback); err != nil { + actx, cancel := attachFetchBound(ctx) + h, err = layout.RunEndClean(actx, l.st, l.me, h.Activity.Session, layout.CauseSessionRollback) + cancel() + if err != nil { return layout.Head{}, layoutRemoteErr(err) } l.ownGen = h.Gen @@ -314,14 +324,36 @@ func (l *LayoutRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { if err != nil { return storage.ChunkHead{}, err } + // Within an attach the conversion reports its completed entries too. + af, _ := storage.AttachFetchFrom(ctx) + var pending uint64 for idx, ref := range m { out.Chunks[idx] = storage.ChunkRef{Key: LayoutKey(ref), SHA256: ref.Chunk.Hash, Encoding: "full"} + if af.Done != nil { + if pending++; pending == 256 { + af.Done(pending) + pending = 0 + } + } + } + if af.Done != nil && pending > 0 { + af.Done(pending) } return out, nil } -// manifest is the chunk map root names. +// manifest is the chunk map root names. Within an attach (ctx carries +// storage.AttachFetch) it is read fetch by fetch: the root and each segment +// under their own bound, each completed segment reported as progress, and +// no bound on the read as a whole (the segment count grows with the volume). func (l *LayoutRemote) manifest(ctx context.Context, rn layout.RootName) (map[uint64]layout.Ref, error) { + if af, ok := storage.AttachFetchFrom(ctx); ok { + m, err := boundedManifest(ctx, l.r, rn, af) + if err != nil { + return nil, layoutRemoteErr(err) + } + return m, nil + } m := map[uint64]layout.Ref{} err := l.r.EachRef(ctx, rn, layout.AllShards, func(idx uint64, ref layout.Ref) bool { m[idx] = ref @@ -333,6 +365,50 @@ func (l *LayoutRemote) manifest(ctx context.Context, rn layout.RootName) (map[ui return m, nil } +// attachFetchBound bounds one object call of an attach's manifest read by +// the AttachFetch bound ctx carries; without one it is ctx unchanged. +func attachFetchBound(ctx context.Context) (context.Context, context.CancelFunc) { + if af, ok := storage.AttachFetchFrom(ctx); ok && af.Bound > 0 { + return context.WithTimeout(ctx, af.Bound) + } + return context.WithCancel(ctx) +} + +// boundedManifest reads root rn's chunk map one fetch at a time: the root, +// then each segment, every fetch under af.Bound on its own, reporting each +// completed segment's entries to af.Done. A fetch that cannot finish within +// its bound fails the read (never a partial map). +func boundedManifest(ctx context.Context, r *layout.Reader, rn layout.RootName, af storage.AttachFetch) (map[uint64]layout.Ref, error) { + fetchCtx := func() (context.Context, context.CancelFunc) { + if af.Bound > 0 { + return context.WithTimeout(ctx, af.Bound) + } + return context.WithCancel(ctx) + } + c, cancel := fetchCtx() + img, err := r.Open(c, rn) + cancel() + if err != nil { + return nil, err + } + m := map[uint64]layout.Ref{} + for _, sh := range img.Shards() { + c, cancel := fetchCtx() + seg, _, err := img.Segment(c, sh) + cancel() + if err != nil { + return nil, err + } + for idx, ref := range seg.Chunks { + m[idx] = ref + } + if af.Done != nil { + af.Done(uint64(len(seg.Chunks))) + } + } + return m, nil +} + // CASHead commits next as this cut's session: the root of next's chunk // map, position next.RemoteLSN, detached when next is, and the pending // snapshot name. It uses the engine view from before this session's Begin. diff --git a/seaweed-block/core/frontend/durable/attach_progress_test.go b/seaweed-block/core/frontend/durable/attach_progress_test.go new file mode 100644 index 0000000000..0f4ecec132 --- /dev/null +++ b/seaweed-block/core/frontend/durable/attach_progress_test.go @@ -0,0 +1,148 @@ +package durable + +import ( + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Each attach attempt reports its own count from zero, as RecoveryAttach: +// a retry that redoes the same work reports nothing above the first +// attempt's high-water mark, so an attach that keeps failing cannot keep +// renewing the host's inactivity window. +func TestAttachProgressCountsEachAttemptFromZero(t *testing.T) { + type rep struct { + phase storage.RecoveryPhase + done uint64 + } + var got []rep + p := &DurableProvider{cfg: ProviderConfig{RecoveryProgress: func(ph storage.RecoveryPhase, done uint64) { got = append(got, rep{ph, done}) }}} + first := p.attachProgress() + first(256) + first(256) + second := p.attachProgress() + second(256) + want := []rep{{storage.RecoveryAttach, 256}, {storage.RecoveryAttach, 512}, {storage.RecoveryAttach, 256}} + if len(got) != len(want) { + t.Fatalf("reports %v, want %v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("reports %v, want %v (each attempt counts from zero)", got, want) + } + } + // The host keeps the furthest (phase, done): the second attempt's 256 + // is below the first's 512 and moves nothing. + hw := uint64(0) + advanced := 0 + for _, r := range got { + if r.done > hw { + hw, advanced = r.done, advanced+1 + } + } + if advanced != 2 { + t.Fatalf("the retry advanced the high-water mark: %d advances", advanced) + } + if (&DurableProvider{}).attachProgress() != nil { + t.Fatal("no callback: no reporter") + } +} + +// An attach's remote call is bounded on its own by chunkAttachTimeout, +// whatever the attach context: the attempt itself carries no deadline, so +// its volume-sized local work is never cut off by one. +func TestAttachRemoteCallsCarryTheirOwnBound(t *testing.T) { + r := &closeBoundRemote{done: context.Background()} + attach, cancel := context.WithCancel(context.Background()) // as the retry loop passes it: no deadline + defer cancel() + r.setAttach(attach, nil) + c, end := r.bind(context.Background()) + defer end() + dl, ok := c.Deadline() + if !ok || time.Until(dl) > chunkAttachTimeout || time.Until(dl) < chunkAttachTimeout-5*time.Second { + t.Fatalf("an attach-time remote call has deadline %v (ok=%v), want about %s from now", dl, ok, chunkAttachTimeout) + } + r.setAttach(nil, nil) + c2, end2 := r.bind(context.Background()) + defer end2() + if _, ok := c2.Deadline(); ok { + t.Fatal("outside an attach, a remote call gained a deadline") + } + cancel() + r.setAttach(attach, nil) + c3, end3 := r.bind(context.Background()) + defer end3() + if c3.Err() == nil { + t.Fatal("a call bound to an ended attach did not end") + } +} + +// An attach's whole-manifest read (GetHead) carries no bound as a whole: +// it carries the per-fetch rule (chunkAttachTimeout for each root or +// segment fetch) and the attempt's progress for each completed segment. +// Outside an attach it is an ordinary call; an ended attach ends it. +func TestAttachManifestReadCarriesThePerFetchRule(t *testing.T) { + r := &closeBoundRemote{done: context.Background()} + attach, cancel := context.WithCancel(context.Background()) + defer cancel() + var got uint64 + r.setAttach(attach, func(n uint64) { got += n }) + c, end := r.bindManifest(context.Background()) + defer end() + if _, ok := c.Deadline(); ok { + t.Fatal("an attach's manifest read is bounded as a whole") + } + af, ok := storage.AttachFetchFrom(c) + if !ok || af.Bound != chunkAttachTimeout || af.Done == nil { + t.Fatalf("the manifest read carries %+v (ok=%v), want the per-fetch bound and the attempt's progress", af, ok) + } + af.Done(7) + if got != 7 { + t.Fatalf("a completed segment did not reach the attempt's progress (%d)", got) + } + r.setAttach(nil, nil) + c2, end2 := r.bindManifest(context.Background()) + defer end2() + if _, ok := storage.AttachFetchFrom(c2); ok { + t.Fatal("outside an attach, a manifest read carries the attach rule") + } + cancel() + r.setAttach(attach, nil) + c3, end3 := r.bindManifest(context.Background()) + defer end3() + if c3.Err() == nil { + t.Fatal("a manifest read bound to an ended attach did not end") + } +} + +// manifestCapture records the context its GetHead was called with. +type manifestCapture struct { + storage.ChunkRemote + got context.Context +} + +func (m *manifestCapture) GetHead(ctx context.Context) (storage.ChunkHead, error) { + m.got = ctx + return storage.ChunkHead{}, nil +} + +// GetHead itself, as the layer calls it during an attach, reaches the +// remote with the per-fetch rule and no bound around the read. +func TestAttachGetHeadUsesThePerFetchRule(t *testing.T) { + inner := &manifestCapture{} + r := &closeBoundRemote{ChunkRemote: inner, done: context.Background()} + attach, cancel := context.WithCancel(context.Background()) + defer cancel() + r.setAttach(attach, func(uint64) {}) + if _, err := r.GetHead(context.Background()); err != nil { + t.Fatal(err) + } + if _, ok := inner.got.Deadline(); ok { + t.Fatal("GetHead during an attach is bounded as a whole") + } + if af, ok := storage.AttachFetchFrom(inner.got); !ok || af.Bound != chunkAttachTimeout { + t.Fatalf("GetHead during an attach carries %+v (ok=%v)", af, ok) + } +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 81ab70076c..89e4401359 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -93,6 +93,8 @@ var ErrDetachOutcomeUnknown = errors.New("durable: detach outcome unknown; I/O s // ProviderConfig configures a DurableProvider. type ProviderConfig struct { + // RecoveryProgress observes completed local-open work before RecoverVolume. + RecoveryProgress func(storage.RecoveryPhase, uint64) // Impl selects which LogicalStorage implementation to open or // create. Zero value (ImplAuto): an existing volume opens with its // on-disk implementation, and a new volume is created as walstore. @@ -988,7 +990,7 @@ func (p *DurableProvider) openExisting(volumeID, path string, impl ImplName) (*v if p.testWALStoreFactory != nil { ws, err = p.testWALStoreFactory(path, false) } else { - ws, err = storage.OpenWALStore(path) + ws, err = storage.OpenWALStoreWithOptions(path, storage.WALStoreOptions{RecoveryProgress: p.cfg.RecoveryProgress}) } if err != nil { return nil, fmt.Errorf("durable: OpenWALStore %s: %w", path, err) @@ -1151,7 +1153,7 @@ func (p *DurableProvider) RecoverVolume(ctx context.Context, volumeID string) (R h.startupIdentityRefused = false p.mu.Unlock() } - report := Recover(h.storage, volumeID) + report := recoverContext(ctx, h.storage, volumeID) if report.Err != nil { h.backend.setRecoveryFailure(report.Evidence, report.Err) return report, report.Err diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 1e1f8ddbd7..fab1a4a412 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -10,6 +10,7 @@ import ( "math/rand/v2" "strings" "sync" + "sync/atomic" "time" "github.com/seaweedfs/seaweed-block/core/frontend" @@ -64,8 +65,11 @@ const ( // chunkAuthorityPoll is how often a volume awaiting authority checks // the projection. chunkAuthorityPoll = 20 * time.Millisecond - // chunkAttachTimeout bounds one deferred attach attempt; a failed - // attempt is retried after chunkAttachRetry. + // chunkAttachTimeout bounds each remote call of a deferred attach + // attempt (the attach check, the layout Start, and the layer's remote + // reads), never the attempt's volume-sized local work, which reports + // RecoveryAttach progress instead. A failed attempt is retried after + // chunkAttachRetry. chunkAttachTimeout = 30 * time.Second chunkAttachRetry = time.Second ) @@ -265,9 +269,9 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen h.attachMu.Unlock() return } - ctx, cancel := context.WithTimeout(waitCtx, chunkAttachTimeout) - err := p.attachChunk(ctx, volumeID, h) - cancel() + // No bound on the attempt as a whole: each remote call carries + // chunkAttachTimeout, local work reports progress. + err := p.attachChunk(waitCtx, volumeID, h) if err == nil { err = chunkFenced(volumeID, h) } @@ -468,7 +472,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h } if check := p.cfg.ChunkAttachCheck; check != nil { g := ChunkGeometry{NumBlocks: uint64(ws.NumBlocks()), BlockSize: uint32(ws.BlockSize()), ChunkBlocks: p.cfg.ChunkBlocks} - cctx, cancel := context.WithCancel(ctx) + cctx, cancel := context.WithTimeout(ctx, chunkAttachTimeout) stop := context.AfterFunc(p.closeCtx, cancel) err := check(cctx, volumeID, g) stop() @@ -486,7 +490,9 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h if e != nil { return nil, e } - layoutHead, err = startLayoutRoot(ctx, ws, st, layout.HolderID{Epoch: proj.Epoch, Holder: holder}) + sctx, scancel := context.WithTimeout(ctx, chunkAttachTimeout) + layoutHead, err = startLayoutRoot(sctx, ws, st, layout.HolderID{Epoch: proj.Epoch, Holder: holder}) + scancel() if err != nil { return nil, err } @@ -513,8 +519,9 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h }); ok { bound.waitUpload = pace.WaitUpload } - bound.setAttach(ctx) // the attach's calls also end with the caller's ctx - defer bound.setAttach(nil) + report := p.attachProgress() // one attempt's: the layer's local work and the manifest read's segments + bound.setAttach(ctx, report) // the attach's calls also end with the caller's ctx + defer bound.setAttach(nil, nil) keyer, ok := inner.(storage.ChunkKeyer) if !ok { return nil, errors.New("durable: layout remote lacks content keys") @@ -532,6 +539,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h CreatedThisStart: h.fresh && h.createdThisStart, ReadMissTimeout: p.cfg.ChunkReadMissTimeout, HydrationWorkers: p.cfg.ChunkHydrationWorkers, + AttachProgress: report, HydrationQueueDepth: p.cfg.ChunkHydrationQueueDepth, UploadConcurrency: p.cfg.ChunkUploadConcurrency, PayloadMemoryBudget: p.cfg.ChunkPayloadMemoryBudget, @@ -573,6 +581,20 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h return layer, err } +// attachProgress reports one attach attempt's completed local work to the +// host's recovery progress callback as RecoveryAttach. Each attempt counts +// from zero: a retry that redoes the same work reports nothing new to the +// host's high-water mark, so an attach that keeps failing never renews the +// inactivity window. nil without a callback. +func (p *DurableProvider) attachProgress() func(uint64) { + report := p.cfg.RecoveryProgress + if report == nil { + return nil + } + var done atomic.Uint64 // one attempt's + return func(n uint64) { report(storage.RecoveryAttach, done.Add(n)) } +} + // closeBoundRemote ends every remote call when the provider closes, so a // shutdown never waits on the remote for an attach or a cut. While an // attach runs, its calls also end with the attach caller's context. @@ -581,21 +603,50 @@ type closeBoundRemote struct { done context.Context waitUpload func(context.Context, int) error - mu sync.Mutex - attach context.Context + mu sync.Mutex + attach context.Context + attachDone func(uint64) // the attempt's progress, for the manifest read's segments } -func (r *closeBoundRemote) setAttach(ctx context.Context) { +func (r *closeBoundRemote) setAttach(ctx context.Context, done func(uint64)) { r.mu.Lock() - r.attach = ctx + r.attach, r.attachDone = ctx, done r.mu.Unlock() } +// bindManifest binds a whole-manifest read (GetHead): during an attach it +// carries the per-fetch rule (each root or segment fetch bounded by +// chunkAttachTimeout on its own, each completed segment reported) instead +// of one bound around the read, whose fetch count grows with the volume. +func (r *closeBoundRemote) bindManifest(ctx context.Context) (context.Context, func()) { + r.mu.Lock() + attach, done := r.attach, r.attachDone + r.mu.Unlock() + if attach == nil { + return r.bind(ctx) + } + c, cancel := context.WithCancel(storage.WithAttachFetch(ctx, storage.AttachFetch{Bound: chunkAttachTimeout, Done: done})) + stops := []func() bool{context.AfterFunc(r.done, cancel), context.AfterFunc(attach, cancel)} + if r.done.Err() != nil || attach.Err() != nil { + cancel() + } + return c, func() { + for _, stop := range stops { + stop() + } + cancel() + } +} + func (r *closeBoundRemote) bind(ctx context.Context) (context.Context, func()) { r.mu.Lock() attach := r.attach r.mu.Unlock() c, cancel := context.WithCancel(ctx) + if attach != nil { + // An attach's remote call is bounded on its own, not by the attempt. + c, cancel = context.WithTimeout(ctx, chunkAttachTimeout) + } stops := []func() bool{context.AfterFunc(r.done, cancel)} if attach != nil { stops = append(stops, context.AfterFunc(attach, cancel)) @@ -648,13 +699,13 @@ func (r *closeBoundRemote) Get(ctx context.Context, key string) ([]byte, error) } func (r *closeBoundRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { - c, end := r.bind(ctx) + c, end := r.bindManifest(ctx) defer end() return r.ChunkRemote.GetHead(c) } func (r *closeBoundRemote) GetHeadRoot(ctx context.Context) (storage.ChunkHead, error) { - c, end := r.bind(ctx) + c, end := r.bindManifest(ctx) defer end() if reader, ok := r.ChunkRemote.(storage.ChunkHeadRootReader); ok { return reader.GetHeadRoot(c) diff --git a/seaweed-block/core/frontend/durable/recovery.go b/seaweed-block/core/frontend/durable/recovery.go index a5e8ba7165..c503e21b6e 100644 --- a/seaweed-block/core/frontend/durable/recovery.go +++ b/seaweed-block/core/frontend/durable/recovery.go @@ -19,6 +19,7 @@ package durable // against master-published state. import ( + "context" "fmt" "github.com/seaweedfs/seaweed-block/core/storage" @@ -46,7 +47,19 @@ type RecoveryReport struct { // (or caller) is responsible for flipping the adapter's // operational gate based on the report. func Recover(s storage.LogicalStorage, volumeID string) RecoveryReport { - lsn, err := s.Recover() + return recoverContext(context.Background(), s, volumeID) +} + +func recoverContext(ctx context.Context, s storage.LogicalStorage, volumeID string) RecoveryReport { + var lsn uint64 + var err error + if observed, ok := s.(interface { + RecoverContext(context.Context) (uint64, error) + }); ok { + lsn, err = observed.RecoverContext(ctx) + } else { + lsn, err = s.Recover() + } if err != nil { return RecoveryReport{ VolumeID: volumeID, diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 1bd1073375..19183f7efe 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -355,7 +355,7 @@ func New(cfg Config) (*Host, error) { h.incarnation = newIncarnation() h.mw = newMasterWait(nil, lg.Printf) h.wd = newRecoveryWatchdog(cfg.RecoverTimeout) - h.log.Printf("blockvolume: volume %s recovery watchdog: a primary assignment must become promotion-ready within %s", cfg.VolumeID, h.wd.timeout) + h.log.Printf("blockvolume: volume %s recovery watchdog: primary startup inactivity window %s (new completed recovery/attach work renews it)", cfg.VolumeID, h.wd.timeout) if cfg.ReplicationVolume != nil { h.setReplicationLocked(cfg.ReplicationVolume) } diff --git a/seaweed-block/core/host/volume/recovery_lock_guard_test.go b/seaweed-block/core/host/volume/recovery_lock_guard_test.go new file mode 100644 index 0000000000..5f6d1db5a7 --- /dev/null +++ b/seaweed-block/core/host/volume/recovery_lock_guard_test.go @@ -0,0 +1,149 @@ +package volume + +import ( + "bytes" + "fmt" + "go/ast" + "go/format" + "go/parser" + "go/token" + "os" + "path/filepath" + "strings" + "testing" +) + +// Pin every call in watchdog-locked methods. Storage may call this observer +// under its barriers, so adding a storage call, wait, or unknown helper here +// requires a lock-order review, not an uncounted exception. +func TestRecoveryWatchdogLockedMethodsNeverCallStorageOrWait(t *testing.T) { + fset := token.NewFileSet() + f, err := parser.ParseFile(fset, "recovery_watchdog.go", nil, 0) + if err != nil { + t.Fatal(err) + } + locked := 0 + for _, decl := range f.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + var body bytes.Buffer + _ = format.Node(&body, fset, fn.Body) + if !strings.Contains(body.String(), ".mu.Lock()") { + continue + } + locked++ + 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/host/volume/recovery_progress_test.go b/seaweed-block/core/host/volume/recovery_progress_test.go new file mode 100644 index 0000000000..6bcb43d462 --- /dev/null +++ b/seaweed-block/core/host/volume/recovery_progress_test.go @@ -0,0 +1,55 @@ +package volume + +import ( + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestRecoveryProgress_CountingEntriesOutliveTheTotalWindow(t *testing.T) { + h, clk := watchdogHost(t, 30*time.Second) + h.applyFixtureFact(selfPrimaryFact(1)) + for done := uint64(1); done <= 262144; done++ { + clk.advance(time.Second) + h.ReportRecoveryProgress(storage.RecoveryReplay, done) + if got := h.UnhealthyReason(); got != "" { + t.Fatalf("steady entry %d timed out: %s", done, got) + } + } + clk.advance(30 * time.Second) + if got := h.UnhealthyReason(); got != UnhealthyRecoveryTimeout { + t.Fatalf("no entries for the window: %q", got) + } +} + +func TestRecoveryProgress_RepeatedAttachPreparationDoesNotRenew(t *testing.T) { + h, clk := watchdogHost(t, 30*time.Second) + h.applyFixtureFact(selfPrimaryFact(1)) + h.ReportRecoveryProgress(storage.RecoveryReplay, 262144) + h.ReportRecoveryProgress(storage.RecoveryAttach, 262144) + for attempt := 0; attempt < 4; attempt++ { + clk.advance(10 * time.Second) + h.ReportRecoveryProgress(storage.RecoveryScan, 999999) + h.ReportRecoveryProgress(storage.RecoveryAttach, 0) + h.ReportRecoveryProgress(storage.RecoveryAttach, 262144) + } + if got := h.UnhealthyReason(); got != UnhealthyRecoveryTimeout { + t.Fatalf("retried preparation kept failed attach alive: %q", got) + } + // Late progress must not undo a timeout's already reported outcome. + h.ReportRecoveryProgress(storage.RecoveryAttach, 262145) + if got := h.UnhealthyReason(); got != UnhealthyRecoveryTimeout { + t.Fatalf("late progress cleared timeout: %q", got) + } +} + +func TestRecoveryProgress_LateEntryCannotHideAnUnobservedStall(t *testing.T) { + h, clk := watchdogHost(t, 30*time.Second) + h.applyFixtureFact(selfPrimaryFact(1)) + clk.advance(31 * time.Second) + h.ReportRecoveryProgress(storage.RecoveryScan, 1) + if got := h.UnhealthyReason(); got != UnhealthyRecoveryTimeout { + t.Fatalf("late entry hid stall: %q", got) + } +} diff --git a/seaweed-block/core/host/volume/recovery_watchdog.go b/seaweed-block/core/host/volume/recovery_watchdog.go index 7188f6e19a..e58708851a 100644 --- a/seaweed-block/core/host/volume/recovery_watchdog.go +++ b/seaweed-block/core/host/volume/recovery_watchdog.go @@ -16,7 +16,7 @@ import ( // // A replica that holds the PRIMARY assignment but whose local recovery // has not produced the engine's promotion-ready fact within the recover -// timeout reports an explicit unhealthy fact (Eligible=false plus a typed +// inactivity window reports an explicit unhealthy fact (Eligible=false plus a typed // reason) instead of staying silently not-ready, so the master fails over // at once to a peer that passes the promotion evidence gate, or, with no // qualifying peer, promotes nobody and surfaces the reason. @@ -24,8 +24,9 @@ import ( // - Scope: only a primary-assigned replica is flagged. A supporting // replica in a long catch-up is not; its catch-up state (elapsed, // lag) is visible in /status instead. -// - The timeout runs from the primary assignment in this incarnation -// (a new primary epoch restarts it). +// - The window starts at the primary assignment in this incarnation and +// advances only on a new (phase, cumulative completed work) high-water mark. +// A new primary epoch restarts the window, not the process's work frontier. // - recovery_timeout latches until a fresh promotion-ready fact clears // it (Eligible=true, reason empty). An epoch that already moved // stays moved: the master decides that, not the volume. @@ -59,8 +60,7 @@ const ( // directory and re-add it. UnhealthyRebuildRetainedBase = "rebuild_retained_base" - // DefaultRecoverTimeout matches blockmaster's default freshness - // window. + // DefaultRecoverTimeout is the shared recovery/attach inactivity window. DefaultRecoverTimeout = 30 * time.Second ) @@ -77,6 +77,9 @@ type recoveryWatchdog struct { supportingEpoch uint64 timedOut bool // recovery_timeout latched until a ready fact readySeen bool // promotion-ready once in this primary assignment: disarmed + progressPhase storage.RecoveryPhase + progressDone uint64 + lastProgress time.Time } func newRecoveryWatchdog(timeout time.Duration) *recoveryWatchdog { @@ -86,6 +89,30 @@ func newRecoveryWatchdog(timeout time.Duration) *recoveryWatchdog { return &recoveryWatchdog{timeout: timeout, now: time.Now} } +// ReportRecoveryProgress observes completed startup work; it grants no readiness. +func (h *Host) ReportRecoveryProgress(phase storage.RecoveryPhase, done uint64) { + if h == nil || h.wd == nil || phase < storage.RecoveryOpenMap || phase > storage.RecoveryAttach || done == 0 { + return + } + w := h.wd + // Lock order: storage barriers -> watchdog.mu. Nothing under this lock + // calls storage or waits for storage; the callback only records a frontier. + w.mu.Lock() + defer w.mu.Unlock() + if phase < w.progressPhase || (phase == w.progressPhase && done <= w.progressDone) { + return + } + now := w.now() + since := w.primarySince + if w.lastProgress.After(since) { + since = w.lastProgress + } + if !w.primarySince.IsZero() && !w.readySeen && now.Sub(since) >= w.timeout { + w.timedOut = true + } + w.progressPhase, w.progressDone, w.lastProgress = phase, done, now +} + // primaryAssigned records a primary assignment for this replica. A new // epoch restarts the timeout. func (w *recoveryWatchdog) primaryAssigned(epoch uint64) { @@ -152,7 +179,11 @@ func (w *recoveryWatchdog) reason(ready bool, readyEpoch uint64, roleAdmissionFa if w.readySeen { return "", false } - if !w.timedOut && w.now().Sub(w.primarySince) >= w.timeout { + since := w.primarySince + if w.lastProgress.After(since) { + since = w.lastProgress + } + if !w.timedOut && w.now().Sub(since) >= w.timeout { w.timedOut, fired = true, true } if w.timedOut { @@ -195,7 +226,7 @@ func (h *Host) unhealthyReason(fact engine.PromotionReadyFact, ready bool) strin local, _ := h.localRecoveryReason.Load().(string) reason, fired := h.wd.reason(ready, fact.Epoch, failed, local) if fired { - h.log.Printf("blockvolume: volume %s primary assignment epoch=%d not promotion-ready after %s: reporting unhealthy (%s)", + h.log.Printf("blockvolume: volume %s primary assignment epoch=%d has no new recovery/attach work for %s: reporting unhealthy (%s)", h.cfg.VolumeID, h.wd.epoch(), h.wd.timeout, UnhealthyRecoveryTimeout) } return reason diff --git a/seaweed-block/core/storage/attach_fetch.go b/seaweed-block/core/storage/attach_fetch.go new file mode 100644 index 0000000000..996090b511 --- /dev/null +++ b/seaweed-block/core/storage/attach_fetch.go @@ -0,0 +1,29 @@ +package storage + +import ( + "context" + "time" +) + +// AttachFetch is carried by the context of an attach's whole-manifest read +// (GetHead): the read is not one remote call but a root fetch and one fetch +// per segment, whose number grows with the volume. Bound limits each fetch +// on its own (never the read as a whole); Done receives the entries of each +// segment as it completes, as the attach's RecoveryAttach progress. +type AttachFetch struct { + Bound time.Duration + Done func(n uint64) +} + +type attachFetchKey struct{} + +// WithAttachFetch marks ctx as an attach's manifest read. +func WithAttachFetch(ctx context.Context, f AttachFetch) context.Context { + return context.WithValue(ctx, attachFetchKey{}, f) +} + +// AttachFetchFrom returns the attach fetch rule ctx carries, if any. +func AttachFetchFrom(ctx context.Context) (AttachFetch, bool) { + f, ok := ctx.Value(attachFetchKey{}).(AttachFetch) + return f, ok +} diff --git a/seaweed-block/core/storage/block_metadata.go b/seaweed-block/core/storage/block_metadata.go index 120ae6d4a6..33fc39ac8d 100644 --- a/seaweed-block/core/storage/block_metadata.go +++ b/seaweed-block/core/storage/block_metadata.go @@ -46,7 +46,10 @@ type BlockMetadataBinding struct { // on open it must accept exactly the stored version. No registry or hook chain. type BlockMetadataFactory func(BlockMetadataFile, BlockMetadataLayout) (BlockMetadataBinding, error) type WALStoreOptions struct { - MetadataFactory BlockMetadataFactory + // RecoveryProgress observes validated open-map entries. It may take the + // watchdog lock, but must never call back into storage or perform I/O. + RecoveryProgress func(RecoveryPhase, uint64) + MetadataFactory BlockMetadataFactory // ChunkBlocks fixes the owned map geometry at create. Zero uses 1024. ChunkBlocks uint32 // WMode is C (lagged) by default; A (strict) is an opt-in per volume. diff --git a/seaweed-block/core/storage/chunk_attach_progress_test.go b/seaweed-block/core/storage/chunk_attach_progress_test.go new file mode 100644 index 0000000000..4a5c5a8632 --- /dev/null +++ b/seaweed-block/core/storage/chunk_attach_progress_test.go @@ -0,0 +1,166 @@ +package storage + +import ( + "fmt" + "path/filepath" + "testing" + "time" +) + +// attachCounter records AttachProgress reports. +type attachCounter struct { + calls int + total uint64 +} + +func (c *attachCounter) report(n uint64) { + c.calls++ + c.total += n +} + +// The attach's volume-sized local work reports its completed entries: +// the HEAD copy, then the per-entry marking of a fresh host's absent +// chunks in batches of 256, all of it by the end of the attempt; an +// existing host reports its presence entries as it loads them. Never +// one report per entry. +func TestAttachReportsItsVolumeSizedLocalWork(t *testing.T) { + const n = 262144 + head := chunkHead{Gen: 1, Epoch: 1, Holder: "old", Chunks: make(map[uint64]chunkRef, n)} + for i := uint64(0); i < n; i++ { + head.Chunks[i] = chunkRef{Key: fmt.Sprintf("c%d", i)} + } + open := func(t *testing.T) *WALStore { + s, err := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "volume"), 1024, 4096, WALStoreOptions{ChunkBlocks: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + return s + } + t.Run("fresh host", func(t *testing.T) { + s := open(t) + remote := newFakeChunkRemote() + remote.head = head + var c attachCounter + layer, err := attachChunkLayer(s, remote, chunkLayerConfig{ChunkBlocks: 1, Epoch: 2, Holder: "me", FreshFromHead: true, AttachProgress: c.report}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = layer.Close() }) + // The HEAD copy, the absent marking and the presence save (its key + // preparation, then each serialized line): every entry, as it completes. + if c.total != 4*n { + t.Fatalf("reported %d entries, want %d (the HEAD copy, the absent marking, the presence save's keys and lines)", c.total, 4*n) + } + if c.calls > 4*n/256+10 { + t.Fatalf("%d reports for %d entries: not batched", c.calls, 4*n) + } + }) + t.Run("existing presence", func(t *testing.T) { + path := filepath.Join(t.TempDir(), "volume") + s0, err := CreateWALStoreWithOptions(path, 1024, 4096, WALStoreOptions{ChunkBlocks: 1}) + if err != nil { + t.Fatal(err) + } + s0.DisableAutoFlushForRecoveryTest() + if _, err := s0.Recover(); err != nil { + t.Fatal(err) + } + remote := newFakeChunkRemote() + remote.head = head + first, err := attachChunkLayer(s0, remote, chunkLayerConfig{ChunkBlocks: 1, Epoch: 2, Holder: "me", FreshFromHead: true}) + if err != nil { + t.Fatal(err) + } + _ = first.Close() + _ = s0.Close() + s, err := OpenWALStore(path) // a restart: the presence file holds n absent entries + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + var c attachCounter + layer, err := attachChunkLayer(s, remote, chunkLayerConfig{ChunkBlocks: 1, Epoch: 2, Holder: "me", AttachProgress: c.report}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = layer.Close() }) + if c.total != 2*n { // the HEAD copy and n "absent" presence lines (an unchanged presence is not saved again) + t.Fatalf("reported %d entries, want %d", c.total, 2*n) + } + if c.calls > 2*n/256+10 { + t.Fatalf("%d reports: not batched", c.calls) + } + }) +} + +// A host that created its store at this start also scans every chunk for +// ones it knows to be zero; that scan reports each entry it inspects, also +// when none is a candidate (a dense HEAD names them all). +func TestAttachReportsTheCreatedThisStartScan(t *testing.T) { + const n = 1024 + attach := func(t *testing.T, named int, created bool) uint64 { + s, err := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "volume"), n, 4096, WALStoreOptions{ChunkBlocks: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + remote := newFakeChunkRemote() + remote.head = chunkHead{Gen: 1, Epoch: 1, Holder: "old", Chunks: map[uint64]chunkRef{}} + for i := 0; i < named; i++ { + remote.head.Chunks[uint64(i)] = chunkRef{Key: fmt.Sprintf("c%d", i)} + } + var c attachCounter + layer, err := attachChunkLayer(s, remote, chunkLayerConfig{ChunkBlocks: 1, Epoch: 2, Holder: "me", FreshFromHead: true, CreatedThisStart: created, AttachProgress: c.report}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = layer.Close() }) + return c.total + } + for _, named := range []int{0, n} { // sparse (all candidates), dense (none) + if d := attach(t, named, true) - attach(t, named, false); d != n { + t.Fatalf("HEAD naming %d of %d chunks: the created-this-start scan reported %d entries, want %d (every inspected entry)", named, n, d, n) + } + } +} + +// The batcher reports the first completion, every 256 entries, and about +// once a second while entries keep completing slowly: a slow loop of fewer +// than 256 entries is never silent for the whole window, and nothing is +// reported for work not completed. +func TestAttachProgressFlushesSlowWorkAboutEverySecond(t *testing.T) { + now := time.Unix(1000, 0) + var reports []uint64 + a := attachProgress{report: func(n uint64) { reports = append(reports, n) }, now: func() time.Time { return now }} + a.add(1) // the first completion + for i := 0; i < 10; i++ { + now = now.Add(300 * time.Millisecond) + a.add(1) + } + // 3 s of slow entries: the first, then about one report a second. + if len(reports) < 3 || len(reports) > 5 { + t.Fatalf("reports %v over 3 s of slow entries: want the first and about one a second", reports) + } + sum := uint64(0) + for _, r := range reports { + sum += r + } + a.flush() + if sum > 11 || sum+a.pending > 11 { + t.Fatalf("reported %d of 11 completed entries", sum) + } + b := attachProgress{report: func(uint64) { t.Fatal("reported with no completed work") }, now: func() time.Time { return now }} + b.flush() +} diff --git a/seaweed-block/core/storage/chunk_fresh_known_zero.go b/seaweed-block/core/storage/chunk_fresh_known_zero.go index f2fba525e2..7b88d65e77 100644 --- a/seaweed-block/core/storage/chunk_fresh_known_zero.go +++ b/seaweed-block/core/storage/chunk_fresh_known_zero.go @@ -31,6 +31,7 @@ func (l *chunkLayerImpl) freshKnownZeroCandidates(head chunkHead) map[uint64]uin defer s.mu.RUnlock() out := map[uint64]uint64{} for idx := uint64(0); idx < l.numChunks && idx < uint64(len(s.v3.mapEntries)); idx++ { + l.attachProgress.add(1) // attach only (its one caller): every inspected entry, candidate or not if _, named := head.Chunks[idx]; named { continue } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 9bc2efe184..1ef1a3edab 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -54,7 +54,44 @@ type chunkHooks struct { const defaultReadMissTimeout = 30 * time.Second +// attachProgress batches an attach's completed local work for +// chunkLayerConfig.AttachProgress: a report once 256 entries completed. +type attachProgress struct { + report func(uint64) + pending uint64 + last time.Time // the last report + now func() time.Time // nil: time.Now (a test's clock otherwise) +} + +func (a *attachProgress) clock() time.Time { + if a.now != nil { + return a.now() + } + return time.Now() +} + +// add counts n completed entries: reported at the first completion, every +// 256, and about once a second while entries keep completing slowly (as +// the recovery reporter does). Nothing is reported for work not completed. +func (a *attachProgress) add(n uint64) { + if a.report == nil { + return + } + a.pending += n + if a.pending >= 256 || a.last.IsZero() || a.clock().Sub(a.last) >= time.Second { + a.flush() + } +} + +func (a *attachProgress) flush() { + if a.report != nil && a.pending > 0 { + a.report(a.pending) + a.pending, a.last = 0, a.clock() + } +} + type chunkLayerImpl struct { + attachProgress attachProgress // attach only; loadPresence reports through it // capMu serializes pre-copy admission and its recent measurements. precopyFreeze func(uint64, time.Time, chunkCutStats) bool precopyPrepare func(context.Context) (func(), error) @@ -256,6 +293,8 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) syncDirFn: syncDir, } l.chunkMut = make([]atomic.Uint64, l.numChunks) + l.attachProgress = attachProgress{report: cfg.AttachProgress} + defer l.attachProgress.flush() // work completed by a failed attempt still counts var nb8 [8]byte if _, err := rand.Read(nb8[:]); err != nil { return nil, err @@ -268,7 +307,7 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) l.cancel() return nil, fmt.Errorf("storage: chunk layer attach: read HEAD: %w", err) } - l.head = copyHead(head) + l.head = copyHeadEach(head, l.attachProgress.add) // reports as it copies l.remoteLSN = head.RemoteLSN // A HEAD that already belongs to a newer epoch or a competing holder is // never used as this holder's publication guard. @@ -295,6 +334,7 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) for idx := range head.Chunks { l.absent[idx] = true l.absentGen[idx]++ + l.attachProgress.add(1) } l.presenceVer++ if cfg.CreatedThisStart { @@ -314,7 +354,7 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) l.cancel() return nil, errors.New("storage: a chunk layer is already attached") } - if err := l.persistPresence(); err != nil { + if err := l.persistPresenceEach(l.attachProgress.add); err != nil { s.chunk.CompareAndSwap(hooks, nil) l.cancel() return nil, err @@ -328,7 +368,11 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) return l, nil } -func copyHead(h chunkHead) chunkHead { +func copyHead(h chunkHead) chunkHead { return copyHeadEach(h, nil) } + +// copyHeadEach is copyHead reporting each copied segment and chunk entry to +// each (nil: none). +func copyHeadEach(h chunkHead, each func(uint64)) chunkHead { out := h if h.DetachedBy != nil { d := *h.DetachedBy @@ -338,11 +382,17 @@ func copyHead(h chunkHead) chunkHead { out.Segments = make(map[uint64]ChunkSegment, len(h.Segments)) for k, v := range h.Segments { out.Segments[k] = v + if each != nil { + each(1) + } } } out.Chunks = make(map[uint64]chunkRef, len(h.Chunks)) for k, v := range h.Chunks { out.Chunks[k] = v + if each != nil { + each(1) + } } return out } @@ -1803,7 +1853,11 @@ func (l *chunkLayerImpl) presencePath() string { return l.s.path + ".chunkpresen // persistPresence makes the absence state durable. It fsyncs the volume // first, so a chunk recorded as present has its filled bytes on disk. -func (l *chunkLayerImpl) persistPresence() error { +func (l *chunkLayerImpl) persistPresence() error { return l.persistPresenceEach(nil) } + +// persistPresenceEach is persistPresence reporting each serialized entry to +// each (the attach's progress; nil elsewhere). +func (l *chunkLayerImpl) persistPresenceEach(each func(uint64)) error { // The whole save runs under presMu, so a snapshot can never be written // after a newer one. Lock order: WALStore.mu -> presMu -> stMu. l.presMu.Lock() @@ -1815,11 +1869,21 @@ func (l *chunkLayerImpl) persistPresence() error { return nil } var b strings.Builder - for _, idx := range sortedKeys(l.absent) { - fmt.Fprintf(&b, "absent %d\n", idx) + absent, local := sortedKeys(l.absent), sortedKeys(l.localBlocks) + if each != nil { // the key collection and sort, completed + each(uint64(len(absent) + len(local))) } - for _, lba := range sortedKeys(l.localBlocks) { + for _, idx := range absent { + fmt.Fprintf(&b, "absent %d\n", idx) + if each != nil { + each(1) + } + } + for _, lba := range local { fmt.Fprintf(&b, "local %d\n", lba) + if each != nil { + each(1) + } } l.stMu.Unlock() if hook := l.testPresenceSnapshotHook; hook != nil { @@ -1873,6 +1937,7 @@ func (l *chunkLayerImpl) loadPresence() error { default: return fmt.Errorf("storage: chunk presence: bad line %q", sc.Text()) } + l.attachProgress.add(1) } l.savedPresVer = l.presenceVer return sc.Err() diff --git a/seaweed-block/core/storage/chunk_lsn_map_v3.go b/seaweed-block/core/storage/chunk_lsn_map_v3.go index 263a599604..a46f1fb469 100644 --- a/seaweed-block/core/storage/chunk_lsn_map_v3.go +++ b/seaweed-block/core/storage/chunk_lsn_map_v3.go @@ -147,6 +147,10 @@ func mapReadAtV3(f *os.File, off, n, size uint64) ([]byte, error) { // readChunkLSNMapV3 checks the descriptor tuple and every immutable dependency // before returning any entries. No corrupt root is treated as an empty map. func readChunkLSNMapV3(f *os.File, d descriptorV3, cb uint64) ([]chunkLSNEntryV3, []mapPageRefV3, error) { + return readChunkLSNMapV3Progress(f, d, cb, nil) +} + +func readChunkLSNMapV3Progress(f *os.File, d descriptorV3, cb uint64, progress *recoveryReporter) ([]chunkLSNEntryV3, []mapPageRefV3, error) { s, e := mapShapeForV3(d, cb) if e != nil { return nil, nil, e @@ -213,6 +217,9 @@ func readChunkLSNMapV3(f *os.File, d descriptorV3, cb uint64) ([]chunkLSNEntryV3 entries = append(entries, chunkLSNEntryV3{LSN: lsn, Unknown: q[8] == 1}) } refs = append(refs, r) + if progress != nil { + progress.advance(count) + } } return entries, refs, nil } @@ -285,11 +292,15 @@ func createChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3 // Open validates the selected generation before permitting any append. The // caller must also validate the fallback descriptor before serving/retiring. func openChunkLSNMapV3(path string, d descriptorV3, cb uint64) (*chunkLSNMapV3, *chunkMapCandidateV3, error) { + return openChunkLSNMapV3Progress(path, d, cb, nil) +} + +func openChunkLSNMapV3Progress(path string, d descriptorV3, cb uint64, progress *recoveryReporter) (*chunkLSNMapV3, *chunkMapCandidateV3, error) { f, e := os.OpenFile(path, os.O_RDWR, 0) if e != nil { return nil, nil, e } - es, refs, e := readChunkLSNMapV3(f, d, cb) + es, refs, e := readChunkLSNMapV3Progress(f, d, cb, progress) if e != nil { f.Close() return nil, nil, e diff --git a/seaweed-block/core/storage/chunk_map_publication_v3.go b/seaweed-block/core/storage/chunk_map_publication_v3.go index 2ef10237b2..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 } } @@ -178,6 +182,10 @@ func (p *descriptorPublisherV3) invalidateMapProofV3() error { // dependencies before any store background worker is started. Geometry is // subsequently checked by the chunk/provider caller against its configuration. func openDescriptorMapV3(path string, selected descriptorV3, fallback *descriptorV3) (*chunkLSNMapV3, *chunkMapCandidateV3, error) { + return openDescriptorMapV3Progress(path, selected, fallback, nil) +} + +func openDescriptorMapV3Progress(path string, selected descriptorV3, fallback *descriptorV3, progress *recoveryReporter) (*chunkLSNMapV3, *chunkMapCandidateV3, error) { if selected.MapRootLocator > math.MaxInt64-64 { return nil, nil, ErrMapInvalid } @@ -192,7 +200,7 @@ func openDescriptorMapV3(path string, selected descriptorV3, fallback *descripto return nil, nil, err } cb := binary.LittleEndian.Uint64(raw[:]) - m, c, err := openChunkLSNMapV3(path, selected, cb) + m, c, err := openChunkLSNMapV3Progress(path, selected, cb, progress) if err != nil { return nil, nil, err } @@ -201,7 +209,7 @@ func openDescriptorMapV3(path string, selected descriptorV3, fallback *descripto err = ErrMapInvalid } else { var refs []mapPageRefV3 - if _, refs, err = readChunkLSNMapV3(m.fd, *fallback, cb); err == nil { + if _, refs, err = readChunkLSNMapV3Progress(m.fd, *fallback, cb, progress); err == nil { if sh, e := mapShapeForV3(*fallback, cb); e == nil { m.registerRootV3(fallback.MapGeneration, fallback.MapRootLocator, sh.aligned, refs) } diff --git a/seaweed-block/core/storage/chunk_mutation_note_guard_test.go b/seaweed-block/core/storage/chunk_mutation_note_guard_test.go index 932f55fb09..34d1fa59aa 100644 --- a/seaweed-block/core/storage/chunk_mutation_note_guard_test.go +++ b/seaweed-block/core/storage/chunk_mutation_note_guard_test.go @@ -173,7 +173,7 @@ func TestEveryDirtyMapInsertNotesTheChunkMutation(t *testing.T) { replay = replayCallersNoted(t, srcs) wantReplay := []string{ "base_install_v3.go resumeBaseInstallV3 noted", - "walstore_v3.go recoverV3 noted by Recover", + "walstore_v3.go recoverV3 noted by RecoverContext", } if fmt.Sprint(replay) != fmt.Sprint(wantReplay) { t.Fatalf("replay callers: %v; want %v", replay, wantReplay) diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 6b97d61eed..f64aa396fc 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -331,6 +331,13 @@ type chunkLayerConfig struct { ReadMissTimeout time.Duration // HydrationWorkers bounds layer-owned fetches (0 defaults to 2). HydrationWorkers int + // AttachProgress, when set, observes the attach's completed local work + // (HEAD entries copied and marked, presence entries loaded): the HEAD copy + // as one report, the per-entry loops in batches of 256, and the rest at + // the end of the attempt, failed or not. n is the work completed + // since the previous call within this attach. It reports completed work + // only, never time. It must not call storage. + AttachProgress func(n uint64) // HydrationQueueDepth bounds distinct queued/in-flight chunks (0 defaults to 64). HydrationQueueDepth int // Bitmap persists the legacy dirty-since-HEAD bitmap. Required for v2; diff --git a/seaweed-block/core/storage/layout_fresh_mutators_test.go b/seaweed-block/core/storage/layout_fresh_mutators_test.go index ede2316f21..0578fd70ba 100644 --- a/seaweed-block/core/storage/layout_fresh_mutators_test.go +++ b/seaweed-block/core/storage/layout_fresh_mutators_test.go @@ -22,7 +22,7 @@ var walStoreMethods = map[string]string{ "ApplyEntry": "replication", "WriteExtentDirect": "base (v3: install handle)", "AdvanceFrontier": "base/replication", "BeginBaseInstall": "base", "CommitChunkAttachV3": "base", "SeedChunkFrontier": "base", "SyncInstallLog": "base", - "AdvanceWALTail": "replication", "FormatV3": "base", "Recover": "recovery", + "AdvanceWALTail": "replication", "FormatV3": "base", "Recover": "recovery", "RecoverContext": "recovery (observed Recover; does not admit guest writes)", "SetLayoutIdentity": "control", "SetWMode": "control", "SetMultiBlockRecords": "control", "SetRecoveryRetentionLSNs": "control", "SetRecycleFloorSource": "control", "AllowBaseRetirementV3": "control", "DeferBaseRetirementV3": "control", "HoldExtentDrainUntilChunkLayer": "control (holds the extent drain until the chunk layer attaches)", diff --git a/seaweed-block/core/storage/recovery_progress.go b/seaweed-block/core/storage/recovery_progress.go new file mode 100644 index 0000000000..00acaf4ba6 --- /dev/null +++ b/seaweed-block/core/storage/recovery_progress.go @@ -0,0 +1,115 @@ +package storage + +import ( + "context" + "time" +) + +// RecoveryPhase orders completed work in one process. Reports may only move +// forward; repeating preparation on a retry is not new recovery progress. +type RecoveryPhase uint8 + +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. +// The observer must not call storage: recovery invokes it under its barriers. +func WithRecoveryProgress(ctx context.Context, observe func(RecoveryPhase, uint64)) context.Context { + if observe == nil { + return ctx + } + return context.WithValue(ctx, recoveryProgressKey{}, observe) +} + +// ObserveRecoveryProgress reports completed work only, never a poll or phase +// entry. The receiver rejects repeated or backwards progress. +func ObserveRecoveryProgress(ctx context.Context, phase RecoveryPhase, done uint64) { + if observe, ok := ctx.Value(recoveryProgressKey{}).(func(RecoveryPhase, uint64)); ok && observe != nil { + observe(phase, done) + } +} + +// recoveryReporter checks time at each bounded disk record, or once per small +// in-memory batch. It never reports work that has not completed. +type recoveryReporter struct { + ctx context.Context + phase RecoveryPhase + done uint64 + lastDone uint64 + lastAt time.Time + now func() time.Time +} + +func newRecoveryReporter(ctx context.Context, phase RecoveryPhase) *recoveryReporter { + 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 { + r.flushAt(now) + } +} + +func (r *recoveryReporter) flushAt(now time.Time) { + if r.done > r.lastDone { + ObserveRecoveryProgress(r.ctx, r.phase, r.done) + r.lastDone, r.lastAt = r.done, 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) { + // 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)) + candidate = append(candidate, src[start:end]...) + progress.advance(uint64(end - start)) + } + progress.finish() + 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 new file mode 100644 index 0000000000..3e1b572406 --- /dev/null +++ b/seaweed-block/core/storage/recovery_progress_test.go @@ -0,0 +1,256 @@ +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 + ctx := WithRecoveryProgress(context.Background(), func(phase RecoveryPhase, done uint64) { + if phase != RecoveryMap || done <= high || done > 262144 { + t.Fatalf("progress %d/%d", phase, done) + } + high = done + }) + got, err := copyRecoveryMap(ctx, nil, src) + if err != nil || high != 262144 || !reflect.DeepEqual(got, src) { + t.Fatalf("copied %d observed %d: %v", len(got), high, err) + } +} + +func TestWALStoreRecoveryReportsRealCompletedWork(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + seen := map[RecoveryPhase]uint64{} + ctx := WithRecoveryProgress(context.Background(), func(phase RecoveryPhase, done uint64) { + if done <= seen[phase] { + t.Fatalf("non-monotone %d/%d", phase, done) + } + seen[phase] = done + }) + if frontier, err := s.RecoverContext(ctx); err != nil || frontier != 1 { + t.Fatalf("recover=%d %v", frontier, err) + } + for _, phase := range []RecoveryPhase{RecoveryScan, RecoveryMap, RecoveryReplay} { + if seen[phase] == 0 { + t.Fatalf("real recovery omitted phase %d: %v", phase, seen) + } + } +} + +func TestWALStoreOpenReportsValidatedMapAndCopyBeforeReplay(t *testing.T) { + s, path := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + if err := s.Close(); err != nil { + t.Fatal(err) + } + seen := map[RecoveryPhase]uint64{} + phase := RecoveryPhase(0) + r, err := OpenWALStoreWithOptions(path, WALStoreOptions{RecoveryProgress: func(p RecoveryPhase, done uint64) { + if p < phase || done <= seen[p] { + t.Fatalf("backwards open progress %d/%d", p, done) + } + phase, seen[p] = p, done + }}) + if err != nil { + t.Fatal(err) + } + defer r.Close() + // 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) + } +} + +func TestRecoveryReporterSlowReplayReportsBeforeTheEntryBatch(t *testing.T) { + now := time.Unix(1000, 0) + last := now + var high uint64 + ctx := WithRecoveryProgress(context.Background(), func(phase RecoveryPhase, done uint64) { + if phase != RecoveryReplay || done <= high || now.Sub(last) > time.Second { + t.Fatalf("steady replay stalled between reports: phase=%d done=%d gap=%s", phase, done, now.Sub(last)) + } + high, last = done, now + }) + r := newRecoveryReporter(ctx, RecoveryReplay) + r.now = func() time.Time { return now } + // A 256-entry batch needs 128 seconds, far longer than the watchdog. + for i := 0; i < 256; i++ { + now = now.Add(500 * time.Millisecond) + r.advance(1) + } + r.finish() + if high != 256 { + 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 f89e568695..ae608fcbdc 100644 --- a/seaweed-block/core/storage/wal_io_v3.go +++ b/seaweed-block/core/storage/wal_io_v3.go @@ -1,6 +1,7 @@ package storage import ( + "context" "encoding/binary" "errors" "fmt" @@ -214,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() @@ -230,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 } @@ -238,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 { @@ -263,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) } } @@ -290,6 +305,12 @@ func scanWALV3(fd *os.File, d descriptorV3) (walScanResultV3, error) { // Only an already-bound metadata factory can authorize a companion format. // Standalone scans retain the OSS-only discriminator check. func scanWALV3Accepted(fd *os.File, d descriptorV3, accept slotImplAcceptor) (walScanResultV3, error) { + return scanWALV3AcceptedProgress(context.Background(), fd, d, accept) +} + +func scanWALV3AcceptedProgress(ctx context.Context, fd *os.File, d descriptorV3, accept slotImplAcceptor) (walScanResultV3, error) { + progress := newRecoveryReporter(ctx, RecoveryScan) + defer progress.finish() r := walScanResultV3{Nonce: d.Nonce} if err := d.validate(accept); err != nil { return r, err @@ -322,6 +343,9 @@ func scanWALV3Accepted(fd *os.File, d descriptorV3, accept slotImplAcceptor) (wa r.Frontier = base r.HighestLSN = base for cursor := start; cursor < limit; { + if err := ctx.Err(); err != nil { + return r, err + } remaining := d.WALSize - cursor%d.WALSize if remaining < walEntryHeaderSizeV3 { if remaining > limit-cursor { @@ -379,6 +403,7 @@ func scanWALV3Accepted(fd *os.File, d descriptorV3, accept slotImplAcceptor) (wa break } cursor += size + progress.advance(1) r.End = cursor if e.Type == walEntryPadding { continue @@ -394,6 +419,8 @@ func scanWALV3Accepted(fd *os.File, d descriptorV3, accept slotImplAcceptor) (wa // 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 @@ -402,13 +429,32 @@ func scanWALV3Accepted(fd *os.File, d descriptorV3, accept slotImplAcceptor) (wa 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.go b/seaweed-block/core/storage/walstore.go index cea922be0f..9a6c2afa9f 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -91,7 +91,7 @@ type WALStore struct { testCloseSnapshot func() // nil in production; called without captureMu // chunk is the attached chunk layer's hooks; nil when none. - chunk atomic.Pointer[chunkHooks] + chunk atomic.Pointer[chunkHooks] // drainHeld (HoldExtentDrainUntilChunkLayer): the flusher drains no // dirty block to the extent until a chunk layer is attached. drainHeld atomic.Bool @@ -418,6 +418,15 @@ func (s *WALStore) HolesSuspected() uint64 { // Idempotent: calling Recover twice on the same on-disk state yields // identical results. func (s *WALStore) Recover() (frontier uint64, err error) { + return s.RecoverContext(context.Background()) +} + +// RecoverContext preserves Recover's barriers and publication order, while +// reporting completed startup work to the shared readiness observer. +func (s *WALStore) RecoverContext(ctx context.Context) (frontier uint64, err error) { + if err := ctx.Err(); err != nil { + return 0, err + } // Drain an attached COW window before taking any lower lock. The lease // blocks a replacement window and retries a racing first attachment. // Legacy fixtures retain their shared barrier ordering with full copying. @@ -465,7 +474,7 @@ func (s *WALStore) Recover() (frontier uint64, err error) { // before s.mu is released, so no read sees recovered bytes first. defer s.noteChunkRecovery() - return s.recoverV3() + return s.recoverV3(ctx) } diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index d542185f9d..d559e4c061 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -1,6 +1,7 @@ package storage import ( + "context" "crypto/rand" "encoding/binary" "errors" @@ -30,10 +31,10 @@ type walStoreV3State struct { // local root is fresh, when no guest write may be acknowledged. layoutFresh atomic.Bool pub *descriptorPublisherV3 - w *walWriterV3 - ownedMap *chunkLSNMapV3 - mapEntries []chunkLSNEntryV3 // guarded by WALStore.mu; UNKNOWN is never cleared here - mapProof *mapProofEpochV3 + w *walWriterV3 + ownedMap *chunkLSNMapV3 + mapEntries []chunkLSNEntryV3 // guarded by WALStore.mu; UNKNOWN is never cleared here + mapProof *mapProofEpochV3 appended atomic.Uint64 // highest LSN pwritten to the WAL wack atomic.Uint64 // highest acknowledged LSN (Sync completed) @@ -355,6 +356,7 @@ func openWALStoreV3WithOptions(path string, requireMap bool, opts WALStoreOption // f is already locked. Creation retains this same descriptor and metadata // binding throughout initialization, so there is no close/reopen owner gap. func openWALStoreV3File(path string, f *os.File, requireMap bool, opts WALStoreOptions, metadata BlockMetadata, creating bool) (*WALStore, error) { + progressCtx := WithRecoveryProgress(context.Background(), opts.RecoveryProgress) if err := refuseLegacyWALStore(f); err != nil { _ = f.Close() return nil, err @@ -383,10 +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{} { - ownedMap, mapCurrent, err = openDescriptorMapV3(path+".chunkmap", d, other) + ownedMap, mapCurrent, err = openDescriptorMapV3Progress(path+".chunkmap", d, other, openProgress) if err != nil { _ = f.Close() return nil, err @@ -448,11 +451,15 @@ 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 = append([]chunkLSNEntryV3(nil), mapCurrent.entries...) + v.mapEntries, err = copyRecoveryMapPhase(progressCtx, RecoveryOpenCopy, nil, mapCurrent.entries) + if err != nil { + return err + } ownedMap.latchPersistence = s.latchV3 } s.v3 = v @@ -470,7 +477,7 @@ func openWALStoreV3File(path string, f *os.File, requireMap bool, opts WALStoreO // recoverV3 is Recover for a v3 store (DESIGN 6.5, 6.6). The caller holds // captureMu, lifecycleMu and s.mu, as v2 Recover does. -func (s *WALStore) recoverV3() (uint64, error) { +func (s *WALStore) recoverV3(ctx context.Context) (uint64, error) { v := s.v3 v.recoverGen.Add(1) // under syncMu and s.mu (see recoverGen); odd now defer v.recoverGen.Add(1) // even again at the end, on every path @@ -478,8 +485,7 @@ func (s *WALStore) recoverV3() (uint64, error) { h() } d := v.pub.current() - s.dm.clear() - scan, err := scanWALV3Accepted(s.fd, d, v.pub.accept) + scan, err := scanWALV3AcceptedProgress(ctx, s.fd, d, v.pub.accept) if err != nil { if d.BaseState == BaseInstalling { // Installing keeps its typed not-ready outcome; the cause is a @@ -489,18 +495,25 @@ func (s *WALStore) recoverV3() (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 @@ -514,6 +527,7 @@ func (s *WALStore) recoverV3() (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 { @@ -522,12 +536,14 @@ func (s *WALStore) recoverV3() (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 } } @@ -543,12 +559,15 @@ func (s *WALStore) recoverV3() (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) @@ -560,11 +579,20 @@ func (s *WALStore) recoverV3() (uint64, error) { // speculative cache changes from a dropped suffix. if v.ownedMap != nil { v.pub.descMu.Lock() - v.mapEntries = append(v.mapEntries[:0], v.pub.mapCurrent.entries...) + var err error + v.mapEntries, err = copyRecoveryMap(ctx, v.mapEntries, v.pub.mapCurrent.entries) v.pub.descMu.Unlock() + if err != nil { + 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 { e := r.Entry if e.LSN > o.R { @@ -586,7 +614,9 @@ func (s *WALStore) recoverV3() (uint64, error) { s.recordMapWriteV3(e.LBA+i, e.LSN+i) } } + progress.advance(1) } + progress.finish() if h := v.testRecoverHold; h != nil { h() } @@ -615,7 +645,7 @@ func (s *WALStore) recoverV3() (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 61fb3924c6..d6470a519f 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -65,7 +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-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` | @@ -567,6 +567,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_timeout only after a window without a new fixed-order phase/count frontier; repeated preparation cannot renew it. Progress never grants readiness or ownership. | M1 Recovering | `core/host/volume/recovery_watchdog.go`; `cmd/blockvolume/durable_startup.go`; `core/storage/recovery_progress.go` | `TestDurableStartup_LocalRecoveryWorkIsOutsideFixedDeadline` (`cmd/blockvolume/durable_startup_budget_test.go`); `TestRecoveryProgress_CountingEntriesOutliveTheTotalWindow`, `TestRecoveryProgress_RepeatedAttachPreparationDoesNotRenew` (`core/host/volume/recovery_progress_test.go`); attach: `TestAttachReportsItsVolumeSizedLocalWork`, `TestAttachReportsTheCreatedThisStartScan`, `TestAttachProgressFlushesSlowWorkAboutEverySecond` (`core/storage/chunk_attach_progress_test.go`), `TestAttachProgressCountsEachAttemptFromZero`, `TestAttachRemoteCallsCarryTheirOwnBound`, `TestAttachManifestReadCarriesThePerFetchRule` (`core/frontend/durable/attach_progress_test.go`), `TestAttachManifestReadBoundsEachFetch` (`core/frontend/chunkstore/layout_attach_fetch_test.go`) | pending shared-start progress review; C.L | STUB | | `INV-WAL-OPGATE-001` | A durable backend refuses `Read`, `Write` and `Sync` until `RecoverVolume` succeeds; a failed recovery leaves it refused. | M1 Opened → Serving; Recovering → RecoveryFailed | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/durable/provider.go` `RecoverVolume` | `TestT3b_DurableProvider_Open_StartsNotOperational` (`core/frontend/durable/provider_test.go`); `TestT3b_Recovery_CleanRecover_FlipsOperational` (`core/frontend/durable/recovery_test.go`); `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | | `INV-FE-NVME-READY-001` | A read or write on a successfully recovered chunk volume awaiting attachment waits for attachment readiness, before storage admission, for at most 3 s or until an earlier caller deadline, on the local monotonic clock. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `admitAfterAttachUnqueued`, `awaitAttachAdmission`, `readyCheck` | `TestWALStoreChunk_PendingReadWaitIsBounded`; `TestWALStoreChunk_PendingReadHonoursEarlierDeadline`; `TestWALStoreChunk_TakeoverWriteWaitsForAttach`; `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`) | — | ACTIVE | | `INV-FE-NVME-READY-STATUS-001` | An NVMe read or write whose attachment-readiness wait times out or is refused completes with Namespace Not Ready (SC 0x82), DNR=0, without reading or mutating storage. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestWALStoreChunk_PendingAttachBeyondHostRetryBudget` (`core/frontend/durable/takeover_read_ready_test.go`) | — | ACTIVE | @@ -1205,8 +1206,8 @@ One row per fixed time limit on a volume's path that surrounds, or once surround | `DurableProvider.chunkCutContext` (`ChunkCutTimeout`) | 5 min per attempt | staging the changed chunks, the check, the commit | yes | uploads finished by an attempt are kept; the next attempt uploads only the rest (same process) | `TestACutAttemptThatRunsOutOfTimeLeavesUploadsTheNextAttemptKeeps` | | the cleaning pass (`boundedPass`) | the configured pass limit | listing and removing by page | yes | the pass resumes at its cursor; a session after a restart starts at the root page | the cleaning cursor's tests | | `core/host/volume/chunk_control.go` `chunkContext` (a chunk control operation: a cut, a snapshot or a detach, each of which takes a cut; the chunk status read also runs under it and reads one HEAD) | 5 min, or the request's shorter limit | the operation, including the cut it takes | yes | the cut's uploads, as the cut's row: an attempt that runs out of time keeps what it uploaded | STUB: no test at the control operation's level yet | -| `core/host/volume/recovery_watchdog.go` (`--recover-timeout`), over `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable` and the chunk layer's attach | 30 s for local recovery and the attach together | replay of the local log (bounded by the log's size, not the volume's) and a copy of the per-chunk map; then the attach | **yes** (the map copy and the attach) | nothing yet | STUB: not measured at 1 TiB; no test. A start of a 1 TiB volume is not claimed to fit this limit | -| `core/frontend/durable/provider_chunk.go` `chunkAttachTimeout` | 30 s per attempt, retried | one attach of the chunk layer | **yes** | nothing yet: a retried attempt starts again | STUB: not measured at 1 TiB; no test | +| `core/host/volume/recovery_watchdog.go` (`--recover-timeout`), over `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable` and the chunk layer's attach | 30 s without a new completed-work frontier, shared by recovery and attach | bounded local reads and final fence/publication; no total context around the per-entry recovery | the WAL scan, map copy and retained replay grow | a cumulative fixed-order phase/count high-water mark; repeated preparation cannot renew the clock; attach retries retain completed local recovery | `TestDurableStartup_LocalRecoveryWorkIsOutsideFixedDeadline`, `TestRecoveryMapCountsOneTiBEntriesWithoutATotalDeadline`, `TestRecoveryProgress_CountingEntriesOutliveTheTotalWindow`, `TestRecoveryReporterSlowReplayReportsBeforeTheEntryBatch`, `TestRecoveryProgress_RepeatedAttachPreparationDoesNotRenew`; STUB until attach-side retry integration and Linux qualification pass together; no 1 TiB time claim | +| `core/frontend/durable/provider_chunk.go` `chunkAttachTimeout` | 30 s around each remote call of an attach (the attach check, the layout Start, the root fetch and each segment fetch of the manifest read), never around the attempt | each object fetch bounded; the fetch count grows (27 segments at 1 TiB); judged by the window | **yes** (the fetch count) | each completed segment and the attach's local entries report RecoveryAttach, per attempt from zero, under the shared window above | `TestAttachReportsItsVolumeSizedLocalWork` (the counting test, 262144 entries), `TestAttachManifestReadBoundsEachFetch`, `TestAttachGetHeadBoundsTheHeadRead`, `TestAttachRemoteCallsCarryTheirOwnBound`, `TestAttachManifestReadCarriesThePerFetchRule`, `TestAttachProgressCountsEachAttemptFromZero`; STUB until the joint recovery+attach Linux qualification passes | Known limits of this table: what an attempt keeps is kept in the memory of one process. After a restart the cut uploads again what it cannot prove was uploaded; names are by content, so this costs time and no correctness. @@ -1279,3 +1280,22 @@ Notes: - `TERM-SERVING-001` and `TERM-STOP-*`: in this release a workspace primary that can no longer serve should stop, not linger. Today `TERM-STOP-HEAD-FENCED-001` and `TERM-STOP-STALE-ROOT-001` leave the process up and its lease renewing. A forced move then waits for that lease. The open entries in those rows track this. - `TERM-HOLDER-001`: supporting replicas (RF greater than 1) are not holders, and their replica-keyed checks (`AdapterProjectionView.supportingReplicaReady`) are outside this row. + +### Recovery progress observer lock order + +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, 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 (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 +rows remain STUB until recovery and attach controls are qualified together. \ No newline at end of file diff --git a/seaweed-block/docs/releases/recovery-progress.md b/seaweed-block/docs/releases/recovery-progress.md new file mode 100644 index 0000000000..5e065f5ea4 --- /dev/null +++ b/seaweed-block/docs/releases/recovery-progress.md @@ -0,0 +1,6 @@ +# Recovery inactivity window + +`--recover-timeout` now measures inactivity during recovery and attachment, +instead of their total duration. Only newly completed work advances the clock; +a retry repeating earlier preparation cannot postpone a stalled-start report. +This changes readiness diagnostics, not ownership, lease or HEAD authority. diff --git a/seaweed-block/docs/volume-lifecycle.md b/seaweed-block/docs/volume-lifecycle.md index b3aff2a6b4..826a190b95 100644 --- a/seaweed-block/docs/volume-lifecycle.md +++ b/seaweed-block/docs/volume-lifecycle.md @@ -338,6 +338,15 @@ without the move does not serve: a sealed HEAD stays sealed for its own epoch. ## After a crash +At startup, `--recover-timeout` (default `30s`) is an inactivity window shared +by local recovery and attachment, not a total startup deadline. Newly completed +WAL records and chunk-map entries advance its progress frontier. Repeating the +same preparation during a retry does not renew it. A full window without new +work reports `recovery_timeout` in status and heartbeats and keeps I/O refused; +it never grants a lease or moves a single-copy volume. Recovery corruption and +I/O failures still report their typed errors immediately. After a physical +restart, recovery reads authoritative local disk again. + **The holder comes back within the lease.** A restarted process (the example unit restarts a crashed one after `RestartSec=5s`) renews at once and serves from its local WAL.