From 53211a2d9dc477af40f3774efe71eee7bf17d034 Mon Sep 17 00:00:00 2001 From: pingqiu-cpu Date: Wed, 2 Dec 2026 16:34:31 -0800 Subject: [PATCH] ops chunk verify: --timeout is a no-progress window; add --deadline (#966) Interim merge note (spec trace workflow startup_failure on all branches since 22:45Z): go test (linux) and process-level tests (real binaries) passed on cc3a8a6c (run 46997615891); spec-trace-check.sh and public-text-check.sh run locally with the base branch's scripts against this head and body: both pass. Code review ACCEPT 6161155789; model review ACCEPT 6161515202 (per-call read/trace follow-up recorded there). --- seaweed-block/cmd/sw-block/chunk.go | 14 +- seaweed-block/cmd/sw-block/chunk_verify.go | 132 +++++- .../cmd/sw-block/chunk_verify_window_test.go | 395 ++++++++++++++++++ .../core/frontend/chunkstore/layout/verify.go | 32 ++ .../core/frontend/chunkstore/layout_verify.go | 15 +- .../frontend/chunkstore/layout_verify_test.go | 24 ++ seaweed-block/docs/releases/v1.1.md | 4 + seaweed-block/docs/standalone-deployment.md | 4 + 8 files changed, 606 insertions(+), 14 deletions(-) create mode 100644 seaweed-block/cmd/sw-block/chunk_verify_window_test.go diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go index 29a800f0f9..34a29a6d89 100644 --- a/seaweed-block/cmd/sw-block/chunk.go +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -58,9 +58,21 @@ var checkSingleFiler = func(ctx context.Context, f chunkstore.Filer) error { // timeout (a stalled filer or master cannot hold the command longer); exit // >= 0 means refused. func refuseUnlessSingleFiler(name string, f chunkstore.Filer, timeout time.Duration, stdout, stderr io.Writer) int { - ctx, cancel := context.WithTimeout(context.Background(), timeout) + return refuseUnlessSingleFilerWithin(context.Background(), name, f, timeout, stdout, stderr) +} + +// refuseUnlessSingleFilerWithin is refuseUnlessSingleFiler bounded by parent +// too (a caller's whole-pass deadline or cancellation); a refusal names the +// parent's cancellation cause. +func refuseUnlessSingleFilerWithin(parent context.Context, name string, f chunkstore.Filer, timeout time.Duration, stdout, stderr io.Writer) int { + ctx, cancel := context.WithTimeout(parent, timeout) defer cancel() err := checkSingleFiler(ctx, f) + if err != nil && parent.Err() != nil { + if c := context.Cause(parent); c != nil && !errors.Is(err, c) { + err = fmt.Errorf("%w (%v)", err, c) + } + } switch { case err == nil: return -1 diff --git a/seaweed-block/cmd/sw-block/chunk_verify.go b/seaweed-block/cmd/sw-block/chunk_verify.go index 71cf5b19e9..279daae6c1 100644 --- a/seaweed-block/cmd/sw-block/chunk_verify.go +++ b/seaweed-block/cmd/sw-block/chunk_verify.go @@ -8,6 +8,7 @@ import ( "flag" "fmt" "io" + "sync" "time" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" @@ -29,7 +30,7 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int { allSnapshots, orphans bool concurrency int bytesPerSec int64 - timeout time.Duration + timeout, deadline time.Duration ) fs.StringVar(&volumeID, "volume", "", "volume name with --master, or an explicit - store directory") fs.StringVar(&master, "master", "", "blockmaster gRPC address (resolves --volume name to its full layout identity)") @@ -41,7 +42,8 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int { fs.BoolVar(&orphans, "orphans", false, "also report the volume's own names no reachable root names (report only)") fs.IntVar(&concurrency, "concurrency", 1, "unsupported: chunks are read one at a time") fs.Int64Var(&bytesPerSec, "bytes-per-sec", 0, "unsupported: chunk reads are not paced") - fs.DurationVar(&timeout, "timeout", 10*time.Minute, "bound for the whole pass; required with --depth data") + fs.DurationVar(&timeout, "timeout", 10*time.Minute, "no-progress window: the pass fails only after this long without completing an object read; required with --depth data") + fs.DurationVar(&deadline, "deadline", 0, "optional bound for the whole pass (0: none)") if err := fs.Parse(args); err != nil { return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) } @@ -77,18 +79,36 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int { return usage("--depth data reads every chunk: give an explicit --timeout for the pass") case timeout <= 0: return usage("--timeout must be positive") + case deadline < 0: + return usage("--deadline must not be negative") } - // One bound for the whole pass, the single-filer start check included. - // Verify writes nothing, but against a split filer view it would report - // false findings, so it runs the check. - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() + // The pass is bounded by progress, not by its length: it ends only when + // no object read has completed for --timeout (each one renews the + // window), or at the optional --deadline. Verify writes nothing, but + // against a split filer view it would report false findings, so it runs + // the single-filer start check, bounded by --timeout. + ctx, cancel := context.WithCancelCause(context.Background()) + defer cancel(nil) + if deadline > 0 { + var stopDeadline context.CancelFunc + ctx, stopDeadline = context.WithTimeoutCause(ctx, deadline, fmt.Errorf("verify: --deadline %s reached: %w", deadline, context.DeadlineExceeded)) + defer stopDeadline() + } + progress := watchVerifyProgress(ctx, timeout, cancel) dir := volumeID - opts := layout.VerifyOptions{Depth: d, Orphans: orphans} + opts := layout.VerifyOptions{Depth: d, Orphans: orphans, Progress: progress} + withCause := func(err error) error { + if ctx.Err() != nil { + if c := context.Cause(ctx); c != nil && !errors.Is(err, c) { + return fmt.Errorf("%w (%w)", err, c) + } + } + return err + } if master != "" { id, err := resolveVolumeID(ctx, master, volumeID) if err != nil { - return verifyIncomplete(layout.VerifyResult{}, err, stdout, stderr) + return verifyIncomplete(layout.VerifyResult{}, withCause(err), stdout, stderr) } dir, opts.ExpectedID = layout.VolumeDir(volumeID, id), id } @@ -97,12 +117,19 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int { return usage(err.Error()) } defer closeFn() - if exit := refuseUnlessSingleFiler("verify", f, timeout, stdout, stderr); exit >= 0 { + if exit := refuseUnlessSingleFilerWithin(ctx, "verify", f, timeout, stdout, stderr); exit >= 0 { return exit } res, err := chunkstore.VerifyLayout(ctx, f, base, dir, opts) if err != nil { - return verifyIncomplete(res, err, stdout, stderr) + return verifyIncomplete(res, withCause(err), stdout, stderr) + } + if !res.Complete && ctx.Err() != nil { + // A pass ended inside a step that reports incomplete rather than an + // error (the final HEAD confirmations): keep why it was ended. + if c := context.Cause(ctx); c != nil { + res.Incomplete += " (" + c.Error() + ")" + } } if master == "" && res.Incomplete == "no VOLUME" { return usage("no VOLUME in the supplied directory: give --master to resolve a name, or the - store directory") @@ -127,6 +154,87 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int { return ops.VolumeStatusExitOK } +// errVerifyStalled is the cause of a verify pass ended by its no-progress +// window: a transient failure, answered like a deadline. +var errVerifyStalled = errors.New("verify: no object read completed within the --timeout no-progress window") + +// verifyWatch is a pass's no-progress window. Renewal and expiry are decided +// under one lock on the clock's (monotonic) time: whichever of a read's +// renewal or the ticker's check comes first after the window elapsed expires +// it, so an elapsed window is never renewed. +type verifyWatch struct { + mu sync.Mutex + window time.Duration + now func() time.Time + last time.Time + expired bool + cancel context.CancelCauseFunc +} + +func newVerifyWatch(window time.Duration, now func() time.Time, cancel context.CancelCauseFunc) *verifyWatch { + return &verifyWatch{window: window, now: now, last: now(), cancel: cancel} +} + +// expireLocked expires the window once it has elapsed; it reports whether +// the window is expired. +func (w *verifyWatch) expireLocked() bool { + if !w.expired && w.now().Sub(w.last) >= w.window { + w.expired = true + } + return w.expired +} + +// renew records a completed read, unless the window has already elapsed. +func (w *verifyWatch) renew() { + w.mu.Lock() + expired := w.expireLocked() + if !expired { + w.last = w.now() + } + w.mu.Unlock() + if expired { + w.fire() + } +} + +// check expires an elapsed window; it reports whether the window expired. +func (w *verifyWatch) check() bool { + w.mu.Lock() + expired := w.expireLocked() + w.mu.Unlock() + if expired { + w.fire() + } + return expired +} + +func (w *verifyWatch) fire() { + w.cancel(fmt.Errorf("%w (%s)", errVerifyStalled, w.window)) +} + +// watchVerifyProgress returns the progress callback of a verify pass and +// cancels ctx (cause errVerifyStalled) once its window elapses without a +// call; the pass start counts as progress. It stops when ctx ends. +func watchVerifyProgress(ctx context.Context, window time.Duration, cancel context.CancelCauseFunc) func() { + w := newVerifyWatch(window, time.Now, cancel) + every := min(max(window/4, time.Millisecond), time.Second) + go func() { + tick := time.NewTicker(every) + defer tick.Stop() + for { + select { + case <-ctx.Done(): + return + case <-tick.C: + } + if w.check() { + return + } + } + }() + return w.renew +} + // verifyJSON is the result as one JSON object whose findings array holds // one finding per line. func verifyJSON(res layout.VerifyResult) ([]byte, error) { @@ -169,7 +277,7 @@ func verifyIncomplete(res layout.VerifyResult, err error, stdout, stderr io.Writ Verify layout.VerifyResult `json:"verify"` }{Verify: res} body.Code, body.Message = codeInternalCLI, err.Error() - if errors.Is(err, context.DeadlineExceeded) { + if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, errVerifyStalled) { body.Code, body.Retryable = chunkstore.CodeDeadlineExceeded, true } fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %s (incomplete)\n", body.Code, body.Message) diff --git a/seaweed-block/cmd/sw-block/chunk_verify_window_test.go b/seaweed-block/cmd/sw-block/chunk_verify_window_test.go new file mode 100644 index 0000000000..3dff5378c0 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_verify_window_test.go @@ -0,0 +1,395 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "path" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// runVerifyBounded runs verify and fails the test if it has not returned +// within bound: a held path is ended by the test itself, not only measured +// after it returned. +func runVerifyBounded(t *testing.T, bound time.Duration, args ...string) (int, string, string) { + t.Helper() + type result struct { + code int + out, errs string + } + done := make(chan result, 1) + joined := make(chan struct{}) + release := make(chan struct{}) + heldRelease = release // read by the held store calls of this run + go func() { + defer close(joined) + code, out, errs := runChunk(append([]string{"verify"}, args...)...) + done <- result{code, out, errs} + }() + // Registered after the fixture's cleanups, so it runs before them: every + // held store call is released, then the command is joined before the + // globals it reads are restored. A worker that survives its release stops + // the test binary, so no later test runs beside it. + t.Cleanup(func() { + close(release) + select { + case <-joined: + heldRelease = make(chan struct{}) // the next run starts unreleased + case <-time.After(10 * time.Second): + panic("a verify command survived the release of its held calls; stopping so no later test runs under restored globals") + } + }) + select { + case r := <-done: + return r.code, r.out, r.errs + case <-time.After(bound): + t.Fatalf("verify %v did not return within %s", args, bound) + return 0, "", "" + } +} + +// heldRelease is closed by runVerifyBounded's cleanup: every held store call +// (and a stubbed start check) also returns on it, so the command can always +// be joined. It is never closed outside a bounded run. +var heldRelease = make(chan struct{}) + +// errHeldReleased is what a held call returns when the test releases it. +var errHeldReleased = errors.New("held call released by the test") + +// verifyAnswer is verify's incomplete answer: the error body and the partial +// result. +type verifyAnswer struct { + Code string `json:"code"` + Message string `json:"message"` + Retryable bool `json:"retryable"` + Verify struct { + Complete bool + Incomplete string + } `json:"verify"` +} + +func decodeVerifyAnswer(t *testing.T, out string) verifyAnswer { + t.Helper() + var a verifyAnswer + if err := json.Unmarshal([]byte(out), &a); err != nil { + t.Fatalf("stdout is not a verify answer: %q (%v)", out, err) + } + return a +} + +// slowStore answers every lookup after delay (a filer slower than the pass +// is long, never silent), and holds a lookup of stall until its context +// ends (a silent filer). +type slowStore struct { + *manifestFixtureFiler + delay time.Duration + stall string +} + +func (s slowStore) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if s.stall != "" && path.Join(dir, name) == s.stall { + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-heldRelease: + return nil, errHeldReleased + } + } + select { + case <-time.After(s.delay): + case <-ctx.Done(): + return nil, ctx.Err() + case <-heldRelease: + return nil, errHeldReleased + } + return s.manifestFixtureFiler.LookupEntry(ctx, dir, name) +} + +// --timeout is a no-progress window, not a bound on the pass: on a filer +// that answers each read within the window, a pass several windows long +// completes clean, at the names depth and at the data depth. (At the 1 TiB +// cap with 10 snapshots a default pass outlasts a fixed 600 s bound.) +func TestOpsChunk_VerifyTimeoutIsANoProgressWindow(t *testing.T) { + for _, depth := range []string{"bindings", "data"} { + t.Run(depth, func(t *testing.T) { + mem, _ := verifyCLIFixture(t) + store := slowStore{manifestFixtureFiler: mem, delay: 60 * time.Millisecond} + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + return store, func() error { return nil }, nil + } + const window = 150 * time.Millisecond + start := time.Now() + code, out, errs := runChunk("verify", "--volume", "v1", "--master", "m:1", "--chunk-filer", "filer:18888", "--depth", depth, "--timeout", window.String()) + took := time.Since(start) + if code != 0 || !decodeVerify(t, out).Complete { + t.Fatalf("a %s pass of %s with each read inside the %s window: exit %d, out %q, err %q; want clean", depth, took, window, code, out, errs) + } + if took < 2*window { + t.Fatalf("fixture: the pass took %s, not several windows of %s; the test proves nothing", took, window) + } + }) + } +} + +// The window still ends a silent pass: a read that never answers fails the +// pass within about one window, as incomplete, naming the no-progress cause. +func TestOpsChunk_VerifyStopsAfterAWindowWithoutProgress(t *testing.T) { + mem, chunk1 := verifyCLIFixture(t) + store := slowStore{manifestFixtureFiler: mem, stall: chunk1} + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + return store, func() error { return nil }, nil + } + code, out, errs := runVerifyBounded(t, 5*time.Second, "--volume", "v1", "--master", "m:1", "--chunk-filer", "filer:18888", "--depth", "data", "--timeout", "200ms") + a := decodeVerifyAnswer(t, out) + if code != chunkExitFailed || a.Verify.Complete || a.Code != chunkstore.CodeDeadlineExceeded || !a.Retryable || !strings.Contains(a.Message, "no object read completed") { + t.Fatalf("a silent pass: exit %d, answer %+v, err %q; want incomplete, retryable deadline_exceeded naming the no-progress cause", code, a, errs) + } +} + +// --deadline bounds the whole pass even while it progresses. +func TestOpsChunk_VerifyDeadlineBoundsAProgressingPass(t *testing.T) { + mem, _ := verifyCLIFixture(t) + store := slowStore{manifestFixtureFiler: mem, delay: 60 * time.Millisecond} + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + return store, func() error { return nil }, nil + } + code, out, errs := runVerifyBounded(t, 5*time.Second, "--volume", "v1", "--master", "m:1", "--chunk-filer", "filer:18888", "--timeout", "10s", "--deadline", "100ms") + a := decodeVerifyAnswer(t, out) + if code != chunkExitFailed || a.Verify.Complete || a.Code != chunkstore.CodeDeadlineExceeded || !a.Retryable || !strings.Contains(a.Message, "--deadline 100ms reached") { + t.Fatalf("a progressing pass past its --deadline: exit %d, answer %+v, err %q; want incomplete, retryable deadline_exceeded naming the deadline", code, a, errs) + } + if code, _, _ := runChunk("verify", "--volume", "v1", "--chunk-filer", "filer:18888", "--deadline", "-1s"); code != 2 { + t.Fatalf("a negative --deadline: exit %d, want usage (2)", code) + } +} + +// listStore delays (or, past stallAfter calls, holds until its context +// ends) every directory page the orphan scan reads, and holds the HEAD +// lookup numbered stallHead (the final confirmation is the last one). +type listStore struct { + *manifestFixtureFiler + pageDelay time.Duration + stallList bool + stallHead int + headLookup *int + mu *sync.Mutex +} + +func (s listStore) ListEntries(ctx context.Context, dir, prefix, startAfter string, limit uint32) ([]*filerpb.Entry, error) { + if s.stallList { + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-heldRelease: + return nil, errHeldReleased + } + } + select { + case <-time.After(s.pageDelay): + case <-ctx.Done(): + return nil, ctx.Err() + case <-heldRelease: + return nil, errHeldReleased + } + return s.manifestFixtureFiler.ListEntries(ctx, dir, prefix, startAfter, limit) +} + +func (s listStore) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if name == "HEAD" && s.stallHead > 0 { + s.mu.Lock() + *s.headLookup++ + n := *s.headLookup + s.mu.Unlock() + if n == s.stallHead { + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-heldRelease: + return nil, errHeldReleased + } + } + } + return s.manifestFixtureFiler.LookupEntry(ctx, dir, name) +} + +func withListStore(t *testing.T, s listStore) { + t.Helper() + if s.mu == nil { + s.mu, s.headLookup = &sync.Mutex{}, new(int) + } + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return s, func() error { return nil }, nil } +} + +// Each orphan-scan page renews the window: a scan whose pages each answer +// inside it completes, though the scan is longer than the window. +func TestOpsChunk_VerifyOrphanPagesRenewTheWindow(t *testing.T) { + mem, _ := verifyCLIFixture(t) + withListStore(t, listStore{manifestFixtureFiler: mem, pageDelay: 80 * time.Millisecond}) + const window = 150 * time.Millisecond + start := time.Now() + code, out, errs := runChunk("verify", "--volume", "v1", "--master", "m:1", "--chunk-filer", "filer:18888", "--orphans", "--timeout", window.String()) + took := time.Since(start) + if code != 0 || !decodeVerify(t, out).Complete { + t.Fatalf("an orphan scan of %s with each page inside the %s window: exit %d, out %q, err %q; want clean", took, window, code, out, errs) + } + // Longer than one window: without a renewal per page the window would + // expire inside the scan. + if took <= window+50*time.Millisecond { + t.Fatalf("fixture: the scan took %s, not longer than the %s window; the test proves nothing", took, window) + } +} + +// A silent orphan scan, and a silent final HEAD confirmation, each end the +// pass within about one window, incomplete, naming the no-progress cause. +func TestOpsChunk_VerifySilentScanOrConfirmationNamesTheCause(t *testing.T) { + for name, s := range map[string]listStore{ + "orphan scan": {stallList: true}, + "final confirmation": {stallHead: 2}, + } { + t.Run(name, func(t *testing.T) { + mem, _ := verifyCLIFixture(t) + s.manifestFixtureFiler = mem + withListStore(t, s) + code, out, errs := runVerifyBounded(t, 5*time.Second, "--volume", "v1", "--master", "m:1", "--chunk-filer", "filer:18888", "--orphans", "--timeout", "200ms") + if code != chunkExitFailed { + t.Fatalf("a silent %s: exit %d, out %q, err %q; want incomplete (1)", name, code, out, errs) + } + a := decodeVerifyAnswer(t, out) + why := a.Message + if a.Code == "" { // the final confirmation answers its partial result + res := decodeVerify(t, out) + if res.Complete { + t.Fatalf("a silent %s: a complete result %+v", name, res) + } + why = res.Incomplete + } else if a.Verify.Complete || a.Code != chunkstore.CodeDeadlineExceeded || !a.Retryable { + t.Fatalf("a silent %s: answer %+v; want incomplete, retryable deadline_exceeded", name, a) + } + if !strings.Contains(why, "no object read completed") { + t.Fatalf("a silent %s: incomplete reason %q does not name the no-progress cause", name, why) + } + }) + } +} + +// --deadline bounds the single-filer start check too: a stalled check ends +// verify at the deadline, though --timeout is far longer, and names it. +func TestOpsChunk_VerifyDeadlineBoundsTheStartCheck(t *testing.T) { + mem := chunkstore.NewMemFiler() + prevDial, prevCheck := dialChunkFiler, checkSingleFiler + t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck }) + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + checkSingleFiler = func(ctx context.Context, _ chunkstore.Filer) error { + select { + case <-ctx.Done(): + return ctx.Err() + case <-heldRelease: + return errHeldReleased + } + } + code, out, errs := runVerifyBounded(t, 5*time.Second, "--volume", "v1", "--chunk-filer", "filer:18888", "--timeout", "1m", "--deadline", "200ms") + a := decodeVerifyAnswer(t, out) + if code == 0 || !a.Retryable || !strings.Contains(a.Message, "--deadline 200ms reached") { + t.Fatalf("a stalled start check past --deadline: exit %d, answer %+v, err %q; want a retryable refusal naming the deadline", code, a, errs) + } +} + +// The window's boundary, on a fake clock: a read just inside the window +// renews it; a read just past it, before any ticker check, expires it +// instead (it is never renewed) and the pass is cancelled with the +// no-progress cause. +func TestVerifyWatchRenewsOnlyInsideTheWindow(t *testing.T) { + base := time.Now() + for _, tc := range []struct { + name string + at time.Duration + expired bool + }{{"inside", 99 * time.Millisecond, false}, {"past", 101 * time.Millisecond, true}} { + t.Run(tc.name, func(t *testing.T) { + now := base + var cause error + w := newVerifyWatch(100*time.Millisecond, func() time.Time { return now }, func(c error) { cause = c }) + now = base.Add(tc.at) + w.renew() + if got := cause != nil; got != tc.expired || w.expired != tc.expired { + t.Fatalf("a read at %s: expired %v, cancelled %v (%v); want %v", tc.at, w.expired, got, cause, tc.expired) + } + if tc.expired { + if !errors.Is(cause, errVerifyStalled) { + t.Fatalf("cancel cause %v, want errVerifyStalled", cause) + } + now = base.Add(tc.at + 10*time.Millisecond) + w.renew() + if !w.check() { + t.Fatal("an expired window was renewed by a later read") + } + return + } + now = base.Add(tc.at + 99*time.Millisecond) // within the renewed window + if w.check() { + t.Fatal("a window renewed inside it expired before its new end") + } + }) + } +} + +// A pass ended inside its final HEAD confirmations publishes no absence or +// reachability conclusion: with a real orphan planted, the control (no +// stall) reports it, and a stalled confirmation ends incomplete with +// OrphansChecked false and no ORPHAN or MISSING finding, naming the +// no-progress cause. +func TestOpsChunk_VerifyStalledConfirmationSuppressesOrphanConclusions(t *testing.T) { + for _, stalled := range []bool{false, true} { + t.Run(map[bool]string{false: "control", true: "stalled confirmation"}[stalled], func(t *testing.T) { + mem, chunk1 := verifyCLIFixture(t) + // A segment no reachable root names (the orphan scan covers roots + // and segments). + root := strings.TrimSuffix(chunk1, "/"+layout.NameChunk(1, bytes.Repeat([]byte{0x31}, 4096)).Path()) + c := layout.NameChunk(7, bytes.Repeat([]byte{0x77}, 4096)) + ownerID, err := layout.NewVolumeID() // the segment is never followed: any owner id + if err != nil { + t.Fatal(err) + } + _, segs, err := layout.Build(map[uint64]layout.Ref{7: {Owner: "v1", OwnerID: ownerID, Chunk: c}}) + if err != nil { + t.Fatal(err) + } + for n, b := range segs { + orphan := path.Join(root, n.Path()) + if err := mem.CreateEntry(context.Background(), path.Dir(orphan), &filerpb.Entry{Name: path.Base(orphan), Content: b}, true); err != nil { + t.Fatal(err) + } + } + s := listStore{manifestFixtureFiler: mem} + if stalled { + s.stallHead = 2 + } + withListStore(t, s) + code, out, errs := runVerifyBounded(t, 5*time.Second, "--volume", "v1", "--master", "m:1", "--chunk-filer", "filer:18888", "--orphans", "--timeout", "200ms") + res := decodeVerify(t, out) + orphans := 0 + for _, f := range res.Findings { + if f.Class == layout.FindOrphan || f.Class == layout.FindMissing { + orphans++ + } + } + if !stalled { + if code != chunkExitFindings || !res.Complete || !res.OrphansChecked || orphans == 0 { + t.Fatalf("control: exit %d, result %+v, err %q; want the planted orphan reported (exit 3)", code, res, errs) + } + return + } + if code != chunkExitFailed || res.Complete || res.OrphansChecked || orphans != 0 || !strings.Contains(res.Incomplete, "no object read completed") { + t.Fatalf("stalled confirmation: exit %d, result %+v, err %q; want incomplete, OrphansChecked false, no ORPHAN/MISSING, the no-progress cause", code, res, errs) + } + }) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/verify.go b/seaweed-block/core/frontend/chunkstore/layout/verify.go index 85ee3422e9..c80eb9dbc4 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/verify.go +++ b/seaweed-block/core/frontend/chunkstore/layout/verify.go @@ -43,6 +43,10 @@ type VerifyOptions struct { // Stat checks a chunk's presence and size without reading its body. // In-memory callers may omit it and supply those bytes through Fetch. Stat func(ctx context.Context, p string, expectedSize uint64) (found bool, err error) + // Progress, when set, is called after every object read (fetch, stat or + // list) that completed without error: a caller bounds the pass by the + // time since the last one, not by its total length. + Progress func() } // Finding is one problem found at Path (relative to ). @@ -104,6 +108,34 @@ func Verify(ctx context.Context, base, vol string, fetch Fetch, opts VerifyOptio if opts.Orphans && opts.List == nil { return VerifyResult{}, errors.New("layout: verify orphans needs a list") } + if progress := opts.Progress; progress != nil { + inner := fetch + fetch = func(ctx context.Context, p string) ([]byte, bool, error) { + b, ok, err := inner(ctx, p) + if err == nil { + progress() + } + return b, ok, err + } + if stat := opts.Stat; stat != nil { + opts.Stat = func(ctx context.Context, p string, expectedSize uint64) (bool, error) { + ok, err := stat(ctx, p, expectedSize) + if err == nil { + progress() + } + return ok, err + } + } + if list := opts.List; list != nil { + opts.List = func(ctx context.Context, p string) ([]string, error) { + names, err := list(ctx, p) + if err == nil { + progress() + } + return names, err + } + } + } v := &verifier{base: base, vol: vol, fetch: fetch, opts: opts, ownPool: map[string]bool{}, ownMeta: map[string]bool{}, owners: map[string]ownerID{}, checked: map[verifyChunkKey]bool{}, geometry: map[string]Geometry{}} v.res.Complete = true head, ok, err := v.head(ctx, vol) diff --git a/seaweed-block/core/frontend/chunkstore/layout_verify.go b/seaweed-block/core/frontend/chunkstore/layout_verify.go index 813d8ca138..e405cc7c51 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_verify.go +++ b/seaweed-block/core/frontend/chunkstore/layout_verify.go @@ -17,6 +17,12 @@ const verifyListPage = 1000 // List returns the entry names of directory p under the store base, all // pages, in name order. A missing directory lists as empty. func (s *LayoutStore) List(ctx context.Context, p string) ([]string, error) { + return s.listPages(ctx, p, nil) +} + +// listPages is List, calling onPage (when set) after each page read: a long +// directory renews a verify pass's no-progress window page by page. +func (s *LayoutStore) listPages(ctx context.Context, p string, onPage func()) ([]string, error) { if !path.IsAbs(p) || path.Clean(p) != p || !strings.HasPrefix(p, path.Dir(s.root)+"/") { return nil, errors.New("chunkstore: list path outside the store base") } @@ -27,6 +33,9 @@ func (s *LayoutStore) List(ctx context.Context, p string) ([]string, error) { if err != nil { return nil, err } + if onPage != nil { + onPage() + } for _, e := range page { out = append(out, e.Name) } @@ -50,7 +59,8 @@ func VerifyLayout(ctx context.Context, f Filer, base, vol string, opts layout.Ve return layout.VerifyResult{}, errors.New("chunkstore: verify needs a clean absolute chunk base") } s := &LayoutStore{f: f, b: b, root: path.Join(base, vol)} - opts.List = s.List + progress := opts.Progress + opts.List = func(ctx context.Context, p string) ([]string, error) { return s.listPages(ctx, p, progress) } opts.Stat = s.verifyStat // Keep the generation from the same lookup as the HEAD bytes walked by // Verify. A later lookup must confirm every observed HEAD, including live @@ -95,6 +105,9 @@ func VerifyLayout(ctx context.Context, f Filer, base, vol string, opts layout.Ve sort.Strings(paths) for _, p := range paths { _, head, found, readErr := s.verifyHead(ctx, p) + if readErr == nil && progress != nil { + progress() // each final confirmation renews the pass's window + } if heads[p].Gen == 0 || !found || readErr != nil || head.Gen == 0 || head.Gen != heads[p].Gen || head.VolumeID != heads[p].VolumeID { why = fmt.Sprintf("HEAD changed or generation unavailable: %s", p) if readErr != nil { diff --git a/seaweed-block/core/frontend/chunkstore/layout_verify_test.go b/seaweed-block/core/frontend/chunkstore/layout_verify_test.go index 4fd80da01c..d00ae95716 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_verify_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_verify_test.go @@ -216,3 +216,27 @@ func TestVerifyLayoutRequiresStableHeadForMissingAndOrphans(t *testing.T) { }) } } + +// One directory listed in several pages renews a verify pass's window on +// every page, not only once the whole directory is listed: listPages calls +// onPage after each page. +func TestLayoutStoreListRenewsOnEveryPage(t *testing.T) { + fb, id := verifyFixtureVolume(t) + dir := path.Join("/blocks", layout.VolumeDir("v", id), "seg") + s, err := NewLayoutStore(fb.fakeFiler, fb.fakeBlobs, path.Join("/blocks", layout.VolumeDir("v", id)), id) + if err != nil { + t.Fatal(err) + } + for i := 0; i < verifyListPage+3; i++ { + putFile(t, fb.fakeFiler, path.Join(dir, strings.Repeat("x", 4)+string(rune('A'+i%26))+string(rune('a'+i/26%26))+string(rune('a'+i/676))), []byte("s")) + } + pages := 0 + names, err := s.listPages(context.Background(), dir, func() { pages++ }) + if err != nil { + t.Fatal(err) + } + want := len(names)/verifyListPage + 1 + if len(names) <= verifyListPage || pages != want { + t.Fatalf("listed %d names in %d renewals, want one renewal per page (%d pages of %d)", len(names), pages, want, verifyListPage) + } +} diff --git a/seaweed-block/docs/releases/v1.1.md b/seaweed-block/docs/releases/v1.1.md index ebc27d3d5b..90a499dc3f 100644 --- a/seaweed-block/docs/releases/v1.1.md +++ b/seaweed-block/docs/releases/v1.1.md @@ -37,6 +37,10 @@ These notes collect v1.1's changes as they land; v1.1 is not released. instead of the whole WAL as one burst; on Linux each slice bypasses the page cache (O_DIRECT, where the filesystem allows it), so a slice does not wait behind other writers' writeback on a shared disk; a new volume's second recovery skips the fence its first one just made (64 MiB at creation instead of 128). Status counts the bytes in `CheckpointPersistence.FenceZeroed` and `FenceSkips`. +- `sw-block ops chunk verify --timeout` is now a no-progress window: the pass fails only after that long without + completing an object read (each read renews it), instead of bounding the whole pass. At the 1 TiB cap with ten + snapshots of distinct data, a default pass takes longer than the old fixed 10 minutes; it now completes while it + progresses. `--deadline` optionally bounds the whole pass. ## Upgrade - With `--host-limit-dir` set, the limiter's `configuration.json` in that directory records the flags it was diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 6d71b8fd37..a287e4ff89 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -859,6 +859,10 @@ sw-block ops chunk verify --master MASTER --volume v1 --chunk-filer FILER --orph sw-block ops chunk verify --master MASTER --volume v1 --chunk-filer FILER --depth data --timeout 10m --orphans ``` +`--timeout` is a no-progress window, not a bound on the pass: the pass fails only after that long without completing +an object read, so a large volume with many snapshots is not cut off while it is still progressing. `--deadline` +optionally bounds the whole pass. + The JSON field `MasterIdentityChecked` states whether the full VOLUME id was checked against the master. Offline directory inspection reports `false`. A name without `--master` that has no VOLUME in the supplied directory is an argument error, with no store finding.