Files
seaweedfs/weed/command/compact_test.go
T
Chris LuandClaude Opus 5.5 d6a657cd92 weed compact -method data: copy past an unreadable record like -method index (#12970)
* storage: resume data compaction past an unreadable record

Compacting by data follows record headers through the .dat, so one corrupt
header ended the scan: the compaction failed, or, when the header's size
jumped past the end, every record after it was dropped. Compacting by index
copies past such a record.

When the scan stops on a corrupt header or jumps past live records, resume
it at each live record the index places further on. A read error still
fails the compaction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: do not copy a record whose header size disagrees with the index

A live record whose header carries a damaged size was copied with that
size, and the compacted volume indexed a needle it could not read. The
index records each live record's size, so a header that disagrees is
damaged: skip it, and let the scan resume at the next live record.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: verify a live record's body instead of comparing its size with the index

Data compaction copied a record whose body failed to parse, and the size
check dropped an intact record when only its index row was wrong. Read the
body only for the record the index points at, drop it on the same errors
-method index drops on, fail on any other read error, and keep the size
the record itself carries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: resume data compaction at every live record the scan did not reach

The resume started past the last header the scan parsed, so a corrupt size
that landed on a later valid header lost the live records it jumped over.
Track the records the scan copied or dropped, resume at each live record it
did not reach in .dat order, and stop a resumed scan at a record an earlier
pass already handled so nothing is copied twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* command: read the compacted volume's version from its super block in tests

Compaction can write a different needle version than the source volume,
so parse the .cpd with the version it records instead of the current one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: do not walk a run of damaged headers again on every resume

A record whose header id is damaged is not marked as handled, so each
resume at one of a run of such records walked the rest of the run before
reaching a copied record, which is quadratic in the run length. Remember
the offsets resumed scans pass, skip resuming at them, and stop a resume
when it reaches one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: count the resumed scans' reads in the damaged-run test

The kept keys come out the same when every resume walks the rest of the
run, so bound the reads made through the volume's data backend instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: drop a record whose header size runs past the end of the .dat

Reading such a record sized its buffer from the corrupt header: a size
near 2 GiB allocated that much on 64-bit and panicked in makeslice on
32-bit. Check the record end against the file size first and drop the
record as unreadable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* needle: compute ReadBytes slice bounds in int

NeedleHeaderSize+size was Size arithmetic and wrapped for a damaged size
near MaxInt32, so the slice panicked instead of failing the read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* needle: fail ReadNeedleBlob for a size that does not fit in an int

On 32-bit a damaged size near MaxInt32 made the buffer length negative
and panicked in makeslice. Return ErrorSizeInvalid instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* needle: compare DataSize bounds in uint64

On 32-bit builds int(DataSize) is negative for a damaged DataSize of
0x80000000 or more, which passes the bounds check and panics on the
slice instead of returning ErrorCorrupted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:48:55 -08:00

142 lines
5.0 KiB
Go

package command
import (
"bytes"
"os"
"slices"
"testing"
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
"github.com/seaweedfs/seaweedfs/weed/storage/idx"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
)
func runCompactOnFixTestVolume(t *testing.T, dir, method string) {
t.Helper()
savedDir, savedCollection, savedId, savedMethod, savedStatus := *compactVolumePath, *compactVolumeCollection, *compactVolumeId, *compactMethod, commandExitStatus
t.Cleanup(func() {
*compactVolumePath, *compactVolumeCollection, *compactVolumeId, *compactMethod, commandExitStatus = savedDir, savedCollection, savedId, savedMethod, savedStatus
})
*compactVolumePath, *compactVolumeCollection, *compactVolumeId, *compactMethod, commandExitStatus = dir, "fix", 7, method, 0
runCompact(cmdCompact, nil)
}
// compactedKeys returns the keys in the .cpx, and those whose .cpd record
// holds the data writeFixTestVolume wrote for them. The .cpd must hold no
// record the .cpx does not list.
func compactedKeys(t *testing.T, base string) (indexed, intact []uint64) {
t.Helper()
datFile, err := os.Open(base + ".cpd")
if err != nil {
t.Fatal(err)
}
dat := backend.NewDiskFile(datFile)
defer dat.Close()
sb, err := super_block.ReadSuperBlock(dat)
if err != nil {
t.Fatal(err)
}
idxFile, err := os.Open(base + ".cpx")
if err != nil {
t.Fatal(err)
}
defer idxFile.Close()
listed := int64(sb.BlockSize())
if err := idx.WalkIndexFile(idxFile, 0, func(key types.NeedleId, offset types.Offset, size types.Size) error {
indexed = append(indexed, uint64(key))
listed += needle.GetActualSize(size, sb.Version)
n := new(needle.Needle)
if n.ReadData(dat, offset.ToActualOffset(), size, sb.Version) == nil && bytes.Equal(n.Data, bytes.Repeat([]byte{byte(key)}, 1000*int(key))) {
intact = append(intact, uint64(key))
}
return nil
}); err != nil {
t.Fatal(err)
}
if datSize, _, err := dat.GetStat(); err != nil || datSize != listed {
t.Errorf(".cpd holds %d bytes, its index lists %d: %v", datSize, listed, err)
}
slices.Sort(indexed)
slices.Sort(intact)
return indexed, intact
}
func damageDat(at int64, b []byte) func(t *testing.T, base string, offsets []int64) {
return func(t *testing.T, base string, offsets []int64) {
overwriteAt(t, base+".dat", offsets[2]+at, b)
}
}
// Damage to the middle record of five: both methods drop it and keep the
// others. -method data trusts an intact record over a wrong index size.
func TestCompactDataMethodSkipsUnreadableRecord(t *testing.T) {
sizeAt := int64(types.NeedleIdSize + types.CookieSize)
others := []uint64{1, 2, 4, 5}
for _, tc := range []struct {
name string
corrupt func(t *testing.T, base string, offsets []int64)
wantData []uint64
wantIndex []uint64
}{
{"garbage header", damageDat(0, bytes.Repeat([]byte{0xa5}, 16)), others, others},
{"size past the end", damageDat(sizeAt, []byte{0x7f, 0xff, 0xff, 0xf0}), others, others},
{"size into the next record", damageDat(sizeAt, []byte{0x00, 0x00, 0x00, 0x10}), others, others},
{"size onto a later record", func(t *testing.T, base string, offsets []int64) {
span := offsets[4] - offsets[2]
size := types.Size(span)
for needle.GetActualSize(size, needle.GetCurrentVersion()) > span {
size--
}
b := make([]byte, types.SizeSize)
types.SizeToBytes(b, size)
overwriteAt(t, base+".dat", offsets[2]+sizeAt, b)
}, others, others},
{"data", damageDat(types.NeedleHeaderSize+10, []byte{0xee}), others, others},
{"index size", func(t *testing.T, base string, _ []int64) {
row := int64(slices.Index(indexedKeys(t, base+".idx"), 3))
overwriteAt(t, base+".idx", row*types.NeedleMapEntrySize+types.NeedleIdSize+types.OffsetSize, []byte{0x00, 0x00, 0x00, 0x01})
}, []uint64{1, 2, 3, 4, 5}, others},
} {
t.Run(tc.name, func(t *testing.T) {
for method, want := range map[string][]uint64{"data": tc.wantData, "index": tc.wantIndex} {
dir := t.TempDir()
base, offsets := writeFixTestVolume(t, dir, 5)
doFixOneVolume(dir, "fix_7", "fix", 7, true)
tc.corrupt(t, base, offsets)
runCompactOnFixTestVolume(t, dir, method)
if CommandExitStatus() != 0 {
t.Fatalf("-method %s: exit status %d", method, CommandExitStatus())
}
indexed, intact := compactedKeys(t, base)
if !slices.Equal(indexed, want) || !slices.Equal(intact, want) {
t.Errorf("-method %s: indexed keys %v, intact keys %v, want %v", method, indexed, intact, want)
}
}
})
}
}
func TestCompactFailureLeavesNoOutput(t *testing.T) {
dir := t.TempDir()
base, _ := writeFixTestVolume(t, dir, 5)
doFixOneVolume(dir, "fix_7", "fix", 7, true)
if err := os.Mkdir(base+".cpd", 0755); err != nil {
t.Fatal(err)
}
runCompactOnFixTestVolume(t, dir, "data")
if CommandExitStatus() == 0 {
t.Error("expected a non-zero exit status")
}
for _, ext := range []string{".cpd", ".cpx"} {
if _, err := os.Stat(base + ext); !os.IsNotExist(err) {
t.Errorf("%s left behind: %v", ext, err)
}
}
}