From 950d636e932ee25c8d7599fca656ce1a3bc9f9f8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 00:03:07 -0800 Subject: [PATCH 1/4] fix: verify chunk bindings without reading their bodies --- seaweed-block/cmd/sw-block/chunk_verify.go | 2 +- .../core/frontend/chunkstore/layout/verify.go | 22 +- .../core/frontend/chunkstore/layout_verify.go | 47 +++- .../chunkstore/verify_bindings_stat_test.go | 238 ++++++++++++++++++ seaweed-block/docs/design/invariants.md | 4 +- seaweed-block/docs/standalone-deployment.md | 6 + 6 files changed, 314 insertions(+), 5 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/verify_bindings_stat_test.go diff --git a/seaweed-block/cmd/sw-block/chunk_verify.go b/seaweed-block/cmd/sw-block/chunk_verify.go index 1d85cc1162..f8dbbac4e2 100644 --- a/seaweed-block/cmd/sw-block/chunk_verify.go +++ b/seaweed-block/cmd/sw-block/chunk_verify.go @@ -37,7 +37,7 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int { fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") fs.StringVar(&snapshot, "snapshot", "", "unsupported: every snapshot HEAD names is always checked") fs.BoolVar(&allSnapshots, "all-snapshots", false, "unsupported: every snapshot HEAD names is always checked") - fs.StringVar(&depth, "depth", "bindings", "meta or bindings: every named object exists; data: and every chunk's bytes hash to its name") + fs.StringVar(&depth, "depth", "bindings", "meta or bindings: named filer entries and declared sizes; data: and every chunk's bytes hash to its name") 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") diff --git a/seaweed-block/core/frontend/chunkstore/layout/verify.go b/seaweed-block/core/frontend/chunkstore/layout/verify.go index cf49814bb4..cbec6337c7 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/verify.go +++ b/seaweed-block/core/frontend/chunkstore/layout/verify.go @@ -40,6 +40,9 @@ type VerifyOptions struct { Depth string // DepthNames (default) or DepthFull Orphans bool // also report unreachable own names (needs List) List List + // 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) (found bool, err error) } // Finding is one problem found at Path (relative to ). @@ -67,6 +70,7 @@ type verifier struct { ownPool map[string]bool // reachable own names, by path relative to the volume ownMeta map[string]bool owners map[string]ownerID // VOLUME id per chunk owner, read once + checked map[string]bool // chunk paths checked across all roots ownID VolumeID } @@ -93,7 +97,7 @@ 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") } - v := &verifier{base: base, vol: vol, fetch: fetch, opts: opts, ownPool: map[string]bool{}, ownMeta: map[string]bool{}, owners: map[string]ownerID{}} + v := &verifier{base: base, vol: vol, fetch: fetch, opts: opts, ownPool: map[string]bool{}, ownMeta: map[string]bool{}, owners: map[string]ownerID{}, checked: map[string]bool{}} v.res.Complete = true head, ok, err := v.head(ctx, vol) if err != nil { @@ -308,6 +312,10 @@ func (v *verifier) chunks(ctx context.Context, r *Reader, seg Segment, count boo v.res.Chunks++ dir := VolumeDir(ref.Owner, ref.OwnerID) p := path.Join(dir, ref.Chunk.Path()) + if v.checked[p] { + continue + } + v.checked[p] = true o, seen := v.owners[dir] if !seen { id, ok, err := v.volumeID(ctx, dir, false) @@ -329,8 +337,18 @@ func (v *verifier) chunks(ctx context.Context, r *Reader, seg Segment, count boo } continue } - _, ok, err := v.fetch(ctx, path.Join(v.base, p)) + var ok bool + var err error + if v.opts.Stat != nil { + ok, err = v.opts.Stat(ctx, path.Join(v.base, p)) + } else { + _, ok, err = v.fetch(ctx, path.Join(v.base, p)) + } if err != nil { + if errors.Is(err, ErrCorrupt) { + v.find(FindCorrupt, p, err.Error()) + continue + } return fmt.Errorf("layout: read %s: %w", p, err) } if !ok { diff --git a/seaweed-block/core/frontend/chunkstore/layout_verify.go b/seaweed-block/core/frontend/chunkstore/layout_verify.go index 06afcc8880..47609cb7db 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_verify.go +++ b/seaweed-block/core/frontend/chunkstore/layout_verify.go @@ -51,13 +51,30 @@ func VerifyLayout(ctx context.Context, f Filer, base, vol string, opts layout.Ve } s := &LayoutStore{f: f, b: b, root: path.Join(base, vol)} opts.List = s.List + 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 // dependent targets, before publishing absence/reachability findings. heads := map[string]layout.Head{} + // Immutable metadata may be shared by several roots. Keep it for this + // pass, but never retain chunk bodies or cache mutable HEAD observations. + type metadataObject struct { + data []byte + found bool + } + metadata := map[string]metadataObject{} fetch := func(ctx context.Context, p string) ([]byte, bool, error) { if path.Base(p) != layout.HeadName { - return s.Fetch(ctx, p) + parts := strings.Split(strings.TrimPrefix(p, base+"/"), "/") + cacheable := len(parts) == 2 && parts[1] == layout.VolumeName || len(parts) == 3 && (parts[1] == layout.RootDir || parts[1] == layout.SegDir) + if cached, ok := metadata[p]; ok && cacheable { + return cached.data, cached.found, nil + } + data, found, err := s.Fetch(ctx, p) + if cacheable && err == nil { + metadata[p] = metadataObject{data, found} + } + return data, found, err } b, head, found, err := s.verifyHead(ctx, p) heads[p] = head @@ -103,6 +120,34 @@ func VerifyLayout(ctx context.Context, f Filer, base, vol string, opts layout.Ve return res, nil } +// verifyStat checks the filer's binding and size, not the needle's bytes. +// Reading and hashing those bytes belongs to data depth. +func (s *LayoutStore) verifyStat(ctx context.Context, p string) (bool, error) { + if !path.IsAbs(p) || path.Clean(p) != p || !strings.HasPrefix(p, path.Dir(s.root)+"/") { + return false, errors.New("chunkstore: object path outside the store base") + } + e, err := s.f.LookupEntry(ctx, path.Dir(p), path.Base(p)) + if errors.Is(err, ErrNotFound) { + return false, nil + } + if err != nil { + return false, err + } + if e == nil || e.IsDirectory { + return false, fmt.Errorf("%w: %s is not a file", layout.ErrCorrupt, p) + } + if len(e.Chunks) == 0 { + if e.Attributes != nil && e.Attributes.FileSize != uint64(len(e.Content)) { + return false, fmt.Errorf("%w: inline size mismatch for %s", layout.ErrCorrupt, p) + } + return true, nil + } + if len(e.Content) != 0 || len(e.Chunks) != 1 || e.Chunks[0] == nil || e.Chunks[0].Offset != 0 || e.Chunks[0].FileId == "" || e.Attributes == nil || e.Attributes.FileSize != e.Chunks[0].Size { + return false, fmt.Errorf("%w: invalid file binding or size for %s", layout.ErrCorrupt, p) + } + return true, nil +} + // verifyHead preserves inline bytes for the kernel's malformed/identity // diagnostics; an invalid envelope has no usable generation for confirmation. func (s *LayoutStore) verifyHead(ctx context.Context, p string) ([]byte, layout.Head, bool, error) { diff --git a/seaweed-block/core/frontend/chunkstore/verify_bindings_stat_test.go b/seaweed-block/core/frontend/chunkstore/verify_bindings_stat_test.go new file mode 100644 index 0000000000..2ee3a6d56b --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/verify_bindings_stat_test.go @@ -0,0 +1,238 @@ +package chunkstore + +import ( + "context" + "errors" + "path" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +func verifyBlobFixture(t *testing.T) (filerBlobs, layout.VolumeID) { + t.Helper() + fb, id := verifyFixtureVolume(t) + for p, e := range fb.fakeFiler.entries { + if !strings.Contains(p, "/pool/") || e.IsDirectory { + continue + } + fid, err := fb.fakeBlobs.Put(context.Background(), e.Content) + if err != nil { + t.Fatal(err) + } + e.Attributes = &filerpb.FuseAttributes{FileSize: uint64(len(e.Content))} + e.Chunks = []*filerpb.FileChunk{{FileId: fid, Size: uint64(len(e.Content))}} + e.Content = nil + } + return fb, id +} + +func TestVerifyBindingsNeverReadsChunkBodies(t *testing.T) { + fb, id := verifyBlobFixture(t) + _, before, _ := fb.fakeBlobs.counts() + res, err := VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames}) + if err != nil || !res.Complete || len(res.Findings) != 0 || res.Chunks != 2 { + t.Fatalf("bindings: %+v, %v", res, err) + } + _, after, _ := fb.fakeBlobs.counts() + if after != before { + t.Fatalf("bindings read %d chunk bodies; want zero", after-before) + } + // Data depth must continue to fetch the two bodies and verify their hashes. + res, err = VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthFull}) + _, full, _ := fb.fakeBlobs.counts() + if err != nil || !res.Complete || len(res.Findings) != 0 || full-after != 2 { + t.Fatalf("data: %+v, %v, body reads=%d", res, err, full-after) + } + // Same-size damage is invisible to bindings, but must be caught by data depth. + e := fb.fakeFiler.entries[path.Join("/blocks", layout.VolumeDir("v", id), layout.NameChunk(0, []byte(strings.Repeat("a", 64))).Path())] + fb.fakeBlobs.data[e.Chunks[0].FileId] = []byte(strings.Repeat("z", 64)) + res, err = VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthFull}) + if err != nil || len(res.Findings) != 1 || res.Findings[0].Class != layout.FindCorrupt { + t.Fatalf("damaged data: %+v, %v", res, err) + } +} + +type verifyLookupCounter struct { + filerBlobs + reads map[string]int +} + +func (f *verifyLookupCounter) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + f.reads[path.Join(dir, name)]++ + return f.filerBlobs.LookupEntry(ctx, dir, name) +} + +func TestVerifyBindingsChecksEachDistinctObjectOnce(t *testing.T) { + fb, id := verifyBlobFixture(t) + dir := path.Join("/blocks", layout.VolumeDir("v", id)) + refs := map[uint64]layout.Ref{} + for _, i := range []uint64{0, 5} { + refs[i] = layout.Ref{Owner: "v", OwnerID: id, Chunk: layout.NameChunk(i, []byte(strings.Repeat(string(rune('a'+i)), 64)))} + } + index := uint64(layout.ShardSize + 1) + n := layout.NameChunk(index, []byte("snapshot-only")) + putFile(t, fb.fakeFiler, path.Join(dir, n.Path()), []byte("snapshot-only")) + refs[index] = layout.Ref{Owner: "v", OwnerID: id, Chunk: n} + root, segs, err := layout.Build(refs) + if err != nil { + t.Fatal(err) + } + for n, b := range segs { + if fb.fakeFiler.entries[path.Join(dir, n.Path())] == nil { + putFile(t, fb.fakeFiler, path.Join(dir, n.Path()), b) + } + } + rn, raw, err := layout.NameRoot(root) + if err != nil { + t.Fatal(err) + } + putFile(t, fb.fakeFiler, path.Join(dir, rn.Path()), raw) + e := fb.fakeFiler.entries[path.Join(dir, layout.HeadName)] + h, err := layout.DecodeHead(e.Content, 0, id) + if err != nil { + t.Fatal(err) + } + h.Snapshots = map[string]layout.Snapshot{"s": {Root: rn}} + e.Content, err = h.Encode() + if err != nil { + t.Fatal(err) + } + f := &verifyLookupCounter{filerBlobs: fb, reads: map[string]int{}} + res, err := VerifyLayout(context.Background(), f, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames}) + if err != nil || !res.Complete || len(res.Findings) != 0 || res.Roots != 2 { + t.Fatalf("shared snapshot objects: %+v, %v", res, err) + } + for p, count := range f.reads { + want := 1 + if path.Base(p) == layout.HeadName { + want = 2 + } + if count != want { + t.Errorf("%s: %d lookups; want %d", p, count, want) + } + } + for _, ref := range refs { + p := path.Join(dir, ref.Chunk.Path()) + if f.reads[p] != 1 { + t.Errorf("reachable chunk %s: %d lookups", p, f.reads[p]) + } + } +} + +func TestVerifyBindingsChecksDeclaredSizesAndRefusals(t *testing.T) { + for _, mode := range []string{"size", "no-attributes", "offset", "empty-fid", "nil-chunk", "multiple-chunks", "directory", "mixed-content", "inline-size", "missing"} { + t.Run(mode, func(t *testing.T) { + fb, id := verifyBlobFixture(t) + p := path.Join("/blocks", layout.VolumeDir("v", id), layout.NameChunk(0, []byte(strings.Repeat("a", 64))).Path()) + e := fb.fakeFiler.entries[p] + switch mode { + case "size": + e.Attributes.FileSize++ + case "no-attributes": + e.Attributes = nil + case "offset": + e.Chunks[0].Offset = 1 + case "empty-fid": + e.Chunks[0].FileId = "" + case "nil-chunk": + e.Chunks[0] = nil + case "multiple-chunks": + e.Chunks = append(e.Chunks, e.Chunks[0]) + case "directory": + e.IsDirectory = true + case "mixed-content": + e.Content = []byte("mixed") + case "inline-size": + e.Chunks = nil + e.Content = []byte("short") + case "missing": + delete(fb.fakeFiler.entries, p) + } + res, err := VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames}) + want := layout.FindCorrupt + if mode == "missing" { + want = layout.FindMissing + } + if err != nil || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != want || res.Findings[0].Path != strings.TrimPrefix(p, "/blocks/") { + t.Fatalf("%s: %+v, %v; want %s at %s", mode, res, err, want, p) + } + _, gets, _ := fb.fakeBlobs.counts() + if gets != 0 { + t.Fatalf("bindings read %d bodies", gets) + } + }) + } +} + +type verifyLookupFailure struct { + filerBlobs + err error +} + +func (f verifyLookupFailure) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + if strings.Contains(dir, "/pool/") { + return nil, f.err + } + return f.filerBlobs.LookupEntry(ctx, dir, name) +} +func TestVerifyBindingsLookupFailureIsNotAMissingObject(t *testing.T) { + fb, id := verifyBlobFixture(t) + injected := errors.New("injected filer unavailable") + res, err := VerifyLayout(context.Background(), verifyLookupFailure{fb, injected}, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames}) + if !errors.Is(err, injected) || res.Complete || len(res.Findings) != 0 { + t.Fatalf("lookup failure: %+v, %v", res, err) + } +} + +type verifyPayloadCounter struct { + Filer + Blobs + payloads map[string]bool + payloadReads, metadataReads int +} + +func (f *verifyPayloadCounter) Get(ctx context.Context, fid string) ([]byte, error) { + if f.payloads[fid] { + f.payloadReads++ + } else { + f.metadataReads++ + } + return f.Blobs.Get(ctx, fid) +} +func TestVerifyBindingsProductionMetadataStillDecodes(t *testing.T) { + ctx := context.Background() + c, source, _, _ := cleanFixture(t) + target := newRef(t, "restored") + if _, err := c.Restore(ctx, source, "s", target); err != nil { + t.Fatal(err) + } + entries, err := c.f.ListEntries(ctx, path.Join(c.base, source.Dir(), layout.PoolDir, "0"), "", "", 0) + if err != nil { + t.Fatal(err) + } + f := &verifyPayloadCounter{Filer: c.f, Blobs: c.b, payloads: map[string]bool{}} + for _, e := range entries { + for _, chunk := range e.Chunks { + f.payloads[chunk.FileId] = true + } + } + if len(f.payloads) == 0 { + t.Fatal("production fixture has no blob-backed chunks") + } + for _, v := range []VolumeRef{source, target} { + res, err := VerifyLayout(ctx, f, c.base, v.Dir(), layout.VerifyOptions{Depth: layout.DepthNames}) + if err != nil || !res.Complete || len(res.Findings) != 0 || res.Chunks != 1 { + t.Fatalf("%s bindings: %+v, %v", v.Name, res, err) + } + } + if f.payloadReads != 0 || f.metadataReads == 0 { + t.Fatalf("body reads: payload=%d metadata=%d; only manifests need body decoding", f.payloadReads, f.metadataReads) + } + res, err := VerifyLayout(ctx, f, c.base, target.Dir(), layout.VerifyOptions{Depth: layout.DepthFull}) + if err != nil || !res.Complete || len(res.Findings) != 0 || f.payloadReads != 1 { + t.Fatalf("restore data: %+v, %v, payload reads=%d", res, err, f.payloadReads) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index bdf33b23eb..abd653fdde 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1059,7 +1059,9 @@ Notes: | `INV-SNAP-SEAL-DURABLE-001` | A named snapshot is reported done only after the commit naming it is confirmed (every object its root reaches written by the session first); an unknown outcome reports failure, settled by reading HEAD. | M5 CAS → Settled; M6 snapshot: name held → published | `core/host/volume/chunk_control.go` `chunkControl.Snapshot`; `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.CASHead`; `core/frontend/chunkstore/layout/commit.go` `RunCommit` | `TestLayoutRemote_CutCommitsThroughTheKernel` (`core/frontend/chunkstore/layout_remote_test.go`); `TestNamedSnapshotWindowAbortNeverSubstitutesPoint` (`core/host/volume/chunk_review271_test.go`) | — | ACTIVE | | `INV-SNAP-SCHEDULE-RESTART-001` | A new snapshot worker seeds its last success from HEAD's newest scheduled creation time (future clamped to now), then the next stable per-volume grid slot; absent history is due now. Restarts preserve overdue age; manual snapshots do not seed it. | M8 scheduled worker Armed → Due | `core/frontend/durable/chunk_snapshot_schedule.go` `snapshotScheduleFromHead`; `provider_chunk.go` `newChunkLayer` | `TestScheduledSnapshotRestartsStillTakeTheDueSnapshot`, `TestScheduledSnapshotRestartPreservesOverdueFromHEAD`, `TestScheduledSnapshotWithoutHistoryIsImmediatelyDue`, `TestScheduledSnapshotProvidersSpreadAfterImmediateFirstAttempt`, `TestSnapshotScheduleHeadSeedKeepsPerVolumeGrid`, `TestSnapshotScheduleHeadSeedClampsFutureCreationTime` | — (read-only timer initialization from existing HEAD metadata) | ACTIVE | | `INV-SNAP-SCHEDULED-KEEP-001` | Retention keeps the newest K scheduled snapshots, K being the newest one's swb.schedule.keep (default 7); scheduled snapshots never count against KeepNewest or get age keeps, so other snapshots are planned as if they were absent. | M6 snapshot: Published → Deleting (retention, class `scheduled`) | `core/frontend/chunkstore/retain/retain.go` `Plan`, `scheduleKeepOf` | `TestPlanRetention_ScheduledClassKeepsItsOwnNewest`, `TestPlanRetention_PinnedScheduledStaysInItsClass` (`core/frontend/chunkstore/retain/retain_test.go`) | — | ACTIVE | -| `INV-VERIFY-READONLY-001` | Verify writes nothing at any depth: it reaches the store only through Fetch and List, and a full pass with orphans leaves every filer entry and blob unchanged. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyLayoutThroughTheAdapter` (`core/frontend/chunkstore/layout_verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-READONLY-001` | Verify writes nothing at any depth: it reaches the store only through Fetch, Stat and List, and a full pass with orphans leaves every filer entry and blob unchanged. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyLayoutThroughTheAdapter` (`core/frontend/chunkstore/layout_verify_test.go`) | — | ACTIVE | +| `INV-VERIFY-BINDINGS-001` | Bindings depth checks each chunk's filer binding and declared size without reading its blob body; data depth retains byte/hash validation. | M6 reader (no transition) | `core/frontend/chunkstore/layout_verify.go` `verifyStat`; `layout/verify.go` `chunks` | `TestVerifyBindingsNeverReadsChunkBodies`, `TestVerifyBindingsChecksDeclaredSizesAndRefusals`, `TestVerifyBindingsLookupFailureIsNotAMissingObject` | — (read-only inspection) | ACTIVE | +| `INV-VERIFY-DISTINCT-001` | A verify pass looks up each immutable metadata object and chunk binding once across roots; HEAD remains independently confirmed, and chunk bodies are never retained in the metadata cache. | M6 reader (no transition) | `core/frontend/chunkstore/layout_verify.go` `VerifyLayout`; `layout/verify.go` `chunks` | `TestVerifyBindingsChecksEachDistinctObjectOnce` | — (pass-local reuse) | ACTIVE | | `INV-VERIFY-STABLE-HEAD-001` | Filer verify publishes MISSING or ORPHAN only after two HEAD observations agree on a nonzero generation and volume identity. An unavailable or changed own/dependent HEAD makes the pass incomplete and suppresses those findings. Unsupported verify options refuse before dialing. | M6 (reader; no transition) | `core/frontend/chunkstore/layout_verify.go` `VerifyLayout`; `cmd/sw-block/chunk_verify.go` `chunkVerify` | `TestVerifyLayoutRequiresStableHeadForMissingAndOrphans`; `TestVerifyConfirmsDependentHeadBeforeReportingOrphans`; `TestOpsChunkVerifyRefusesUnsupportedFlagsBeforeDial` | — | ACTIVE | | `INV-VERIFY-NOTFOUND-001` | Verify reports `MISSING` only when the store answers that the object does not exist; any other read failure ends the pass as incomplete with that error, and is never a finding. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyReadErrorIsReturned`, `TestVerifyFindsMissingAndCorrupt` (`core/frontend/chunkstore/layout/verify_test.go`); `TestOpsChunk_VerifyReadErrorIsIncomplete` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE | | `INV-VERIFY-REACH-001` | A complete pass checks every object the current root and every snapshot root name (roots, segments, chunks): an absent one is `MISSING`; one whose bytes do not hash to its name, at depth full, is `CORRUPT`. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyCleanVolume`, `TestVerifyFindsMissingAndCorrupt`, `TestVerifyWalksSnapshotRoots` (`core/frontend/chunkstore/layout/verify_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 560f9921a6..35f2dd1eaf 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -869,6 +869,12 @@ must also match VOLUME; the eight-character directory suffix is not an identity check. Source and restore-target chunks are checked in their owners' canonical directories using each reference's full owner id. +The default `--depth bindings` (also named `meta`) checks each distinct chunk's +filer entry and the consistency of its declared size without fetching the chunk +body. It does not detect content damage or a missing backing needle behind a +present entry; use `--depth data` for those checks. Roots and segments are still +read and decoded, and shared immutable objects are checked once per pass. + Verify is read-only: exit 0 means complete with no findings, 3 means complete with findings, 1 means incomplete, and 2 means invalid arguments. `--depth data` checks chunk hashes and requires an explicit timeout. `--orphans` only reports; From 697afeedf819ab61219d52c225fc18bc09901ff8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 00:19:15 -0800 Subject: [PATCH 2/4] fix: validate owner identity before verify deduplication --- .../cmd/sw-block/chunk_verify_test.go | 2 +- .../core/frontend/chunkstore/layout/verify.go | 25 +++- .../volume_writer_repository_guard_test.go | 3 + .../core/frontend/chunkstore/layout_verify.go | 7 +- .../frontend/chunkstore/layout_verify_test.go | 6 +- .../chunkstore/verify_bindings_stat_test.go | 122 +++++++++++++++++- .../verify_production_layout_test.go | 23 +++- seaweed-block/docs/design/invariants.md | 6 +- seaweed-block/docs/standalone-deployment.md | 3 +- 9 files changed, 171 insertions(+), 26 deletions(-) diff --git a/seaweed-block/cmd/sw-block/chunk_verify_test.go b/seaweed-block/cmd/sw-block/chunk_verify_test.go index 551563eec8..4ac1cd30f0 100644 --- a/seaweed-block/cmd/sw-block/chunk_verify_test.go +++ b/seaweed-block/cmd/sw-block/chunk_verify_test.go @@ -43,7 +43,7 @@ func verifyCLIFixture(t *testing.T) (*manifestFixtureFiler, string) { oldResolve := resolveVolumeID resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return id, nil } t.Cleanup(func() { resolveVolumeID = oldResolve }) - vb, err := layout.Volume{ID: id, Name: "v1", Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: layout.VolumeFormat}.Encode() + vb, err := layout.Volume{ID: id, Name: "v1", Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4096}, Format: layout.VolumeFormat}.Encode() if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/frontend/chunkstore/layout/verify.go b/seaweed-block/core/frontend/chunkstore/layout/verify.go index cbec6337c7..7433730f67 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/verify.go +++ b/seaweed-block/core/frontend/chunkstore/layout/verify.go @@ -42,7 +42,7 @@ type VerifyOptions struct { List List // 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) (found bool, err error) + Stat func(ctx context.Context, p string, expectedSize uint64) (found bool, err error) } // Finding is one problem found at Path (relative to ). @@ -71,6 +71,7 @@ type verifier struct { ownMeta map[string]bool owners map[string]ownerID // VOLUME id per chunk owner, read once checked map[string]bool // chunk paths checked across all roots + geometry map[string]Geometry ownID VolumeID } @@ -97,7 +98,7 @@ 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") } - v := &verifier{base: base, vol: vol, fetch: fetch, opts: opts, ownPool: map[string]bool{}, ownMeta: map[string]bool{}, owners: map[string]ownerID{}, checked: map[string]bool{}} + v := &verifier{base: base, vol: vol, fetch: fetch, opts: opts, ownPool: map[string]bool{}, ownMeta: map[string]bool{}, owners: map[string]ownerID{}, checked: map[string]bool{}, geometry: map[string]Geometry{}} v.res.Complete = true head, ok, err := v.head(ctx, vol) if err != nil { @@ -200,6 +201,7 @@ func (v *verifier) volumeID(ctx context.Context, vol string, report bool) (Volum v.incomplete("VOLUME identity mismatch") return VolumeID{}, false, nil } + v.geometry[vol] = rec.Geometry return rec.ID, true, nil } @@ -312,10 +314,6 @@ func (v *verifier) chunks(ctx context.Context, r *Reader, seg Segment, count boo v.res.Chunks++ dir := VolumeDir(ref.Owner, ref.OwnerID) p := path.Join(dir, ref.Chunk.Path()) - if v.checked[p] { - continue - } - v.checked[p] = true o, seen := v.owners[dir] if !seen { id, ok, err := v.volumeID(ctx, dir, false) @@ -329,6 +327,10 @@ func (v *verifier) chunks(ctx context.Context, r *Reader, seg Segment, count boo v.find(FindIdentity, p, fmt.Sprintf("names owner %s id %s; its VOLUME has %s", ref.Owner, ref.OwnerID, map[bool]string{true: o.id.String(), false: "none"}[o.ok])) continue } + if v.checked[p] { + continue + } + v.checked[p] = true if v.opts.Depth == DepthFull { if _, err := r.get(ctx, dir, ref.Chunk.Path(), ref.Chunk.Hash); err != nil { if err := v.classify(p, err); err != nil { @@ -337,10 +339,19 @@ func (v *verifier) chunks(ctx context.Context, r *Reader, seg Segment, count boo } continue } + var expectedSize uint64 + if v.opts.Stat != nil { + g := v.geometry[dir] + if ref.Chunk.Index > (g.SizeBytes-1)/g.ChunkBytes { + v.find(FindCorrupt, p, "chunk index is outside its owner's VOLUME geometry") + continue + } + expectedSize = min(g.ChunkBytes, g.SizeBytes-ref.Chunk.Index*g.ChunkBytes) + } var ok bool var err error if v.opts.Stat != nil { - ok, err = v.opts.Stat(ctx, path.Join(v.base, p)) + ok, err = v.opts.Stat(ctx, path.Join(v.base, p), expectedSize) } else { _, ok, err = v.fetch(ctx, path.Join(v.base, p)) } diff --git a/seaweed-block/core/frontend/chunkstore/layout/volume_writer_repository_guard_test.go b/seaweed-block/core/frontend/chunkstore/layout/volume_writer_repository_guard_test.go index 30eb2b8f84..4dce73c726 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/volume_writer_repository_guard_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/volume_writer_repository_guard_test.go @@ -87,6 +87,9 @@ func TestVolumeWriterRepositorySites(t *testing.T) { "core/frontend/chunkstore/layout/verify.go volumeID VolumeName": 1, "core/frontend/chunkstore/layout_create.go ReadVolumeRecord VolumeName": 1, "core/frontend/chunkstore/layout_create.go CreateVolumeRecord VolumeName": 1, + // Read-only cache discriminator; the distinct-object verifier control + // proves VOLUME is observed once while HEAD is confirmed separately. + "core/frontend/chunkstore/layout_verify.go VerifyLayout VolumeName": 1, } got := map[string]int{} root := filepath.Clean("../../../..") diff --git a/seaweed-block/core/frontend/chunkstore/layout_verify.go b/seaweed-block/core/frontend/chunkstore/layout_verify.go index 47609cb7db..7977d946e2 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_verify.go +++ b/seaweed-block/core/frontend/chunkstore/layout_verify.go @@ -122,7 +122,7 @@ func VerifyLayout(ctx context.Context, f Filer, base, vol string, opts layout.Ve // verifyStat checks the filer's binding and size, not the needle's bytes. // Reading and hashing those bytes belongs to data depth. -func (s *LayoutStore) verifyStat(ctx context.Context, p string) (bool, error) { +func (s *LayoutStore) verifyStat(ctx context.Context, p string, expectedSize uint64) (bool, error) { if !path.IsAbs(p) || path.Clean(p) != p || !strings.HasPrefix(p, path.Dir(s.root)+"/") { return false, errors.New("chunkstore: object path outside the store base") } @@ -137,12 +137,15 @@ func (s *LayoutStore) verifyStat(ctx context.Context, p string) (bool, error) { return false, fmt.Errorf("%w: %s is not a file", layout.ErrCorrupt, p) } if len(e.Chunks) == 0 { + if uint64(len(e.Content)) != expectedSize { + return false, fmt.Errorf("%w: inline size differs from VOLUME geometry for %s", layout.ErrCorrupt, p) + } if e.Attributes != nil && e.Attributes.FileSize != uint64(len(e.Content)) { return false, fmt.Errorf("%w: inline size mismatch for %s", layout.ErrCorrupt, p) } return true, nil } - if len(e.Content) != 0 || len(e.Chunks) != 1 || e.Chunks[0] == nil || e.Chunks[0].Offset != 0 || e.Chunks[0].FileId == "" || e.Attributes == nil || e.Attributes.FileSize != e.Chunks[0].Size { + if len(e.Content) != 0 || len(e.Chunks) != 1 || e.Chunks[0] == nil || e.Chunks[0].Offset != 0 || e.Chunks[0].FileId == "" || e.Attributes == nil || e.Attributes.FileSize != e.Chunks[0].Size || e.Attributes.FileSize != expectedSize { return false, fmt.Errorf("%w: invalid file binding or size for %s", layout.ErrCorrupt, p) } return true, nil diff --git a/seaweed-block/core/frontend/chunkstore/layout_verify_test.go b/seaweed-block/core/frontend/chunkstore/layout_verify_test.go index f0a421695b..4fd80da01c 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_verify_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_verify_test.go @@ -48,7 +48,7 @@ func verifyFixtureVolume(t *testing.T) (filerBlobs, layout.VolumeID) { manifest := map[uint64]layout.Ref{} putDir(t, f, path.Join("/blocks", layout.VolumeDir("v", id), "pool/0")) for _, i := range []uint64{0, 5} { - d := []byte(strings.Repeat(string(rune('a'+i)), 64)) + d := []byte(strings.Repeat(string(rune('a'+i)), 4*4096)) c := layout.NameChunk(i, d) putFile(t, f, path.Join(path.Join("/blocks", layout.VolumeDir("v", id)), c.Path()), d) manifest[i] = layout.Ref{Owner: "v", OwnerID: id, Chunk: c} @@ -87,7 +87,7 @@ func TestVerifyLayoutThroughTheAdapter(t *testing.T) { } extra := layout.NameChunk(9, []byte("zz")) putFile(t, fb.fakeFiler, path.Join(path.Join("/blocks", layout.VolumeDir("v", id)), extra.Path()), []byte("zz")) - c0 := layout.NameChunk(0, []byte(strings.Repeat("a", 64))) + c0 := layout.NameChunk(0, []byte(strings.Repeat("a", 4*4096))) delete(fb.fakeFiler.entries, path.Join(path.Join("/blocks", layout.VolumeDir("v", id)), c0.Path())) before = snapshotStore(fb) r, err = VerifyLayout(ctx, fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Orphans: true}) @@ -190,7 +190,7 @@ func TestVerifyLayoutRequiresStableHeadForMissingAndOrphans(t *testing.T) { fb, id := verifyFixtureVolume(t) hp := path.Join("/blocks", layout.VolumeDir("v", id), layout.HeadName) fb.fakeFiler.entries[hp].Extended = map[string][]byte{layoutKind: []byte("head"), layoutVolume: []byte(id.String()), layoutGen: []byte("1")} - c := layout.NameChunk(0, []byte(strings.Repeat("a", 64))) + c := layout.NameChunk(0, []byte(strings.Repeat("a", 4*4096))) delete(fb.fakeFiler.entries, path.Join("/blocks", layout.VolumeDir("v", id), c.Path())) extra := layout.NameChunk(9, []byte("orphan")) putFile(t, fb.fakeFiler, path.Join("/blocks", layout.VolumeDir("v", id), extra.Path()), []byte("orphan")) diff --git a/seaweed-block/core/frontend/chunkstore/verify_bindings_stat_test.go b/seaweed-block/core/frontend/chunkstore/verify_bindings_stat_test.go index 2ee3a6d56b..37da50da03 100644 --- a/seaweed-block/core/frontend/chunkstore/verify_bindings_stat_test.go +++ b/seaweed-block/core/frontend/chunkstore/verify_bindings_stat_test.go @@ -47,8 +47,8 @@ func TestVerifyBindingsNeverReadsChunkBodies(t *testing.T) { t.Fatalf("data: %+v, %v, body reads=%d", res, err, full-after) } // Same-size damage is invisible to bindings, but must be caught by data depth. - e := fb.fakeFiler.entries[path.Join("/blocks", layout.VolumeDir("v", id), layout.NameChunk(0, []byte(strings.Repeat("a", 64))).Path())] - fb.fakeBlobs.data[e.Chunks[0].FileId] = []byte(strings.Repeat("z", 64)) + e := fb.fakeFiler.entries[path.Join("/blocks", layout.VolumeDir("v", id), layout.NameChunk(0, []byte(strings.Repeat("a", 4*4096))).Path())] + fb.fakeBlobs.data[e.Chunks[0].FileId] = []byte(strings.Repeat("z", 4*4096)) res, err = VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthFull}) if err != nil || len(res.Findings) != 1 || res.Findings[0].Class != layout.FindCorrupt { t.Fatalf("damaged data: %+v, %v", res, err) @@ -70,11 +70,22 @@ func TestVerifyBindingsChecksEachDistinctObjectOnce(t *testing.T) { dir := path.Join("/blocks", layout.VolumeDir("v", id)) refs := map[uint64]layout.Ref{} for _, i := range []uint64{0, 5} { - refs[i] = layout.Ref{Owner: "v", OwnerID: id, Chunk: layout.NameChunk(i, []byte(strings.Repeat(string(rune('a'+i)), 64)))} + refs[i] = layout.Ref{Owner: "v", OwnerID: id, Chunk: layout.NameChunk(i, []byte(strings.Repeat(string(rune('a'+i)), 4*4096)))} + } + // This snapshot deliberately reaches the next shard; its volume covers it. + vp := path.Join(dir, layout.VolumeName) + volume, err := layout.DecodeVolume(fb.fakeFiler.entries[vp].Content) + if err != nil { + t.Fatal(err) + } + volume.SizeBytes = uint64(layout.ShardSize+2) * volume.ChunkBytes + fb.fakeFiler.entries[vp].Content, err = volume.Encode() + if err != nil { + t.Fatal(err) } index := uint64(layout.ShardSize + 1) - n := layout.NameChunk(index, []byte("snapshot-only")) - putFile(t, fb.fakeFiler, path.Join(dir, n.Path()), []byte("snapshot-only")) + n := layout.NameChunk(index, []byte(strings.Repeat("s", 4*4096))) + putFile(t, fb.fakeFiler, path.Join(dir, n.Path()), []byte(strings.Repeat("s", 4*4096))) refs[index] = layout.Ref{Owner: "v", OwnerID: id, Chunk: n} root, segs, err := layout.Build(refs) if err != nil { @@ -126,7 +137,7 @@ func TestVerifyBindingsChecksDeclaredSizesAndRefusals(t *testing.T) { for _, mode := range []string{"size", "no-attributes", "offset", "empty-fid", "nil-chunk", "multiple-chunks", "directory", "mixed-content", "inline-size", "missing"} { t.Run(mode, func(t *testing.T) { fb, id := verifyBlobFixture(t) - p := path.Join("/blocks", layout.VolumeDir("v", id), layout.NameChunk(0, []byte(strings.Repeat("a", 64))).Path()) + p := path.Join("/blocks", layout.VolumeDir("v", id), layout.NameChunk(0, []byte(strings.Repeat("a", 4*4096))).Path()) e := fb.fakeFiler.entries[p] switch mode { case "size": @@ -204,7 +215,7 @@ func (f *verifyPayloadCounter) Get(ctx context.Context, fid string) ([]byte, err } func TestVerifyBindingsProductionMetadataStillDecodes(t *testing.T) { ctx := context.Background() - c, source, _, _ := cleanFixture(t) + c, source := verifyProductionFixture(t) target := newRef(t, "restored") if _, err := c.Restore(ctx, source, "s", target); err != nil { t.Fatal(err) @@ -236,3 +247,100 @@ func TestVerifyBindingsProductionMetadataStillDecodes(t *testing.T) { t.Fatalf("restore data: %+v, %v, payload reads=%d", res, err, f.payloadReads) } } + +func TestVerifyBindingsRejectsSelfConsistentTruncationAgainstGeometry(t *testing.T) { + fb, id := verifyBlobFixture(t) + p := path.Join("/blocks", layout.VolumeDir("v", id), layout.NameChunk(0, []byte(strings.Repeat("a", 4*4096))).Path()) + e := fb.fakeFiler.entries[p] + e.Attributes.FileSize = 32 + e.Chunks[0].Size = 32 + res, err := VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames}) + if err != nil || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != layout.FindCorrupt || res.Findings[0].Path != strings.TrimPrefix(p, "/blocks/") { + t.Fatalf("self-consistent truncation: %+v, %v", res, err) + } +} + +func TestVerifyBindingsUsesTailGeometryAndRejectsOutsideVolume(t *testing.T) { + for _, mode := range []string{"tail", "short-tail", "outside"} { + t.Run(mode, func(t *testing.T) { + fb, id := verifyBlobFixture(t) + dir := path.Join("/blocks", layout.VolumeDir("v", id)) + vp := path.Join(dir, layout.VolumeName) + volume, err := layout.DecodeVolume(fb.fakeFiler.entries[vp].Content) + if err != nil { + t.Fatal(err) + } + volume.SizeBytes = 5*volume.ChunkBytes + 4096 + if mode == "outside" { + volume.SizeBytes = 5 * volume.ChunkBytes + } + fb.fakeFiler.entries[vp].Content, err = volume.Encode() + if err != nil { + t.Fatal(err) + } + p := path.Join(dir, layout.NameChunk(5, []byte(strings.Repeat("f", 4*4096))).Path()) + // Names depth observes declared metadata only; it must not read this body. + e := fb.fakeFiler.entries[p] + e.Attributes.FileSize, e.Chunks[0].Size = 4096, 4096 + if mode == "short-tail" { + e.Attributes.FileSize, e.Chunks[0].Size = 2048, 2048 + } + res, err := VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames}) + if err != nil || !res.Complete { + t.Fatalf("%s: %+v, %v", mode, res, err) + } + if mode == "tail" { + if len(res.Findings) != 0 { + t.Fatalf("valid tail: %+v", res.Findings) + } + } else if len(res.Findings) != 1 || res.Findings[0].Class != layout.FindCorrupt || res.Findings[0].Path != strings.TrimPrefix(p, "/blocks/") { + t.Fatalf("%s: %+v", mode, res.Findings) + } + _, gets, _ := fb.fakeBlobs.counts() + if gets != 0 { + t.Fatalf("bindings read %d bodies", gets) + } + }) + } +} + +func TestVerifyDeduplicationNeverSkipsFullOwnerIdentity(t *testing.T) { + for _, depth := range []string{layout.DepthNames, layout.DepthFull} { + t.Run(depth, func(t *testing.T) { + fb, id := verifyBlobFixture(t) + wrong := id + wrong[15] ^= 1 + if layout.VolumeDir("v", wrong) != layout.VolumeDir("v", id) { + t.Fatal("fixture needs an id8 collision") + } + ref := layout.Ref{Owner: "v", OwnerID: wrong, Chunk: layout.NameChunk(0, []byte(strings.Repeat("a", 4*4096)))} + root, segs, err := layout.Build(map[uint64]layout.Ref{0: ref}) + if err != nil { + t.Fatal(err) + } + dir := path.Join("/blocks", layout.VolumeDir("v", id)) + for n, b := range segs { + putFile(t, fb.fakeFiler, path.Join(dir, n.Path()), b) + } + rn, raw, err := layout.NameRoot(root) + if err != nil { + t.Fatal(err) + } + putFile(t, fb.fakeFiler, path.Join(dir, rn.Path()), raw) + e := fb.fakeFiler.entries[path.Join(dir, layout.HeadName)] + h, err := layout.DecodeHead(e.Content, 0, id) + if err != nil { + t.Fatal(err) + } + h.Snapshots = map[string]layout.Snapshot{"different-owner": {Root: rn}} + e.Content, err = h.Encode() + if err != nil { + t.Fatal(err) + } + res, err := VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: depth}) + if err != nil || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != layout.FindIdentity { + t.Fatalf("id8 collision after a valid reference: %+v, %v", res, err) + } + }) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/verify_production_layout_test.go b/seaweed-block/core/frontend/chunkstore/verify_production_layout_test.go index 5ed3d073f6..cd435c590d 100644 --- a/seaweed-block/core/frontend/chunkstore/verify_production_layout_test.go +++ b/seaweed-block/core/frontend/chunkstore/verify_production_layout_test.go @@ -1,6 +1,7 @@ package chunkstore import ( + "bytes" "context" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" "google.golang.org/protobuf/proto" @@ -19,7 +20,7 @@ type verifyProductionStore struct { // restored image borrows the source's chunks while owning copied metadata. func TestVerifyProductionLayoutCurrentAndRestored(t *testing.T) { ctx := context.Background() - c, source, _, _ := cleanFixture(t) + c, source := verifyProductionFixture(t) target := newRef(t, "restored") if _, err := c.Restore(ctx, source, "s", target); err != nil { t.Fatal(err) @@ -58,7 +59,7 @@ func (f *verifyMovingDependent) LookupEntry(ctx context.Context, dir, name strin } func TestVerifyConfirmsDependentHeadBeforeReportingOrphans(t *testing.T) { ctx := context.Background() - c, source, _, _ := cleanFixture(t) + c, source := verifyProductionFixture(t) target := newRef(t, "restored") if _, err := c.Restore(ctx, source, "s", target); err != nil { t.Fatal(err) @@ -80,3 +81,21 @@ func TestVerifyConfirmsDependentHeadBeforeReportingOrphans(t *testing.T) { t.Fatalf("moving dependent: %+v %v reads=%d", r, err, f.reads) } } + +// Unlike catalog-only fixtures, a verifier fixture stores full geometry-sized chunks. +func verifyProductionFixture(t *testing.T) (*BCatalog, VolumeRef) { + t.Helper() + c, err := NewBCatalog(NewMemFiler(), newFakeBlobs(), "/blocks") + if err != nil { + t.Fatal(err) + } + source := newRef(t, "source") + if _, err := c.CreateVolume(context.Background(), source, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + commitSnapshot(t, c, source, bytes.Repeat([]byte{7}, 4*4096), "s") + if err := c.f.CreateEntry(context.Background(), path.Join(c.base, source.Dir(), layout.PoolDir), &filerpb.Entry{Name: "0", IsDirectory: true}, false); err != nil { + t.Fatal(err) + } + return c, source +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index abd653fdde..f76ca2fcd9 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1060,14 +1060,14 @@ Notes: | `INV-SNAP-SCHEDULE-RESTART-001` | A new snapshot worker seeds its last success from HEAD's newest scheduled creation time (future clamped to now), then the next stable per-volume grid slot; absent history is due now. Restarts preserve overdue age; manual snapshots do not seed it. | M8 scheduled worker Armed → Due | `core/frontend/durable/chunk_snapshot_schedule.go` `snapshotScheduleFromHead`; `provider_chunk.go` `newChunkLayer` | `TestScheduledSnapshotRestartsStillTakeTheDueSnapshot`, `TestScheduledSnapshotRestartPreservesOverdueFromHEAD`, `TestScheduledSnapshotWithoutHistoryIsImmediatelyDue`, `TestScheduledSnapshotProvidersSpreadAfterImmediateFirstAttempt`, `TestSnapshotScheduleHeadSeedKeepsPerVolumeGrid`, `TestSnapshotScheduleHeadSeedClampsFutureCreationTime` | — (read-only timer initialization from existing HEAD metadata) | ACTIVE | | `INV-SNAP-SCHEDULED-KEEP-001` | Retention keeps the newest K scheduled snapshots, K being the newest one's swb.schedule.keep (default 7); scheduled snapshots never count against KeepNewest or get age keeps, so other snapshots are planned as if they were absent. | M6 snapshot: Published → Deleting (retention, class `scheduled`) | `core/frontend/chunkstore/retain/retain.go` `Plan`, `scheduleKeepOf` | `TestPlanRetention_ScheduledClassKeepsItsOwnNewest`, `TestPlanRetention_PinnedScheduledStaysInItsClass` (`core/frontend/chunkstore/retain/retain_test.go`) | — | ACTIVE | | `INV-VERIFY-READONLY-001` | Verify writes nothing at any depth: it reaches the store only through Fetch, Stat and List, and a full pass with orphans leaves every filer entry and blob unchanged. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyLayoutThroughTheAdapter` (`core/frontend/chunkstore/layout_verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-BINDINGS-001` | Bindings depth checks each chunk's filer binding and declared size without reading its blob body; data depth retains byte/hash validation. | M6 reader (no transition) | `core/frontend/chunkstore/layout_verify.go` `verifyStat`; `layout/verify.go` `chunks` | `TestVerifyBindingsNeverReadsChunkBodies`, `TestVerifyBindingsChecksDeclaredSizesAndRefusals`, `TestVerifyBindingsLookupFailureIsNotAMissingObject` | — (read-only inspection) | ACTIVE | -| `INV-VERIFY-DISTINCT-001` | A verify pass looks up each immutable metadata object and chunk binding once across roots; HEAD remains independently confirmed, and chunk bodies are never retained in the metadata cache. | M6 reader (no transition) | `core/frontend/chunkstore/layout_verify.go` `VerifyLayout`; `layout/verify.go` `chunks` | `TestVerifyBindingsChecksEachDistinctObjectOnce` | — (pass-local reuse) | ACTIVE | +| `INV-VERIFY-BINDINGS-001` | Bindings depth checks each chunk's filer binding and size against its owner's VOLUME geometry (tail excepted), without reading the blob body. | M6 reader (no transition) | `core/frontend/chunkstore/layout_verify.go` `verifyStat`; `core/frontend/chunkstore/layout/verify.go` `chunks` | `TestVerifyBindingsNeverReadsChunkBodies`, `TestVerifyBindingsChecksDeclaredSizesAndRefusals`, `TestVerifyBindingsLookupFailureIsNotAMissingObject`, `TestVerifyBindingsRejectsSelfConsistentTruncationAgainstGeometry`, `TestVerifyBindingsUsesTailGeometryAndRejectsOutsideVolume` | — (read-only inspection) | ACTIVE | +| `INV-VERIFY-DISTINCT-001` | A verify pass looks up each immutable metadata object and chunk binding once across roots; HEAD remains independently confirmed, and chunk bodies are never retained in the metadata cache. | M6 reader (no transition) | `core/frontend/chunkstore/layout_verify.go` `VerifyLayout`; `core/frontend/chunkstore/layout/verify.go` `chunks` | `TestVerifyBindingsChecksEachDistinctObjectOnce` | — (pass-local reuse) | ACTIVE | | `INV-VERIFY-STABLE-HEAD-001` | Filer verify publishes MISSING or ORPHAN only after two HEAD observations agree on a nonzero generation and volume identity. An unavailable or changed own/dependent HEAD makes the pass incomplete and suppresses those findings. Unsupported verify options refuse before dialing. | M6 (reader; no transition) | `core/frontend/chunkstore/layout_verify.go` `VerifyLayout`; `cmd/sw-block/chunk_verify.go` `chunkVerify` | `TestVerifyLayoutRequiresStableHeadForMissingAndOrphans`; `TestVerifyConfirmsDependentHeadBeforeReportingOrphans`; `TestOpsChunkVerifyRefusesUnsupportedFlagsBeforeDial` | — | ACTIVE | | `INV-VERIFY-NOTFOUND-001` | Verify reports `MISSING` only when the store answers that the object does not exist; any other read failure ends the pass as incomplete with that error, and is never a finding. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyReadErrorIsReturned`, `TestVerifyFindsMissingAndCorrupt` (`core/frontend/chunkstore/layout/verify_test.go`); `TestOpsChunk_VerifyReadErrorIsIncomplete` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE | | `INV-VERIFY-REACH-001` | A complete pass checks every object the current root and every snapshot root name (roots, segments, chunks): an absent one is `MISSING`; one whose bytes do not hash to its name, at depth full, is `CORRUPT`. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyCleanVolume`, `TestVerifyFindsMissingAndCorrupt`, `TestVerifyWalksSnapshotRoots` (`core/frontend/chunkstore/layout/verify_test.go`) | — | ACTIVE | | `INV-VERIFY-INCOMPLETE-001` | A volume whose VOLUME or HEAD is absent or does not decode is never reported clean: the pass is incomplete and says which object. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyHeadMissingOrMalformedIsIncomplete` (`core/frontend/chunkstore/layout/verify_test.go`) | — | ACTIVE | | `INV-VERIFY-ORPHAN-001` | With orphans on, only this volume's own full-id names that no root or live restore target names are ORPHAN. Owner/target paths use VolumeDir(name,id); an unreadable live target suppresses orphan findings. Verify deletes nothing. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyOrphans`, `TestVerifyDependentReachIsNotOrphanAndUnreadableDependentSuppresses` (`core/frontend/chunkstore/layout/verify_test.go`) ; `TestVerifyProductionLayoutCurrentAndRestored` (`core/frontend/chunkstore/verify_production_layout_test.go`) | — | ACTIVE | -| `INV-VERIFY-IDENTITY-001` | Verify reads canonical VolumeDir(name,id) directories. VOLUME must match its directory, HEAD must match VOLUME, and a master-resolved id must match in full. A mismatched chunk-owner VOLUME is IDENTITY, never clean. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyVolumeRecordAndHeadID`, `TestVerifyChunkOwnerIdentity` (`core/frontend/chunkstore/layout/verify_test.go`) ; `TestVerifyProductionLayoutCurrentAndRestored` (`core/frontend/chunkstore/verify_production_layout_test.go`); `TestOpsChunk_VerifyProductionLayoutNameAndDirectory`, `TestOpsChunk_VerifyBindsMasterFullIDDespiteDirectoryPrefixCollision` (`cmd/sw-block/chunk_verify_production_test.go`) | — | ACTIVE | +| `INV-VERIFY-IDENTITY-001` | Verify reads canonical VolumeDir(name,id) directories. VOLUME must match its directory, HEAD must match VOLUME, and a master-resolved id must match in full. A mismatched chunk-owner VOLUME is IDENTITY, never clean. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyVolumeRecordAndHeadID`, `TestVerifyChunkOwnerIdentity` (`core/frontend/chunkstore/layout/verify_test.go`), `TestVerifyDeduplicationNeverSkipsFullOwnerIdentity` (`core/frontend/chunkstore/verify_bindings_stat_test.go`) ; `TestVerifyProductionLayoutCurrentAndRestored` (`core/frontend/chunkstore/verify_production_layout_test.go`); `TestOpsChunk_VerifyProductionLayoutNameAndDirectory`, `TestOpsChunk_VerifyBindsMasterFullIDDespiteDirectoryPrefixCollision` (`cmd/sw-block/chunk_verify_production_test.go`) | — | ACTIVE | | `INV-RESTORE-HYDRATE-001` | The background hydrate walker fetches a chunk only through that chunk's shared fill flight: at most one fetch per chunk absence, and a fetched block is never installed over a block written locally. | M4 Holder (background hydrate) | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `HydrateAllAt`, `startWalkerFill`, `nextHydrateTarget`, `admitFill`; `core/storage/chunk_hydration.go` `hydrationFlightLocked`; `core/storage/chunk_layer.go` `fillOnce` | `TestHydrateAll_FillsEveryChunkOnceAndReadsTheHeadImage`, `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_AdmitsEachFillThroughTheLimiterWithTheCallersClass`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld`, `TestHydrateAll_PacedByByteRate` (`core/storage/chunk_hydrate_all_test.go`) | — | DORMANT | | `INV-RESTORE-OWN-BATCH-001` | A batch cut re-uploads at most N local chunks whose HEAD keys name another volume under new own keys, even when their bytes equal HEAD's, in one ordinary cut (one intent, one HEAD CAS); it never fetches an absent chunk. | M6.Restore.Owning>Owning | `core/storage/chunk_own.go` `OwnBatch`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`, `TestOwnBatch_SkipsChunksNotLocal`, `TestOwnBatch_CarriesGuestWrites` (`core/storage/chunk_own_test.go`) | `RestoreIndependence` `NoGap` | DORMANT | | `INV-RESTORE-READ-REF-001` | A restore target reads each chunk its HEAD names from the pool of the reference's owner, by the reference alone (no other copy, no name-built path); a chunk missing there is an error on a fresh host, never zeros. | M6 restore target read (no transition) | `core/frontend/chunkstore/layout/read.go` `Reader.ReadRef`; `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.Get` | `TestLayoutRemote_RestoreTargetReadsItsSource` (`core/frontend/chunkstore/layout_restore_read_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 35f2dd1eaf..e489e42760 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -870,7 +870,8 @@ check. Source and restore-target chunks are checked in their owners' canonical directories using each reference's full owner id. The default `--depth bindings` (also named `meta`) checks each distinct chunk's -filer entry and the consistency of its declared size without fetching the chunk +filer entry and its declared size against its owner's VOLUME geometry (including +the final partial chunk) without fetching the chunk body. It does not detect content damage or a missing backing needle behind a present entry; use `--depth data` for those checks. Roots and segments are still read and decoded, and shared immutable objects are checked once per pass. From 95abcb3183baa17a11b8b544061d42689652012e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 00:42:47 -0800 Subject: [PATCH 3/4] fix: verify backing needles with HEAD and retain exact chunk hashes --- seaweed-block/cmd/sw-block/chunk_verify.go | 2 +- .../core/frontend/chunkstore/fake_test.go | 10 +++ .../core/frontend/chunkstore/layout/verify.go | 17 ++-- .../core/frontend/chunkstore/layout_verify.go | 18 +++- .../core/frontend/chunkstore/swfs_head.go | 85 +++++++++++++++++++ .../frontend/chunkstore/swfs_head_test.go | 80 +++++++++++++++++ .../chunkstore/verify_bindings_stat_test.go | 85 ++++++++++++++++++- .../verify_production_layout_test.go | 4 + seaweed-block/docs/design/invariants.md | 3 +- seaweed-block/docs/standalone-deployment.md | 9 +- 10 files changed, 300 insertions(+), 13 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/swfs_head.go create mode 100644 seaweed-block/core/frontend/chunkstore/swfs_head_test.go diff --git a/seaweed-block/cmd/sw-block/chunk_verify.go b/seaweed-block/cmd/sw-block/chunk_verify.go index f8dbbac4e2..71cf5b19e9 100644 --- a/seaweed-block/cmd/sw-block/chunk_verify.go +++ b/seaweed-block/cmd/sw-block/chunk_verify.go @@ -37,7 +37,7 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int { fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") fs.StringVar(&snapshot, "snapshot", "", "unsupported: every snapshot HEAD names is always checked") fs.BoolVar(&allSnapshots, "all-snapshots", false, "unsupported: every snapshot HEAD names is always checked") - fs.StringVar(&depth, "depth", "bindings", "meta or bindings: named filer entries and declared sizes; data: and every chunk's bytes hash to its name") + fs.StringVar(&depth, "depth", "bindings", "meta or bindings: named filer entries, sizes and needle HEAD; data: and every chunk's bytes hash to its name") 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") diff --git a/seaweed-block/core/frontend/chunkstore/fake_test.go b/seaweed-block/core/frontend/chunkstore/fake_test.go index 273ae134c2..b1bc06d73f 100644 --- a/seaweed-block/core/frontend/chunkstore/fake_test.go +++ b/seaweed-block/core/frontend/chunkstore/fake_test.go @@ -264,6 +264,16 @@ type fakeBlobs struct { func newFakeBlobs() *fakeBlobs { return &fakeBlobs{data: map[string][]byte{}} } +func (b *fakeBlobs) HeadBlob(_ context.Context, fid string) (uint64, error) { + b.mu.Lock() + defer b.mu.Unlock() + d, ok := b.data[fid] + if !ok { + return 0, ErrBlobNotFound + } + return uint64(len(d)), nil +} + func (b *fakeBlobs) Put(_ context.Context, d []byte) (string, error) { b.mu.Lock() defer b.mu.Unlock() diff --git a/seaweed-block/core/frontend/chunkstore/layout/verify.go b/seaweed-block/core/frontend/chunkstore/layout/verify.go index 7433730f67..85ee3422e9 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/verify.go +++ b/seaweed-block/core/frontend/chunkstore/layout/verify.go @@ -69,8 +69,8 @@ type verifier struct { res VerifyResult ownPool map[string]bool // reachable own names, by path relative to the volume ownMeta map[string]bool - owners map[string]ownerID // VOLUME id per chunk owner, read once - checked map[string]bool // chunk paths checked across all roots + owners map[string]ownerID // VOLUME id per chunk owner, read once + checked map[verifyChunkKey]bool // exact immutable chunk identities across all roots geometry map[string]Geometry ownID VolumeID } @@ -80,6 +80,12 @@ type ownerID struct { ok bool } +type verifyChunkKey struct { + owner VolumeID + index uint64 + hash Hash +} + // Verify checks the canonical store directory vol under base; callers resolve // logical names through the master before choosing VolumeDir(name, id). func Verify(ctx context.Context, base, vol string, fetch Fetch, opts VerifyOptions) (VerifyResult, error) { @@ -98,7 +104,7 @@ 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") } - v := &verifier{base: base, vol: vol, fetch: fetch, opts: opts, ownPool: map[string]bool{}, ownMeta: map[string]bool{}, owners: map[string]ownerID{}, checked: map[string]bool{}, geometry: map[string]Geometry{}} + 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) if err != nil { @@ -327,10 +333,11 @@ func (v *verifier) chunks(ctx context.Context, r *Reader, seg Segment, count boo v.find(FindIdentity, p, fmt.Sprintf("names owner %s id %s; its VOLUME has %s", ref.Owner, ref.OwnerID, map[bool]string{true: o.id.String(), false: "none"}[o.ok])) continue } - if v.checked[p] { + key := verifyChunkKey{owner: ref.OwnerID, index: ref.Chunk.Index, hash: ref.Chunk.Hash} + if v.checked[key] { continue } - v.checked[p] = true + v.checked[key] = true if v.opts.Depth == DepthFull { if _, err := r.get(ctx, dir, ref.Chunk.Path(), ref.Chunk.Hash); err != nil { if err := v.classify(p, err); err != nil { diff --git a/seaweed-block/core/frontend/chunkstore/layout_verify.go b/seaweed-block/core/frontend/chunkstore/layout_verify.go index 7977d946e2..813d8ca138 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_verify.go +++ b/seaweed-block/core/frontend/chunkstore/layout_verify.go @@ -120,8 +120,8 @@ func VerifyLayout(ctx context.Context, f Filer, base, vol string, opts layout.Ve return res, nil } -// verifyStat checks the filer's binding and size, not the needle's bytes. -// Reading and hashing those bytes belongs to data depth. +// verifyStat checks the filer binding and the needle's existence and size by +// HEAD. Reading and hashing the response body belongs to data depth. func (s *LayoutStore) verifyStat(ctx context.Context, p string, expectedSize uint64) (bool, error) { if !path.IsAbs(p) || path.Clean(p) != p || !strings.HasPrefix(p, path.Dir(s.root)+"/") { return false, errors.New("chunkstore: object path outside the store base") @@ -148,6 +148,20 @@ func (s *LayoutStore) verifyStat(ctx context.Context, p string, expectedSize uin if len(e.Content) != 0 || len(e.Chunks) != 1 || e.Chunks[0] == nil || e.Chunks[0].Offset != 0 || e.Chunks[0].FileId == "" || e.Attributes == nil || e.Attributes.FileSize != e.Chunks[0].Size || e.Attributes.FileSize != expectedSize { return false, fmt.Errorf("%w: invalid file binding or size for %s", layout.ErrCorrupt, p) } + head, ok := s.b.(BlobHeaders) + if !ok { + return false, errors.New("chunkstore: verify needs needle HEAD support") + } + size, err := head.HeadBlob(ctx, e.Chunks[0].FileId) + if errors.Is(err, ErrBlobNotFound) { + return false, nil + } + if err != nil { + return false, err + } + if size != expectedSize { + return false, fmt.Errorf("%w: needle size differs from VOLUME geometry for %s", layout.ErrCorrupt, p) + } return true, nil } diff --git a/seaweed-block/core/frontend/chunkstore/swfs_head.go b/seaweed-block/core/frontend/chunkstore/swfs_head.go new file mode 100644 index 0000000000..9b9efeb100 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/swfs_head.go @@ -0,0 +1,85 @@ +package chunkstore + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" +) + +// BlobHeaders checks needle existence and logical size without transferring its +// body to the client. The volume server may read small needles internally. +type BlobHeaders interface { + HeadBlob(context.Context, string) (uint64, error) +} + +// HeadBlob resolves every replica with the same fresh-location absence rule as +// Get. A reachable copy is sufficient; only all fresh 404s prove absence. +func (c *SWFS) HeadBlob(ctx context.Context, fid string) (uint64, error) { + vid, needle, ok := strings.Cut(fid, ",") + if !ok || vid == "" || needle == "" || strings.ContainsAny(fid, "/\\?#% \r\n") { + return 0, fmt.Errorf("chunkstore: bad fid %q", fid) + } + urls, cached, err := c.lookupVolume(ctx, vid) + if err != nil { + return 0, err + } + for attempt := 0; ; attempt++ { + size, absent, readErr := c.headFromAll(ctx, urls, fid) + if readErr == nil { + return size, nil + } + c.mu.Lock() + delete(c.vidCache, vid) + c.mu.Unlock() + if absent && cached && attempt == 0 { + urls, _, err = c.lookupVolume(ctx, vid) + if err != nil { + return 0, err + } + continue + } + if absent { + readErr = &blobNotFoundError{readErr} + } + return 0, fmt.Errorf("chunkstore: HEAD %s: %w", fid, readErr) + } +} + +func (c *SWFS) headFromAll(ctx context.Context, urls []string, fid string) (uint64, bool, error) { + absent := true + var last error + for _, host := range urls { + req, err := http.NewRequestWithContext(ctx, http.MethodHead, "http://"+host+"/"+fid, nil) + if err != nil { + return 0, false, err + } + resp, err := c.http.Do(req) + if err == nil { + closeErr := resp.Body.Close() + switch { + case closeErr != nil: + err = closeErr + case resp.StatusCode != http.StatusOK: + err = &blobStatusError{code: resp.StatusCode, host: host} + case resp.ContentLength < 0: + err = errors.New("chunkstore: needle HEAD has no size") + default: + return uint64(resp.ContentLength), false, nil + } + } + last = err + var se *blobStatusError + if !errors.As(err, &se) || se.code != http.StatusNotFound { + absent = false + } + } + if last == nil { + last = errors.New("chunkstore: needle HEAD has no locations") + absent = false + } + return 0, absent, last +} + +var _ BlobHeaders = (*SWFS)(nil) diff --git a/seaweed-block/core/frontend/chunkstore/swfs_head_test.go b/seaweed-block/core/frontend/chunkstore/swfs_head_test.go new file mode 100644 index 0000000000..8cb6af0068 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/swfs_head_test.go @@ -0,0 +1,80 @@ +package chunkstore + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" +) + +func TestSWFSHeadBlobUsesOnlyHEADAndClassifiesAbsence(t *testing.T) { + for _, tc := range []struct { + name, length string + status int + missing bool + wantError bool + }{ + {"exists", "4194304", 200, false, false}, + {"missing", "0", 404, true, true}, + {"unavailable", "0", 503, false, true}, + {"size-unavailable", "", 200, false, true}, + } { + t.Run(tc.name, func(t *testing.T) { + methods := make(chan string, 4) + vol := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + methods <- r.Method + if tc.length != "" { + w.Header().Set("Content-Length", tc.length) + } + w.WriteHeader(tc.status) + })) + defer vol.Close() + host := strings.TrimPrefix(vol.URL, "http://") + f := &fakeFilerGRPC{lookupVol: &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{"7": {Locations: []*filerpb.Location{{Url: host}}}}}} + c := startFakeFiler(t, f) + size, err := c.HeadBlob(context.Background(), "7,01abcdef") + if (err != nil) != tc.wantError || errors.Is(err, ErrBlobNotFound) != tc.missing || !tc.wantError && size != 4194304 { + t.Fatalf("size=%d err=%v", size, err) + } + if method := <-methods; method != http.MethodHead { + t.Fatalf("body request %s", method) + } + }) + } +} + +func TestSWFSHeadBlobRefreshesCachedMissingLocation(t *testing.T) { + stale := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(404) })) + defer stale.Close() + live := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodHead { + t.Errorf("body request %s", r.Method) + } + w.Header().Set("Content-Length", "4096") + })) + defer live.Close() + f := &fakeFilerGRPC{lookupVol: &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{"7": {Locations: []*filerpb.Location{{Url: strings.TrimPrefix(live.URL, "http://")}}}}}} + c := startFakeFiler(t, f) + c.vidCache["7"] = []string{strings.TrimPrefix(stale.URL, "http://")} + size, err := c.HeadBlob(context.Background(), "7,01abcdef") + if err != nil || size != 4096 || f.volLookups != 1 { + t.Fatalf("size=%d err=%v fresh lookups=%d", size, err, f.volLookups) + } +} + +func TestSWFSHeadBlobMixedReplicaFailureDoesNotProveAbsence(t *testing.T) { + missing := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(404) })) + defer missing.Close() + failed := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(503) })) + defer failed.Close() + f := &fakeFilerGRPC{lookupVol: &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{"7": {Locations: []*filerpb.Location{{Url: strings.TrimPrefix(failed.URL, "http://")}, {Url: strings.TrimPrefix(missing.URL, "http://")}}}}}} + c := startFakeFiler(t, f) + _, err := c.HeadBlob(context.Background(), "7,01abcdef") + if err == nil || errors.Is(err, ErrBlobNotFound) { + t.Fatalf("mixed operational/404 answer: %v", err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/verify_bindings_stat_test.go b/seaweed-block/core/frontend/chunkstore/verify_bindings_stat_test.go index 37da50da03..09440743ac 100644 --- a/seaweed-block/core/frontend/chunkstore/verify_bindings_stat_test.go +++ b/seaweed-block/core/frontend/chunkstore/verify_bindings_stat_test.go @@ -55,6 +55,84 @@ func TestVerifyBindingsNeverReadsChunkBodies(t *testing.T) { } } +func TestVerifyBindingsReportsMissingNeedleBehindPresentEntry(t *testing.T) { + fb, id := verifyBlobFixture(t) + dir := layout.VolumeDir("v", id) + n := layout.NameChunk(0, []byte(strings.Repeat("a", 4*4096))) + e := fb.fakeFiler.entries[path.Join("/blocks", dir, n.Path())] + delete(fb.fakeBlobs.data, e.Chunks[0].FileId) + _, before, _ := fb.fakeBlobs.counts() + res, err := VerifyLayout(context.Background(), fb, "/blocks", dir, layout.VerifyOptions{Depth: layout.DepthNames}) + _, after, _ := fb.fakeBlobs.counts() + if err != nil || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != layout.FindMissing || after != before { + t.Fatalf("missing needle without body reads: %+v, %v, gets=%d", res, err, after-before) + } +} + +type verifyNeedleFailure struct { + filerBlobs + err error + size uint64 +} + +func (f verifyNeedleFailure) HeadBlob(context.Context, string) (uint64, error) { + return f.size, f.err +} + +func TestVerifyBindingsNeedleFailureAndSize(t *testing.T) { + fb, id := verifyBlobFixture(t) + injected := errors.New("needle service unavailable") + res, err := VerifyLayout(context.Background(), verifyNeedleFailure{filerBlobs: fb, err: injected}, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames}) + if !errors.Is(err, injected) || res.Complete || len(res.Findings) != 0 { + t.Fatalf("unavailable needle: %+v, %v", res, err) + } + res, err = VerifyLayout(context.Background(), verifyNeedleFailure{filerBlobs: fb, size: 32}, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames}) + if err != nil || !res.Complete || len(res.Findings) != 2 { + t.Fatalf("wrong needle sizes: %+v, %v", res, err) + } + for _, f := range res.Findings { + if f.Class != layout.FindCorrupt { + t.Fatalf("wrong-size class: %+v", f) + } + } +} + +func TestVerifyDistinctChunksRetainHashAcrossSnapshots(t *testing.T) { + for _, depth := range []string{layout.DepthNames, layout.DepthFull} { + t.Run(depth, func(t *testing.T) { + fb, id := verifyBlobFixture(t) + dir := path.Join("/blocks", layout.VolumeDir("v", id)) + missing := layout.NameChunk(0, []byte(strings.Repeat("z", 4*4096))) + root, segs, err := layout.Build(map[uint64]layout.Ref{0: {Owner: "v", OwnerID: id, Chunk: missing}}) + if err != nil { + t.Fatal(err) + } + for n, b := range segs { + putFile(t, fb.fakeFiler, path.Join(dir, n.Path()), b) + } + rn, raw, err := layout.NameRoot(root) + if err != nil { + t.Fatal(err) + } + putFile(t, fb.fakeFiler, path.Join(dir, rn.Path()), raw) + e := fb.fakeFiler.entries[path.Join(dir, layout.HeadName)] + h, err := layout.DecodeHead(e.Content, 0, id) + if err != nil { + t.Fatal(err) + } + h.Snapshots = map[string]layout.Snapshot{"older": {Root: rn}} + e.Content, err = h.Encode() + if err != nil { + t.Fatal(err) + } + res, err := VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: depth}) + if err != nil || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != layout.FindMissing || res.Findings[0].Path != path.Join(layout.VolumeDir("v", id), missing.Path()) { + t.Fatalf("different content at the same owner/index: %+v, %v", res, err) + } + }) + } +} + type verifyLookupCounter struct { filerBlobs reads map[string]int @@ -205,6 +283,10 @@ type verifyPayloadCounter struct { payloadReads, metadataReads int } +func (f *verifyPayloadCounter) HeadBlob(ctx context.Context, fid string) (uint64, error) { + return f.Blobs.(BlobHeaders).HeadBlob(ctx, fid) +} + func (f *verifyPayloadCounter) Get(ctx context.Context, fid string) ([]byte, error) { if f.payloads[fid] { f.payloadReads++ @@ -279,8 +361,9 @@ func TestVerifyBindingsUsesTailGeometryAndRejectsOutsideVolume(t *testing.T) { t.Fatal(err) } p := path.Join(dir, layout.NameChunk(5, []byte(strings.Repeat("f", 4*4096))).Path()) - // Names depth observes declared metadata only; it must not read this body. + // A valid tail has both a shortened needle and matching metadata. e := fb.fakeFiler.entries[p] + fb.fakeBlobs.data[e.Chunks[0].FileId] = fb.fakeBlobs.data[e.Chunks[0].FileId][:4096] e.Attributes.FileSize, e.Chunks[0].Size = 4096, 4096 if mode == "short-tail" { e.Attributes.FileSize, e.Chunks[0].Size = 2048, 2048 diff --git a/seaweed-block/core/frontend/chunkstore/verify_production_layout_test.go b/seaweed-block/core/frontend/chunkstore/verify_production_layout_test.go index cd435c590d..416de9c193 100644 --- a/seaweed-block/core/frontend/chunkstore/verify_production_layout_test.go +++ b/seaweed-block/core/frontend/chunkstore/verify_production_layout_test.go @@ -16,6 +16,10 @@ type verifyProductionStore struct { Blobs } +func (f verifyProductionStore) HeadBlob(ctx context.Context, fid string) (uint64, error) { + return f.Blobs.(BlobHeaders).HeadBlob(ctx, fid) +} + // Use the production creators, not a hand-written name-only directory: a // restored image borrows the source's chunks while owning copied metadata. func TestVerifyProductionLayoutCurrentAndRestored(t *testing.T) { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index f76ca2fcd9..d513ea9684 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1060,7 +1060,8 @@ Notes: | `INV-SNAP-SCHEDULE-RESTART-001` | A new snapshot worker seeds its last success from HEAD's newest scheduled creation time (future clamped to now), then the next stable per-volume grid slot; absent history is due now. Restarts preserve overdue age; manual snapshots do not seed it. | M8 scheduled worker Armed → Due | `core/frontend/durable/chunk_snapshot_schedule.go` `snapshotScheduleFromHead`; `provider_chunk.go` `newChunkLayer` | `TestScheduledSnapshotRestartsStillTakeTheDueSnapshot`, `TestScheduledSnapshotRestartPreservesOverdueFromHEAD`, `TestScheduledSnapshotWithoutHistoryIsImmediatelyDue`, `TestScheduledSnapshotProvidersSpreadAfterImmediateFirstAttempt`, `TestSnapshotScheduleHeadSeedKeepsPerVolumeGrid`, `TestSnapshotScheduleHeadSeedClampsFutureCreationTime` | — (read-only timer initialization from existing HEAD metadata) | ACTIVE | | `INV-SNAP-SCHEDULED-KEEP-001` | Retention keeps the newest K scheduled snapshots, K being the newest one's swb.schedule.keep (default 7); scheduled snapshots never count against KeepNewest or get age keeps, so other snapshots are planned as if they were absent. | M6 snapshot: Published → Deleting (retention, class `scheduled`) | `core/frontend/chunkstore/retain/retain.go` `Plan`, `scheduleKeepOf` | `TestPlanRetention_ScheduledClassKeepsItsOwnNewest`, `TestPlanRetention_PinnedScheduledStaysInItsClass` (`core/frontend/chunkstore/retain/retain_test.go`) | — | ACTIVE | | `INV-VERIFY-READONLY-001` | Verify writes nothing at any depth: it reaches the store only through Fetch, Stat and List, and a full pass with orphans leaves every filer entry and blob unchanged. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyLayoutThroughTheAdapter` (`core/frontend/chunkstore/layout_verify_test.go`) | — | ACTIVE | -| `INV-VERIFY-BINDINGS-001` | Bindings depth checks each chunk's filer binding and size against its owner's VOLUME geometry (tail excepted), without reading the blob body. | M6 reader (no transition) | `core/frontend/chunkstore/layout_verify.go` `verifyStat`; `core/frontend/chunkstore/layout/verify.go` `chunks` | `TestVerifyBindingsNeverReadsChunkBodies`, `TestVerifyBindingsChecksDeclaredSizesAndRefusals`, `TestVerifyBindingsLookupFailureIsNotAMissingObject`, `TestVerifyBindingsRejectsSelfConsistentTruncationAgainstGeometry`, `TestVerifyBindingsUsesTailGeometryAndRejectsOutsideVolume` | — (read-only inspection) | ACTIVE | +| `INV-VERIFY-BINDINGS-001` | Bindings checks each chunk's filer binding, declared size and needle HEAD size against its owner's VOLUME geometry (tail excepted), without transferring the blob body. | M6 reader (no transition) | `core/frontend/chunkstore/layout_verify.go` `verifyStat`; `core/frontend/chunkstore/layout/verify.go` `chunks` | `TestVerifyBindingsNeverReadsChunkBodies`, `TestVerifyBindingsChecksDeclaredSizesAndRefusals`, `TestVerifyBindingsLookupFailureIsNotAMissingObject`, `TestVerifyBindingsRejectsSelfConsistentTruncationAgainstGeometry`, `TestVerifyBindingsUsesTailGeometryAndRejectsOutsideVolume` | — (read-only inspection) | ACTIVE | +| `INV-VERIFY-NEEDLE-001` | Bindings reports a missing needle only after every freshly resolved location answers 404; operational failures remain incomplete. A needle HEAD never falls back to a client GET. | M6 reader (no transition) | `core/frontend/chunkstore/swfs_head.go` `HeadBlob`; `core/frontend/chunkstore/layout_verify.go` `verifyStat` | `TestVerifyBindingsReportsMissingNeedleBehindPresentEntry`, `TestSWFSHeadBlobUsesOnlyHEADAndClassifiesAbsence`, `TestSWFSHeadBlobRefreshesCachedMissingLocation` | — (read-only inspection) | ACTIVE | | `INV-VERIFY-DISTINCT-001` | A verify pass looks up each immutable metadata object and chunk binding once across roots; HEAD remains independently confirmed, and chunk bodies are never retained in the metadata cache. | M6 reader (no transition) | `core/frontend/chunkstore/layout_verify.go` `VerifyLayout`; `core/frontend/chunkstore/layout/verify.go` `chunks` | `TestVerifyBindingsChecksEachDistinctObjectOnce` | — (pass-local reuse) | ACTIVE | | `INV-VERIFY-STABLE-HEAD-001` | Filer verify publishes MISSING or ORPHAN only after two HEAD observations agree on a nonzero generation and volume identity. An unavailable or changed own/dependent HEAD makes the pass incomplete and suppresses those findings. Unsupported verify options refuse before dialing. | M6 (reader; no transition) | `core/frontend/chunkstore/layout_verify.go` `VerifyLayout`; `cmd/sw-block/chunk_verify.go` `chunkVerify` | `TestVerifyLayoutRequiresStableHeadForMissingAndOrphans`; `TestVerifyConfirmsDependentHeadBeforeReportingOrphans`; `TestOpsChunkVerifyRefusesUnsupportedFlagsBeforeDial` | — | ACTIVE | | `INV-VERIFY-NOTFOUND-001` | Verify reports `MISSING` only when the store answers that the object does not exist; any other read failure ends the pass as incomplete with that error, and is never a finding. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyReadErrorIsReturned`, `TestVerifyFindsMissingAndCorrupt` (`core/frontend/chunkstore/layout/verify_test.go`); `TestOpsChunk_VerifyReadErrorIsIncomplete` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index e489e42760..15ad5eba72 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -871,9 +871,12 @@ directories using each reference's full owner id. The default `--depth bindings` (also named `meta`) checks each distinct chunk's filer entry and its declared size against its owner's VOLUME geometry (including -the final partial chunk) without fetching the chunk -body. It does not detect content damage or a missing backing needle behind a -present entry; use `--depth data` for those checks. Roots and segments are still +the final partial chunk), then checks the backing needle's existence and size +using HTTP HEAD without downloading its body. A missing needle behind a present +entry is MISSING; an unreachable server makes the pass incomplete. This does +not detect same-size content damage; use `--depth data` for the hash check. +SeaweedFS 4.53 reads only metadata for ordinary uncompressed 4 MiB needles on +HEAD, but may read small needles internally. Roots and segments are still read and decoded, and shared immutable objects are checked once per pass. Verify is read-only: exit 0 means complete with no findings, 3 means complete From c967152e63163774f8eddda2b593db2d26e87540 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 01:32:59 -0800 Subject: [PATCH 4/4] docs: qualify inline and replicated needle verification --- seaweed-block/docs/standalone-deployment.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 15ad5eba72..db608cdbf0 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -873,11 +873,14 @@ The default `--depth bindings` (also named `meta`) checks each distinct chunk's filer entry and its declared size against its owner's VOLUME geometry (including the final partial chunk), then checks the backing needle's existence and size using HTTP HEAD without downloading its body. A missing needle behind a present -entry is MISSING; an unreachable server makes the pass incomplete. This does +entry is MISSING. A successful replica is sufficient; when none succeeds, +an operational failure makes the pass incomplete rather than proving absence. This does not detect same-size content damage; use `--depth data` for the hash check. SeaweedFS 4.53 reads only metadata for ordinary uncompressed 4 MiB needles on HEAD, but may read small needles internally. Roots and segments are still read and decoded, and shared immutable objects are checked once per pass. +Inline filer entries are checked directly from the content returned by the +lookup; they have no backing needle and require no needle HEAD. Verify is read-only: exit 0 means complete with no findings, 3 means complete with findings, 1 means incomplete, and 2 means invalid arguments. `--depth data`