fix: verify chunk bindings without reading their bodies

This commit is contained in:
pingqiu committed 2026-12-01 00:03:07 -08:00
1 parent 13d0627043
commit 950d636e93
6 files changed
+314 -5

No files matched your search

+1 -1
View File
@@ -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")
@@ -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 <base>).
@@ -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 {
@@ -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) {
@@ -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)
}
}
+3 -1
View File
@@ -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 |
@@ -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;